Perl in_array

PHP has a great function called in_array that allows you to test a value against an array to see if the value is in the array, returning TRUE or FALSE depending. I've now had to come up with this same thing in Perl a couple of times so I figured I would share. I can't remember where I found help or I'd reference them. But here you go. I've included both a syntax highlighted screenshot and the plain text to copy and paste.



my @states = ('California', 'Nevada', 'Texas', 'Utah');
my $findme = 'Utah';

if (in_array($findme, \@states)) {
  print "Found it!";
} else {
  print "Not found.";
}

sub in_array {
  my ($item, $array) = @_;
  my %hash = map { $_ => 1 } @$array;
  if ($hash{$item}) { return 1; } else { return 0; }
}

Tagged as , , , ,
Posted in Perl Programming