Perl Tutorial
Learn Perl step by step: 43 lessons in 13 chapters with examples, quizzes, diagrams and projects.
Start learning →
of lessons completed
Getting Started
- What Is Perl? Meet Perl, the practical scripting language built for text processing and glue code: its history, strengths, CPAN, the TMTOWTDI motto, and where Perl is used today.
- Installing and Running Perl Install Perl with Strawberry Perl, your package manager or perlbrew, then run code with perl -e, script files and the shebang line, and read docs with perldoc.
- Your First Perl Program Write and run your first Perl program: print and say, comments, statements and semicolons, quotes and escapes, plus the errors beginners meet first.
- use strict and use warnings Learn why every Perl program starts with use strict and use warnings: typos, undeclared variables and bad numbers are caught early. Includes use v5.40 boilerplate.
Scalars and Operators
- Scalar Variables Learn Perl scalar variables: the $ sigil, my declarations, numbers and strings, undef, string interpolation, q and qq quoting, here-docs and naming rules.
- Working with Strings Work with Perl strings: length, substr (including 4-argument and lvalue forms), index, uc and lc, the x operator, join, reverse, sprintf, chomp and chop.
- Operators and Numbers Learn Perl operators: arithmetic, == versus eq, <=> versus cmp, logical and defined-or, ranges, string increment, and how numbers are written and printed.
- Context: Scalar vs List Understand Perl context: how the same expression returns different results in scalar and list context, wantarray, arrays as counts, and the common surprises.
Arrays and Hashes
- Arrays Learn Perl arrays: creating lists with qw, zero-based and negative indexing, $#array, push, pop, shift, unshift, splice, slices and looping with foreach.
- List Functions and Sorting Learn Perl's list functions: map, grep, sort with custom comparisons, the Schwartzian transform, reverse, join and the List::Util helpers first, sum, max and uniq.
- Hashes Learn Perl hashes: key/value pairs, exists and delete, keys, values and each, hash slices, counting words, and how a hash behaves in list context.
- Hash Patterns Learn the hash idioms every Perl programmer uses: frequency tables, grouping with array refs, inverting, sets, removing duplicates, sorting by value and key order.
- Dates and Times Work with dates and times in Perl: time, localtime, gmtime, POSIX strftime, Time::Piece, Time::Local, and when to reach for the DateTime module.
Control Flow
- Conditionals Learn how Perl makes decisions with if, elsif, else, unless, the ternary operator and statement modifiers, and which values Perl treats as true or false.
- Loops and Loop Control Repeat work in Perl with for, foreach, while and until, control loops with last, next, redo and labels, and avoid the do-while trap.
Subroutines
- Subroutines Write reusable Perl subroutines: how sub, @_ and return work, why arguments are aliases, modern signatures with default values, and wantarray.
- Scope, Closures and Recursion Understand Perl variable scope with my, our, local and state, build closures and counters, write recursive subs, and use dispatch tables.
Regular Expressions
- Regular Expressions Basics Start with Perl regular expressions: the m// operator, the =~ binding, metacharacters, character classes, quantifiers, anchors, alternation and lazy matching.
- Captures and Modifiers Pull data out of text with Perl regex capture groups, $1, named captures in %+, list-context matching, global matches with pos, and the /i /g /m /s /x modifiers.
- Substitution and Transliteration Rewrite text in Perl with s///, the /g /e /r modifiers, tr/// character mapping and counting, split and join with regex, plus real-world cleanups.
- Advanced Regex Go beyond the basics in Perl regex: lookahead and lookbehind, backreferences, possessive quantifiers, recursion, qr// objects and how to avoid slow patterns.
Files and I/O
- Reading and Writing Files Read and write files in Perl the safe way: three-argument open, lexical filehandles, die on failure, the diamond operator, chomp, append mode and UTF-8 layers.
- Directories and File Tests Check files with -e -f -d -s, list folders with opendir and glob, walk trees with File::Find, and handle paths portably with File::Spec, File::Basename and Path::Tiny.
- Text Processing Idioms Write compact Perl text filters: the default variable $_, while(<>) loops, -n and -p switches, field splitting, formatted reports with printf, and here-docs.
References and Data
- References Learn Perl references: the backslash operator, arrow dereferencing, array, hash and code refs, ref(), anonymous structures, autovivification and weak references.
- Nested Data Structures Build and walk nested Perl data: arrays of hashes, hashes of arrays, deep copies with Storable, debugging with Data::Dumper and JSON::PP encode and decode.
Modules and Errors
- Packages and Modules Organize Perl code with packages and modules: use versus require, the @INC search path, Exporter, writing your own .pm file and a tour of useful core modules.
- CPAN and Dependency Management Install and manage Perl dependencies: CPAN, cpanm, cpanfile, Carton, local::lib and perlbrew, plus how to judge module quality using MetaCPAN.
- Errors, die and eval Handle errors in Perl with die and warn, trap them with eval, avoid the $@ pitfalls, throw exception objects, and use Try::Tiny, try/catch and Carp.
- CGI and Web Scripts Learn how Perl CGI scripts work: the request-response cycle, environment variables, headers, parsing GET and POST data by hand, escaping output and modern alternatives.
Object-Oriented Perl
- Classes and Objects Learn object-oriented Perl from scratch: packages as classes, bless, constructors, instance and class methods, accessors, SUPER::, DESTROY and common pitfalls.
- Inheritance, Roles and Moo Learn Perl inheritance with use parent and @ISA, method resolution order, can/isa/DOES, roles, Moo and Moose attributes, and the new class feature.
Tools and Quality
- Testing with Test::More Write Perl tests with Test::More: ok, is, is_deeply, plans, subtests, .t files, prove, mocking with local, a look at Test2, and coverage with Devel::Cover.
- Perl One-Liners Learn Perl one-liners: the -e, -n, -p, -i, -l, -a and -F flags, in-place edits, practical text recipes, and how they compare with sed and awk.
- Performance and Profiling Make Perl code faster the right way: measure with Benchmark, profile with Devel::NYTProf, avoid string copies, tame regexes, pick hashes or arrays, and save memory.
- Security and Safe Perl Write safer Perl: taint mode, avoiding shell injection, three-argument open, DBI placeholders, encoding pitfalls, handling secrets and vetting CPAN modules.
Projects
- Project: Log Analyzer Build a Perl log analyzer step by step: parse access log lines with a regex, count requests by status, IP and path, and print a top-N report.
- Project: CSV Report Generator Build a Perl report generator: read a CSV with Text::CSV, validate rows, group and total sales by region, print an aligned table and handle bad data.
- Project: Batch File Renamer Build a safe batch file renamer in Perl: glob files, rename them with a regex, parse options with Getopt::Long, add a dry-run mode and refuse to overwrite.
- Project: Link Checker and Scraper Build a polite Perl link checker: fetch a page with HTTP::Tiny, parse links with Mojo::DOM, honor robots.txt, rate-limit requests and test the pure parts.
Practice and Review
- Practice Exercises with Solutions Practice Perl with 25 graded exercises on scalars, lists, hashes, regex, files, references and subroutines. Every exercise has a tested solution.
- Perl Interview Questions Prepare for a Perl interview: context, my vs local, references, closures, regex, OOP, CPAN and classic pitfalls, each with a clear answer and tested code.
- Perl Cheat Sheet A compact Perl cheat sheet: variables, operators, special variables, regex, file I/O, references, sprintf formats, one-liner flags and everyday modules.