views:

43

answers:

1

I have 3 dimensional hash and a 2 dimensional hash, and I want to merge the 2 dimensional hash with one of the inner hashes of the 3 dimensional hash, something like this, which is similar to what I do to merge a pair of 2d hashes:

my %3dhash;
my %2dhash;
my $key = "some string";
%3dhash{$key} = ($3dhash{$key}, %2dhash);

But when I tried that it didn't work. What should I be doing?

+2  A: 

Try the following:

my %hash3d;
my %hash2d;
....
my $key = "some string";
$hash3d{$key} = { %{ $hash3d{$key} }, %hash2d };

Variables in Perl can't start with a number, so I renamed the variables. The %{ ... } around the existing hash expands it as a list. This list flattens with the list from %hash2d. The { ... } around that list is the anonymous hash reference constructor, which creates a new hash reference that is then stored in $hash3d{$key}

Eric Strom
Thank you! I was typing the code from memory, which is the reason for all the syntax errors. Your solution worked though.
DAG
Variables can too start with numbers — what about `$0 $1 $2 … $9`? ;-)
ephemient
@ephemient, those are built-in special variables. You can't create new variables that begin with a number.
cjm
Well if you have a really good reason for starting with a number, it is legal to say `%{"3dhash"}` ...
mobrule
@mobrule => spaces, numbers, punctuation, its all fair game if you quote it. hopefully we haven't given anyone bad ideas :)
Eric Strom