Saturday, January 1, 2011

To test if a value is in an array?

Method 1: 
 
@int_array = (7,101,80,22,42);
 
if ( grep $_ == 80, @int_array ) {
 
print "80 exists in an array..."; 
 
 
 
 
 
 
Method 2:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util 'first';
my @int_array       = qw( 7 101 80 22 42 );
my $number_to_check = 80;
if ( first { $_ == $number_to_check } @int_array ) {
    print "$number_to_check exists in ", join ', ', @int_array;
}
 
 
 
Method 3: 

use List::MoreUtils qw{any}; print "found!\n" if any { $_ == 7 } (7,101,80,22,42);
 
 

No comments: