john IT
john IT

Reputation: 69

Push operation not working while pushing array to a hash

I have two arrays @arr1 and @arr2 and I have a hash %hash in my Perl code.

I have certain elements in @arr1 and similarly certain elements in @arr2. I want to push elements of @arr1 as key for hash %hash and elements of the array @arr2 as values for those keys for hash %hash.

I am using the below code in my Perl script to do so:

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

my %hash = ();
my @abc = ('1234', '2345', '3456', '4567');
my @xyz = ('1234.txt', '2345.txt', '3456.txt', '4567.txt');

push(@{$hash{@abc}}, @xyz);
print Dumper(%hash);

After executing, I am getting the below output:

./test.pl

$VAR1 = '4';
$VAR2 = [
          '1234.txt',
          '2345.txt',
          '3456.txt',
          '4567.txt'
        ];

It is not printing the key values but their total number. I need the output to be that every key with its value gets printed after I execute the script.

Can someone please help. Thanks.

Upvotes: 3

Views: 119

Answers (1)

Shawn
Shawn

Reputation: 52344

You're looking for a slice to assign multiple elements of a hash at once:

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

my %hash = ();
my @abc = ('1234', '2345', '3456', '4567');
my @xyz = ('1234.txt', '2345.txt', '3456.txt', '4567.txt');

@hash{@abc} = @xyz;
print Dumper(\%hash);

produces (Though order of keys might vary):

$VAR1 = {
          '4567' => '4567.txt',
          '2345' => '2345.txt',
          '3456' => '3456.txt',
          '1234' => '1234.txt'
        };

Explanation

What push(@{$hash{@abc}}, @xyz); does is push elements into an array reference stored in a single hash entry - @abc is used in scalar context here, which evaluates to the length of the array, hence the 4. Using a slice instead assigns a list of values to a corresponding list of keys.

Then print Dumper(%hash); first turns %hash into a list of alternating keys and values, hence them being two different Data::Dumper entries. Passing a reference to the hash instead makes it print out the actual data structure as one thing.

Upvotes: 8

Related Questions