in reply to Re: how could I use map here?
in thread how could I use map here?

Re your last solution: what do you gain by localizing $_? Or, equivalently, what is the difference between

@my_array_2 = map { local $_ = $_; s/^CHOP_ME_OFF_//; $_ } @my_array;
and

@my_array_2 = map {s/^CHOP_ME_OFF_//; $_ } @my_array;
I've used the latter version often and it seemed to work perfectly fine...

pike

Update:OK, to be honest what I really used was

@my_array = map {s/^CHOP_ME_OFF_//; $_ } @my_array;
i. e. I did the replacements in-place, which explains why I never noticed the effect pointed out by adrianh++.

Replies are listed 'Best First'.
Re: Why localize $_ in the map block?
by adrianh (Chancellor) on Feb 07, 2003 at 13:59 UTC

    Without the local the original array is changed. Since $_ is aliased to each element the s// changes the original array. Try:

    my @x = qw(foo bar CHOP_ME_OFF_foo); my @y = @x; my @copies = map { local $_ = $_; s/^CHOP_ME_OFF_//; $_ } @x; my @changes = map {s/^CHOP_ME_OFF_//; $_ } @y; print "x @x\ny @y\ncopies @copies\nchanges @changes\n";
      Ahh, very interesting. I remember that in the Camel book where it explains the use of grep, there is an example along the lines of:

      @subset = grep {s/x/y/} @set;
      and it points out that this will alter the entries in @set, but it never mentions that you can avoid this by localizing $_...

      pike

Re: Why localize $_ in the map block?
by bronto (Priest) on Feb 07, 2003 at 14:26 UTC

    adrianh++

    It's often (always?) a good practice to localize $_ whenever you need to use it, like any other global variable: it could be accessed by your program, or used by modules (File::Find is one of them AFAIK) and it's not fair to mess up with it.

    With localizing it you have a better protection: if something elsewhere in your code relied on $_'s value you won't be messing with it.

    Ciao!
    --bronto


    The very nature of Perl to be like natural language--inconsistant and full of dwim and special cases--makes it impossible to know it all without simply memorizing the documentation (which is not complete or totally correct anyway).
    --John M. Dlugosz