Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: How to check whether my array contains element x

by choroba (Abbot)
on Jan 17, 2013 at 13:07 UTC ( #1013774=note: print w/ replies, xml ) Need Help??


in reply to How to check whether my array contains element x

TIMTOWTDI: you can use the Smartmatch Operator, grep for the value, or just use the old plain loop:

#!/usr/bin/perl use warnings; use strict; use Test::More; my @checks = ( sub { my ($entity, @array) = @_; $entity ~~ @array; }, sub { my ($entity, @array) = @_; grep $entity eq $_, @array; }, sub { my ($entity, @array) = @_; for (@array) { return 1 if $entity eq $_; } return; }, ); for my $check (@checks) { ok $check->('b', qw(a b c)); ok not $check->('z', qw(a b c)); } done_testing();
لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ


Comment on Re: How to check whether my array contains element x
Download Code
Re^2: How to check whether my array contains element x
by LanX (Canon) on Jan 17, 2013 at 13:15 UTC
    You forgot to mention hashes! =)

    DB<101> sub in { my ($entity, @array) = @_; my %hash; @hash{@array}=(); return exists $hash{$entity}; } DB<102> in(5,0..10) => 1 DB<103> in(42,0..10) => ""

    but I wouldn't pass @array as a flat list.

    Cheers Rolf

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1013774]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (11)
As of 2014-10-20 10:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (75 votes), past polls