Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re^4: Map Vs Foreach

by JadeNB (Chaplain)
on Nov 28, 2009 at 05:29 UTC ( [id://809846]=note: print w/replies, xml ) Need Help??


in reply to Re^3: Map Vs Foreach
in thread Map Vs Foreach

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://809846]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (8)
As of 2024-03-28 10:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found