in reply to Re^3: Using regex in Map function
in thread Using regex in Map function

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__