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

If the keys are distinct over the hashes, the question is why to store them in an array.
my %hash = ( k0 => 'c0', k1 => 'v1', k2 => 'v2', k3 => 'v3', ); my $search = 'k2'; my $val = $hash{$search};

Even if the keys aren't unique, you might want to store the data in a HoA instead:

my %hash = ( k0 => ['c0'], k1 => ['v1'], k2 => ['v2', 'v42'], k3 => ['v3'], ); my $search = 'k2'; my @vals = @{ $hash{$search} };
لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Replies are listed 'Best First'.
Re^2: extracting elements by key from an array of hashes
by ciderpunx (Vicar) on Sep 25, 2015 at 10:06 UTC
    True that. However, the data is coming from an xmlrpc source via XML::RPC and that's how it's structured. I don't have control over the source API or at least I don't want to change it.

      You can easily create a temporary hash to do the searches:
      my %hash = map %$_, @rpc;
      لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

      Keep in mind that you have no obligation to store data internally in inconvenient formats. If it is more convenient to manipulate it internally as a hash, do that conversion at the earliest possible point after reading it in, and convert back at the latest possible point if you ever have to output the structure again.


      Dave

      ... and if there is potentially more than one value per bucket, simply make each element an arrayref. Auto-vivification makes this trivially easy to do.