Avatar of Tolgar
Tolgar
 asked on

How to check eleements of an array in Perl?

Hi,
Let's say I have an array called resultList.

I have some elements in this array. (Let's say 1,1,1,1,1,1,0,1,1,1,1,......)

I would like to check if any elements of this array (we don't know the length of the array)
has a a value of 0.

How can I do it in Perl? Are there any Perl functions that does this?

Thanks,
Perl

Avatar of undefined
Last Comment
ozo

8/22/2022 - Mon
farzanj

If you have at least Perl 5.10.1 you can do this:

use v5.10.1;
@array = (1, 2, 3, 0, 4, 5);
say "some elements is zero " if 0 ~~ @array;

Open in new window



Otherwise you will have to test one element at a time.
Tolgar

ASKER
Can I do something like this?

if ('0' eq any(@resultList))

Open in new window

farzanj

That is Python like :)
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
SOLUTION
farzanj

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Tolgar

ASKER
So, there is no built in function in Perl to do this. Am I right?

Thanks,
ASKER CERTIFIED SOLUTION
FishMonger

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
ozo

if( grep{$_==0} @array ){
}
ozo

#or
use Quantum::Superpositions;
if( 0==any @array ){
}
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
wilcoxon

Personally, I'm a fan of first (in List::Utils I think).  It's more efficient than grep (and I'm guessing any).

use List::Utils qw(first);
if (first {$_==0} @array) {
}

Open in new window

ozo

Yes, it more efficient, but grep is a core built-in function, as is the more efficient for this purpose ~~ operator in v5.10.1 or later.
Quantum::Superpositions is neither built-in, nor efficient (unless you have perl running on a quantum computer) but it has the syntax of http:#a38172275