48

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?

1
  • 1
    You can define and initialize @match on the same line - my @match = grep etc. Commented Oct 5, 2012 at 18:40

3 Answers 3

85

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.

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

3 Comments

Don't forget unless ( @match )
Do forget unless (@match). (but that's just, like, my opinion, man)
Are the converses to these also true? If you wanted to control behavior for when at least one element was present, I'm assuming it would be if (@match) and if (@match != 0) but I thought I ought to check
-2

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) 

1 Comment

The boolean context already takes care of that so writing it all out is redundant.
-3

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

if ($#match == -1)

3 Comments

Please, no one ever do this. :) It's always if (@match) { } or if (not @match) { } or if (! @match) { }.
@lordadmira What about if ($#match < -0.5) {}?
In other words, is your objection only that it's dangerous to test for exact equality of two integers in a language where variables are not clearly typed as integer or floating-point?

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.