๐Ÿ“˜ Typed variables in Perl 6

๐Ÿ“˜ Typed variables in Raku

N. B. Perl 6 has been renamed to Raku. Click to read more.


This is how you declare a typed variable:

my Int $x;

Here, a scalar container $x may only hold an integer value. Attempts to assign it a value that is not an integer leads to an error:

my Int $x;
$x = "abc"; # Error: Type check failed in assignment to '$x';
ย ย ย ย ย ย ย ย ย ย ย  # expected 'Int' but got 'Str'

For typecasts, a respective method call is quite handy. Remember that while $x holds an integer, it is treated as a container object as a whole, which is why you may use some predefined methods on it. The same you can do directly on a string. For example:

my Int $x;
$x = "123".Int; # Now this is OK
say $x; # 123

Leave a Reply

Your email address will not be published. Required fields are marked *