Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Have hash of arrays. Want to test if variable is a member of any of the arrays

by toolic (Bishop)
on Dec 13, 2014 at 03:15 UTC ( [id://1110238]=note: print w/replies, xml ) Need Help??


in reply to Have hash of arrays. Want to test if variable is a member of any of the arrays

I don't think you need to build a new array, and I think any may be faster than grep because it doesn't always traverse the whole array and it potentially uses the C implementation (List::MoreUtils). I used $x instead of $a, which has special super powers.
use warnings; use strict; use List::MoreUtils qw(any); my %hoa = ( x => [ qw(a b c d) ], y => [ qw(e f g) ], z => [ qw(h i c j) ], ); my $x = 'c'; for my $k (keys %hoa) { print "key $k has $x\n" if any { $_ eq $x } @{ $hoa{$k} }; } __END__ key x has c key z has c

Replies are listed 'Best First'.
Re^2: Have hash of arrays. Want to test if variable is a member of any of the arrays
by tobyink (Canon) on Dec 13, 2014 at 20:08 UTC
      Though you need a fairly recent List::Util
      From perl5200delta
      List::Util has been upgraded from version 1.27 to 1.38.

      From the CPAN Changes file, it looks like "any" was added in 1.33.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (4)
As of 2024-03-28 15:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found