Sonali
Sonali

Reputation: 77

Hash key is storing only the last element of loop

I am trying to store the array values in the hash, but the hash key is storing only the last value of array in the for loop.

My expected output is, 'STORE' key should have all the array elements. I knew there are few other ways to store the array values in the hash, but I curious why the below script doesn't work.

use strict;
use warnings;
use Data::Dumper;

my @array = (1,2,3);
my %record;

for my $array(@array) {
    $record{"STORE"} = $array;
}
print Dumper \%record;

Upvotes: 3

Views: 91

Answers (1)

toolic
toolic

Reputation: 62037

The hash has only the last value from the array because you keep overwriting the value in the for loop.

One way to store all values from the array is:

use strict;
use warnings;
use Data::Dumper;

my @array = (1,2,3);
my %record;

for my $array (@array) {
    push @{ $record{"STORE"} }, $array;
}

print Dumper \%record;

This stores the array as a reference.

$VAR1 = {
          'STORE' => [
                       1,
                       2,
                       3
                     ]
        };

Another way to store the whole array is to assign it to an array reference:

my @array = (1,2,3);
my %record;

$record{"STORE"} = [@array];

print Dumper \%record;

Refer to perldsc

Upvotes: 4

Related Questions