rakudo-2010.08
Version of implementation Perl 6 of programming language PerlA version or rakudo compiler for Perl 6.
Examples:
Factorial - Perl (82):
This version uses the reduction metaoperator to multiply every number from 1 to N (the leading [*]
means “apply the *
operator between each element of the following list”).
Note that the say
statement could also be written as:
say "$i! = &fact($i)";
with the function call interpolated directly into the string being printed.
sub fact($n) { [*] 1..$n }
for 0..16 -> $i {
say "$i! = ", fact($i);
}
Hello, World! - Perl (83):
say
command is available only in Perl 6. The semicolon at the end is optional.
say 'Hello, World!';
Quadratic equation - Perl (234):
This example differs from one in Perl 5 in two major ways: the way user input is read and results are printed, and the way all variables have to be predeclared with my
keyword before using them. Note that explicit declaration of variable type stays optional.
my $A = $*IN.get;
if ($A == 0) {
say "Not a quadratic equation.";
}
else {
my $B = $*IN.get;
my $C = $*IN.get;
my $D = $B * $B - 4 * $A * $C;
if ($D == 0) {
say "x = ", -0.5 * $B / $A;
}
else {
if ($D > 0) {
say "x1 = ", 0.5*(-$B + sqrt($D))/$A, "\nx2 = ", 0.5*(-$B - sqrt($D))/$A
}
else {
say "x1 = (", -0.5*$B/$A, ",", 0.5*sqrt(-$D)/$A, ")\nx2 = (", -0.5*$B/$A, ",", -0.5*sqrt(-$D)/$A, ")\n"
}
}
}
Fibonacci numbers - Perl (81):
Not the shortest possible implementation, but perhaps the easiest to read and understand.
sub fib { 1,1, {$^x + $^y} ... * }
fib[^16], '...' ==> join(', ') ==> say;
Hello, World! - Perl (63):
print "Hello, world!\n";
CamelCase - Perl (372):
The first line reads the string to process, the second one — declares the variable which will store the result.
The most interesting things happen in the third line. The regular expression <[a..zA..Z]>+
finds all words in the string, and for each found word the built-in code { $cc ~= $0.capitalize; }
is executed. It translates the word to the required case and appends it to the result.
my $A = $*IN.get;
my $cc = "";
$A ~~ s:g /(<[a..zA..Z]>+) { $cc ~= $0.capitalize; } //;
print $cc;
Comments
]]>blog comments powered by Disqus
]]>