有没有办法在
perl
中做类似这样的事情?$str = "A"
print "Yes" if $str in ('A','B','C','D');
使用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};
}
另请参见:
first
作为替代方案。如果列表元素可以为假值,则first
还要求您检查未定义:say“match”if defined first { ... } @array
与简单的say“match”if any { ... } @array
。 - ThisSuitIsBlackNot'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'};
$str = "A";
@arr = ('A','B','C','D');
print "Yes" if $str ~~ @arr;
print "Yes" if 'A' ~~ ['A','B','C','D'];
也可以工作,但这可能不是最好的选择。 - reflective_mind
~~
但它是实验性的。 - mkHun