Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

Re: Compare all array values without a loop

by radiantmatrix (Parson)
on Oct 19, 2004 at 14:35 UTC ( #400546=note: print w/replies, xml ) Need Help??

in reply to Compare all array values without a loop

You could join the array into a scalar with an unusual character as a separator, then use a match.

$foobar='D'; $sep = chr(1); @array = ('A','B','C','D'); if (($sep.join($sep,@array).$sep) =~ m/$sep$foobar$sep/) { print "Found a $foobar in \@array!"; }

The $sep on either side of the join() ensures that any potential match will begin and end with chr(1). You can pick other separator characters, as long as you can be sure they will not exist in your array (chr(1) is a pretty unlikely thing to find).

Of course, it would be better to use hash-keys if you can...

$foobar='D'; %hash = ( 'A' => undef, 'B' => undef, 'C' => undef, 'D' => undef ); print "Found a $foobar in \%hash" if exists $hash{$foobar};

If you're avoiding multiple loop passes for performance, then you could use a one-time loop to convert the array to a hash:

@array = ('A','B','C','D'); for (@array) { $hash{$_} = undef; } #now we have the same hash as in the previous example. #so, you can do this repeatedly with out a hit: $foo = 'D'; if (exists $hash{$foo}) { print "There was a $foo in the array\n"; }
require General::Disclaimer;
"Users are evil. All users are evil. Do not trust them. Perl specifically offers the -T switch because it knows users are evil." - japhy

Replies are listed 'Best First'.
Re^2: Compare all array values without a loop
by Crian (Deacon) on Oct 19, 2004 at 15:21 UTC

    Instead of

    @array = ('A','B','C','D'); for (@array) { $hash{$_} = undef; }
    you can use
    my @array = qw/A B C D/; my %hash; @hash{@array} = ();

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (2)
As of 2023-02-07 04:05 GMT
Find Nodes?
    Voting Booth?
    I prefer not to run the latest version of Perl because:

    Results (38 votes). Check out past polls.