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

Hello Monks, I have file which contains name, payment and date. I'm trying to extract the data and store in an array as a hash reference.

sub main { my $file = 'new_text.csv'; open FH, '<', $file or die "Cannot open the $file: $!"; <FH>; my %hash; my @array_of_hash; LINE: while(my $line = <FH>) { chomp $line; $line =~ s/\s+\$|approx\.\s*|\?|^\s*//g; next LINE if ( $line !~ /\S+/ ); my @values = split /\s*,\s*/, $line; if ( scalar @values != 3){ next LINE; } foreach ( @values ){ if ( $_ eq '' ) { next LINE; } } my ($name, $payment, $date ) = @values; %hash = ( 'name' => $name, 'payment' => $payment, 'date' => $date, ); push @array_of_hash, \%hash; } } main();
#I'm expecting an output like { name => xxx, payment => xxx, date => xxx, }, { name => xxx, payment => xxx, date => xxx, }, { name => xxx, payment => xxx, date => xxx, }, { name => xxx, payment => xxx, date => xxx, }, #Unfortunately i'm getting an output like... print Dumper (@array_of_hash); $VAR1 = { 'payment' => '0.57', 'name' => 'Rene Descarted', 'date' => '10072033' }; $VAR2 = $VAR1; $VAR3 = $VAR1; $VAR4 = $VAR1;

I'm not sure what silly mistake i'm making here. Thank You.

Replies are listed 'Best First'.
Re^2: Array of hashes not working as expected
by toolic (Bishop) on Feb 25, 2015 at 18:13 UTC
    Change:
    push @array_of_hash, \%hash;

    to:

    push @array_of_hash, {%hash};

    Complete example:

    use warnings; use strict; my %hash; my @array_of_hash; for (1..3) { %hash = ( 'name' => $_, 'payment' => $_, ); push @array_of_hash, {%hash}; } use Data::Dumper; $Data::Dumper::Sortkeys=1; print Dumper(\@array_of_h +ash); __END__ $VAR1 = [ { 'name' => 1, 'payment' => 1 }, { 'name' => 2, 'payment' => 2 }, { 'name' => 3, 'payment' => 3 } ];
Re^2: Array of hashes not working as expected
by fishmonger (Chaplain) on Feb 25, 2015 at 18:21 UTC

    Declare the hash inside the loop instead of outside.
    Borrowing from tollic's example.

    use warnings; use strict; my @array_of_hash; for (1..3) { my %hash = ( 'name' => $_, 'payment' => $_, ); push @array_of_hash, \%hash; } use Data::Dumper; $Data::Dumper::Sortkeys=1; print Dumper(\@array_of_h +ash);
    Outputs:
    $VAR1 = [ { 'name' => 1, 'payment' => 1 }, { 'name' => 2, 'payment' => 2 }, { 'name' => 3, 'payment' => 3 } ];
Re^2: Array of hashes not working as expected
by hdb (Monsignor) on Feb 25, 2015 at 20:20 UTC

    toolic and fishmonger have already provided a solution to your problem, but in case you want to know what the problem was: you are pushing a reference to the very same hash onto your array every time, overwriting its contents every time. This is exactly what you see in the output of Data::Dumper. toolic's and fishmonger's approaches both create a new hash in each iteration and store a reference to that new hash in the array.