25 November 2016

Tired but Friday;

Just a tiny micro-post today; I have a new job! It's Perl 5 related so expect more Perl 5 posts since I want to stay in that headspace, but I haven't forgotten about Perl 6.

I want to show off a little neat feature of Perl 6 that might not be the most widely used feature you're ever gonna see, but is still going to be useful once in a while.

But but but

You might already be familiar with classes and roles, and I'll spare you the full explanation for now. Basically roles are ways to extend or mix-in functionality into classes, which makes code re-use much easier. What if you don't have a class though? What if all you've got is an object, or a value type?

The Perl 6 'but' operator lets you mix a role into an object, even if you're talking about something immutable like a value type. I'm sure there are lots of goofy ways to abuse this to make objects that don't behave like they normally would, but I can think of one legitimate use-case - shell return values. For those not familiar with the UNIX shell, a return value of 0 is usually considered 'success', with non-zero values being various error codes. This goes against pretty much every other language when considering the 'truthiness' of an int - zero is false, and leads to odd invocations like

if ( ! system("run_my_thing")) {
  say "Success!";
}

Perl 6 has shell and run instead of system, which as far as I know return plain old ints, but if we were to write our own function to do something similar, we could make code that returns special values that can be treated as a number but also have truth tests work:

$ perl6
To exit type 'exit' or '^D'
> my $thing = 0 but True;
0
> say "It's true!" if $thing;
It's true!
>

Anyway... I just think it's cool ;)

1 comment: