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


In reply to Re^2: Problem with while loop inside a foreach loop by Laurent_R
in thread Problem with while loop inside a foreach loop by andylevel2

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.