in reply to Convert arrayref to AoH

Hello neilwatson,

If your data is really always in the form shown, then, as Laurent_R says, you can simplify your data structure to a plain hash and overwrite default values easily:

#! perl use strict; use warnings; use Data::Dump; my %h = map { $_ => 0 } qw(kept notkept repaired); my $a = [ [ 'kept', '1', ], [ 'repaired', '3', ], ]; dd \%h; %h = (%h, map { $_->[0] => $_ ->[1] } @$a); dd \%h;

Output:

0:16 >perl 1022_SoPW.pl { kept => 0, notkept => 0, repaired => 0 } { kept => 1, notkept => 0, repaired => 3 } 0:16 >

But if (as I suspect) you really do need the more complex AoH, you can still make the overwriting code more efficient by breaking out of the inner loop when a match is found:

# Overwrite defaults with arrayref OUTER: for my $i (@{$a}) { for my $t (@t) { if ($i->[0] eq $t->{label}) { $t->{value} = $i->[1]; next OUTER; } } }

Hope that helps,

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

Replies are listed 'Best First'.
Re^2: Convert arrayref to AoH
by AnomalousMonk (Archbishop) on Sep 20, 2014 at 20:57 UTC

    If data organization can be changed, update can be made simpler and (slightly, perhaps even detectably) faster by changing update array element dereference:

    c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -e "my %h = map { $_ => 0 } qw(kept notkept repaired); my $a = [ [ 'kept', '1', ], [ 'repaired', '3', ], ]; ;; dd \%h; %h = (%h, map @$_, @$a); dd \%h; " { kept => 0, notkept => 0, repaired => 0 } { kept => 1, notkept => 0, repaired => 3 }

    OTOH, using a for-loop to avoid creation of intermediate temp arrays might be yet simpler and even faster, although again, whether any speed gain would be significant or even detectable is an open question:

    c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -e "my %h = map { $_ => 0 } qw(kept notkept repaired); my $a = [ [ 'kept', '1', ], [ 'repaired', '3', ], ]; ;; dd \%h; $h{ $_->[0] } = $_->[1] for @$a; dd \%h; " { kept => 0, notkept => 0, repaired => 0 } { kept => 1, notkept => 0, repaired => 3 }