On Thu, Aug 18, 2016 at 9:39 PM <kp...@freenet.de> wrote:

> Hello,
>
> What's the better way to decide if an element exists in an array?
> Something like what ruby does,
>
> irb(main):001:0>  x=[3,1,4,2,9,0]
> => [3, 1, 4, 2, 9, 0]
> irb(main):002:0> x.include? 4
> => true
> irb(main):003:0> x.include? 10
> => false
> irb(main):004:0> quit
>
>
> I tried searching but found nothing such a method in perl.


The grep builtin does what you want

perldoc -f grep

http://perldoc.perl.org/functions/grep.html

my $found = grep { $_ == 4 } (3, 1, 4, 2, 9, 0); # 1
my $not_found = grep { $_ == 10 } (3, 1, 4, 2, 9, 0); # 0

The return value for grep in scalar context is the number of times it
matches.  In list context, it returns all of the elements that match:

my @found = grep { $_ % 2 } (3, 1, 4, 2, 9, 0); # @found holds (3, 1, 9)

The any function from List::Util will also do what you want.

perldoc List::Util

http://perldoc.perl.org/List/Util.html#any

my $found = any { $_ == 4 } (3, 1, 4, 2, 9, 0); # true
my $not_found = any { $_ == 10 } (3, 1, 4, 2, 9, 0); # false

Which you want depends on the application.  The grep function will return a
number between 0 and the size of the list and reads the entire list.  The
any function returns the canonical true (a tri-value that holds "1", 1, and
1.0) or false (a tri-value that holds "", 0, 0.0) values and stops at the
first matching value.  The canonical false value often throws people for a
loop as they expect it to be "0" in string context, but it is "".  You may
want to say

my $found = (any { $_ == 10 } (3, 1, 4, 2, 9, 0)) || 0;

to force it to be 0 instead of the canonical false value.

Reply via email to