in reply to Turning foreach into map?
At some point you're guaranteed to try something like this, but it won't work:
This is because s/// returns the *count* of the changes, rather than the changed string (most people agree this is a DWIM violation: this is an area where Larry blew it).# WRONG @new_list_wrong = map{ s/that idiot/our esteemed leader/ } @list;
What actually works is something like this:
@new_list_right = map{ s/that idiot/our esteemed leader/; $_ } @list;
There's still another gotcha here though, in that if you look at the original @list after doing this, you'll find that it was transformed in exactly the same way as the new list. Each item in the @list array is aliased to $_, so it can be changed by running map on it. (Of course, you knew this. But you'll still get bitten by it on occasion.)
Weirdly enough, the m// operator doesn't have the same problem as s/// does: m// does pretty much what you'd expect in list context:
# yet another way to strip leading and trailing whitespace: @cleaned_list = map{ m/^\s*?(\w.*?)\s*?$/ } @list;
Trivia: perl is well known for having ripped off features form shell and awk, but map was lifted from lisp.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: A hint about using map
by merlyn (Sage) on Apr 05, 2005 at 23:29 UTC | |
by doom (Deacon) on Apr 05, 2005 at 23:37 UTC | |
by Anonymous Monk on Apr 06, 2005 at 08:54 UTC | |
by doom (Deacon) on Apr 08, 2005 at 20:31 UTC | |
|
Re: A hint about using map
by jdporter (Paladin) on Apr 06, 2005 at 03:34 UTC |