Development

Perl 6: Fun with Objects

6 Aug 2019 12:00pm, by

This tutorial is the second in a series on learning the basics of the Perl 6 programming language. Check back about once a month for a new installment.

OReilly Book cover - Think Perl 6 (via Amazon) Our first tutorial documented how easy it is to get Perl 6 up and running. But if you want an even easier way to try out the language, there’s a really nice tip in O’Reilly’s 2017 book “Think Perl 6: How to Think Like a Computer Scientist.” It reminds beginners they can also run Perl 6 in their browsers, pointing them to the handy site Glot.io (which lets you run and share snippets of code online in 37 different programming languages — including Perl 6).

Just remember that Glot.io is actually running the code you type — it’s not one of those handy and ever-versatile Read-Eval-Print Loops.

Whereas from the Windows command line on my system, typing perl6 now launches that interactive REPL environment. So if I then type in a string and hit return, the value of that string will be just printed out on the screen.

> "Hello World"
Hello World

Typing the same thing as a stand-alone Perl 6 program in Glot.io generates an error.

screenshot - StdErr for Perl 6 on Glot dot IO

Of course, it’s still possible to generate an error in my REPL environment too. If I type “Hello Perl 6” without quotation marks — I still get a (surprisingly loquacious) four-line error message.

> Hello Perl 6
===SORRY!=== Error while compiling:
Two terms in a row
at line 6
------> Hello Perl 6
expecting any of:
infix
infix stopper
postfix
statement end
statement modifier
statement modifier loop

Oh, and speaking of the shell… Just like the original Perl programming language, Perl 6 can also run shell commands — even on my Windows system. in Perl 6 the syntax is surprisingly easy. Shell commands are just placed in quotation marks and preceded by the word shell

shell "dir"

Prints…

Volume in drive C is OS
Volume Serial Number is 8A6A-491E


Directory of C:\Users\desti
05/07/2019 04:06 PM <DIR> .
05/07/2019 04:06 PM <DIR> ..
05/07/2019 03:53 PM <DIR> .perl6

But now that I’m basking in the glories of my first Perl 6 Read-Eval-Print Loop – there’s one very cool new Perl 6 features that I’ve been waiting to play around with…

Fun with Objects

Even if you’re just trying to print “Hello world,” the Perl Intro documentation site reveals another fun Perl 6 trick. Yes, you can obviously say “Hello world” (using Perl’s “say” command to follow it with a new line).

say 'Hello world'

But you can also accomplish the same thing with a new, Perl 6-ish syntax.

'hello world'.say

What’s going on? I think back to that night in 2015 when Larry Wall first introduced Perl 6 to an audience in San Francisco. There was a lot of sophisticated new technology hiding under the hood, and at one point he smiled and said that “Everything is an object. But only if you want it to be…”

To demonstrate, he showed that it was possible to ask the REPL to provide the object type for — well, pretty much anything.

> say 8.WHAT
(Int)

> say "eight".WHAT
(Str)

Perl 6 Deep Dive - Oreilly book cover (via Amazon)So .say and .WHAT are just two of the handy built-in object methods available to spew out information about the variables that you’re working with. (The .WHAT method obviously provides the object’s type.)

Andrew Shitov’s book “Perl 6 Deep Dive” explains that the .say method actually calls the gist method, which then prints out a “textual representation” of an object. For a string, the textual representation is the string, obviously.

That’s what’s been going on when I enter say pi (which, I realize now, could also have been written pi.say. It’s giving me a representation of Pi (which, in this case, is its value up to 15 digits).

Perl 6 has adopted a strict “everything is an object” model, so everything already has a slew of very powerful methods pre-installed.

> pi.say
3.141592653589793

So what other fun built-in methods can I call? The Perl Intro document points out that every string will have a .flip method which will reverse the order of all their characters.

> my $site = "The New Stack"
The New Stack
> $site.flip
kcatS weN ehT

And in general Perl 6 anticipates those things that a programmer does – and installs them into their corresponding methods. For arrays, there’s now a built-in .elems method to print out the number of elements.

> my @array = ("Manny", "Moe", "Jack")
[Manny Moe Jack]
> say @array
[Manny Moe Jack]
> @array.elems
> 3

And the old “push” and “pop” functions (which used to add and remove elements from arrays in Perl 5) are now the .push and .pop methods.

> @array.push("Curly")
[Manny Moe Jack Curly]
> @array.pop
Curly
> say @array
[Manny Moe Jack]

There’s also a built-in method offering an easier way to sort your arrays.

> my @numerical_array = (99, 50, 1)
[99 50 1]
> @numerical_array.sort
(1 50 99)

And there’s even a new for-loop syntax for cycling through every item in an array.

for @numerical_array -> $array-item {
say $array-item * 100
}

Of course, Perl 6 also still has hash arrays.

> my %Trek_actors = ('Spock', 'Nimoy')
{Spock => Nimoy}

But they’re also objects, with their own built-in methods.

> %Trek_actors.push: ('Kirk', 'Shatner')
{Kirk => Shatner, Spock => Nimoy}

And since they’re objects, there’s a much simpler syntax for retrieving their keys and values

> %Trek_actors.keys
(Kirk Spock)
> %Trek_actors.values
(Shatner Nimoy)
> %Trek_actors.kv
(Kirk Shatner Spock Nimoy)

You can also use Perl 6’s .WHAT method to return the type of your hash array’s variables.

> %Trek_actors.WHAT
(Hash)

Tell Me More

If a variable can hold more than one type, WHAT returns the value of the currently-held variable.

But if you want all of an object’s attributes (and not just its type), there’s also the built-in method .^attributes

In the same, Larry Wall also wowed the audience back in 2015 by revealing that you could pull up a list of all the available methods for interacting with Perl 6’s objects-when-you-want-them-to-be — by just asking with the proper syntax.

> 8.^methods
(new Capture Int Num Rat FatRat abs Bridge chr sqrt base polymod expmod is-prime floor ceiling round lsb msb narrow Range unival rand acotanh sech succ acotan tan asech pred tanh atan2 acos cosh roots cosec sec unpolar Complex cotan sinh log cos truncate log10 asinh cis asin cosech exp acosec sin atanh acosech asec conj cotanh sign atan isNaN acosh WHICH perl Bool Str Real gist Numeric ACCEPTS DUMP)

Wait, so there’s a built-in is-prime method that I can run on numbers? Let’s try it…

> 8.is-prime
False

> 2.is-prime
True

It’s hard to capture what a unique experience this is. I’m doing things with code — easily and instantaneously — that I’ve never done before. I’ve used other programming languages before, but even with that, for me, Perl 6 is an entirely different animal.

And it reminds me of the very last thing Larry Wall said on the night he unveiled Perl 6. After 15 years of development, someone in the audience had asked him, which part of Perl 6 was his favorite?

“The part where we get done,” he joked at first. But then he seemed to be contemplating all the new wonders he was about to share with the world, and answered…

“I kind of like all of it, really.”

Feature image: A hot, expanding stellar debris cloud, 36 light-years wide, from a supernova explosion, Chandra Observatory, NASA/CXC/SAO.

A newsletter digest of the week’s most important stories & analyses.

View / Add Comments

Please stay on topic and be respectful of others. Review our Terms of Use.