我遇到了下一个问题,我在一个数组中有一些随机值,如果数组中的其中一个值与我的变量匹配,我想打印一条消息。 例如:
my @random_pool = (1, 30, 13, 40, 58, 7);
my $value = 17;
我想要做的是:
if($value in @random_pool) {
print "match";
} else {
print "not mach";
如果没有数组而是字符串,也可以使用解决方案吗?
示例:
my $random_pool = "1, 30, 13, 40, 58, 7";
my $value = 17;
if($value in $random_pool) {
print "match";
} else {
print "not mach";
谢谢
答案 0 :(得分:8)
我使用map来创建哈希:
#!/usr/bin/env perl
use strict;
use warnings;
my @random_pool = (1, 30, 13, 40, 58, 7);
my %is_in_pool = map { $_ => 1 } @random_pool;
my $value = 17;
print "Match\n" if $is_in_pool{$value};
这种方法的优点是,如果你想用不同的值进行迭代,你可以重用哈希 - map
迭代你的数组一次,其中类似grep
的东西每次需要迭代。
答案 1 :(得分:2)
if (grep { $_ == $value } @array) {
print "match\n";
} else {
print "not match\n";
}
grep { $_ eq $value } @array
在匹配字符串时更合适。
对于大型列表,如果$value
不是undef
,List::Util::first
效率更高,因为它不一定要搜索整个列表:
use List::Util 'first';
if (defined( first { $_ == $value } @array )) { ... }
但我的快速搜索是将字符串化并使用正则表达式搜索值。
if (" @array " =~ / $value /) { ... }
(它很脏,因为它可能不适用于像@array
这样的边缘情况,其元素中包含空格或$value
具有正则表达式元字符)