Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: playing with map

by Anonymous Monk
on Mar 09, 2001 at 23:16 UTC ( [id://63315]=note: print w/replies, xml ) Need Help??


in reply to playing with map

I have written lots and lots of Perl code without ever really using the map command very much. But I often see it in other's code. So, my impression is that the code

@new = map { act_on($_); } @old;

is functionally equivalent to

for (0..$#old) { $new[$_] = act_on( $old[$_] ); }

Is this a correct view of things?

CJW

Replies are listed 'Best First'.
Re: Re: playing with map
by merlyn (Sage) on Mar 09, 2001 at 23:18 UTC
    No, that presumes a 1-1 mapping. Some are, some aren't. It's more like this:
    @new = (); for (@old) { push @new, act_on($_); }
    Consider this to see the difference:
    @old = (10..20); sub act_on { return 1..$_; }
    The first element becomes 10 elements of output, the second becomes 11, and so on.

    -- Randal L. Schwartz, Perl hacker

Re: Re: playing with map
by mirod (Canon) on Mar 09, 2001 at 23:20 UTC

    Not exactly, more like:

    for (0..$#old) { push @new, act_on( $old[$_] ); }

    usually written as:

    foreach @old { push @new, act_on( $_); }

    If act_on returns a list then all members are pushed into @old.

    Update: darn! merlyn is right, you need to initialize @new to () to get the exact equivalent statement.

      If act_on returns a list then all members are pushed into @old.
      In a list context, act_on must return a list! And map (and the map-equivalents) are providing list context.

      -- Randal L. Schwartz, Perl hacker

        OK, I was not clear. I should have written "if act_on returns a list with more than one element" then the original code is not equivalent to a map (and I can play with fonts too ;--). If act_on returns a scalar or a 1 element list then the original code behaves the same way as a map.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (3)
As of 2024-04-25 09:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found