perlhash

How to access elements of an associative array in Perl


I have the below code:

my %ages = ();

$a1 = "Michael Caine";
$a2 = "Dirty Den";
$a3 = "Angie";
$a4 = "Willy";
$a5 = "The Queen Mother";

$ages{$a1} = 39;
$ages{$a2} = 34;
$ages{$a3} = 27;
$ages{$a4} = "21 in dog years";
$ages{$a5} = 108;

print $age->{$a1};

But this is not printing. I do not want to use keys or values. How can I access the contents of hash using '$age->{$a1}' type syntax?


Solution

  • You are trying to access $age which does not exist. Also, you are trying to use extra reference ->, which is wrong.

    You need to use this:

    $ages{$a1}