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

Re: How would I write this using map?

by monarch (Priest)
on Jan 13, 2009 at 00:38 UTC ( [id://735842]=note: print w/replies, xml ) Need Help??


in reply to How would I write this using map?

The map is used for performing an action on every item in an array, with the result of that action returned.

In this case it appears that you want to push (in order) each key from the hash reference $obj->things.

As you're not performing a transformation the quickest thing to do is to push the list directly onto the array:

push( @{$ref2array}, sort( keys( %{$obj->things()} ) ) );

However map could be used to re-write your loop as:

map { push( @{$ref2array}, $_ ) } ( sort( keys( %{$obj->things() } );
which is identical to
foreach ( sort( keys( %{$obj->things} ) ) ) { push( @{$ref2array}, $_ ); }
However using map here isn't so common because nothing is being done with the output of map. You're merely using map to iterate through each item (which is a valid use, though).

What if you wanted to, say, store an uppercase-version of all the keys into the array? Then map becomes very useful:

push( @{$ref2array}, map { uc($_) } ( sort( keys( %{$obj->things()} ) ) ) );
This is much quicker than, but functionally the same as:
my @uppercasekeys; foreach ( sort( keys( %{$obj->things()} ) ) ) { push( @uppercasekeys, uc( $_ ) ); } push( @{$ref2array}, @uppercasekeys );

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2024-04-24 08:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found