in reply to Defined vs ne ""

An empty string is quite well defined. It is a false value, but it is very much not the same as undef

Replies are listed 'Best First'.
Re^2: Defined vs ne ""
by Anonymous Monk on Oct 12, 2011 at 15:07 UTC
    Then can you explain this?
    my $test; if (defined($test)) { print "test is defined"; } if ($test ne "") { print "test is defined again"; }
    Test comes back as undefined in this for tests. Actually the second test fails because there's an uninitialized value.

    That's partly why I have been using DEFINE because it's the only way I can get by without getting those UNDEFINED errors to make sure there is content.

    Is there a better way to see if it IS definied, meaning it contains something, so if I try to compare it to something it won't fail like the above sample I just pasted?
      It depends on whether or not you consider the empty string "something". You didn't assign anything to your test variable above, so it is undefined. But the undefined value evaluates to false in a boolean context, the empty string in a string context, and zero in numerical context (although you get an uninitialized warning in the last two with warnings on). If you want your hash values in the OP to be undefined, then assign undef instead of the empty string. Or, always initialize your variables (to the empty string if necessary), and compare to the empty string.

      Now try with my $test = '';, which is what you had in your original post.

      Perhaps you want length instead of defined.

      It seems to me that you should simply initialize your variables up front. IE: my $test = '';

      Then you don't have to worry about undefined values, and string compares with the empty string will do what you want.