Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Convert arrayref to AoH

by Athanasius (Archbishop)
on Sep 20, 2014 at 14:21 UTC ( [id://1101393]=note: print w/replies, xml ) Need Help??


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 }

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (5)
As of 2024-04-23 06:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found