user3499014
user3499014

Reputation: 1

Perl trouble accessing array within hash

I've looked around for an answer to this question but haven't found one; thanks in advance for your help.

I'm trying to construct a hash of arrays and then randomly generate arrays from the hash. The hash is length 3, and each array is a pair of values:

undef %pairs;

$pairs{'one'} = @pair1;
$pairs{'two'} = @pair2;
$pairs{'three'} = @pair3;

@keys = keys %pairs;

@keys = shuffle(@keys);

push (@file1, @{$pairs{$keys[0]}});
push (@file2, @{$pairs{$keys[1]}});
push (@file3, @{$pairs{$keys[2]}});

The following call doesn't return anything:

    print STDOUT @{$pairs{$keys[0]}};

Although the next call does correctly return the length of the array (i.e. 2):

    print STDOUT $pairs{$keys[0]};

What am I doing wrong here?

Upvotes: 0

Views: 58

Answers (1)

TLP
TLP

Reputation: 67900

You are not assigning the arrays, you are assigning their size:

$pairs{'one'} = @pair1;

When in scalar context, an array returns its size, and this is scalar context. You want either:

$pairs{'one'} = \@pair1;      # use direct reference
$pairs{'one'} = [ @pair1 ];   # anonymous reference using copied values

Or possibly

@{ $pairs{'one'} } = @pair1; 

Also, you are not using:

use strict;
use warnings;

Or you would already know why this code fails:

print STDOUT @{$pairs{$keys[0]}};

Because you would have received the fatal error:

Can't use string ("2") as an ARRAY ref while "strict refs" in use

Because your hash value $pairs{$keys[0]} is set to 2 (the size of the array).

Upvotes: 5

Related Questions