Perl 6

Implementation of programming language Perl

Next generation of Perl implementation; is currently under development, alpha-version available, but changes a lot.

Examples:

Factorial:

Example for versions rakudo-2010.08

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!:

Example for versions rakudo-2010.08

say command is available only in Perl 6. The semicolon at the end is optional.

say 'Hello, World!';

Quadratic equation:

Example for versions rakudo-2010.08

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:

Example for versions Perl 6 (alpha), rakudo-2010.08

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!:

Example for versions perl 5.8.8, rakudo-2010.08
print "Hello, world!\n";

CamelCase:

Example for versions rakudo-2010.08

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;