Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re^2: extracting elements by key from an array of hashes

by Athanasius (Archbishop)
on Sep 25, 2015 at 13:25 UTC ( [id://1143013]=note: print w/replies, xml ) Need Help??


in reply to Re: extracting elements by key from an array of hashes
in thread extracting elements by key from an array of hashes

Hello Discipulus,

grep defined, map {$_->{'k2'}} @aoh;

This works well as long as the hash value is itself defined. But if the hash entry exists with a value of undef:

my @aoh = ( { k0 => 'v0' }, { k1 => 'v1' }, { k2 => undef }, { k3 => 'v3' }, );

then the result of the grep will be indistinguishable from the case in which the hash entry does not exist at all. The following does distinguish between these two cases:

map { exists $_->{k2} ? $_->{k2} : () } @aoh;

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Replies are listed 'Best First'.
Re^3: extracting elements by key from an array of hashes
by mr_ron (Chaplain) on Sep 26, 2015 at 00:52 UTC
    Another cleaner variant that works with the initial data structure.
    my @aoh = ( {k0 => 'v0' } , {k1 => 'v1' } , {k2 => 'v2' } , {k3 => 'v3' } ); my ($val) = grep {exists $_->{k2}} @aoh; $val &&= $val->{k2};
Re^3: extracting elements by key from an array of hashes
by Discipulus (Canon) on Sep 25, 2015 at 19:24 UTC
    yes, i was aware of that possibility. thanks for your code. Perl can be incredibly expressive!

    L*
    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (2)
As of 2024-04-26 03:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found