As documented, the default for the first argument of split is ' '. ("As a special case, specifying a PATTERN of space (' ') will split on white space just as split with no arguments does.")
$ perl -MData::Dumper -e' $_=" 56 1752.eps a b"; print Dumper split; ' $VAR1 = '56'; $VAR2 = '1752.eps'; $VAR3 = 'a'; $VAR4 = 'b'; $ perl -MData::Dumper -e' $_=" 56 1752.eps a b"; print Dumper split " "; ' $VAR1 = '56'; $VAR2 = '1752.eps'; $VAR3 = 'a'; $VAR4 = 'b';
The next problem is that "2" is wrong for the third argument. You'd want to use "3" and ignore the last value returned.
$ perl -MData::Dumper -e' $_=" 56 1752.eps a b"; print Dumper split " ", $_, 2; ' $VAR1 = '56'; $VAR2 = '1752.eps a b'; $ perl -MData::Dumper -e' $_=" 56 1752.eps a b"; print Dumper split " ", $_, 3; ' $VAR1 = '56'; $VAR2 = '1752.eps'; $VAR3 = 'a b';
Solutions:
for (@data) { my @a = (split)[0,1]; my @a = (split " ", $_, 3)[0,1]; my ($x, $y) = split(" ", $_, 3); my ($x, $y) = split; ... }
split is optimised so that it doesn't do any unnecessary work for the last one. You could also avoid split entirely.
my ($x, $y) = /^\s*(\S+)\s+(\S+)/;
In reply to Re: Split(), Initial Spaces, & a limit?
by ikegami
in thread Split(), Initial Spaces, & a limit?
by cmv
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |