Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether variable is in list? [duplicate]

Tags:

list

set

perl

Is there way to do something like this in perl?

$str = "A"
print "Yes" if $str in ('A','B','C','D');
like image 669
CJ7 Avatar asked Dec 29 '25 00:12

CJ7


2 Answers

Smart matching is experimental and will change or go away in a future release. You will get warnings for the same in Perl 5.18+ versions. Below are the alternatives:

Using grep

#!/usr/bin/perl
use strict;
use warnings;
my $str = "A";
print "Yes" if grep {$_ eq 'A'} qw(A B C D);

Using any

#!/usr/bin/perl
use strict;
use warnings;
use List::Util qw(any);
print any { $_ eq 'A' } qw(A B C D);

Using hash

#!/usr/bin/perl
use strict;
use warnings;
my @array = qw(A B C D);
my %hash = map { $_ => 1 } @array;
foreach my $search (qw(A)) #enter list items to be searched here
{
   print exists $hash{$search};
}

Also see:

  • match::smart - provides a match operator |M| that acts like more or less identically to the (as of Perl 5.18) experimental smart match operator.
  • Syntax::Feature::Junction - provides keywords for any, all, none, or one
  • You may also use List::Util::first which is faster as it stops iterating when it finds a match.
like image 91
Chankey Pathak Avatar answered Dec 30 '25 15:12

Chankey Pathak


You can transform your array to a hash. Then you can efficiently (in constant time, or O(1)) check if your string was in the original array. Here are two different approaches on how to look for the string 'C':

#!/usr/bin/perl
use strict;
use warnings;

my %hash1 = map {$_ => 0} qw/A B C D/;
print 'Yes' if exists $hash1{'C'};

#!/usr/bin/perl
use strict;
use warnings;

my %hash2;
@hash2{qw/A B C D/} = ();
print 'Yes' if exists $hash2{'C'};

But of course like always in Perl, TIMTOWTDI.

like image 26
reflective_mind Avatar answered Dec 30 '25 14:12

reflective_mind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!