Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Play golf on an array of hashrefs

by very empty (Scribe)
on Jun 10, 2002 at 15:33 UTC ( [id://173196]=perlquestion: print w/replies, xml ) Need Help??

very empty has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,
I have an array of hashrefs. Each hash has a key "mykey". Now would like to know if there is a one-line-way to get an array consisting of all values at this common key.
foreach $elem (@array) { push @myvalues, $$elem{"mykey"}; }
should do what I want, but  @myvalues is an auxiliary variable I do not want to introduce.

Regards...

Replies are listed 'Best First'.
Re: Play golf on an array of hashrefs
by Abigail-II (Bishop) on Jun 10, 2002 at 15:37 UTC
Re: Play golf on an array of hashrefs
by Joost (Canon) on Jun 10, 2002 at 15:36 UTC
    @array = map { exists $_->{mykey} ? $_->{mykey} : () } @array;
    Update: this also checks for existence of the key, if you don't need to, go for Abigail's solution.
    -- Joost downtime n. The period during which a system is error-free and immune from user input.
Re: Play golf on an array of hashrefs
by frankus (Priest) on Jun 10, 2002 at 15:38 UTC
      Actually, the use of $elem in the map won't work, as the OP used $elem as the "alias" variable in the foreach loop. There is no alias in this map.
      $> perl -e '@array=({mykey=>foo}, {mykey=>bar}), @out = map{ $$elem{my +key} } @array; print @out;' $>
      Use $_ instead, as Joost or Abigail suggested.

      --

      There are 10 kinds of people -- those that understand binary, and those that don't.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://173196]
Approved by Rex(Wrecks)
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (8)
As of 2024-04-19 09:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found