work in many cases, they don't work when you need to distinguish certain false values from undefined. Now the following:$dir= $ENV{TMPDIR} || "/tmp"; $file ||= "default";
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= defined $ENV{MAXSIZE} ? $ENV{MAXSIZE} : -1; $size= -1 if ! defined $size;
$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; }
In reply to def -- Deal nicely with undefined values by tye
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |