Sign up for Linode and get a 60-day $100 credit

The evolution of a Perl programmer

[ ↑ Go up a level ]  [ next page → ]

Advertisement space · 468×60

Every Perl programmer grows up eventually. Here's the same function, factorial(6), as written at each stage of the journey.

# Newbie programmer
sub factorial {
    my $x = shift;
    if ($x == 0) {
        return 1;
    } else {
        return $x * factorial($x - 1);
    }
}
print factorial(6), "\n";
# First year programmer, studied C
use strict;
use warnings;

my $result = 1;
for (my $i = 1; $i <= 6; $i++) {
    $result = $result * $i;
}
print "$result\n";
# Discovered objects
package Factorial;
sub new    { my ($class, $n) = @_; return bless { n => $n }, $class }
sub result { my $self = shift; my $r = 1; $r *= $_ for 1 .. $self->{n}; $r }

package main;
print Factorial->new(6)->result, "\n";
# Regex wizard
my ($n, $f) = ("6", 1);
$f *= $& while $n =~ s/^[1-9]\d*$/$& - 1/e;
print "$f\n";
# Perl golfer
$r=1;$r*=$_ for 1..6;print"$r\n"
# Discovered List::Util
use List::Util qw(reduce);
print reduce { $a * $b } 1 .. 6;
print "\n";
# There's more than one way to do it
print eval(join '*', 1 .. 6), "\n";
# EXPERT PROGRAMMER
use Math::BigInt;
print Math::BigInt->new(6)->bfac, "\n";

See also: the evolution of a Python, Ruby, JavaScript, PHP or C programmer, and where this joke started, Fritz Ruehr's The Evolution of a Haskell Programmer (itself a riff on the old "Hello World" Evolution of a Programmer).