Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Re: map versus for

by pc88mxer (Vicar)
on Aug 04, 2008 at 15:21 UTC ( #702085=note: print w/replies, xml ) Need Help??

in reply to map versus for

I often will use for instead of map for generating lists, especially when I am in the process of developing the code. Once I've got things figured out I might go back and re-code the loop as a map.

Using for has the following advantages:

  • you have more control and options over loop execution (last, next, etc.)
  • you can use your own more descriptive named lexical instead of $_
  • it's more readable (especially for non-perl experts)
If the list-generation logic is just a simple transformation, I'll just opt for a map implementation. Once, however, the logic becomes more complex, an explicit for loop begins to look more attractive. For instance, which of the following do you find easier to understand?
my @result = map { f($_) ? g($_) : () } @list; # or: my @result; for (@list) { push(@result, g($_)) if (f($_)); }

Replies are listed 'Best First'.
Re^2: map versus for
by Fletch (Bishop) on Aug 04, 2008 at 15:28 UTC
    my @result = map { g($_) } grep { f($_) } @list;

    But that's just me . . .

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re^2: map versus for
by dreadpiratepeter (Priest) on Aug 04, 2008 at 15:28 UTC
    Oh definately, because once you put more than one statement into a map, you have violated a bigger stylistic rule.
    In that case, I will either pull the logic into a subroutine and call it from the map (assuming that I may need to reuse it), or switch to a for loop.
    actually, I will switch to a foreach loop. I find that always using foreach for the
    for $var (@list)
    form and for for the c-style form adds to the grokiness of my code.
    UPDATE: should have looked closer at the body of the for there, I agree with Fletch on that one

    "Worry is like a rocking chair. It gives you something to do, but it doesn't get you anywhere."

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2023-03-24 15:45 GMT
Find Nodes?
    Voting Booth?
    Which type of climate do you prefer to live in?

    Results (61 votes). Check out past polls.