On 19 August 2016 at 13:35,  <kp...@freenet.de> wrote:
>
> 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.
>
> thank you.


People tend to use grep for this purpose, as grepping an array returns
an array of matched items, and that,
in scalar context, returns the number of matches, and the number of
matches being 1 or more is sufficient for "includes"

However, using grep for that purpose is slightly inefficient, as I
mentioned earlier, it returns all matching items,
so grep *always* traverses the whole list even if the found item is at
$ARRAY[0], and this is slow if you have 100,000 items.

Instead, its recommended to use List::Utils qw/ first /;

"First" works like "Grep", but only returns the first matching item, so:

   if ( first { $item == 4 }  @items ) {
       say "Yes";
   }


So, because first only returns at most 1 item, it is more efficient
when there is a match.

( But still as slow if there are no matches ).

And again, the "number of matches being nonzero" is your "its
included" mechanic.

-- 
Kent

KENTNL - https://metacpan.org/author/KENTNL

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to