Link to home
Create AccountLog in
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,
Avatar of farzanj
farzanj
Flag of Canada image

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.
Avatar of Tolgar
Tolgar

ASKER

Can I do something like this?

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

Open in new window

That is Python like :)
SOLUTION
Avatar of farzanj
farzanj
Flag of Canada image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of Tolgar

ASKER

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

Thanks,
ASKER CERTIFIED SOLUTION
Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
if( grep{$_==0} @array ){
}
#or
use Quantum::Superpositions;
if( 0==any @array ){
}
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

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