dave93 has asked for the wisdom of the Perl Monks concerning the following question:

In my code I frequently have to write conditions like this:

if (defined $string and $string ne "") { ..... }

What I really want is to check if the string is not entirely empty. I would like to be able to do something like if ($string) but this would exclude "0".

So I hope that there is a shorter and nicer way to do this. For now I have been using a utility strempty subroutine which runs that check but I doubt it's idiomatic.

In my own code I try to have it so that empty strings are simply undef, where applicable, but sometimes it can't be helped and external modules don't follow this rule hence why I have to write these conditions.

Replies are listed 'Best First'.
Re: Checking string emptiness
by jwkrahn (Abbot) on Apr 04, 2025 at 22:09 UTC
    if ( length $string ) {

    I believe that length is more efficient than using a string comparison.

    Naked blocks are fun! -- Randal L. Schwartz, Perl hacker
      It would need to be length($string // '') to avoid uninitialized value warnings.

        Not since 5.12. length undef returns undef without warning since then.

Re: Checking string emptiness
by dave93 (Acolyte) on Apr 05, 2025 at 00:01 UTC

    Thanks, jwkrahn and sleet. It seems that starting with Perl 5.12 it's valid to call length with an undef value. It's a relatively recent change.

    My only concern with this is that it seems too obtuse, so I wondered if it is really idiomatic. I checked a couple of modules and that seems to be the case.

    Thanks. I consider this resolved.

Re: Checking string emptiness
by harangzsolt33 (Deacon) on Apr 06, 2025 at 04:13 UTC
    There are a few other ways too...

    sub isEmpty { return defined $_[0] ? !length($_[0]) : 1; }


    sub isEmpty { defined $_[0] or return 1; return !($_[0] =~ tr|||c); }


    sub isEmpty { return !(defined $_[0] && $_[0] =~ m/./); }

      Why try to obfuscate it? Just use if (length $string) { as suggested by jwkrahn?

      Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond
      A reply falls below the community's threshold of quality. You may see it by logging in.