Variables, Sigils, and Basic Syntax
Perl has three primary variable types distinguished by sigil: scalars ($name) hold a single value (number, string, or reference), arrays (@list) hold an ordered sequence accessed by index starting at 0, and hashes (%map) hold unordered key-value pairs. Note that when accessing a single element, the sigil changes to $ regardless of the container type: $list[0] for an array element and $map{key} for a hash value, because you are retrieving one scalar value. Every script should begin with use strict; use warnings; and variables should be declared with my at their first use. Statements end with a semicolon, blocks are delimited with curly braces, and comments start with #. String interpolation happens automatically inside double quotes ("Hello, $name") but not inside single quotes ('Hello, $name' prints literally).
Cricket analogy: The three sigils are like three types of scoreboard entries: $scalar is a single player's current score, @array is the full over-by-over ball log, and %hash is a lookup table of player name to total runs.
Control Flow and Loops
Perl supports the familiar if/elsif/else, unless (the negated form of if, best reserved for simple guard clauses), while, until, for (C-style three-part), and foreach (iterating over a list, often abbreviated for). Postfix conditionals are idiomatic for short statements: print "error\n" if $status != 200; reads naturally and avoids an extra block. Loop control uses next to skip to the next iteration and last to break out entirely, both of which can target labeled outer loops (OUTER: for my $i (...) { ... next OUTER; }) for cleanly escaping nested loops without a flag variable. The ternary operator condition ? true_val : false_val is fully supported and commonly used for concise inline assignment.
Cricket analogy: A postfix conditional like 'print "six!" if $runs == 6;' is like a commentator's terse call, saying only what's needed exactly when the condition is met, no elaborate windup.
Regular Expressions and String Functions
Matching uses $str =~ /pattern/, substitution uses $str =~ s/pattern/replacement/, and the g modifier makes either operation apply globally rather than stopping at the first match. Common modifiers include i (case-insensitive), m (multiline, so ^ and $ match at line boundaries), s (dot matches newline), and x (extended, allowing whitespace and comments in the pattern for readability). Useful built-in string functions include split(/,/, $csv_line) to break a string into a list, join(', ', @items) to do the reverse, sprintf("%05d", $n) for formatted output, length($str), substr($str, 0, 3), uc()/lc() for case conversion, and index($str, $needle) for finding a substring position. For array manipulation, push/pop operate on the end and shift/unshift operate on the beginning, while map and grep provide functional-style transformation and filtering over lists.
Cricket analogy: The /g global modifier is like reviewing every ball of an entire match for a specific event (like a six) instead of stopping analysis after finding the first one.
Use the x extended regex modifier for any pattern more complex than a few characters -- it allows whitespace and # comments inside the pattern, turning an unreadable wall of symbols into a self-documenting block, e.g. /^(?<year>\d{4}) - (?<month>\d{2})/x.
Never use the deprecated two-argument form of open (open(FH, "file.txt")) -- always use the three-argument form with a lexical filehandle and explicit mode: open(my $fh, '<', 'file.txt') or die $!;. The two-argument form is vulnerable to filename injection and shell metacharacter interpretation.
use strict;
use warnings;
my @nums = (4, 8, 15, 16, 23, 42);
# map + grep functional idiom
my @doubled_evens = map { $_ * 2 } grep { $_ % 2 == 0 } @nums;
print "@doubled_evens\n"; # 8 16 32 84
# hash + string functions
my %inventory = (apples => 10, bananas => 5);
for my $item (sort keys %inventory) {
printf("%-10s %3d\n", $item, $inventory{$item});
}
# regex substitution with capture reuse
my $date = "2026-07-10";
$date =~ s/(\d{4})-(\d{2})-(\d{2})/$3\/$2\/$1/;
print "$date\n"; # 10/07/2026- Sigils indicate container type: $scalar, @array, %hash; single-element access always uses $.
- Always begin scripts with use strict; use warnings; and declare variables with my.
- Postfix conditionals and the ternary operator provide concise inline control flow.
- next and last (optionally with loop labels) control iteration; unless is the negated form of if.
- Regex modifiers /g, /i, /m, /s, and /x change matching behavior; /x enables readable, commented patterns.
- split/join, sprintf, substr, and map/grep are core tools for string and list manipulation.
- Always use the three-argument form of open with a lexical filehandle for safety.
Practice what you learned
1. What sigil is used to access a single element of an array, e.g. the first element of @list?
2. Which regex modifier allows whitespace and # comments to be embedded inside a pattern for readability?
3. What is the recommended, safe way to open a file in modern Perl?
4. Which two functions together provide list transformation and filtering in a functional style?
5. What does the loop control keyword 'next' do inside a loop?
Was this page helpful?
You May Also Like
Modern Perl Best Practices
A guide to writing clean, safe, and maintainable Perl using strict, warnings, modern object systems, and idiomatic patterns favored in current Perl codebases.
Perl vs Python
A practical comparison of Perl and Python covering syntax philosophy, text processing, and ecosystem tooling to help you choose the right tool for a scripting task.
Building a Log Parser in Perl
A hands-on walkthrough of building a robust Perl log parser that reads, matches, aggregates, and reports on structured log data using core Perl idioms.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics