in reply to Using map

Your for code has the exact same problem that you noted with your map code. In both cases, $_ becomes an alias for the original element and so modifying $_ modifies the original elements.

So you need to copy each element, either before the loop or in the loop.

There is another difference between your two samples. The if inside of the for means that non-matching items don't get put into the new array. But the map puts the empty string into the new array for each non-matching item. This is because the value returned by the statement $x if $y will be $y when $y is false.

You are using . in your regex when you appear to want to match a literal ".". You may want to anchor that regex to start-of-line. You don't appear to actually need the /g modifier.

So several fixes could yield you:

my @sub_locs= map { local( $_ )= $_; $_ =~ s/^taxman\.add\.subloc\.// ? $_ : (); } @session_keys; my @sub_locs= map { s/^taxman\.add\.subloc\.// ? $_ : (); } @{[ @session_keys ]}; my @sub_locs= grep { s/^taxman\.add\.subloc\.// } @{[ @session_keys ]}; my @sub_locs= map { /^taxman\.add\.subloc\.(.*)/ } @session_keys;

        - tye (but my friends call me "Tye")

Replies are listed 'Best First'.
Re: (tye)Re: Using map
by blackjudas (Pilgrim) on Oct 05, 2001 at 10:21 UTC
    Quite the few examples there tye! As for having the current value of $_ modified in the original in the for loop, I was aware of this happening, though what I guess I was trying to say is that my above map example did _only_ that, and just returned blank elements.

    Thanks for the extra effort tye, it makes all the difference, my "light" came on :) (rarely happens as you can tell :)

    BlackJudas