Something cool about Perl 6 every day

Primary Menu

Day 3: static types and multi subs

The third box is ready for opening this Advent. Inside…well, looks like two gifts! Inside the box are static types and multi subs.

In Perl 5, $scalar variables could contain either references or values. Specifically, the values could be anything. They could be integers, strings, numbers, dates: you name it. This offers some flexibility, but at the cost of clarity.

Perl 6 is going to change that with its static types. If you want a particular variable, you place the type name in between my and $variable-type. As an example, to set up a variable to be an Int, one can do this:

my Int $days = 24;

Other static types are as follows:

my Str $phrase = "Hello World";

my Num $pi = 3.141e0;

my Rat $other_pi = 22/7;

If you still want the old behavior of the variables, you can either choose not to declare a static type or use Any instead.

This gift can easily go hand in hand with the second gift inside the box today: multi subs. What exactly are multi subs? In short, multi subs allow for the overloading of sub names. While multi subs can also do so much more, those are gifts for another day. For now, here are some subs that can be useful:

If you had a string of digits (say, read in from a config file), would those be recognized as of type Int at runtime..? How does the runtime dispatch system figure out types and castings if you don’t specify them at compile time? Maybe I misunderstood your comment…

No, a string of digits is still a string. The multi dispatcher doesn’t do any type conversions for you.

What I meant is the following: You have a type A, and B inherits from A. If you have a variable with type constraint A, but it contains a B, then C++ dispatches with the type constraint (A), while Perl 6 dispatches with the actual type (B). My attempt to make it more concrete:

Ok ok, that makes a lot more sense than what I was thinking. That’s a good example, too. I haven’t before seen Perl 6 classes used in a constraints-based manner, only in a more inheritance-based manner (like C). Very cool! I guess I should just sit down and read the synopses…