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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With