How to check in Perl a variable contains undef

Task. The code in the Perl programming language is the variable. You need to check whether the value of this variable undef or not.

The decision

A variable contains undef only if the function defined for the variable returns false. Here is the code that displays text if a variable contains undef:

▶ Run
#!/usr/bin/perl

my $foo;

if ( !defined($foo) ) {
    print "foo is undef";
}

The wrong decision

To check whether undef in a variable you need to use defined. But it often happens what to check for undef use of other, wrong ways.

Here is the first example of how not to do it:

▶ Run
#!/usr/bin/perl

my $foo;

if ( !$foo ) { # error!
    print "foo is undef";
}

This example is really just the string foo is undef if the variable $foo contains the value undef, but the code prints this line in other cases. For example, if $foo contains the number 0 or the empty string ''. This code is not to check that $foo contains undef, and check that $foo contains the value false, and it is absolutely not the same as undef.

Here is another example of incorrect validation undef:

▶ Run
#!/usr/bin/perl

my $foo;

if ( $foo == undef ) { # error!
    print "foo is undef";
}

There are just all completely wrong. If the variable $foo contains a value undef, this code prints place foo is undef, but the code prints this line in other cases. For example, if in a variable $foocontains string 'Hello'.

The operator == is intended for comparison of numbers. Before you make comparison of this operator converts its arguments to numbers. Variable $foo which is undef becomes the number 0. And undef the right of the operator also becomes the number 0. Zero is zero, the condition is triggered. But zero be and some lines, for example 'Hello'.

If you add this code use strict; and use warnings;, then Perl will output foo is undef, but just let you know about what's going on something strange:

Use of uninitialized value in numeric eq (==) at script.pl line 8.
Use of uninitialized value $foo in numeric eq (==) at script.pl line 8.
foo is undef

In General, it is always a very good practice to always use use strict; and use warnings;.

Related topics

Other articles

Comments