Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tokuhirom/290980 to your computer and use it in GitHub Desktop.
Save tokuhirom/290980 to your computer and use it in GitHub Desktop.
# Newbie programmer
sub factorial {
my $x = shift;
if ($x == 0) {
return 1;
} else {
return $x * factorial($x - 1);
}
}
print factorial(6);
# First year programmer, studied Pascal
sub factorial {
my $x = shift;
my $result = 1;
my $i = 2;
while ($i <= $x) {
$result = $result * $i;
$i = $i + 1;
}
return $result;
}
print factorial(6);
# First year programmer, studied C
sub fact($){
my $x = int(shift);
my $result = 1;
my $i;
for ($i = 1; $i <= $x; $i++) {
$result *= $i;
}
return $result;
}
print(fact(6));
# First year programmer, SICP
sub fact {
my($x, $acc) = @_;
$acc ||= 1;
if ($x > 1) { return(fact(($x - 1), ($acc * $x))) }
else { return($acc) }
}
print(fact(6));
# First year programmer, Perl
sub factorial {
my $x = shift;
my $res = 1;
$res *= $_ for 2..$x;
return $res;
}
print factorial(6)
# Lazy Perl programmer
sub fact {
return $_[0] > 1 ? $_[0] * fact($_[0] - 1) : 1;
}
print fact(6);
# Lazier Perl programmer
sub fact {
my $res = 1;
eval join '*', 1..$_[0];
}
print fact(6);
# CPAN expert programmer
use Math::Big qw(factorial);
print factorial(6);
# Unix programmer
sub fact {
`factorial $_[0]`;
}
print fact(6);
# CGI programmer
sub fact {
local $q = $ENV{QUERY_STRING};
$q =~ s/%([0-9a-fA-F]{2})/chr(hex($1))/eg;
local %q = map { split /=/, $_ } split /[&;]/, $q;
my $x = $q{x} or &printErrorHTML("Bad input");
print STDERR "x=$x\n";
my $result = 1;
$result *= $_ for 2..$x;
print <<HTML;
Content-Type: text/html
Factorial of $x is $result.
HTML
}
# Haskell Progammer
use Language::Functional 'foldl';
sub fact {
my $x = shift;
foldl { $_[0] * $_[1] } 1, [ 2..$x ];
}
print fact(6);
# XS programmer
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
int fact(int n) { return n==0 ? 1 : n * fact(n-1); }
MODULE = Factorial PACKAGE = Factorial
PROTOTYPES: disable
IV
fact(int n)
# C programmer
use Inline C => <<'...';
int fact(int n) { return n==0 ? 1 : n * fact(n-1); }
...
print fact(6);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment