Gambit2007 Gambit2007 - 1 month ago 7
Perl Question

Perl - reference to a hash of a hash

I have the following code:

my $hhref = {'ancient' => {'Adam' => 'Eve',
'Antony' => 'Cleopatra'},
'modern' => {'Clyde' => 'Bonnie'}};
print "$hhref->{'ancient'}{'Antony'}\n";


Which prints out:

REF(0x35c320)Cleopatra


And i really don't understand why. Why doesn't it just print
Cleopatra
?

Thanks!

Answer

Depending on which version of perl and which OS you are using you will get slightly different results. The trouble really comes from having quotes in your print statement. If instead your code was

my $hhref = {'ancient' => {'Adam' => 'Eve',
                      'Antony' => 'Cleopatra'}, 
         'modern' => {'Clyde' => 'Bonnie'}};
print $hhref->{'ancient'}{'Antony'};
print "\n";

then it will print correctly. Why? Well, perl has trouble understanding what you mean. Do you mean "$hhref" followed by "->{'ancient'}{'Antony'}", or do you mean "$hhref->{'ancient'}" followed by "{'ancient'}", or is it all together as one variable? Outside of a string the compiler is exact but inside a string it has to make guesses at what you mean because white space is used differently and not deterministically like it is in code.

Basically, if you want variables to be interpreted correctly every time then reference them outside of quotes in perl.

Comments