Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re^2: Problem with while loop inside a foreach loop

by Laurent_R (Canon)
on May 03, 2013 at 22:06 UTC ( [id://1031964]=note: print w/replies, xml ) Need Help??


in reply to Re: Problem with while loop inside a foreach loop
in thread Problem with while loop inside a foreach loop

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 $_.

Replies are listed 'Best First'.
Re^3: Problem with while loop inside a foreach loop
by Anonymous Monk on May 03, 2013 at 22:25 UTC

    map or grep are much much safer than for or foreach.

    No they aren't :) They alias just like for/foreach.

    I know that this is quite far-fetched LISP-like Perl code

    Not really :)

      No they aren't :) They alias just like for/foreach.

      I know that they alias the same way. But for some reason, I found that nesting foreach statements with the default $_ variable often seems to lead to confusions between the internal and the external values of $_, while I do not have this problem with nested map statements. But it is also possible that I simply don't do it right with the nesting of foreach statement. I don't do that too often anyway, I usually prefer to use explicit variables when nesting such statements in production code.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1031964]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (6)
As of 2024-04-23 12:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found