Because a hash key is always stringified, and a stringified value of an array REFERENCE (which $test_ref
is) is exactly that: "ARRAY(0x...)"
. This is different from Java maps which can store arbitrary object as a key.
Therfore, your hash would have 1 ket-value pair, with the key being a string ""ARRAY(0x...)"
"
So, when you have your for
loop, it loops over all the keys (all 1 of them), and then assigns the key value (a string "ARRAY(0x...)"
) to $key
variable.
You then try to array-dereference that string - which of course can't be done since it is not an array reference - it is merely a string containing the string representation of what array reference used to be.
If you want to have "24, 26, 55" as 3 hash keys, you can do this:
my %new = map { $_ => 10 } @$test_ref;
If you actually want to store a list in a hash key, it's doable but not always (in your case of a list of integers, you can, but it's slow, clumzy and I can't imagine when you'd ever wish to.
# Trivial example:
my $test_ref = [24, 26, 55];
$new{ join(",",@$test_ref) } = 10;
foreach my $key (keys %new){
my @list = split(/,/,$key);
print $list[0];
}
This approach has some performance penalties, and can be optimized a bit (e.g. by memoizing the split results). But again, for pretty much ANY reason you might want to do this, there probably are better solutions.