Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to grep perl Hash Keys in to an array?

Tags:

perl

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?

like image 335
rajachan Avatar asked Dec 07 '25 10:12

rajachan


1 Answers

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 because myFavourite does not contain values for the keys Orange and Grape. 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 is Apple.

like image 116
William Pursell Avatar answered Dec 09 '25 23:12

William Pursell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!