I was trying to read a text file each of whose lines should contain two whitespace-separated fields. I wrote the file so I know it has two fields per line, but it's better to be cautious, so I decided to check that it's indeed two fields. I wrote this.
That gives the errorwhile (<>) { 2 == (my($x, $y) = split " ") or die "wrong number of fields"; ... }
despite that line 1 of the file really has exactly two fields. Why? Solution under the fold.wrong number of fields at -e line 1, <> line 1.
Let's look more closely.
$ perl -e 'warn 0+(@x = split " ", "foo bar\n");' 2 at -e line 1. $ perl -e 'warn 0+(($x, $y) = split " ", "foo bar\n");' 3 at -e line 1. $
The reason is one of the several ways how the split function is magical. Let me quote the relevant phrase from the perlfunc section about split.
When assigning to a list, if LIMIT is omitted, or zero, Perl supplies a LIMIT one larger than the number of variables in the list, to avoid unnecessary work.
The side effect here could be a feature or a misfeature, but in any case, this is what perl 5.10, 5.12 and 5.14 does.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Surprise: scalar(($x, $y) = split)
by JavaFan (Canon) on Oct 28, 2011 at 14:55 UTC | |
by ambrus (Abbot) on Oct 28, 2011 at 15:24 UTC | |
by hbm (Hermit) on Oct 28, 2011 at 15:26 UTC | |
|
Re: Surprise: scalar(($x, $y) = split)
by roboticus (Chancellor) on Oct 28, 2011 at 14:03 UTC | |
by ambrus (Abbot) on Oct 28, 2011 at 14:05 UTC | |
by roboticus (Chancellor) on Oct 28, 2011 at 14:21 UTC | |
|
Re: Surprise: scalar(($x, $y) = split)
by Fox (Pilgrim) on Oct 28, 2011 at 18:17 UTC | |
|
Re: Surprise: scalar(($x, $y) = split)
by Anonymous Monk on Oct 29, 2011 at 08:19 UTC |