The split() function also has some practical uses in conjunction with the operators mentioned above:
If you need to split a string into words, you can do this:
s/^\s+//; @array = split;
After this statement executes, @array will be an array of words. Before splitting the string, you need to remove any beginning white space. If this is not done, split will create an array element with the white space as the first element in the array, and this is probably not what you want.
$line =~ s/^\s+//; @array = split(/\W/, $line);
After this statement executes, @array will be an array of words.
@array = split(//);
After this statement executes, @array will be an array of characters. split recognizes the empty pattern as a request to make every character into a separate array element.
@array = split(/:/);
@array will be an array of strings consisting of the values between the delimiters. If there are repeated delimiters-:: in this example-then an empty array element will be created. Use /:+/ as the delimiter to match in order to eliminate the empty array elements.
Lots of other good example may be found in the excellent Perl Cookbook, by T. Christianson and N. Torkington, O'Reilly, 1998.