Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: How to check whether my array contains element x

by choroba (Cardinal)
on Jan 17, 2013 at 13:07 UTC ( [id://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();
لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Replies are listed 'Best First'.
Re^2: How to check whether my array contains element x
by LanX (Saint) 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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1013774]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (6)
As of 2024-04-24 10:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found