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.
In reply to A hint about using map
by doom
in thread Turning foreach into map?
by ghenry
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |