ciderpunx has asked for the wisdom of the Perl Monks concerning the following question:
I have an AoH that looks like this:
I want to pull out the value of the element with key k2. The nicest way I can think of to do this is something likemy @aoh = ( {k0 => 'v0' } , {k1 => 'v1' } , {k2 => 'v2' } , {k3 => 'v3' } );
But that's kind of disgusting. Is there a nicer way?$val = [grep {(keys $_)[0] eq 'k2'} @aoh]->[0]{'k2'};
Update: Corion pointed out that I could just convert the AoH into a hash given the keys are unique and have a single value each. Like:
my %h = map {%$_} @aoh; ## now its just: say $h{'k2'};
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: extracting elements by key from an array of hashes
by choroba (Cardinal) on Sep 25, 2015 at 09:58 UTC | |
by ciderpunx (Vicar) on Sep 25, 2015 at 10:06 UTC | |
by choroba (Cardinal) on Sep 25, 2015 at 10:35 UTC | |
by davido (Cardinal) on Sep 25, 2015 at 14:57 UTC | |
by Anonymous Monk on Sep 25, 2015 at 10:45 UTC | |
Re: extracting elements by key from an array of hashes
by Discipulus (Canon) on Sep 25, 2015 at 10:37 UTC | |
by Athanasius (Archbishop) on Sep 25, 2015 at 13:25 UTC | |
by mr_ron (Chaplain) on Sep 26, 2015 at 00:52 UTC | |
by Discipulus (Canon) on Sep 25, 2015 at 19:24 UTC |
Back to
Seekers of Perl Wisdom