Hi Blazer & Randal,

Hi

Could you guys please explain why we need to localize $_ inside the map? I am not sure I understand why we need to do this.I seem to get the same result even if I do not localize $_. Is there something I am missing?

It seems to me that merlyn's very clear example explains it quite well. Is there anything about it that you specifically can't understand? Basically map is a filter between an input list and an output one. Due to the way it works, you can use a side effect in the expression or in the code block it comprises to also modify the input list, provided that it's doable, e.g. if the latter is an array, which is a common situation. But as a general rule you don't want to exploit this possibility because it's not what map() is really for. You would probably use an explicit for loop in case you wanted to achieve the same effect. As Tad McClellan recently put it in clpmisc:

More humorously:

There are 9 ways to do the same thing in Perl, and 8 of them are no good!

The following minimal example may also help you:

#!/usr/bin/perl -l use strict; use warnings; my @in=(1,2,3); my @out1=map {s/^/F/; $_} @in; print "@out1"; my @out2=map {s/^/F/; $_} 1,2,3; print "@out2"; __END__

In reply to Re^4: Using regex in Map function by blazar
in thread Using regex in Map function by narashima

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.