Warnings can be very helpful; I like them. But dealing with undefined values without triggering a warning can be a slight pain. While the following:
$dir= $ENV{TMPDIR} || "/tmp";
$file ||= "default";
work in many cases, they don't work when you need to distinguish certain false values from undefined. Now the following:
$size= defined $ENV{MAXSIZE} ? $ENV{MAXSIZE} : -1;
$size= -1 if ! defined $size;
aren't so bad but require repeating either the variable name or the value. So def() gives you something that works very much like || and ||= but based on definedness, not falseness:
$size= def( $ENV{MAXSIZE}, -1 );
def( $size, -1 ); # void context causes $size to be modified
if( 0 < def( $size= $ENV{MAXSIZE), -1, 1 ) )
# The third argument above forces $size to be modified
# even though no void context used. An alternative is:
if( 0 < ( $size= def $ENV{MAXSIZE), -1 ) )
sub def {
my( $val, $alt, $force )= @_;
$val= defined $alt ? $alt : "" if ! defined $val;
$_[0]= $val if ! defined wantarray || $force;
return $val;
}