无法找到项目数组中是否存在一个项目,并在 Perl 中返回必要的消息



>我有 ID 数组。我有一个 ID,我想查找该 ID 是否存在于 Perl 中的 ID 数组中

我尝试了以下代码:

my $ids = [7,8,9];
my $id = 9;
foreach my $new_id (@$ids) {
if ($new_id == $id) {
print 'yes';
} else {
print 'no';
}
}

我得到的输出为:

nonoyes

相反,我只想将输出作为:

yes

由于 ID 存在于 ID 数组中

任何人都可以帮忙吗?

提前致谢

my $ids = [7,8,9];
my $id = 9;
if (grep $_ == $id, @ids) {
print $id. " is in the array of ids";
} else {
print $id. " is NOT in the array";
}

您只需要删除 else 部分并在找到匹配项时中断循环:

my $flag = 0;
foreach my $new_id (@$ids) {
if ($new_id == $id) {
print 'yes';
$flag = 1;
last;
}
}
if ($flag == 0){
print "no";
}

使用哈希的另一个选项:

my %hash = map { $_ => 1 } @$ids;
if (exists($hash{$id})){
print "yes";
}else{
print "no";
}
use List::Util qw(any);   # core module
my $id = 9;
my $ids = [7,8,9];
my $found_it = any { $_ == $id } @$ids;
print "yes" if $found_it;

以下代码段应满足您的要求

use strict;
use warnings;
my $ids  = [7,8,9];
my $id   = 9;
my $flag = 0;
map{ $flag = 1 if $_ == $id } @$ids;
print $flag ? 'yes' : 'no';

注意:也许my @ids = [7,8,9];是将数组分配给变量的更好方法

最新更新