in reply to Can a defined value be of zero length?

To answer the why part of your question:

This code was maybe written in this way by the original coder because he/she got used to the pattern of testing a value for definedness before using it in order to avoid the "Use of uninitialized value" warning:

$ perl -wMstrict -e 'my $x; print length $x' Use of uninitialized value in print at -e line 1. $ perl -wMstrict -e 'my $x; print length $x if defined $x' $

or:

$ perl -wMstrict -e 'my $x; print "yes" if $x=~/foo/' Use of uninitialized value $x in pattern match (m//) at -e line 1. $ perl -wMstrict -e 'my $x; print "yes" if defined $x && $x=~/foo/' $

However, in this particular case, the test for definedness is not needed:

$ perl -wMstrict -e 'my $x; print "yes" if defined $x && length $x' $ perl -wMstrict -e 'my $x; print "yes" if length $x' $

This is because the length function is being used in a boolean context, and whether it returns 0 or undef doesn't matter since they are both evaluated as a false value, see Truth and Falsehood.

Replies are listed 'Best First'.
Re^2: Can a defined value be of zero length?
by ikegami (Patriarch) on Apr 21, 2014 at 03:41 UTC

    However, in this particular case, the test for definedness is not needed:

    Only since 5.12. Many people still use 5.8 and 5.10.