Tiny Games with Perl 6

Note: due to positive feedback on the post and at a client, I've released DBIx::Class::Report to the CPAN. You can read the original announcement here.

An offhand tweet about Perl 6, inspired by this ycombinator response, led to what I think is my most popular tweet of all time (which, compared to many others, isn't that big of a deal):

But I was also asked what the heck the code is doing, so let me walk you through it.

The code itself is rather trivial (repasting here so you can cut n' drool if you like):

$ perl6 -e 'for ^6 { say ("⚀".."⚅").roll(3) }'
⚄ ⚃ ⚀
⚀ ⚀ ⚁
⚂ ⚅ ⚃
⚄ ⚅ ⚃
⚂ ⚂ ⚄
⚃ ⚅ ⚃

If you don't already have an up-to-date Rakudo installed, do this:

git clone https://github.com/tadzik/rakudobrew ~/.rakudobrew

Then add that to your $PATH (I put mine in my .bashrc file):

export PATH=~/.rakudobrew/bin:$PATH

Then build it and (optionally) install the panda package manager (because we need more package managers, right?):

rakudobrew build moar && rakudobrew build-panda

Any time you want to get a more recent version of rakudo, just rerun that command.

So that gets you a recent Perl 6. So what does the code do?

First, ^ is the upto operator. This generates a Range from zero upto (but not including) its argument. So ^6 is the same as 0..5. Also note that like many things in Perl 6, it's lazy, so writing perl6 -e 'say (^Inf)[3]' won't eat all of your memory.

The "⚀".."⚅" uses the normal range operator. Remember that in Perl 5 you can write 'a' .. 'z' to get a list of lower-case letters from 'a' to 'z'? This is the same thing, but Perl 6 assumes Unicode, while Perl 5 does not:

$ perl -Mutf8::all -E 'say join "," => "⚀".."⚅"'
⚀
$ perl -Mutf8::all -E 'say join "," => map { chr } ord("⚀")..ord("⚅")'
⚀,⚁,⚂,⚃,⚄,⚅

The roll($x) method returns $x random elements, allowing duplicates. This is different from the pick method which does not return duplicates.

For more fun, you can generate poker hands, too:

$ perl6 -e 'say (2..10,<J Q K A> X~ <♡ ♢ ♣ ♠>).pick(5)'
7♠ 4♡ J♠ 10♡ Q♣

The solution is left as an exercise for the reader.

3 Comments

Great with native utf8 support. I've often had to use base64 encoding to make sure output is translated correctly when I move data between systems.

In latest Rakudo MoarVM (rakudobrewed minutes ago), Poker example requires ().flat to flatten the 2..10, list from 2 to 13 elems.

About Ovid

user-pic Freelance Perl/Testing/Agile consultant and trainer. See http://www.allaroundtheworld.fr/ for our services. If you have a problem with Perl, we will solve it for you. And don't forget to buy my book! http://www.amazon.com/Beginning-Perl-Curtis-Poe/dp/1118013840/