Categories

Posts in this category

Sat, 12 Dec 2009

Defined Behaviour with Undefined Values


Permanent link

In Perl 5 there is the undef value. Uninitialized variables contain undef, as well as non-existing hash values, reading from unopened or exhausted file handles and so on.

In Perl 6 the situation is a bit more complicated: variables can have a type constraint, and are initialized with the corresponding type object:

my Int $x;
say Int.WHAT();     # Int()

These type objects are also undefined, but in Perl 6 that doesn't mean they are a magical value named undef, but that they respond with False to the defined() subroutine and method.

In fact there is no undef anymore. Instead there are various values that can take its place:

Mu is the type object of the root type of the object hierarchy (or put differently, every object in Perl 6 conforms to Mu). It's the most general undefined value you can think of.

Nil is a "magic" value: in item (scalar) context it evaluates to Mu, in list context it evaluates to the empty list. It's the nothing to see here, move along value.

Each type has a type object; if you want to return a string, but can't decide which, just return a Str.

Other interesting undefined values are Exception (which usually contain a message and a back trace), Failure (unthrown exceptions), Whatever is a generic placeholder that can stand for "all", "infinitely many", "many" or as a placeholder for a real value.

[/perl-6] Permanent link