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.