Categories

Posts in this category

Thu, 19 Nov 2009

Immutable Sigils and Context


Permanent link

If you have an array @a and want to access the first element, in Perl 5 you write that as $a[0], in Perl 6 you write it as @a[0]. We call the former mutable sigil, and the latter immutable sigil.

You might think that's a small change, but the implications are rather deep, and we've had quite a few discussions about it in #perl6. In particular people often ask if it's possible to backport the Perl 6 behavior to Perl 5. The answer is "not easily".

In Perl 5 context propagates inwards, which means that in a statement like

... = func()

The compiler wants to know at compile time which context func() is in. If it doesn't, it complains:

2$ perl -ce '(rand() < 0.5 ? $a : @a) = func()'
Assignment to both a list and a scalar at -e line 1, at EOF
-e had compilation errors.

This also means that, in Perl 5, array slices and scalar array accesses have to be syntactically distinguished:

my @a;
$a{other_func()} = ...; # scalar context
@a{other_func()} = ...; # list context

So you can't just make sigils in Perl 5 immutable without also rewriting the whole context handling rules.

In Perl 6 that's not a problem at all, because functions don't know the context they're in, in fact can't know because of multi dispatch.

Instead functions return objects that behave appropriately in various contexts, and the context is determined at run time.

After getting used to it the immutable sigils are quite nice, and less complicated when references are involved. Anybody who objects without having tried it for at least three weeks, and is spoiled by Perl 5, will be shot.

[/perl-6] Permanent link