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 (;;);