packetie
packetie

Reputation: 5069

change the behavior of "if" statement in perl a little bit

I inherit lots of code like the following

if (func1()) { .... }

The "func1()" may return a scalar, an array or an reference to array. I would like the evaluation of "if" in the above as the following:

I know I can do something like the following

@a = func1();
if (!defined $a[0]) {
    #false
} elsif (ref($a[0] eq "ARRAY") {
    if (scalar(@{$a[0]})) {
        #true
    } else {
        #false
    }
} elsif ($a[0]) {
    #true
} else {
    #false
}

But this is tedious and there are many such occurance of if (func1()).... Wonder if there is a simple way to make the perl "if" statement behave as I want.

Thanks in advance.

Update:

Thanks to @ikegami 's question, I realized my real issue is the following (see the comment in the following, reproduced here to make it easy to read)

funcX() will return a reference to a list. The current behavior of if is that it will always evaluate to be true regardless of whether the referenced list is empty or not. But I would like if (funcX()) to evaluate to be false if the referenced list is empty and true otherwise.

Upvotes: 1

Views: 71

Answers (1)

ikegami
ikegami

Reputation: 385764

sub check($) {
   return undef if !$_[0];
   return undef if ( ref($_[0]) || '' ) eq 'ARRAY' && !@{ $_[0] };
   return 1;
}

if (check(func1()) {
   ...
}

Like in your original code (and contrary to what you said), func1 must return a scalar. check return false if the scalar is false, false if the scalar is a reference to an empty array, and true otherwise. (Just like your overly complex check that doesn't compile and can throws a warning when func1 returns a true value that's not an reference.)

Upvotes: 2

Related Questions