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

I am buliding an array of hash references, but i am unable to access the content of an hash. Here is my sample code:
$hash = {A1 => 'AB', A2 => '', A3 => ''}; # read info from file open (INFH,$myfile); create_array(*INFH, $hash, \$arry_hash); for $i (0 .. $#arry_hash) { for $key (keys %{$arry_hash[$i]}) { print "key :$key = $arry_hash[$i]->{$key} "; } print "}\n"; } sub create_array { my $FH = shift; my $rec_hash = shift; my $arry_ref = shift; while (<$FH>) { $tmp_hash = $rec_hash; for $field (spilt ',') { ($key, $value) = split /=/, field; chomp($value); $tmp_hash->{$key} = $value; } push @$arry_ref, {%tmp_hash}; } close ($FH); }
My input file looks like this:
A2=ABCD,A3=0123 A2=QWER,A3=4567 A2=ASDF,A3=7890
How can I access the value of A1 and A2 and loop through the array.

Replies are listed 'Best First'.
Re: How do I access array of hashes reference
by ikegami (Patriarch) on Aug 07, 2007 at 19:42 UTC

    Problems of varying importance:

    • use strict; and use warnings; are missing, hidding some errors.
    • split is misspelled.
    • Most variables are not declared.
    • Some sigils are missing.
    • $arry_hash contains a reference to a scalar (\$arry_hash) instead of a reference to an array (\@arry_hash) as it should.
    • Unsafe 2-arg open is used.
    • The file is closed at a different level than the one at which it was opened.

    Fixed:

    use strict; use warnings; use Data::Dumper qw( Dumper ); sub create_array { my ($fh) = @_; my @data; while (<$fh>) { chomp(); my %record; for my $field (split ',') { my ($key, $value) = split /=/, $field; $record{$key} = $value; } push @data, \%record; } return \@data; } # open(my $infh, '<', $myfile) # or die("Unable to open data file \"$myfile\": $!\n"); # my $data = create_array($infh); # close($infh); my $data = create_array(*DATA); print(Dumper($data)); __DATA__ A2=ABCD,A3=0123 A2=QWER,A3=4567 A2=ASDF,A3=7890
Re: How do I access array of hashes reference
by thezip (Vicar) on Aug 07, 2007 at 19:45 UTC
    • Perhaps you might try compiling this first, which will give you a clue as to where the errors are
    • use strict;
    • As mjd says, "You can't just make shit up and expect the computer to know what you mean."

      Here are the errors, if you're interested:

      C:\Temp--> perl -c test.pl String found where operator expected at test.pl line 18, near "spilt ' +,'" (Do you need to predeclare spilt?) syntax error at test.pl line 18, near "spilt ','" syntax error at test.pl line 26, near "}" test.pl had compilation errors.

      Where do you want *them* to go today?