Perl

Implementation of programming language Perl

Standard implementation of Perl, written in C.

Examples:

Hello, World!:

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

Factorial:

Example for versions perl 5.8.8

This example uses the reduce function from the List::Util module. Note that we have to put an extra 1 in the beginning, so that it will work when 1 .. $n is empty (i.e. when $n is 0).

use List::Util qw(reduce);
sub fact {
  my $n = shift;
  reduce { $a * $b } 1, 1 .. $n
}

foreach my $i (0..16) {
    print "$i! = ", fact($i), "\n";
}

Factorial:

Example for versions perl 5.8.8

This example uses recursive factorial definition.

sub fact {
  my $n = shift;
  $n == 0 ? 1 : $n*fact($n-1);
}

foreach my $i (0..16) {
    print "$i! = ", fact($i), "\n";
}

Factorial:

Example for versions perl 5.8.8

This example uses iterative factorial definition.

sub fact {
  my $n = shift;
  my $result = 1;
  foreach my $i (1 .. $n) {
    $result *= $i;
  }
  $result
}

foreach my $i (0..16) {
    print "$i! = ", fact($i), "\n";
}

Fibonacci numbers:

Example for versions perl 5.8.8

This example uses recursive definition of Fibonacci numbers.

sub fibonacci {
  my $n = shift;
  $n < 3 ? 1 : fibonacci($n-1) + fibonacci($n-2)
}

foreach (1..16) {
  print fibonacci($_), ", ";
}
print "..."

Quadratic equation:

Example for versions perl 5.12.1, perl 5.8.8

Note that Perl 6 has no backwards compatibility; this example won’t be valid in Perl 6.

$A = <>;
if ($A == 0) {
    print "Not a quadratic equation.";
}
else {
    $B = <>;
    $C = <>;
    $D = $B * $B - 4 * $A * $C;
    if ($D == 0) {
        print "x = ", -0.5 * $B / $A;
    }
    else {
        if ($D > 0) {
            print "x1 = ", 0.5*(-$B + sqrt($D))/$A, "\nx2 = ", 0.5*(-$B - sqrt($D))/$A
        }
        else {
            print "x1 = (", -0.5*$B/$A, ",", 0.5*sqrt(-$D)/$A, ")\nx2 = (", -0.5*$B/$A, ",", -0.5*sqrt(-$D)/$A, ")\n"
        }
    }
}

CamelCase:

Example for versions perl 5.12.1, perl 5.8.8
my $text = <STDIN>;
$text = join('', map(ucfirst, split(/[^a-z]+/, lc $text)));
print $text, "\n";

CamelCase:

Example for versions perl 5.12.1, perl 5.8.8

This is similar to the previous example, except that instead of splitting on non-alphabetical characters, we match on runs of alphabetical characters.

my $text = <STDIN>;
$text = join('', map(ucfirst, lc($text) =~ /[a-z]+/g));
print "$text\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;