m/\s*(\S+)\s*(\S+)\s*(\S+)\s*(\S+)\s*/
I was going to assert that this would generally be equivalent to splitting on whitespace, with the obvious difference that, if the string began with whitespace, split would return a list that included an empty string as the first element -- the first element returned by the regex would be the second element returned by split.
But then I noticed another difference, which gave me pause, and I wondered if the OP had a clear grasp of the relevant detail -- that is, whether this regex is really doing what was intended. Consider the following:
$s1="ABC D E";
$s2=" ABCD E "; # (leading and trailing spaces)
print join( ":", split /\s+/, $s1 ), $/;
print join( ":", split /\s+/, $s2 ), $/;
print $/;
print join( ":", ($s1=~/\s*(\S+)\s*(\S+)\s*(\S+)\s*/)), $/;
print join( ":", ($s2=~/\s*(\S+)\s*(\S+)\s*(\S+)\s*/)), $/;
__OUTPUT__
ABC:D:E
:ABCD:E
ABC:D:E
ABC:D:E
The first two lines of output show that split will return an empty string as the first list item if the string begins with a delimiter, whereas it will (by default) ignore trailing delimiters (but you can control that).
The last two lines demonstrate the tenacity of the regex engine -- it does its best to match as much of the regex as possible. In this case, it takes the liberty of breaking up the "ABCD" portion of $s2, so that it can have non-empty values inside every set of capturing parens. The behavior is very different from split, indeed!
Personally, I wouldn't feel comfortable using that particular regex pattern -- split seems more suitable.
|