Search code examples
regexperlsplitwhitespaceinverse

Perl: Split string by everything but whitespaces


I want to split a string by everything but whitespaces.

Example:

Assume that I have a string:

"The    quick  brown fox    jumps over   the lazy dog"

I want to split it and get the following list of space-strings:

["    ", "  ", " ", "    ", " ", "   ", " ", " "]

Can you please show me how to do it?

Thanks!


Solution

  • You can use \S to split by here which means match any non-white space character.

    my @list = split /\S+/, $string;
    

    Or better yet, just match your whitespace instead of having to split.

    my @list = $string =~ /\s+/g;