Perl trouble accessing array within hash -
i've looked around answer question haven't found one; in advance help.
i'm trying construct hash of arrays , randomly generate arrays hash. hash length 3, , each array 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 next call correctly return length of array (i.e. 2):
print stdout $pairs{$keys[0]};
what doing wrong here?
you not assigning arrays, assigning size:
$pairs{'one'} = @pair1;
when in scalar context, array returns size, , scalar context. want either:
$pairs{'one'} = \@pair1; # use direct reference $pairs{'one'} = [ @pair1 ]; # anonymous reference using copied values
or possibly
@{ $pairs{'one'} } = @pair1;
also, not using:
use strict; use warnings;
or know why code fails:
print stdout @{$pairs{$keys[0]}};
because have received fatal error:
can't use string ("2") array ref while "strict refs" in use
because hash value $pairs{$keys[0]}
set 2
(the size of array).
Comments
Post a Comment