Reputation: 351
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
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
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
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
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