Markus Dehmann <> wrote:
> I am using a two-dim hash with a string as first key, and an array as 2nd
> key.
You cannot have arrays as keys in Perl hashes.
> But it doesn't work!
What were you hoping that it would do?
> Can anyone tell me what's wrong?
You are trying to create an impossible data structure.
If you had told us what you really want, then we would have a
chance of showing you how to refactor your data structure.
> #!/usr/bin/perl -w
> $hash{"test"}{["one", "two"]} = 42;
Hash keys are forced to be strings.
If you give it an array ref as a hash key, you will get a stringified
representation of the reference, which can no longer be used to
access the array.
> $hash{"test"}{["three", "four"]} = 23;
Do you want the 2nd level hash to have 4 key/value pairs in it?
$hash{test}{one} = 42;
$hash{test}{two} = 42;
$hash{test}{three} = 23;
$hash{test}{four} = 23;
or, by using a "hash slice":
@hash{ qw/ one two three four / } = (42, 42, 23, 23);
If you wanted something else, try telling us what that something else is.
> my $key = "test";
> foreach(keys %{$hash{$key}}){
> print "Value for $_ is $hash{$key}{$_}\n"; # ARRAY(0x804c95
> # print "@$_\n"; # Can't use string ("ARRAY(0x804c95
") as an ARRAY ref
> }
>
> The output is:
> Value for ARRAY(0x804c95
is 23
>
> Why does it print only *one* value?
Because there is only one key ("test") in the hash, your 2nd
assignment stomped over the value of the 1st assignment.
> Why can't I dereference
> the array ref $_?
Because it is NOT an array ref, it is a string.
--
Tad McClellan SGML consulting
Perl programming
Fort Worth, Texas