How grep perl hash keys to an array?

Iam a perl newbie and you need help understanding the code below.

I have perl hash defined as

1   my %myFavourite = ("Apple"=>"Apple");
2   my @fruits = ("Apple", "Orange", "Grape");
3   @myFavourite{@fruits}; # This returns Apple. But how?

It would be great if the perl gurus could explain what is happening in Line-3 of the above code. MyFavourite declaration is declared hash, but is used as an array? And the operator simply takes the hash key, inserts it into the array and returns the hash values ​​corresponding to the found key. Is it so that we insert hash keys into an array?

+3
source share
2 answers

Apple. -, , @fruits. , , 2 . , myFavourite Orange Grape. "-" perldata.

, @myFavourite{@fruits} ($myFavourite{Apple}, $myFavourite{Orange}, $myFavourite{Grape}), ($myFavourite{Apple},undef,undef). , , , Apple.

+6

myFavourite has hash, ?

, . -. .: http://perldoc.perl.org/perldata.html

@fruits -. @hash {@keys} - .

:

@myFavourite{@fruits}

:

($myFavourite{'Apple'},$myFavourite{'Orange'},$myFavourite{'Grape'})

, (, )

my @slice_values = @myFavourite{@fruits}
# @slice_values now contains ('Apple',undef,undef)
# which is functionally equivalent to:
my @slice_values = map { $myFavourite{$_} } @fruits;

- , :

my @favourite_fruits = @myFavourite{ grep { exists $myFavourite{$_} } @fruits };
# @favourite_fruits now contains ('Apple')

:

use warnings;

, undef.

+5

Source: https://habr.com/ru/post/1724913/


All Articles