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

Without using 5.10's // operator, is there a more concise way to perform the following test?

use warnings; ... if (defined($x) && length($x)) { ... }
Just $x ne "" or testing the length alone doesn't work since I'd like to avoid the Use of uninitialized value ... warning in the case that $x is undef.

Thanks!

Replies are listed 'Best First'.
Re: testing defined($x) && length($x)
by ikegami (Patriarch) on Mar 25, 2009 at 15:45 UTC

    Sure:

    if (has_length($x)) { ... }

    Implementation of has_length left to the reader.

Re: testing defined($x) && length($x)
by kyle (Abbot) on Mar 25, 2009 at 15:53 UTC

    Building on the remarks from Bloodnok and ikegami, I think this does what you're asking:

    if ( length( $x // '' ) {

    Update: Oops, kennethk has informed me that I missed an important part of the question.

    Maybe this is better, but maybe not:

    if ( length( defined $x ? $x : '' ) ) {
Re: testing defined($x) && length($x)
by ruzam (Curate) on Mar 25, 2009 at 17:20 UTC

    When I do need to worry about '0', I generally stick with

    if (defined $x and $x ne '')

    Now I'm wondering if there's any particular advantage of using "length($x)" over "$x ne ''"?

    If $x is a sub parameter and both '0' and 'undef' are acceptable input, then I sanitize it right up front so I don't have to worry about undefined warnings later in the code when I start using/testing with it.

    my $x = shift; $x = '' unless defined $x;
Re: testing defined($x) && length($x)
by Bloodnok (Vicar) on Mar 25, 2009 at 15:46 UTC
    Given that the test will fail if either $x is undefined or is defined but is empty, you could avoid the uninitialized value... warning by using
    if (length($x || '')) { ... }

    A user level that continues to overstate my experience :-))
      That introduces a false negative. The if's body is no longer executed when $x eq '0'.
Re: testing defined($x) && length($x)
by Herkum (Parson) on Mar 25, 2009 at 16:26 UTC
    Why are you not just doing this?
    if ($x and length($x)) {} # Do something

    This should take care of your $x not being defined.

    Update: Too early did not think clearly see below. Removed the offending/incorrect text.

      No, it still has the '0' false negative:

      $ perl -e '$x = 0; print "failed\n" unless $x and length($x)' failed $

      vs.

      $ perl -e '$x=0; $ print "failed\n" unless defined $x and length($x)' $

      ...length test will catch it if the value of $x = 0, hmmm, if $x == 0, then length() test will not be executed - aka, it suffers from the same problem (with my attempt) that ikegami kindly pointed out.

      A user level that continues to overstate my experience :-))
Re: testing defined($x) && length($x)
by JavaFan (Canon) on Mar 26, 2009 at 01:04 UTC
    The more concise way is to not write use warnings; to begin with, and then:
    if(''ne$x) {...}