JDS
JDS

Reputation: 16978

Perl how to check if array is still empty?

This should be simple hopefully. I initialize an empty array, do a grep and place the results (if any) in it, and then check if it's empty. Like so:

my @match = ();
@match = grep /$pattern/, @someOtherArray;
if (#match is empty#) {
    #do something!
}

What's the standard way of doing this?

Upvotes: 47

Views: 112207

Answers (3)

Tom Wilson
Tom Wilson

Reputation: 1

I've also found that this works too, but I'm not sure if it's documented:

if ($#match == -1)

Upvotes: -3

shirish kumar
shirish kumar

Reputation: 45

If you are using an arrayref instead of an array say for e.g.

my $existing_match = data_layer->find('Sale',{id => $id});

Say above returns an array, then use:

if( scalar(@$existing_match) == 0) 

Upvotes: -2

mob
mob

Reputation: 118605

You will see all of these idioms used to test whether an array is empty.

if (!@match)
if (@match == 0)
if (scalar @match == 0)

In scalar context, an array is evaluated as the number of elements it contains.

Upvotes: 82

Related Questions