Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

def -- Deal nicely with undefined values

by tye (Sage)
on Dec 04, 2000 at 12:07 UTC ( [id://44760]=CUFP: print w/replies, xml ) Need Help??

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; }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: CUFP [id://44760]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (2)
As of 2024-03-19 10:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found