Perl

Let’s start programming in Perl.

Overview

Perl is a very dynamic scripting language that was hugely popular in the 1990s for web applications, and has always been used in system administration, networking, and bioinformatics. It is sometimes credited with bringing regular expressions and other forms of text processing to the masses. A fair amount of infrastructure code has been implemented in Perl.

It is now a family of languages. All languages in the family except Perl 5 and Raku are obsolete.

Perl is a high-level programming language with an eclectic heritage written by Larry Wall and a cast of thousands.

Perl's process, file, and text manipulation facilities make it particularly well-suited for tasks involving quick prototyping, system utilities, software tools, system management tasks, database access, graphical programming, networking, and web programming. ... These strengths make it especially popular with web developers and system administrators. Mathematicians, geneticists, journalists, managers and many other people also use Perl.

Perl FAQ.

The Perl home page is at perl.org.

Perl 1 came out in 1987. Perl 5.000 arrived in 1994. Perl 5.42 is current as of July 2025. See the complete Perl history at perlhist.

Hello, World

The simplest hello program, which works on any version of Perl, all the way back to the OG Perl 1, is:

hello.pl
# The classic hello world script.

print "Hello, World\n";

To compile and run this, just enter:

perl hello.pl

On a Unix system, you can simply rename the file hello (instead of hello.pl), add a shebang comment with the pathname of your Perl interpreter, and give the file executable permission.

Perl has evolved so much over the years, with new features being constantly added, so modern Perl apps will start with a use directive with a minimal version to support the features used in the current script. The use-version directive, if high enough (v.5.35 or higher), also turns on strict error and warning checking, so you should always use it. For the examples on this page, we’ll be using 5.40 as our baseline.

helloworld.pl
use v5.40;

say "Hello, World"

See the Wikipedia’s Perl History to see what was added in each version through the years.

More Simple Examples

Here is a simple script with for-loops:

triple.pl
use v5.40;

for my $c (1..100) {
    for my $b (1..$c) {
        for my $a (1..$b) {
            say "$a, $b, $c" if $a**2 + $b**2 == $c**2;
        }
    }
}

And a Fibonacci number script that illustrates command line arguments:

fib.pl
use v5.40;

# We need a command line argument. If we don't have one, die
my $n = shift // die "Usage: $0 <max>\n";

# Check that the argument is a positive integer
unless ($n =~ /^\d+$/ && $n > 0) {
    die "Error: argument must be a positive integer\n";
}

# Generate and print as you go
my ($a, $b) = (0, 1);
while ($b < $n) {
    print "$b ";
    ($a, $b) = ($b, $a + $b);
}

# Finish with a newline
say "";

What most languages call functions, Perl calls subroutines:

stats.pl
# A simple script that displays the mean and median
# of an array of values, passed in on the command line.

use v5.40;

sub median (@list) {
    my @a = sort { $a <=> $b } @list;
    my $length = @a;
    return undef unless $length;
    return $length % 2
        ? $a[$length/2]
        : ($a[$length/2] + $a[$length/2 - 1]) / 2.0;
}

# There's a sum built-in, but we're just learning so let's write our own.
sub sum (@list) {
    my $total = 0;
    $total += $_ for @list;
    return $total;
}

sub mean (@list) {
    return @list ? sum(@list) / @list : undef;
}

say "input array is: @ARGV";
say "sum is: ", sum(@ARGV);
say "mean is: ", mean(@ARGV);
say "median is: ", median(@ARGV);
say "input array is: @ARGV (just making sure it did not change)";

Demonstration of Basic Features

This script attempts to walk you through some very basic elements of the language. For a better tutorial, see perlintro.

basics.pl
# Illustration of Perl basics

use v5.40;

# Variables can be scalars, arrays or hashes. Hash is the Perl word for
# associative array, dictionary, or map. There are no type names in
# declarations. Introduce new names with the my keyword. (Perl also has
# a keyword called local, but you should really avoid it.)
my $x = 8;
my $y = $x * 2;
my @animals = ('cow', 'pig', 'horse', 'beetle', 'whale');
my %numbers = ('один' => 1, 'два' => 2, 'три' => 3);

# Assignments.
$x = 85.2E13;
$x = $x * 3 + 2 / 21;
$x = "Another string";
$x = 883;

# Strings can be in apostrophes ("single-quotes") or quotation marks
# ("double quotes"), but only double quotes interpolate escape characters
# and variables.
say 'The answer is \t $x';  # The answer is \t $x
say "The answer is \t $x";  # The answer is    883

# You can say multiple things and they will be joined with the value of
# the special variable $,, which is the print separator. By default it
# is the empty string, but it can be changed. If you change it to a space,
# you won't have to always remember to get spaces correct in your string
# literals and between arguments.
say "$x cubed is ", $x ** 3;  # That space was important!
$, = " ";
say "$x cubed is", $x ** 3;  # Yay, no space needed!

# Index arrays with [], get the index of the last element with #, and
# and get the length of the array by using it in a "scalar context".
# Array "indexing" can also make slices!
my @stuff = (2.5, "cat", 2, 'dog', 'bear', 100);
say "The array is @stuff";
say "The first element is $stuff[0]";
say "The second element is $stuff[1]";
say "The last index is $#stuff";
say "The last element is $stuff[$#stuff]";
$x = @stuff;
say "The length of the array is $x";
say "Yep, it is six" if @stuff == 6;
say "Slicing items: @stuff[1, 3, 5]";
say "Here is a slice with a range (it's inclusive): @stuff[2..4]";

# Access values of hashes with {}. By the way, you can't interpolate
# a hash directly into a string, so you have to print it separately.
# But notice that it just prints as a big list of keys and values!
say "Here is a hash:", %numbers;
say "Lookup: $numbers{'два'}";
$numbers{'четыри'} = 4;
say "It is now:", %numbers;
say "You cannot interpolate a hash, this is wrong: %numbers";

# Here is a simple function.
sub average($a, $b) {
    return ($a + $b) / 2;
}
say "The average of 2 and 5 is", average(2, 5);

# You can write functions without mentioning the parameters and access them
# via the special array @_.
sub ave {
    return ($_[0] + $_[1]) / 2;
}
say "The average of 2 and 5 is", ave(2, 5);

# This is because all the arguments to a function get passed in as one
# gigantic flattened list, means that if you have an "array parameter",
# it has to show up last, otherwise the compiler will reject your code.
sub parameter_check($a, $b, @c) {
    say "The first parameter is $a";
    say "The second parameter is $b";
    say "The third parameter is @c";
}
parameter_check(1, (2, 3, 4, 5), 6);  # YIKES: a=1, b=2

# So how do you pass an array as its own thing to a function? You can pass
# a *reference* to the array, which is a scalar that points to the array.
sub array_ref_example($x, $array_ref, $y) {
    say "Parameters are $x, $array_ref, and $y";
}
my @arg = (1, 2, 3);
array_ref_example(100, \@arg, 200);

# Ok good, so we make a reference with the backslash, but how to we dereference
# a reference? You just have to just dereference it with the proper sigil.
my $dog = 'Lisichka';
my $dog_ref = \$dog;
say "For $dog, the ref is $dog_ref, dereferenced back to $$dog_ref";
my @friends = ('cat', 'pig', 'horse');
my $friends_ref = \@friends;
say "For @friends, the ref is $friends_ref, dereferenced back to @$friends_ref";
my %capitals = ('CA' => 'Sacramento', 'HI' => 'Honolulu', 'OR' => 'Salem');
my $capitals_ref = \%capitals;
say "For %capitals, the ref is $capitals_ref, dereferenced back to %$capitals_ref";

# But if you are dereferencing a pointer to an array or hash then immediately
# digging into it, the preferred way is to use the arrow operator (->).
say "Not", @$friends_ref[1], "but", $friends_ref->[1];
say "Not", @$capitals_ref{'HI'}, "but", $capitals_ref->{'HI'};

# Remember how hashes only print as a big list? Well, Data::Dumper can help.
# Since you are calling a function to do the dumping, passing in the hash
# directly would pass the keys and values in a big list. So, you pass in a
# reference to the hash! Make sense?
use Data::Dumper;
$Data::Dumper::Terse = 1;
say Dumper(\%numbers);

# You can't assign a function to a variable directly, but you can assign
# a reference to a function. Functions really should have the "&" sigil but
# you generally leave it off. EXCEPT when you are making a reference to a
# named function!
sub add_five($x) { return $x + 5; }
my $five_more = \&add_five;

# It is common to pass function references as parameters to other functions.
# (You have to pass a reference. You can not directly pass a function, just
# like you can't directly assign a function.)
sub twice($f, $x) { return $f->($f->($x)); }
say "Adding five twice to 3 is", twice(\&add_five, 3);
say "Adding five twice to 13 is", twice($five_more, 13);

# You can pass functions anonymously. When you do, it is super common
# to access the parameters with $_[0], $_[1], etc. Also, the anonymous
# function expression is automatically a reference, so you don't need the
# backslash to make the reference. (But the reference is there, so make
# sure to use -> to use the function.)
say "Adding five twice to 2 is", twice(sub { $_[0] + 5 }, 2);
say "Squaring 256 twice is", twice(sub { $_[0] ** 2 }, 256);

Types

Perl has various kinds of types, including:

You can only make variables of the first three types.

Names for scalars start with $, arrays with @, hashes with %, subroutines with &, and typeglobs with *. The others just start with letters, so be careful to not confuse them with keywords.

Declarations

A declaration can go anywhere a statement can go. Declarations can be scoped with my, our, or local.

ourmylocal.pl
use v5.40;

our $x = 1;
our $y = 101;
our $z = 201;

sub g {
    say "Entering g";
    say "In g, x = $x and y = $y and z = $z";
    say "Leaving g";
}

sub f {
    say "Entering f";
    my $x = 2;
    local $y = 102;
    $z = 202;
    say "In f, assigned my x = $x and local y = $y and z = $z";
    g();
    say "Leaving f";
}

say "Initially globals x = $x and y = $y and z = $z";
f();
say "Finally globals x = $x and y = $y and z = $z";

Statements

A Perl statement is either an expression (possibly with a modifier) or an if, unless, while, until, or for statement.

SimpleStmt
  ← Exp Modifier?

Modifier
  ← "if" Exp
  | "unless" Exp
  | "while" Exp
  | "until" Exp
  | ("for" | "foreach") List

CompoundStmt
  ← "if" "(" Exp ")" Block ("elsif" "(" Exp ")" Block)* ("else" Block)?
  | "unless" "(" Exp ")" Block ("elsif" "(" Exp ")" Block)* ("else" Block)?
  | Label? "while" "(" Exp ")" Block ("continue" Block)?
  | Label? "until" "(" Exp ")" Block ("continue" Block)?
  | Label? ("for" | "foreach") "(" Exp ';' Exp ';' Exp ")" Block
  | Label? ("for" | "foreach") Var? "(" List ")" ("continue" Block)?

Operators

Here are the Perl operators, presented from highest to lowest precedence.

Operator(s)AssociativityComments
Terms No Variables, quote and quote-like operators, parenthesized expressions, subroutine or operator call with parenthesized args, [] constructor, {} constructor, do{}, eval{}, sub{}
->
Left Infix dereference
++  --
No Increment, decrement
**
Right Exponentiation
!  ~  \  +  -
Right Unary prefix operators: logical not, bitwise complement, reference creator, unary plus, unary negation
=~  !~
Left Binding (binds a string to a pattern match, substitution, or transliteration).
*  /  %  x
Left multiply, divide, modulo, string repetition
+  -  .
Left numeric add, numeric subtract, string concatenation
<<  >>
Left bitwise shifts
Named unary operators Right There are around 75 of these, including the 27 filetest operators. Examples: chdir, exists, length, scalar, sin, sqrt. Make your own by using the ($) prototype.
<  <=  >  >=
lt  gt  le  ge
No less-than, less-than-or-equal, greater-than, greater-than-or-equal
==  !=  <=>
eq, ne, cmp
No equal-to, not-equal-to, compare
&
Left bitwise-and
|  ^
Left bitwise-or, bitwise-xor
&&
Left logical-short-circuit-and
||
Left logical-short-circuit-or
.. ...
No Range operators
?: Right conditional
=  **=  +=  -=  .=
*=  /=  %=  x=
&=  |=  ^=
<<=  >>=  &&=  ||=
Right assignment
,  =>
Left comma
List operators Right Basically, these are the functions that aren’t explicitly named unary operators.
not
Right Logical negation
and
Left logical-short-circuit-and
or  xor
Left logical-short-circuit-or, logical xor

Built-in Functions

Perl has a couple hundred functions (you can call them operators, too) that aren’t part of any package. They are:

Scalars chomp, chop, chr, crypt, hex, index, lc, lcfirst, length, oct, ord, pack, q/STRING/, qq/STRING/, reverse, rindex, sprintf, substr, tr///, uc, ucfirst, y///
Regexs/pattern matching m//, pos, quotemeta, s///, split, study, qr//
Numerics abs, atan2, cos, exp, hex, int, log, oct, rand, sin, sqrt, srand
For real @ARRAYs pop, push, shift, splice, unshift
For list data grep, join, map, qw/STRING/, reverse, sort, unpack
%HASHes delete, each, exists, keys, values
Input and output binmode, close, closedir, dbmclose, dbmopen, die, eof, fileno, flock, format, getc, print, printf, read, readdir, rewinddir, seek, seekdir, select, syscall, sysread, sysseek, syswrite, tell, telldir, truncate, warn, write
Fixed length data pack, read, syscall, sysread, syswrite, unpack, vec
Filehandles, files, directories -X, chdir, chmod, chown, chroot, fcntl, glob, ioctl, link, lstat, mkdir, open, opendir, readlink, rename, rmdir, stat, symlink, sysopen, umask, unlink, utime
Control flow caller, continue, die, do, dump, eval, exit, goto, last, next, redo, return, sub, wantarray
Scoping caller, import, local, my, our, package, use
Miscellaneous defined, dump, eval, formline, local, my, our, reset, scalar, undef, wantarray
Processes and process groups alarm, exec, fork, getpgrp, getppid, getpriority, kill, pipe, qx/STRING/, setpgrp, setpriority, sleep, system, times, wait, waitpid
Modules do, import, no, package, require, use
Classes and OOP bless, dbmclose, dbmopen, package, ref, tie, tied, untie, use
Sockets accept, bind, connect, getpeername, getsockname, getsockopt, listen, recv, send, setsockopt, shutdown, socket, socketpair
System V IPC msgctl, msgget, msgrcv, msgsnd, semctl, semget, semop, shmctl, shmget, shmread, shmwrite
User and group endgrent, endhostent, endnetent, endpwent, getgrent, getgrgid, getgrnam, getlogin, getpwent, getpwnam, getpwuid, setgrent, setpwent
Networking endprotoent, endservent, gethostbyaddr, gethostbyname, gethostent, getnetbyaddr, getnetbyname, getnetent, getprotobyname, getprotobynumber, getprotoent, getservbyname, getservbyport, getservent, sethostent, setnetent, setprotoent, setservent
Time gmtime, localtime, time, times

Note: If you’re the type that doesn’t use a lot of parentheses, then you need to remember which of these are list operators and which of these are true unary operators! Good luck!

Predefined Variables

See http://perldoc.perl.org/perlvar.html for the complete list.

Packages

Perl has pacakges for namespace control, and some nice syntax to make object oriented programming look pleasant.

packagedemo.pl
$x = 1;

package A;
$x = 2;

package B;
$x = 3;
print "$x\n";
print "$A::x\n";
print "$B::x\n";
print "$main::x\n";
print "$C::x\n";

package A;
$x = 7;
$B::y = 12;
sub f {print "The f in A\n";}
sub g {print "(", scalar(@_), " args) ", "@_\n";}

package B;
print "$y\n";
A::f();

package main;
print "$x\n";
A::g();
A::g(100);
A::g(1, 2, 3);
A->g();
A->g(100);
A->g(1, 2, 3);

package C;
A->g(100);

package A;
$y = {name=>"alice", age=>21};
print "$y\n";
print "%$y\n";
bless $y, "A";
print "$y\n";
print "%$y\n";
%x = %$y;
print "$x{name}\n";
g($y);
$y->g();
$y->g(400);
g();

package B;
print "%$A::y\n";
$A::y->g(100);
A->g(100);
g A(100);
g A;
A->g;

Modules

Modules allow for separate compilation. Keep the package names in sync with the file names and it all works out.

Trig.pm
# Trig.pm
#
# Just illustrates how to write a simple module.  Note this
# doesn't "export" anything, so all users have to qualify
# names.

use warnings;

package Trig;

$pi = atan2(1,1) * 4;

sub tan {
    sin($_[0]) / cos($_[0]);
}

sub circle_area {
    my $radius = shift;
    return $pi * $radius * $radius;
}

1;

To use...

frustum.pl
# This little script calculates frustum parameters given
# a vertical field of view and an aspect ratio.  The only
# reason I wrote this is to show how to use a user-defined
# module.

use Trig;

print "Did you know pi was about $Trig::pi?\n";

# Given: fovy, depth, aspect.
# Returns width, height.

sub frustum {
    my ($fovy, $depth, $aspect) = @_;
    my $height = (2 * $depth) * Trig::tan($fovy / 2);
    my $width = $aspect * $height;
    return ($width, $height);
}

$, = ",";
print frustum($Trig::pi/2, 10, 2);
print "\n";

More fun stuff with modules: BEGIN, END, AUTOLOAD. Privacy? Well you can’t stop other people from inserting names into your package’s namespace, but you can use "my" to "hide" variables and subroutine references.

Standard Modules

The "standard" ones are listed at http://perldoc.perl.org/perlmodlib.html but there are many others that have been contributed; see http://www.perl.com/CPAN/modules/00modlist.long.html.

Object Orientation

Perl’s OOP is based on the idea that

This example barely scratches the surface of what you can, and should, do:

animals.pl
# Very small, but classic, OOP demo.

use strict;
use warnings;

#
# Abstract base class.  Create animals of any subclass by calling
# new with the animal's name.  There is a speak method which delgates
# to the subclass-supplied sound subroutine.
#

package Animal;
sub new {
    my ($class, $name) = @_;            # first parameter is class name
    my $animal = {name => $name};       # representation is a hash
    bless $animal, $class;              # "tags" (blesses) the hash
    return $animal;                     # constructors return object refs
}

sub speak {
    my $self = shift;
    print $self->{name}, " says ", $self->sound(), "\n";
}

#
# Subclasses.
#

package Cow;
@Cow::ISA = qw(Animal);
sub sound { "moooo" }

package Horse;
@Horse::ISA = qw(Animal);
sub sound { "neigh" }

package Sheep;
@Sheep::ISA = qw(Animal);
sub sound { "baaaaa" }

#
# Illustration of use, showing the variety of styles one can
# use make an animal and tell it to speak.
#

package main;
my $s = Horse->new("CJ");               # The usual way to call "constructor"
$s->speak;                              # dispatches perfectly - see why?

my $c = new Cow "Bessie";               # Funny syntax to make C++ folks happy
$c->speak();

my $h = new Sheep("Little Lamb");       # In case you love parens
Animal::speak($h);                      # Works, but verbose and uncommon

Tutorials and references at perl.org: Beginner’s OO Tutorial, Tom’s OO Tutorial, Tom’s OO Tutorial for Class Data, and Reference page on Perl objects.

Miscellany

These notes are in no way meant to be complete. We barely got started! Here are a few things not covered in these notes: