无法确定一个项是否存在于项数组中,并在Perl中返回必要的消息。

huangapple go评论70阅读模式
英文:

Unable to find if one item exists in array of items and return the necessary message in 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数组中。

有人可以帮忙吗?

提前感谢。

英文:

I have array of IDs. I have one ID which I want to find if that ID exists in the array of IDs in Perl

I tried the following code:

my $ids = [7,8,9];

my $id = 9;

foreach my $new_id (@$ids) {
   if ($new_id == $id) {
       print 'yes';
   } else {
       print 'no';
   }
}

I get the output as:

nonoyes

Instead I want to get the output as only:

yes

Since ID exists in array of IDs

Can anyone please help ?

Thanks in advance

答案1

得分: 5

my $ids = [7,8,9];
my $id = 9;
if (grep $_ == $id, @ids) {
print $id. " 在 ids 数组中";
} else {
print $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";
}

答案2

得分: 3

只需删除 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";
}
英文:

You just need to remove the else part and break the loop on finding the match:

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

if ($flag == 0){
    print "no";
}

Another option using hash:

my %hash = map { $_ => 1 } @$ids;
if (exists($hash{$id})){
    print "yes";
}else{
    print "no";
}

答案3

得分: 2

use List::Util qw(any); # 核心模块

my $id = 9;
my $ids = [7, 8, 9];

my $found_it = any { $_ == $id } @$ids;

print "yes" if $found_it;

英文:
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;

答案4

得分: 0

以下是翻译好的部分:

下面的代码段应该满足您的要求

    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];` 是将数组分配给变量的更好方式
英文:

The following piece of code should cover your requirements

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';

NOTE: perhaps my @ids = [7,8,9]; is better way to assign an array to variable

huangapple
  • 本文由 发表于 2020年1月3日 17:52:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/59576379.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定