Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: Different ways to access nested hash keys

Tags:

hash

perl

Im almost newbie in Perl. So just wondering about the differences between two ways of accessing a value in nested hash.

Consider the following hash:

my %hsh = ( 
    'fruits' => { 
        'red'    => 'apple', 
        'yellow' => 'banana', 
    },
    'veg' => {
        'red'    => 'capcicum',
        'yellow' => 'lemon',
    },
);

#way 1
print $hsh{'fruits'}{'red'}; 

#way 2
print $hsh{'fruits'}->{'red'};

Both has same output apple. But what is the difference between these two ways?

like image 301
Samiron Avatar asked Dec 31 '25 09:12

Samiron


1 Answers

The -> operator is used to de-reference a hash or array reference. In your case, it is not needed, because Perl assumes de-referencing when dealing with a multidimension data structure. However in other cases, it is necessary:

my $ref = [ 'a','b','c' ];

print $ref[0];    #Fails
print $ref->[0];  #Succeeds
like image 195
dan1111 Avatar answered Jan 02 '26 02:01

dan1111