Perl Tutorial for Beginners

A hands-on tour of Perl 5: scalars, arrays, hashes, context, control flow, and subroutines — everything you need to read and write real Perl.

  • perl
  • tutorial
  • beginner
  • perlretut

This is a practical tour of the core language. By the end you’ll be able to read most Perl you encounter and write useful programs of your own. Every example assumes use strict; and use warnings; at the top.

Scalars

A scalar holds a single value — a number or a string. Perl converts between them as needed.

my $count    = 42;
my $greeting = "hello";
my $total    = $count + 8;      # 50
my $shout    = $greeting . "!"; # "hello!" (. joins strings)

Arrays and lists

An array is an ordered list of scalars:

my @fruits = ("apple", "banana", "cherry");
print $fruits[0];      # apple (indexing uses $)
push @fruits, "date";  # add to the end
my $n = @fruits;       # 4 (an array in scalar context gives its length)

Useful list tools:

my @sorted = sort @fruits;
my @upper  = map { uc } @fruits;              # transform each element
my @long   = grep { length($_) > 5 } @fruits; # keep some elements

Hashes

A hash maps keys to values — an unordered lookup table:

my %price = (apple => 1.20, banana => 0.50);
print $price{apple};        # 1.20 (lookup uses $)
$price{cherry} = 3.00;      # add a pair
my @items = keys %price;    # the keys
if (exists $price{banana}) { ... }

Context: the idea that unlocks Perl

Perl evaluates expressions in either list or scalar context, and many things behave differently in each. The classic example is an array: in list context it’s its elements; in scalar context it’s its length.

my @list = (10, 20, 30);
my $len = @list;        # scalar context -> 3
my ($first) = @list;    # list context -> 10

Once context clicks, a lot of Perl’s “magic” becomes predictable.

Control flow

if ($x > 10)   { print "big\n"; }
elsif ($x > 5) { print "medium\n"; }
else           { print "small\n"; }

while ($n > 0) { $n--; }

for my $i (1..5) { print "$i\n"; }        # 1 through 5
foreach my $fruit (@fruits) { print "$fruit\n"; }

Perl also has handy statement modifiers:

print "$_\n" for @fruits;
say "found it" if $found;   # `say` needs: use feature 'say';

Subroutines

use feature 'say';

sub greet {
    my ($name) = @_;   # arguments arrive in @_
    return "Hello, $name!";
}

say greet("Ada");   # Hello, Ada!

A first taste of regular expressions

Regexes are one of Perl’s superpowers — covered fully in Regular Expressions in Perl:

my $line = "order 4821 shipped";
if ($line =~ /(\d+)/) {
    print "id is $1\n";   # id is 4821
}

Where to go next

Build something runnable in Writing Your First Perl Script, then learn to read and write files in Working with Files and I/O.