Iam a perl newbie and need help in understanding the below piece of code.
I have a perl Hash defined like this
1 my %myFavourite = ("Apple"=>"Apple");
2 my @fruits = ("Apple", "Orange", "Grape");
3 @myFavourite{@fruits}; # This returns Apple. But how?
It would be great if perl gurus could explain what’s going on in Line-3 of the above code.
myFavourite is declared has a hash,but used as an array? And the statement simply takes the key of the hash ,greps it in to the array and returns the hash values corresponding the key searched. Is this the way we grep Hash Keys in to the Array?
It doesn’t return Apple. It evaluates to a hash slice consisting of all of the values in the hash corresponding to the keys in
@fruits. Notice if you turn on warnings that you get 2 warnings about uninitialized values. This is becausemyFavouritedoes not contain values for the keysOrangeandGrape. Look up ‘hash slice’ in perldata.Essentially,
@myFavourite{@fruits}is shorthand for($myFavourite{Apple}, $myFavourite{Orange}, $myFavourite{Grape}), which in this case is($myFavourite{Apple},undef,undef). If you print it, the only output you see isApple.