The language that reads text for a living
A great deal of computing is about text. Log files from web servers, CSV exports from spreadsheets, configuration files, DNA sequences, email, the output of one command that must become the input of another. Someone has to read those lines, pick out the interesting parts, count, compare and rearrange them, and write a report.
In 1987 a programmer and linguist named Larry Wall was doing exactly that kind of work on Unix machines, and found that the tools he had did not fit. The shell was good at gluing commands together but clumsy with data. awk and sed were good with lines of text but limited as programming languages. C could do anything but took a page of code to do what felt like one line of work. So he wrote a new language that borrowed from all of them, and called it Perl.
Perl's sweet spot is still the same: programs of ten to a few thousand lines that read text, transform it and write it out, often run from a terminal, a scheduled job or a build script. It is rarely the language people choose for a new mobile app or a game. But it is installed on almost every Linux and macOS machine, it is very fast at text processing, and an enormous amount of working software is written in it. You will meet it:
- In system administration and tooling. Scripts that rotate logs, audit servers and glue systems together. The Linux kernel's
scripts/checkpatch.pl, which checks every proposed patch for style problems, is Perl, as aregit send-emailand GNU Automake. - In bioinformatics. In the 1990s Perl became the everyday language of genome researchers, who needed to slice and match very long strings of DNA letters. The BioPerl project and many lab pipelines still use it.
- In text processing everywhere. Perl's regular expressions became the model most other languages copied; "Perl-compatible regular expressions" (PCRE) are a library used by many other tools.
- In long-lived web applications. Perl powered much of the early dynamic web. Bugzilla and the Request Tracker ticket system are Perl, and some large companies still run big Perl codebases in production.
If you have heard that Perl is "write-only" (easy to write, impossible to read), that reputation comes from code written without discipline. Perl gives you many ways to say the same thing, and it is your job to choose the clear one. This course teaches the clear one, and shows you the terse forms you will meet in other people's code so they do not surprise you.
From Perl 1 to Perl 5, and Raku
Larry Wall released Perl 1.0 in December 1987. Version 2 (1988) brought a better regular expression engine, version 3 (1989) could handle binary data, and Perl 4 (1991) came out alongside the first edition of the book Programming Perl, known from its cover as the "Camel book".
Perl 5 (1994) was nearly a rewrite. It added the things that make Perl a language for large programs: references (so data structures can nest), modules and packages, and objects. In 1995 the CPAN, the Comprehensive Perl Archive Network, opened as a shared, mirrored archive of reusable modules. It was one of the first language package repositories of its kind and inspired many later ones.
In 2000 the community began designing Perl 6, a clean break meant to fix the language's oldest mistakes. That project took many years and produced a genuinely different language. In 2019 it was renamed Raku to make that clear. Raku is interesting and has its own website (raku.org), its own compiler (Rakudo) and its own community, but it is not the next version of Perl, and Perl 5 code does not run on it. When people say "Perl" today they mean Perl 5, and that is what this course teaches.
Perl 5 itself kept moving. Since 2010 a new stable version has appeared roughly once a year, numbered with even minor versions: 5.12, 5.14, and so on (odd numbers are development releases). Some milestones you will see mentioned:
| Version | Year | What it added that you will use |
|---|---|---|
| 5.10 | 2007 | say, the defined-or operator //, named regex captures |
| 5.24 | 2016 | postfix dereferencing such as $ref->@*, stable |
| 5.34 | 2021 | an experimental try/catch |
| 5.36 | 2022 | subroutine signatures stable; use v5.36 also switches on warnings |
| 5.38 | 2023 | an experimental class feature for object-oriented code |
| 5.40 | 2024 | try/catch declared stable |
The checked programs in this course were run with Perl 5.34, still the system Perl on many long-term-support Linux servers, and they also run on every newer Perl. Where a newer release makes something nicer, the lesson shows that too and names the version.
Perl has no separate written standard. The perl interpreter is the definition of the language, and its documentation, which ships with every installation, describes it. The development community is called p5p (the perl5-porters), and the Perl and Raku Foundation supports both languages.
Getting perl, and reading its manual
Check what you have. Open a terminal and type:
perl -v # the version, e.g. "This is perl 5, version 34"
perl -V # how it was built and where it looks for modules
which perl # where the program livesOn Linux and macOS you almost certainly have Perl already, because the operating system's own tools use it. That system Perl belongs to the operating system: it is fine for learning and for small scripts, but professionals avoid installing modules into it, because an upgrade of the operating system can change or break it.
Getting your own Perl. The page perl.org/get.html lists the official routes:
- On Linux or macOS, perlbrew (or the similar plenv) builds and installs any Perl version inside your home directory and lets you switch between them.
- On Windows, Strawberry Perl is a complete distribution that includes a C compiler, so modules that need compiling install smoothly.
- With Docker, the official
perlimage gives you a recent Perl without installing anything.
Reading the manual. Perl's documentation comes with Perl. It is written in a simple markup called POD (Plain Old Documentation) and read with the perldoc command:
perldoc perlintro # a short tour of the language
perldoc -f split # one built-in function
perldoc -v '$_' # one special variable
perldoc List::Util # a module's documentation
perldoc -q "sort a hash" # search the FAQThe same pages are on perldoc.perl.org, where you can also choose the version that matches yours. Learning to look things up there is one of the most useful habits you can build; experienced Perl programmers use perldoc -f every day.
Definition— Script, interpreter and compilation
A Perl program is a plain text file, by convention ending in .pl (scripts) or .pm (modules). The perl program reads the whole file, compiles it into an internal tree of operations, and then runs that tree. Because the whole file is compiled first, a syntax error anywhere stops the program before any of it runs. There is no separate build step for you to run.
A first script
Save this as hello.pl and run it with perl hello.pl:
#!/usr/bin/env perl
use strict;
use warnings;
use feature qw(say);
# A first Perl program. Run it with: perl hello.pl
my $name = 'Ngozi';
my $born = 1987;
my $age = 2026 - $born;
say "Hello, $name!";
say "Perl appeared in $born, so in 2026 it turns $age.";
say 'Single quotes keep $name as it is.';
print "print needs its own newline\n";
say "Joined with a dot: " . uc($name) . "!";
printf "%s has %d letters; %.1f%% are vowels.\n", $name, length $name, 2 / 5 * 100;
say "Perl ", $^V, " is running this.";It printed:
Hello, Ngozi!
Perl appeared in 1987, so in 2026 it turns 39.
Single quotes keep $name as it is.
print needs its own newline
Joined with a dot: NGOZI!
Ngozi has 5 letters; 40.0% are vowels.
Perl v5.34.0 is running this.The last line will show your own version. Now line by line:
- The first line,
#!/usr/bin/env perl, is a shebang. Perl ignores it, but on Unix it lets you make the file executable (chmod +x hello.pl) and run it as./hello.pl. use strict;anduse warnings;switch on two safety nets. The next section shows exactly what they catch. Treat them as part of every script.use feature qw(say);turns onsay, which isprintwith a newline added. It is off by default only because old programs might have their own function calledsay.qw(...)means "quote words": a list of strings written without quotes or commas.my $name = 'Ngozi';declares a variable. The$is a sigil, a symbol that says what kind of variable it is:$for a single value (a scalar). The next lesson introduces@for arrays and%for hashes.- Statements end with a semicolon.
#starts a comment that runs to the end of the line. - In a double-quoted string, variables are replaced by their values (this is interpolation) and
\nis a newline. A single-quoted string is taken literally. - The dot
.joins strings. Perl keeps+for numbers only. ucandlengthare built-in functions. Parentheses around arguments are optional when the meaning is clear;length $nameandlength($name)are the same. Use parentheses whenever leaving them out could confuse a reader.printfformats like C's:%sa string,%dan integer,%.1fa number with one decimal place,%%a percent sign.$^Vis one of Perl's special variables: the version of the running perl.
Notice that 2026 - $born worked without any declaration of types. Perl scalars hold strings or numbers, and Perl converts between them as the operator demands. That flexibility is convenient, and the next section shows how warnings keeps it honest.
Why every script starts with strict and warnings
Perl was designed to be forgiving, so that a three-line script would not need ceremony. Without help, it will happily invent a new variable when you mistype a name, and silently treat "12 apples" as the number 12. In a large program those kindnesses hide bugs. Two pragmas (modules that change how the compiler behaves) turn them into errors and warnings.
Example— A typo that strict catches
Here is a script, typo.pl, with a misspelt variable: $totl instead of $total.
my $total = 0;
for my $price (12, 30, 8) {
$totl += $price;
}
print "Total: $total\n";Without use strict, it runs and prints Total: 0. Perl quietly created a global variable called $totl, added the prices to it, and printed the untouched $total. Add use strict; and use warnings; at the top, and Perl refuses to run it at all:
Global symbol "$totl" requires explicit package name (did you forget to declare "my $totl"?) at typo.pl line 5.
Execution of typo.pl aborted due to compilation errors.The bug is found before a single line runs.
use strict makes three rules. Every variable must be declared (usually with my). Strings cannot be used as references to variables by name, an old trick that leads to chaos. And a bare word that is not a known function or file handle is an error rather than a string.
use warnings reports things that are legal but probably wrong, and lets the program continue:
use strict;
use warnings;
my $count = "12 apples";
my $sum = $count + 3;
my $missing;
print "Sum is $sum and missing is '$missing'\n";Saved as main.pl and run, it printed these two warnings on standard error, followed by its normal output:
Argument "12 apples" isn't numeric in addition (+) at main.pl line 4.
Use of uninitialized value $missing in concatenation (.) or string at main.pl line 6.
Sum is 15 and missing is ''Perl took the leading 12 from the string, as promised, but now it tells you that it did. The second warning says $missing was used before anything was stored in it: its value is the special "nothing" value undef, which acts as an empty string or zero.
Misconception
"strict and warnings are for beginners; experts leave them off." It is the other way round. Professional Perl code bases enforce both, often with a linter that rejects any file without them, and most experienced programmers go further, for example by turning certain warnings into fatal errors with use warnings FATAL => 'all'; in tests. On Perl 5.36 or newer, the single line use v5.36; switches on strict, warnings, say and subroutine signatures at once; you will see that line at the top of a lot of modern code. Because this course is checked on Perl 5.34, its programs spell the pieces out instead.
Perl at home: a small report from text
Here is a taste of what Perl is for. The program below reads lines of data, skips comments and blank lines, adds up rainfall per city, and prints a sorted report. The data sits in the same file after the marker __DATA__, and Perl lets the program read it through the special file handle DATA; in real use the lines would come from a file or another program.
use strict;
use warnings;
use feature qw(say);
# Perl's home ground: read lines, pick them apart, add things up.
my %total;
while (my $line = <DATA>) {
chomp $line;
next if $line =~ /^\s*(#|$)/; # skip comments and blank lines
my ($city, $mm) = split /\s*,\s*/, $line;
$total{$city} += $mm;
}
for my $city (sort { $total{$b} <=> $total{$a} } keys %total) {
printf "%-10s %5d mm\n", $city, $total{$city};
}
__DATA__
# city, rainfall in mm for one month
Mumbai, 480
Lagos, 210
Bergen, 190
Mumbai, 310
Bergen, 220
Lima, 1It printed:
Mumbai 790 mm
Bergen 410 mm
Lagos 210 mm
Lima 1 mmMuch of this will be explained properly in later lessons, but you can already read it:
<DATA>reads one line at a time; the loop stops when there are no more.chompremoves the newline from the end of the line.$line =~ /^\s*(#|$)/is a regular expression match: "the line is only spaces, then a#or the end". Regular expressions are built into Perl's syntax, which is a big part of why it is good at this work. A whole lesson is devoted to them.split /\s*,\s*/, $linecuts the line at commas, swallowing any spaces around them.%totalis a hash, a table from keys (city names) to values (totals).$total{$city} += $mmadds to the entry, creating it the first time.sort { $total{$b} <=> $total{$a} } keys %totalsorts the city names by their totals, largest first.
Ten lines of logic, and most of them would look much the same in a program a hundred times larger.
One-liners: Perl on the command line
Perl is also a command-line tool. The -e switch runs code given as an argument:
perl -e 'print "Hello from a one-liner\n"'A few more switches turn Perl into a super-powered sed or awk:
-nwraps your code in a loop over every input line;-pdoes the same and prints each line afterwards.-lremoves the newline from each input line and adds one to each output line.-asplits each line into the array@Fon whitespace ("autosplit").-iedits files in place (-i.bakkeeps a backup copy).
For example, given input lines apple 3, pear 5 and apple 4, this adds up the numbers per fruit:
perl -lane '$t{$F[0]} += $F[1]; END { print "$_ $t{$_}" for sort keys %t }'and prints apple 7 and pear 5. And this replaces every colour with color in a set of files, keeping backups:
perl -pi.bak -e 's/colour/color/g' *.txtOne-liners like these are why many system administrators keep Perl in their toolbox even if they never write a large Perl program. They skip strict for brevity, which is acceptable for a throwaway command and a bad idea for anything you save. The full list of switches is in perlrun.
Note
Perl's motto is "There's more than one way to do it", often abbreviated TMTOWTDI and pronounced "Tim Toady". It is a real design choice: Perl was shaped by a linguist who wanted it to feel like a natural language, with synonyms, idioms and room for personal style. The price is that a team must agree on which way to do it. The Perl community's answer is shared style guides (see perlstyle), a formatter (Perl::Tidy) and a linter (Perl::Critic), which you will meet in the last lessons.
How professionals work with Perl
A few habits separate comfortable Perl programmers from struggling ones, and you can adopt them from the first day:
- Start every file with
use strict; use warnings;(oruse v5.36;on new enough Perls). - Declare variables with
myin the smallest scope that works, usually right where you first assign them. A variable declared inside a loop or block disappears when the block ends. - Look things up.
perldoc -f open,perldoc perlop,perldoc perlvar. Perl's built-ins are many and their details matter. - Prefer clarity over cleverness. Perl will let you write a program as one dense line. Your colleagues, and you in six months, will be grateful if you do not.
- Use your own Perl for serious work, installed with perlbrew, plenv or a container, and keep modules for each project separate. Lesson 7 shows how.
Optional Christian reflection · Laziness, impatience and hubris
A reflection from the Christian tradition that inspires Lumenary Academy. It is not part of the mathematics and you are welcome to skip it.
Larry Wall half-jokingly named three "virtues" of a programmer: laziness (writing tools so you never do the same tedious job twice), impatience (making programs that anticipate what people need), and hubris (writing code you would be proud for others to see). He has also spoken openly about his Christian faith and about how it shaped his hopes for a language that serves people rather than the other way round. Whatever you make of the joke, the underlying idea is a generous one: that the drudgery of work can be lifted from people by careful craft, and that the craft itself should be done well enough to share.
Exercises
1. Getting started with Perl
Warm-upHumanA script starts with use strict; and later, by mistake, assigns to $cuont instead of the declared $count. What happens when you run it?
2. Getting started with Perl
Warm-upComputationalWhat does this program print?
use strict;
use warnings;
use feature qw(say);
my $lang = 'Perl';
my $n = 5;
say "I know $lang " . 'and $n more';
3. Getting started with Perl
CoreComputationalWhat does this program print? Type the line exactly, including spaces.
use strict;
use warnings;
printf "%-6s|%4d|%.2f\n", "ab", 42, 2 / 3;
4. Getting started with Perl
CoreComputationalThis program prints a warning on standard error and then a number on standard output. What number?
use strict;
use warnings;
use feature qw(say);
my $days = "7 days";
my $total = $days + 3;
say $total;
5. Getting started with Perl
CoreComputationalWhat does this program print? It prints two lines; type them separated by a single space.
use strict;
use warnings;
use feature qw(say);
my $word = "camel";
say "The ", uc $word, " has ", length($word), " letters";
print "no newline";
say " here";
6. Getting started with Perl
Warm-upHumanWhich command shows, in your terminal, the documentation for Perl's built-in function split?
7. Getting started with Perl
Warm-upHumanWhich statement about Perl and Raku is accurate?
8. Getting started with Perl
StretchHumanWhich of these statements about perl's command-line switches are true? Choose all that apply.
Further reading and resources
- Getting PerlThe official page listing ways to install Perl on Linux, macOS and Windows.
- perlintroThe official short tour of the language, a good companion to this lesson.
- perlrunEvery command-line switch of the perl program, including -e, -n, -p, -l, -a and -i.
- perlhistThe release history of Perl, with the date of every version.
- strict and warningsWhat use strict forbids, and why. The warnings pragma is documented at perldoc.perl.org/warnings.
- perlbrewA tool to install and switch between several Perl versions in your home directory.