Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Finding hash keys in array

by Grimy (Pilgrim)
on May 29, 2013 at 18:42 UTC ( [id://1035901]=note: print w/replies, xml ) Need Help??


in reply to Finding hash keys in array

Looping through all the keys in the hash is very inefficient. To check if $name is a key of %$all_names, you could use :

exists $$all_names{$name}; %$all_names ~~ $name; # Shortcut using the smartmatch operator

Note that this isn't the same as defined $$all_names{$names}. If you do $$all_names{$key} = undef, exists would return true (because the key exists), but defined would return false (because the value is undefined).

To select elements from an array based on a condition, you can use grep { condition } @array. Putting it all together, to get all elements of @arr_of_names that are keys of %$all_names, you can try this :

@good = grep { %$all_names ~~ $_ } @arr_of_names;

Note that inside the grep condition, the element being tested is aliased to $_.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1035901]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2024-04-16 22:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found