Search code examples
perlperl-data-structures

How to print hash of anonymous hashes?


How would I get value of stones if hash structure is as follows?

%HoA = 
(
[stones    => "ruby"],
[metal     => "gold"],
);

I am trying to get using print $HoA->{stones};, but no value is returned.


Solution

  • The problem is that the members of %HoA are arrays, not hashes. In fact, what you have is a hash with one element. The key of that element is a reference to an array holding two elements: "stones" and "ruby". The value of that element is a reference to an array holding two elements: "metal" and "gold".

    I'm guessing you want a hash that will contain a list of stones, a list of metals etc. The way to do that is:

    %HoA = 
    (
        stones    => ["ruby"],
        metal     => ["gold"],
    );
    

    Now $HoA{stones} is a reference to an array containing the single element "ruby".

    print @($HoA{stones});
    

    should give you:

    ruby