Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Check Variables for NULL

by davorg (Chancellor)
on Feb 08, 2007 at 09:16 UTC ( #598956=note: print w/replies, xml ) Need Help??


in reply to Check Variables for NULL

Perl tries to make things as easy as possible for you and this is a good example.

In most cases, what you actually want is as simple as:

if ($value) { # $value contains something useful } else { # $value is "empty" }

(Note that the logic is reversed from your original example)

What we're doing here is checking the "truth" of $value. $value will be "false" if it contains any of the following values:

  • "undef" (i.e. if it hasn't been given a value)
  • The number 0
  • The string "0"
  • The empty string ("")

Any other value in $value will evaluate to "true".

This is all you need in most cases. There are a couple of "corner cases" that you sometimes have to consider:

  • Sometimes 0 is an acceptable value. You account for that by using if ($value or $value == 0).
  • Sonetimes you might want to test that $value contains nothing but whitespace characters. The easiest way to do that is by checking for the presence of non-whitespace characters with if ($value =~ /\S/).

Replies are listed 'Best First'.
Re^2: Check Variables for NULL
by jhourcle (Prior) on Feb 08, 2007 at 11:40 UTC
    Sometimes 0 is an acceptable value. You account for that by using if ($value or $value == 0).

    This may be more inclusive than you wish. (it will be true for both undef and the empty string), as it's basically asking for everything that's true or everyhing that's false. You likely wanted eq instead of == :

    ($value or $value eq 0)

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://598956]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (7)
As of 2017-12-13 18:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What programming language do you hate the most?




















    Results (375 votes). Check out past polls.

    Notices?