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

I am building an array of hashes...can't figure out how to access the hash elements.
for ( 0 .. ( $offense_line_count - 1 ) ) { my $value = $offense_value_array[$_]; # next if ( !defined $value ); my $label = $offense_label_array[$_]; $title = $value if ( $label eq 'Title'); $section = $value if ( $label eq 'Section' ); $subsection = $value if ( $label eq 'Subsection' ); $class = $value if ( $label eq 'Class' ); $category = $value if ( $label eq 'Category' ); $degree = $value if ( $label eq 'Degree' ); $num_chgs = $value if ( $label eq 'CountOfCharges'); $hash{$label} = $value; print "$hash{$label}\n"; if ( $label eq 'CountOfCharges') { for (0 .. ($num_chgs - 1)) { push (@AOH, %hash); } } }

Replies are listed 'Best First'.
Re: accessing elements in array of hashes
by johngg (Canon) on Jun 27, 2013 at 19:18 UTC

    The core Data::Dumper module is an extremely useful tool when trying to work out whether your data structures have turned out as you intended.

    $ perl -Mstrict -Mwarnings -MData::Dumper -E ' my %h1 = ( a => 1, b => 2 ); my %h2 = ( z => 26, y => 25 ); my @badAoH; push @badAoH, %h1; push @badAoH, %h2; print Data::Dumper->Dumpxs( [ \ @badAoH ], [ qw{ *badAoH } ] ); my @goodAoH; push @goodAoH, \ %h1; push @goodAoH, \ %h2; print Data::Dumper->Dumpxs( [ \ @goodAoH ], [ qw{ *goodAoH } ] );' @badAoH = ( 'a', 1, 'b', 2, 'y', 25, 'z', 26 ); @goodAoH = ( { 'a' => 1, 'b' => 2 }, { 'y' => 25, 'z' => 26 } ); $

    I hope this is helpful.

    Cheers,

    JohnGG

Re: accessing elements in array of hashes
by Eily (Monsignor) on Jun 27, 2013 at 18:15 UTC
    I am building an array of hashes...can't figure out how to access the hash elements. ...   push (@AOH, %hash);

    I'm afraid you're not. What you are doing here is adding the content of your hash (keys and values) alike, in the array, not the hash itself. What you want to do is push a reference to the hash into your array. push (@AOH, \%hash). Then you can simply call $AOH[0]{Key}

    You should read perldsc on that point, and the part about arrays of hashes

    Upgrade : I saw that you wrote your own answer before I could finish mine, but it might still be useful for other people, and the links I gave you could still be of some interest to you too.

Re: accessing elements in array of hashes
by fionbarr (Friar) on Jun 27, 2013 at 18:09 UTC
    got it....need to push a hash reference, not the hash itself
      To paraphrase an old carpenter's saw, "Think twice; post once!"

      And if it's teddy-bear syndrome that's working for you, use your text editor to write out your puzzlement in the privacy PRISM (ha, ha; Gag!, hrmph!) of your own work station.

      And, just BTW, this question is one answered almost daily. Try Super Search; Uncle G; or p(b)ing M$ for an answer.


      If you didn't program your executable by toggling in binary, it wasn't really programming!