user1613245
user1613245

Reputation: 351

Unable to find if one item exists in array of items and return the necessary message in Perl

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

Upvotes: 2

Views: 94

Answers (4)

Polar Bear
Polar Bear

Reputation: 6798

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

Upvotes: 0

pilcrow
pilcrow

Reputation: 58524

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;

Upvotes: 2

user429356
user429356

Reputation: 71

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";
}

Upvotes: 5

Guru
Guru

Reputation: 16974

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";
}

Upvotes: 3

Related Questions