I wouldn't normally do it this way, this is just to show you that it is possible:
foreach my $root (map { sqrt($_) }@data)
{
#do something with this square root...
}
Possible, but, as you doubtless know, not desirable: This version makes two passes over the list—or, rather, one pass over the list, then one pass over its transformation—whereas
foreach my $orig ( @data ) {
my $root = sqrt $orig;
... do something with square root here ...
}
does the same thing in only one pass.
I do take issue, though, with the statement that map is best for 1- or 2-line transformations. I think that's a readability opinion, and these are always subjective. It also might lead some into using map for a short transformation to which it's not suited. I think a less subjective guideline, and one that might be more useful when deciding which to use, is:
- Use map if we want to take in a list and output a list, and there is a 1-to-1 correspondence between input and output, however complicated that correspondence is to implement. (I know that one can use the fact that the return value from the BLOCK in map is interpreted in list context to get around this—indeed, I've done it—but I think that, if you know that, then you're past the point where general slogans will give you any guidance. :-) )
- Use foreach for any other transformation, no matter how simple.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.