Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Problem with nested array/hashes

by Dandello (Monk)
on Jan 18, 2016 at 23:35 UTC ( [id://1153042]=perlquestion: print w/replies, xml ) Need Help??

Dandello has asked for the wisdom of the Perl Monks concerning the following question:

@AoH = ({'key1' => 'value1', 'key2' => 'value2', 'key3' => [{'var1 => +'val1', 'var2' => 'val2'}, NEED TO ADD ANOTHER HASH HERE],} );

I can add another 'key'=>'value', to the first hash (the one with key1), that's not a problem, but I'm having trouble figuring out how to add more hashes to the array in key3. (Indicated by 'NEED TO ADD ANOTHER HASH HERE'

I didn't create the original code but I need to add more to it and the new hash is generated from other variables. This is a much simplified example.

Replies are listed 'Best First'.
Re: Problem with nested array/hashes
by choroba (Cardinal) on Jan 18, 2016 at 23:46 UTC
    You can either push to the inner array, or you can assign to its particular member:
    #!/usr/bin/perl use warnings; use strict; use Data::Dumper; my @AoH = ({key1 => 'value1', key2 => 'value2', key3 => [ { var1 => 'val1', var2 => 'val2', }, #NEED TO ADD ANOTHER HASH HERE ], }, ); push @{ $AoH[0]{key3} }, { key => 'value' }; # ^ ^ ^ # | | | # deref 0th | # as an hash | # array key in # the hash $AoH[0]{key3}[2]{another} = 'way'; # if you know the index. print Dumper \@AoH;
    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
Re: Problem with nested array/hashes
by AnomalousMonk (Archbishop) on Jan 19, 2016 at 00:57 UTC
Re: Problem with nested array/hashes
by stevieb (Canon) on Jan 18, 2016 at 23:43 UTC

    This is pretty simple, especially if you're just adding them manually. Might help to look at it formatted:

    my @AoH = ( { 'key1' => 'value1', 'key2' => 'value2', 'key3' => [ # aref starts here { 'var1' => 'val1', 'var2' => 'val2', }, { new_hash_key1 => 'val1', new_hash_key2 => 'val2' }, ], }, );

      This: $AoH[0]{key3}[2]{another} = 'way'; was the clue I needed, thanks.

      Adding them manually wasn't an option as the actual number of added hashes is dependent on a separate list.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1153042]
Approved by 1nickt
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (3)
As of 2024-04-24 06:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found