Your skill will accomplishwhat the force of many cannot PerlMonks

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

 on Nov 12, 2000 at 15:19 UTC Need Help??
Contributed by Anonymous Monk on Nov 12, 2000 at 15:19 UTC
Q&A  > arrays

Answer: How do I test if an array is empty or not?
contributed by merlyn

The name of the array (like @a) in a scalar context yields the number of elements currently in the array. And a boolean test selects scalar context automatically, so something like:

```if (@a) { # @a is not empty...
...
} else { # @a is empty
...
}
should work just fine.
Answer: How do I test if an array is empty or not?
contributed by Fastolfe

As a supplement to merlyn's answer, never be tempted to use defined on an array (or a hash for that matter). Simply testing the value of the @array in a scalar context is sufficient. The defined function makes little sense on any data type other than a \$scalar.

Answer: How do I test if an array is empty or not?
contributed by quidity

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.

• Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
• Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
• Read Where should I post X? if you're not absolutely sure you're posting in the right place.
• Posts may use any of the Perl Monks Approved HTML tags:
a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
• You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
 For: Use: & & < < > > [ [ ] ]
• Link using PerlMonks shortcuts! What shortcuts can I use for linking?

Create A New User
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (3)
As of 2018-04-25 01:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
My travels bear the most uncanny semblance to ...

Results (88 votes). Check out past polls.

Notices?