Null in Perl

In some programming languages there is a special value null. For example, in JavaScript you can assign nullvariable:

var a = null;

Also null is one of the possible values in JSON:

{
  "a": null
}

And NULL is a value in the database:

mysql> select null;
+------+
| NULL |
+------+
| NULL |
+------+
1 row in set (0.00 sec)

Null means absence of value.

In the Perl programming language there is no value called null. You can write code trying to assign a value nullvariable:

▶ Run
#!/usr/bin/perl

use strict;
use warnings;

my $a = null;

But running this code will generate an error:

Bareword "null" not allowed while "strict subs" in use at script.pl line 6.
Execution of script.pl aborted due to compilation errors.

In the programming language Perl uses a special value undef which means there is no value. This is the same as null, but only with a different name.

There's a difference between working as JavaScript and Perl. In JavaScript, if you define the variable but not assign it a value, its value will be undefined. And then it is already possible to assign null. Perl work easier. In Perl there are no different values undefined and null, in Perl there is only one special value undef.

null in JSON and Perl

When serializing Perl data structures to JSON values undef will be converted to null values in JSON. Here is an example code:

▶ Run
#!/usr/bin/perl

use strict;
use warnings;
use JSON::PP;

my $data = {
    a => undef,
};

print encode_json($data);

This code will display {"a":null}.

Conversely, if you expand JSON into a Perl structure, the values null will be replaced by undef:

▶ Run
#!/usr/bin/perl

use strict;
use warnings;
use JSON::PP;
use Data::Dumper;

print Dumper decode_json('{"a":null}');

The program will display:

$VAR1 = {
          'a' => undef
        };

Related topics

Other articles