如何检查变量是否在列表中? [英] How to check whether variable is in list?

查看:54
本文介绍了如何检查变量是否在列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 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};
}

另请参阅:

这篇关于如何检查变量是否在列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆