Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: How do I test if an array is empty or not?

by quidity (Pilgrim)
on Nov 12, 2000 at 22:43 UTC ( [id://41207]=note: print w/replies, xml ) Need Help??


in reply to How do I test if an array is empty or not?

The answer here does depend a little bit on what you mean by 'empty'. The earlier answers only tell you if an array has any elements, but not tell you what they contain.

If by empty you mean 'only contains defined elements' then you will need the following test instead:

my @a = (0,1,2,3); foreach (@a) {print "'$_'\n";} # Prints each element. print "\@a exists\n" if @a; print "\@a is not Empty\n" if grep {defined($_)} @a; # Prints '@a is not empty' if any element in '@a' is defined. my @b = (1, undef) foreach (@b) {print "'$_'\n";} print "\@b exists\n" if @b; print "@b is not Empty\n" if grep {defined($_)} @b;

Of course, if you want to know if the array contains only true values, then you can get away without using the defined() bit.

Edited: Examples reworked by davido.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://41207]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (3)
As of 2024-04-24 05:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found