Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

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?

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

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (8)
As of 2018-06-24 20:56 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (126 votes). Check out past polls.