Alex Rivera | Logout

How can I verify that a value is present in an array (list) in Perl?

Asked 2009-04-06T07:28:24.420
21

I have a list of possible values:

@a = qw(foo bar baz);

How do I check in a concise way that a value $val is present or absent in @a?

An obvious implementation is to loop over the list, but I am sure TMTOWTDI.


Thanks to all who answered! The three answers I would like to highlight are:

  1. The accepted answer - the most "built-in" and backward-compatible way.

  2. RET's answer is the cleanest, but only good for Perl 5.10 and later.

  3. draegtun's answer is (possibly) a bit faster, but requires using an additional module. I do not like adding dependencies if I can avoid them, and in this case do not need the performance difference, but if you have a 1,000,000-element list you might want to give this answer a try.

Edit
Report

2 Answers

8

One possible approach is to use List::MoreUtils 'any' function.

use List::MoreUtils qw/any/;

my @array = qw(foo bar baz);

print "Exist\n" if any {($_ eq "foo")} @array;

Update: corrected based on zoul's comment.

answered 2009-04-06T07:34:54.060
1

If you don't like unnecessary dependency, implement any or first yourself

sub first (&@) {
  my $code = shift;
  $code->() and return $_ foreach @_;
  undef
}

sub any (&@) {
  my $code = shift;
  $code->() and return 1 foreach @_;
  undef
}
answered 2009-04-07T19:11:56.933

Your Answer