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

Hi, new to this forum...

I'm am trying to add an element to a hash of arrays, but can't quite figure out the correct syntax...The original data structure was created using XML::Simple()...

my $gxmlConfigObjt = new XML::Simple( forcearray => 1 ,keyattr => {} ,rootname => 'feedback' ); # OPEN : Open the file... # my $gxmlConfigDoc = $gxmlConfigObjt->XMLin( $gxmlConfigFile );

And looks like the following from Data::Dumper()...(p.s. I doctored the output to save on space) ...

.$gxmlConfigDoc = { . 'item' => [ . { 'zip-code' => ['03036'] . ,'city' => ['Chester'] . ,'name' => ['Adym S. Lincoln'] . ,'address' => ['123 Lane Road'] . ,'state' => ['NH'] . }, . { 'zip-code' => ['03103'] . ,'city' => ['Manchester'] . ,'name' => ['Joseph C. Lincoln'] . ,'address' => ['1050 Perimeter Road'] . ,'state' => ['NH'] . } . ] .};

I tried/wanted to use push, but that didn't work...Here's some failed attempts...

$gxmlConfigDoc{item}[++$#{gxmlConfigDoc{item}}] = { 'zip-code' => ['01880'], 'city' => ['Wakefield'], 'name' => ['Whatdb'], 'address' => ['20 Harvard Mill S +q'], 'state' => ['MA'] }; #$gxmlConfigDoc{item} = { 'item' => [ # { # 'zip-code' => ['01880'], # 'city' => ['Wakefield'], # 'name' => ['Whatdb'], # 'address' => ['20 Harvard Mill +Sq'], # 'state' => ['MA'] # } # ] # }; #push @{ $gxmlConfigDoc{item} }, # 'item' => [ # { # 'zip-code' => ['01880'], # 'city' => ['Wakefield'], # 'name' => ['Whatdb'], # 'address' => ['20 Harvard Mill Sq'], # 'state' => ['MA'] # } # ] #;

tia,
adym

Replies are listed 'Best First'.
Re: Adding elements to hashes of arrays...
by broquaint (Abbot) on Oct 29, 2003 at 16:11 UTC
    You were close on your first attempt
    push @{ $gxmlConfigDoc->{item} }, { ... };
    So you dereference the array in the hash ref (you were treating it as a hash) and push on an anonymous hash. See. perlreftut and tye's References quick reference for a good start on references in perl.
    HTH

    _________
    broquaint

      bless you...the -> was the missing piece...

      thx again,

      adym
Re: Adding elements to hashes of arrays...
by Abigail-II (Bishop) on Oct 29, 2003 at 16:10 UTC
    $gxmlConfigDoc is a reference, so you can't index it directly. Use something like (untested):
    push @{$gxmlConfigDoc -> {item}} => { ... }; # Or push @{$$gxmlConfigDoc {item}} => { ... };

    Abigail