One of the things you always want to do with map is to use it to do a transformation on a list of strings.

At some point you're guaranteed to try something like this, but it won't work:

# WRONG @new_list_wrong = map{ s/that idiot/our esteemed leader/ } @list;
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).

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.