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

If you have a big data you can also try (even if ambiguous, equivocal, devious..)
grep defined, map {$_->{'k2'}} @aoh;

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.

Replies are listed 'Best First'.
Re^2: extracting elements by key from an array of hashes
by Athanasius (Archbishop) on Sep 25, 2015 at 13:25 UTC

    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,

      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};
      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.