perl
Implementation of programming language PerlExamples:
Hello, World!:
Example for versions perl 5.8.8#!/usr/bin/env perl
print "Hello, world!\n";
Factorial:
Example for versions perl 5.8.8This 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 (1..16) {
print "$i! = ", fact($i), "\n";
}
Factorial:
Example for versions perl 5.8.8sub fact {
my $n = shift;
$n == 0 ? 1 : $n*fact($n-1);
}
foreach my $i (1..16) {
print "$i! = ", fact($i), "\n";
}
Factorial:
Example for versions perl 5.8.8sub fact {
my $n = shift;
my $result = 1;
foreach my $i (1 .. $n) {
$result *= $i;
}
$result
}
foreach my $i (1..16) {
print "$i! = ", fact($i), "\n";
}
Fibonacci numbers:
Example for versions perl 5.8.8naive recursive solution
sub fibonacci {
my $n = shift;
$n < 3 ? 1 : fibonacci($n-1) + fibonacci($n-2)
}
foreach (1..16) {
print fibonacci($_), "\n";
}
Fibonacci numbers:
Example for versions Perl 6 (alpha)Not the shortest possible implementation, but perhaps the easiest to read and understand.
sub fib { 1,1...{$^x + $^y} }
fib[^16], '...' ==> join(', ') ==> say;
Factorial:
Example for versions Perl 6 (alpha)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 1..16 -> $i {
say "$i! = ", fact($i);
}
Hello, World!:
Example for versions Perl 6 (alpha)The comma at the end is optional.
This is also a valid Perl 5.10 program.
say 'Hello, World!';
Comments
]]>blog comments powered by Disqus
]]>