Common tasks in Perl 6
From AJS.COM
Common tasks in Perl 6 is an overview of some of the most oft-performed tasks in Perl programming language, version 5, re-cast in Perl 6 syntax. This is intended to help newcomers to Perl 6 development get their feet.
Making things unique
In Perl 5, I often write:
foreach (@x) {
push @y, $_ unless $seen{$_}++;
}
This creates a new list y which contains all of the elements of x that were unique, preserving original order. In Perl 6, this is:
for @x {
push @y, $_ unless %seen{$_}++;
}
As you can see, it looks almost exactly the same. However, you can also name that loop variable with ease, and probably should:
for @x -> $item {
push @y, $item unless %seen{$item}++;
}
Junctions
Junctions are multiple values represented in a single expression or variable. They are aggregated with some logical operation (and/or) and can be negative as well. Here are some examples:
if $x == any(1,2,3) { ... } # Only if $x is 1, 2 or 3
all($x,$y,$z).say; # Call the say method on all three
if $x < all(@y) { ... } # only if $x is less than all values in @y
URL encoding
I very often use this Perl 5 code to transform strings into valid URL query components:
s/([^\w._-])/sprintf "%%%02x", $1/eg;
In Perl 6, that's:
s:g /<-[\w._-]>/{sprintf "%%%02x", $1}/;
Or, if we assume a URI module:
s:g /<-URI.valid_querychars>/{sprintf "%%%02x", $1}/;
... TBD ...
