2

My understanding is that I can use

if (@array) { print "array not null"; }

to test if all the elements of an array are null. Is there a way I can use this to test a 2 dimensional array?

1
  • 2
    if (@array) test if array is empty/has no elements. If it has elements and these are undef/null, it will be boolean true. Commented May 8, 2014 at 15:19

1 Answer 1

4

Essentially you need to loop through the first dimension of the array to find out if any of the sub-arrays contain anything. This works:

use List::Util qw( any );

if (any { @$_ } @array) { print "array not null\n"; }

If you're stuck using an old version of List::Util that doesn't provide any, in this case first will work as a reasonable substitute:

use List::Util qw( first );

if (first { @$_ } @array) { print "array not null\n"; }

Though I think than any better clarifies the intent of the code.

Sign up to request clarification or add additional context in comments.

8 Comments

Why not just use map @$_, @array?
@Zaid any and first are short circuited. Map will loop even if first element is not empty
@DVK : (rolls eyes) :)
@Zaid - if your list has 100000000 elements, it's not such a trivial optimization
@DVK : Totally agree. To each his/her own problem domain.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.