Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Convert arrayref to AoH

by Laurent_R (Canon)
on Sep 21, 2014 at 09:35 UTC ( [id://1101441]=note: print w/replies, xml ) Need Help??


in reply to Convert arrayref to AoH

Hmm, thinking more about your problem, assuming you really need your array of hashes for some other reasons than what you have shown us, and also assuming that your labels are unique, you could build an auxiliary hash of hashes providing direct access to the values that you want to update, through the magics of references, i.e. store references to the data items that you need to change in an additional hash.
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; # Defaults my @t = ( { 'label' => 'kept', 'value' => '0', }, { 'label' => 'notkept', 'value' => '0', }, { 'label' => 'repaired', 'value' => '0', }, ); # Create another structure (hash) to access the same data in a faster +way my %faster_access; for my $valref (@t) { $faster_access{$valref->{'label'}} = $valref; } # Get this from another sub my $a = [ [ 'kept', '1', ], [ 'repaired', '3' ] ]; # Overwrite defaults for my $i ( @{ $a } ) { $faster_access{$i->[0]}{value} = $i->[1]; } warn Dumper( \$a ); warn Dumper( \@t );
The auxiliary HoH makes it possible to access directly (and much faster) to the data that you want to update. This is the output of the program:
$ perl defaults.pl $ perl defaults.pl $VAR1 = \[ [ 'kept', '1' ], [ 'repaired', '3' ] ]; $VAR1 = [ { 'value' => '1', 'label' => 'kept' }, { 'value' => '0', 'label' => 'notkept' }, { 'value' => '3', 'label' => 'repaired' } ];
As you can see, the @t array has been modified indirectly thanks to the changes made to the %faster_access containing references to the values that you need to update. There is no longer a need to browse through the whole AoH when you want to update it, which is handy if you need to update many times in the course of your program execution.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (6)
As of 2024-04-23 14:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found