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

What's the shortest/best way to test for an empty string ? I found a place where I foolishly used a simple if statement:
if ($rc=$ref->getc) { .... }
Of course, that works fine until the string coming back happens to be 0x30 ... :(
"length(...)" seems like just a little bit too much work (for Perl).
if ($rc=$ref->getc!~/./) { ... }
won't work because the !~ binds tighter than the "=" (and perhaps it's a little too obscure). I'm just wondering if there is some simple idiom that I'm overlooking. Thanks !

Replies are listed 'Best First'.
Re: Testing for empty string
by chip (Curate) on Mar 19, 2004 at 02:58 UTC
    I use length():

    if (length($rc=$ref->getc)) { ... }

    But if that's the standard getc() then you probably want defined() instead.

        -- Chip Salzenberg, Free-Floating Agent of Chaos

Re: Testing for empty string
by graff (Chancellor) on Mar 19, 2004 at 03:11 UTC
    if ($rc=$ref->getc!~/./) { ... }
    won't work because the !~ binds tighter than the "="...
    So? That's what parens are for:
    if (( $rc = $ref->getc ) !~ /./ ) { ... }
    I like parens -- they're Good Things. But the first reply was right: since you're using getc, you should just test for the return value being defined:
    if ( defined( $rc = $ref->getc )) { ... }