Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 无法找到项数组中是否存在一个项并以Perl返回必要的消息_Arrays_Perl - Fatal编程技术网

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

Arrays 无法找到项数组中是否存在一个项并以Perl返回必要的消息,arrays,perl,Arrays,Perl,我有一个ID数组。我有一个ID,我想在Perl中的ID数组中查找该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数组中 有人能

我有一个ID数组。我有一个ID,我想在Perl中的ID数组中查找该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数组中

有人能帮忙吗


提前感谢

您只需删除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 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]
是将数组分配给变量的更好方法

如果数组没有ID,我希望在case中显示no消息,因此我需要else条件
如果($flag==0)
<代码>如果(!$标志)!请注意,哈希使用字符串键,因此不能表示所有数值相等的值(例如,
0==0.0
0==0e0
@$ids
,而不是
@ids
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';