如何检查变量是否在列表中?

如何检查变量是否在列表中?

问题描述:

是否可以在 perl 中执行类似的操作?

Is there way to do something like this in perl?

$str = "A"
print "Yes" if $str in ('A','B','C','D');

智能匹配是

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:

使用grep

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

使用任何

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

使用哈希

#!/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};
}

另请参阅: