Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 610
MaxVT Avatar asked Apr 06 '09 07:04

MaxVT


People also ask

How do you check if a value is present in an array?

JavaScript Array includes() The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found. The includes() method is case sensitive.

How do I extract an element from an array in Perl?

Array slicing can be done by passing multiple index values from the array whose values are to be accessed. These values are passed to the array name as the argument. Perl will access these values on the specified indices and perform the required action on these values. print "Extracted elements: " .

How do I view an array reference in Perl?

The Perl array reference can also be passed to a subroutine as shown below. sub add_numbers { my $array_ref = shift; ..... } @numbers = (11,2,3,45); $array_ref = add_numbers(\@numbers); In the above code snippet, we need to de-reference the array, so that the subroutine can take the elements from the original array.

What does ~~ mean in Perl?

It is the smartmatch operator. In general, when you want information about operators in Perl, see perldoc perlop. Follow this answer to receive notifications.


1 Answers

If you have perl 5.10, use the smart-match operator ~~

print "Exist\n" if $var ~~ @array;

It's almost magic.

like image 56
RET Avatar answered Sep 29 '22 16:09

RET