grep acts a lot like the *nix "grep" command, i.e. it returns the things that match a certain condition. Baseline idea that should get you going is that the condition you pass to grep acts as a filter: grep grabs the things in one list that match some condition or other and puts them into another.

 my @filtered = grep { length($_) > 15 } @unfiltered;

gives you a list of the strings in @unfiltered that are 16 characters or greater in length.

map is more suited to *transforming* the things in the original list. Suppose I want to uppercase every string in a list, I'd do:

my @uppercased = map { uc($_) } @list_of_strings;

Warning: arrays and lists are not the same thing in Perl, even though my presentation here might suggest that. Moreover, in scalar contexts, these functions will not return lists, but rather scalar values (e.g grep returns the number of things that match the condition)

HTH

Philosophy can be made out of anything. Or less -- Jerry A. Fodor


In reply to Re: Map and Grep by arturo
in thread Map and Grep by Anonymous Monk

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.