如何检查变量是否在列表中?
问题描述:
是否可以在 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};
}
另请参阅:
- match :: smart -提供匹配运算符|M |与Perl 5.18版本中的实验性智能匹配运算符大致相同.
- 语法:: Feature :: Junction -为任何,全部,没有或一个提供关键字
- 您还可以使用 列表:: Util :: first ,它更快,因为找到匹配项时它会停止迭代.