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:
The accepted answer - the most "built-in" and backward-compatible way.
RET's answer is the cleanest, but only good for Perl 5.10 and later.
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.
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.
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: " .
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.
It is the smartmatch operator. In general, when you want information about operators in Perl, see perldoc perlop. Follow this answer to receive notifications.
If you have perl 5.10, use the smart-match operator ~~
print "Exist\n" if $var ~~ @array;
It's almost magic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With