Produces '100', not '5'. Obviously for localizes $_, but apparently while does not...
I do not know for sure how the compiler does this with $_, but I have noticed that for or foreach is safer than while, and that map or grep are much much safer than for or foreach.
I was able to do deeply nested map instructions and get it right (almost) immediately, while the equivalent constructs with foreach did not work because of $_ corruption.
As an example, consider this code, which I gave as an example of functional programming under Perl on another forum:
while (my $line = <$FILE_IN>) {
my ($start, $end) = split /##/, $line;
my $out_line = $start . "##" . join ";",
map {$_->[0]}
sort {$a->[1] <=> $b->[1]}
map { my ($id, @values) = split /;/, $_;
@values = map { (split /-/, $_)[0]} @values;
map {[$id, $_]} @values;}
split /@/, $end;
}
I know that this is quite far-fetched LISP-like Perl code (I proposed this code just for the fun, not for serious consideration), but it does work perfectly on the data provided. Trying to replace some of the map instructions with some foreach instructions simply breaks every thing, presumably because the program gets confused about $_.
|