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

标签 arrays 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";
}

关于arrays - 无法找到项目数组中是否存在一项并在 Perl 中返回必要的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59576379/

相关文章:

java - 尝试返回值时出现两个错误

java - 我们如何使用映射从 double 组中获取唯一元素‽

perl - 人们为什么说Perl是动态类型的?

python - 正则表达式可选匹配运算符 : how to apply to a string of characters?

c - 打印数组值,无地址

javascript - 通过创建水平表的数组进行映射

perl - 用 perl 打印列表的前几个元素

html - 将日志文件 (*.txt) 转换为网络友好文件(*.html、*.jsp 等)的最佳方式?

mysql - Perl MySQL DBI - 更新并获取最后的值

javascript - ng-repeat 数组按数据源的属性索引排序