Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Slice of an array of hashes

by Anonymous Monk
on Oct 24, 2005 at 19:10 UTC ( [id://502565]=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

O Wise Monks; Suppose I had a reference to an array of hashes, such as:
my $aref = [{DB => 'Alpha', SOURCE => 'here'}, {DB => 'Beta', SOURCE => 'there'}, {DB => 'Gamma', SOURCE => 'someplace'}];
How do I extract a list of DB values (Alpha, Beta, Gamma)? Can I do this with a slice?
my @list = @$aref[0..2]->{DB};
only yields "Gamma". Thanks in advance.

Replies are listed 'Best First'.
Re: Slice of an array of hashes
by dragonchild (Archbishop) on Oct 24, 2005 at 19:11 UTC
    my @list = map { $_->{DB} } @$aref;

    My criteria for good software:
    1. Does it work?
    2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?
Re: Slice of an array of hashes
by Roy Johnson (Monsignor) on Oct 24, 2005 at 19:16 UTC
    You can only use arrow notation to extract a single scalar. Slice notation requires that you use the more general @{block-returning-hashref}{index-list} form. You should review the two rules for using references.

    And no, you can't slice along any but the last dimension. dragonchild's map is the solution for what you want to do.


    Caution: Contents may have been coded under pressure.
Re: Slice of an array of hashes
by ioannis (Abbot) on Oct 24, 2005 at 20:55 UTC
Re: Slice of an array of hashes
by murugu (Curate) on Oct 25, 2005 at 08:48 UTC

    Here is my try,

    my $aref = [{DB => 'Alpha', SOURCE => 'here'}, {DB => 'Beta', SOURCE => 'there'}, {DB => 'Gamma', SOURCE => 'someplace'}]; foreach $arr (@$aref) { push @list,$arr->{DB}; } print $_."\n" for @list;

    Regards,
    Murugesan Kandasamy
    use perl (;;);

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://502565]
Approved by Corion
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 06:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found