Home > OS >  Hash key is storing only the last element of loop
Hash key is storing only the last element of loop

Time:11-29

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;

CodePudding user response:

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

CodePudding user response:

Thanks for your response, But, if I have a condition like below, how to store required elements in the hash key if condition met? In the below script, I would like to store 3 & 6 if condition met in the loop. But, the key of hash is storing only the last iterated value.

Please suggest.

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

    my @array = (1,2,3,4,5,6,7);
    my %record;

    for my  $array(@array){
    if (($array ==3)|| ($array==6) ){
    $record{"STORE"} = $array;
    }
    }
    print Dumper \%record;
  • Related