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:
- tye (but my friends call me "Tye")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;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: (tye)Re: Using map
by blackjudas (Pilgrim) on Oct 05, 2001 at 10:21 UTC |