in reply to how could I use map here?

I tried unsuccessfully doing this with map. ...

You're running into two pitfalls. A slight rewrite might make it clearer. Consider:

@my_array_2 = map { s/^CHOP_ME_OFF_//g } @my_array;
But this won't work. It gives you an array full of integers, and it modifies the contents of @my_array.

In this case, it's better to use substr.

@my_array_2 = map { /^CHOP_ME_OFF_/ ? substr($_, length("CHOP_ME_OFF_")) : $_ } @my_array;

Update: On reflection, might be better off localizing $_

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

Replies are listed 'Best First'.
Why localize $_ in the map block?
by pike (Monk) on Feb 07, 2003 at 11:22 UTC
    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++.

      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

      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