Reputation: 526
I have an array and an hash. I'd like to match the key of the hash with the elements of the array.
I found an expression to grep all of the keys which matches with the array. It works, but I'm not sure that I've understood how it works. Can you explain what does it happen after grep
?
Array @text
and hash %sys
are already defined.
my @new_array = grep { exists $sys{$_} ? $sys{$_} : 0 } @text;
Upvotes: 0
Views: 118
Reputation: 27207
The code you found is over-complicated. It could/should be*:
my @new_array = grep { $sys{$_} } @text;
The grep
function processes a list - in this case the contents of @text
array - into a new list that only includes elements where the expression in the middle evaluates to a true value. The default value $_
is set to each list item in turn so that the expression can take account of the list contents.
The expression in your example includes a ternary operator ?
which evaluates to the item before the :
if the first part is true, or the value after it if false. So, in your case, it checks whether each key is in the %sys
hash, and evaluates to a lookup of the hash entry if it exists, or 0 (a false value) if it does not. Functionally inside a grep
this should be identical to just $sys{$_}
because undef
that you get from looking up the value of a non-existing key is also a false value.
*
However, there is a caveat - if %sys
was tied to a Perl class and had some hash functions overridden, different hash methods are called for exists
and hash lookup. So in that scenario there can be a difference either in performance or behaviour.
Upvotes: 2