Home > Perl6 > Nil statement considered harmful

Nil statement considered harmful

Nil is the little parent of Failure and represents the absence of a value. It’s the John Doe of the Perl 6 world. Its undefined nature means we can talk about it but we don’t know its value. If we try to coerce it to a presentable value we will be warned.

my $a := Nil; dd $a.Str, $a.Int;
# OUTPUT«Use of Nil in string context  in block <unit> at <tmp> line 1␤Use of Nil
 in numeric context  in block <unit> at <tmp> line 1␤""0␤»

As the output shows it still coerces to the closest thing we have for a undefined string or number. Some times the empty string is outright dangerous.

sub somesub { Nil };
my $basename = somesub;
spurt("$basename.html", "<body>oi!</body>");

If we do that in a loop we would drop plenty of “.html” into the filesystem. Since this can depend on input data, some cunning individual might take advantage of our neglect. We can’t test for Nil in $basename, because assignment of Nil reverts the container to it’s default value. The default default value for the default type is Any. We can protect ourselves against undefined values with a :D-typesmile.

my Str:D $basename = somesub;

That would produce a runtime error for anything but Nil, because the default value for a container of type Str:D is Str:D. A type object that happens to be undefined and wont turn into anything then the empty string. Not healthy when use with filenames.

We still get the warning though, what means that warn is called. As it happens warn will raise a control exception, in this instance of type CX::Warn. We can catch that with a CONTROL block and forward it to die.

sub niler {Nil};
my Str $a = niler();
say("$a.html", "sometext");
say "alive"; # this line is dead code
CONTROL { .die };

That’s quite a good solution to handle interpolation problems stemming from undefined values. Given that any module or native function could produce undefined values makes it hard to reason about our programs. Having the control exception allows us to catch such problems anywhere in the current routine and allows us to deal with more then one place where we interpolate in one go.

Sometimes we want to stop those values early because between an assignment of a undefined value and the output of results minutes or even hours can pass by. Fail loudly and fail early they rightfully say. Type smileys can help us there but for Nil it left me with a nagging feeling. So I nagged and requested judgment, skids kindly provide a patch and judgement was spoken.

Perl 6 will be safe and sound again.

Categories: Perl6

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: