Reading — step 1 of 5
Learn
Perl has a zoo of special variables — short names for built-in functionality. Some core ones:
$_ — the default variable:
for (1..5) {
print "$_\n"; # $_ holds the current item
}
map { $_ * 2 } @nums; # block uses $_ for each item
grep { $_ > 5 } @nums;
Most Perl built-ins fall back to $_ when no argument given.
@ARGV — command-line arguments:
foreach my $arg (@ARGV) { ... }
my ($input, $output) = @ARGV;
$0 — script name. Useful for die "$0: error...".
$1, $2, ... — regex capture groups:
if ("2026-05-08" =~ /(\d{4})-(\d{2})-(\d{2})/) {
print "year: $1, month: $2, day: $3\n";
}
$/ — input record separator. Default is \n. Set to undef to slurp the whole file:
{
local $/; # local — restore on scope exit
my $contents = <$fh>;
}
$\ — output record separator. Set to \n and every print adds a newline:
{
local $\ = "\n";
print "hello"; # "hello\n"
print "world"; # "world\n"
}
$! — last system error message:
open(my $fh, '<', $path) or die "can't open $path: $!";
$@ — last eval error:
eval { risky_op(); };
if ($@) {
warn "failed: $@";
}
Pragmas are special modules that change compilation behavior:
use strict— require declarations, no soft refsuse warnings— runtime warningsuse utf8— source code is UTF-8use feature 'say'— enable specific features (say, switch, state, etc.)use 5.020— require Perl >= 5.20 + enables featuresno strict 'refs'— locally turn off (when you need glob magic)
use English — give plain names to special vars: $ARG for $_, $INPUT_RECORD_SEPARATOR for $/. Slower; mostly for readability when teaching.
local — temporarily replace a (package or special) variable in dynamic scope:
sub silence {
local *STDERR;
open STDERR, '>', '/dev/null';
return inner_call();
}
my is lexical (visible in the same block); local is dynamic (visible in called functions).
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…