PERLSYN(1perl)
π perlsyn β Perl syntax: declarations, statements, comments π
(this is part of the 1perl manual, bestie β the Perl Programmers Reference Guide section, and yes, this is literally where all the syntax vibes live)
β¨ NAME β¨
perlsyn β Perl syntax: declarations, statements, comments π
πΈ DESCRIPTION πΈ
okay so listen. A Perl program is just a sequence of declarations and statements, and it runs top to bottom, like reading a story. π Loops, subroutines, and other control structures are what let you jump around within the code β they're the plot twists, iykyk.
Perl is a free-form language: you can format and indent it literally however you want. π Whitespace is mostly just there to separate tokens β unlike languages like Python where whitespace is an important part of the syntax, or Fortran where it's immaterial. No cap.
Many of Perl's syntactic elements are optional. Instead of making you put parentheses around every single function call and declare every variable like some kind of syntax cop π¨, you can often just leave those explicit elements off and Perl will ~figure out~ what you meant. This is known as Do What I Mean, aka DWIM. It lets programmers be lazy and code in a style they're comfy with. Periodt.
Perl borrows syntax and concepts from so many languages: awk, sed, C, Bourne Shell, Smalltalk, Lisp and even English. π And other languages borrowed syntax from Perl, especially its regular expression extensions. So if you've programmed in another language, you'll see familiar pieces in Perl. They often work the same β but check perltrap for info on how they differ. β οΈ
π¦ Declarations π¦
The only things you need to declare in Perl are report formats and subroutines (and sometimes not even subroutines, she's chill like that).
A scalar variable holds the undefined value (undef) until it's been assigned a defined value, which is anything other than undef. When used as a number, undef is treated as 0; when used as a string, it's treated as the empty string, ""; and when used as a reference that isn't being assigned to, it's treated as an error. π
If you enable warnings, you'll get notified of an uninitialized value whenever you treat undef as a string or a number. Wellβ¦ usually. π Boolean contexts, like:
if ($x) {}
are exempt from warnings (because they care about truth rather than definedness). Operators such as ++, --, +=, -=, and .=, that operate on undefined variables like:
undef $x;
$x++;
are also always exempt from such warnings. π«Ά
A declaration can be put anywhere a statement can, but it has no effect on the execution of the primary sequence of statements: declarations all take effect at compile time. All declarations are typically put at the beginning or the end of the script. However, if you're using lexically-scoped private variables created with my(), state(), or our(), you'll have to make sure your format or subroutine definition is within the same block scope as the my() if you expect to be able to access those private variables. π
Declaring a subroutine lets a subroutine name be used as if it were a list operator from that point forward in the program. You can declare a subroutine without defining it by saying sub name, thus:
sub myname;
$me = myname $0 or die "can't get myname";
A bare declaration like that declares the function to be a list operator, not a unary operator, so you have to be careful to use parentheses (or or instead of ||). The || operator binds too tightly to use after list operators; it becomes part of the last element. You can always use parentheses around the list operator's arguments to turn the list operator back into something that behaves more like a function call. Alternatively, you can use the prototype ($) to turn the subroutine into a unary operator:
sub myname ($);
$me = myname $0 || die "can't get myname";
That now parses as you'd expect, but you still ought to get in the habit of using parentheses in that situation. For more on prototypes, see perlsub. π
Subroutine declarations can also be loaded up with the require statement, or both loaded and imported into your namespace with a use statement. See perlmod for details on this. π
A statement sequence may contain declarations of lexically-scoped variables, but apart from declaring a variable name, the declaration acts like an ordinary statement, and is elaborated within the sequence of statements as if it were an ordinary statement. That means it actually has both compile-time and run-time effects. π
π¬ Comments π¬
Text from a # character until the end of the line is a comment, and is ignored. π« Exceptions include # inside a string or regular expression.
β Simple Statements β
The only kind of simple statement is an expression evaluated for its side-effects. Every simple statement must be terminated with a semicolon, unless it's the final statement in a block, in which case the semicolon is optional. But put the semicolon in anyway if the block takes up more than one line, because you may eventually add another line. π
Note that there are operators like eval {}, sub {}, and do {} that look like compound statements, but aren't β they're just TERMs in an expression β and thus need an explicit termination when used as the last item in a statement. π
π Statement Modifiers π
Any simple statement may optionally be followed by a SINGLE modifier, just before the terminating semicolon (or block ending). The possible modifiers are:
if EXPR
unless EXPR
while EXPR
until EXPR
for LIST
foreach LIST
when EXPR
The EXPR following the modifier is referred to as the "condition". Its truth or falsehood determines how the modifier will behave. β¨
if executes the statement once if and only if the condition is true. unless is the opposite β it executes the statement unless the condition is true (that is, if the condition is false). See "Scalar values" in perldata for definitions of true and false.
print "Basset hounds got long ears" if length $ear >= 10;
go_outside() and play() unless $is_raining;
The for(each) modifier is an iterator: it executes the statement once for each item in the LIST (with $_ aliased to each item in turn). There is no syntax to specify a C-style for loop or a lexically scoped iteration variable in this form.
print "Hello $_!\n" for qw(world Dolly nurse);
while repeats the statement while the condition is true. Postfix while has the same magic treatment of some kinds of condition that prefix while has. until does the opposite β it repeats the statement until the condition is true (or while the condition is false):
# Both of these count from 0 to 10.
print $i++ while $i <= 10;
print $j++ until $j > 10;
The while and until modifiers have the usual "while loop" semantics (conditional evaluated first), except when applied to a do-BLOCK, in which case the block executes once before the conditional is evaluated. π
This is so that you can write loops like:
do {
$line = <STDIN>;
...
} until !defined($line) || $line eq ".\n"
See "do" in perlfunc. Note also that the loop control statements described later will NOT work in this construct, because modifiers don't take loop labels. Sorry. π You can always put another block inside of it (for next/redo) or around it (for last) to do that sort of thing.
For next or redo, just double the braces:
do {{
next if $x == $y;
# do something here
}} until $x++ > $z;
For last, you have to be more elaborate and put braces around it:
{
do {
last if $x == $y**2;
# do something here
} while $x++ <= $z;
}
If you need both next and last, you have to do both and also use a loop label:
LOOP: {
do {{
next if $x == $y;
last LOOP if $x == $y**2;
# do something here
}} until $x++ > $z;
}
π NOTE: The behaviour of amy,state, orourmodified with a statement modifier conditional or loop construct (for example,my $x if ...) is undefined. The value of themyvariable may beundef, any previously assigned value, or possibly anything else. Don't rely on it. Future versions of perl might do something different from the version of perl you try it out on. Here be dragons. π
The when modifier is an experimental feature that first appeared in Perl 5.14. To use it, you should include a use v5.14 declaration. (Technically, it requires only the switch feature, but that aspect of it was not available before 5.14.) Operative only from within a foreach loop or a given block, it executes the statement only if the smartmatch $_ ~~ EXPR is true. If the statement executes, it's followed by a next from inside a foreach and break from inside a given. π₯
Under the current implementation, the foreach loop can be anywhere within the when modifier's dynamic scope, but must be within the given block's lexical scope. This restriction may be relaxed in a future release. See "Switch Statements" below. π
π Compound Statements π
In Perl, a sequence of statements that defines a scope is called a block. Sometimes a block is delimited by the file containing it (in the case of a required file, or the program as a whole), and sometimes a block is delimited by the extent of a string (in the case of an eval). πΈ
But generally, a block is delimited by curly brackets, also known as braces. We will call this syntactic construct a BLOCK. Because enclosing braces are also the syntax for hash reference constructor expressions (see perlref), you may occasionally need to disambiguate by placing a ; immediately after an opening brace so that Perl realises the brace is the start of a block. You will more frequently need to disambiguate the other way, by placing a + immediately before an opening brace to force it to be interpreted as a hash reference constructor expression. It is considered good style to use these disambiguating mechanisms liberally β not only when Perl would otherwise guess incorrectly. π
The following compound statements may be used to control flow:
if (EXPR) BLOCK
if (EXPR) BLOCK else BLOCK
if (EXPR) BLOCK elsif (EXPR) BLOCK ...
if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
unless (EXPR) BLOCK
unless (EXPR) BLOCK else BLOCK
unless (EXPR) BLOCK elsif (EXPR) BLOCK ...
unless (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
given (EXPR) BLOCK
LABEL while (EXPR) BLOCK
LABEL while (EXPR) BLOCK continue BLOCK
LABEL until (EXPR) BLOCK
LABEL until (EXPR) BLOCK continue BLOCK
LABEL for (EXPR; EXPR; EXPR) BLOCK
LABEL for VAR (LIST) BLOCK
LABEL for VAR (LIST) BLOCK continue BLOCK
...and the rest of the statement forms you can write look like this, bestie, no cap:
LABEL foreach (EXPR; EXPR; EXPR) BLOCK
LABEL foreach VAR (LIST) BLOCK
LABEL foreach VAR (LIST) BLOCK continue BLOCK
LABEL BLOCK
LABEL BLOCK continue BLOCK
PHASE BLOCK
Starting in Perl 5.36 you can also go absolutely feral and iterate over multiple values at once by handing it a list of lexicals wrapped up in parens:
LABEL for my (VAR, VAR) (LIST) BLOCK
LABEL for my (VAR, VAR) (LIST) BLOCK continue BLOCK
LABEL foreach my (VAR, VAR) (LIST) BLOCK
LABEL foreach my (VAR, VAR) (LIST) BLOCK continue BLOCK
And if the try feature has been enabled, these are also on the menu:
try BLOCK catch (VAR) BLOCK
try BLOCK catch (VAR) BLOCK finally BLOCK
The experimental given statement does not turn itself on automatically, okay? Scroll down to "Switch Statements" to find out how to wake it up, plus all the caveats that come with it. π
So here's the thing that trips people up: unlike C and Pascal, every single one of these is defined in terms of BLOCKs, not statements. Translation? The curly brackets are mandatory β no dangling statements allowed, periodt. If you're out here wanting conditionals without curly brackets, there are several other ways to pull it off. All four of these do exactly the same thing:
if (!open(FOO)) { die "Can't open $FOO: $!" }
die "Can't open $FOO: $!" unless open(FOO);
open(FOO) || die "Can't open $FOO: $!";
open(FOO) ? () : die "Can't open $FOO: $!";
# a bit exotic, that last one
The if statement is straightforward, slay. Because BLOCKs are always bounded by curly brackets, there's never any ambiguity about which if an else belongs to. (Iconic behavior, honestly.) If you use unless instead of if, the sense of the test is reversed. Just like if, unless can be followed by an else. unless can even be followed by one or more elsif statements β though lowkey you should think twice before using that particular language construct, because everyone reading your code will have to think at least twice before they understand what's going on. π«
The while statement executes the block as long as the expression is true. The until statement executes the block as long as the expression is false. The LABEL is optional, and if it's there it's an identifier followed by a colon. The LABEL names the loop for the loop control statements next, last, and redo. If you leave the LABEL off, the loop control statement refers to the innermost enclosing loop. That may include dynamically searching through your call-stack at run time to find the LABEL β and such desperate behavior triggers a warning if you use the use warnings pragma or the -w flag. π If more than one label with the same name shows up, any reference to that name refers to the one labelling the innermost enclosing loop.
Now the fun part: if the condition expression of a while statement is based on any of a group of iterative expression types, it gets some magic treatment. The affected iterative expression types are readline, the <FILEHANDLE> input operator, readdir, glob, the <PATTERN> globbing operator, and each. If the condition expression is one of these types, then the value yielded by the iterative operator gets implicitly assigned to $_. And if the condition expression is one of these types β or an explicit assignment of one of them to a scalar β then the condition actually tests for definedness of the expression's value, not for its regular truth value. Wild, right? β¨
If there's a continue BLOCK, it's always executed just before the conditional is about to be evaluated again. So you can use it to increment a loop variable, even when the loop has been continued via the next statement. π
When a block is preceded by a compilation phase keyword like BEGIN, END, INIT, CHECK, or UNITCHECK, then the block only runs during the corresponding phase of execution. Go read perlmod for the details, iykyk.
Extension modules can also hook into the Perl parser to define brand-new kinds of compound statements. These get introduced by a keyword the extension recognizes, and the syntax following that keyword is defined entirely by the extension. If you're an implementor, see "PL_keyword_plugin" in perlapi for the mechanism. If you're just using such a module, see the module's documentation for the syntax it defines. π§
π Loop Control
The next command starts the next iteration of the loop:
LINE: while (<STDIN>) {
next LINE if /^#/; # discard comments
...
}
The last command immediately exits the loop in question. The continue block, if any, is not executed:
LINE: while (<STDIN>) {
last LINE if /^$/; # exit when done with header
...
}
The redo command restarts the loop block without evaluating the conditional again. The continue block, if any, is not executed. This command is normally used by programs that want to lie to themselves about what was just input. π (not the self-deception core)
For example, when processing a file like /etc/termcap. If your input lines might end in backslashes to indicate continuation, you want to skip ahead and grab the next record:
while (<>) {
chomp;
if (s/\\$//) {
$_ .= <>;
redo unless eof();
}
# now process $_
}
which is just Perl shorthand for the more explicitly written version:
LINE: while (defined($line = <ARGV>)) {
chomp($line);
if ($line =~ s/\\$//) {
$line .= <ARGV>;
redo LINE unless eof(); # not eof(ARGV)!
}
# now process $line
}
Heads up: if there were a continue block on the above code, it would get executed only on lines discarded by the regex (since redo skips the continue block). A continue block is often used to reset line counters or m?pat? one-time matches:
# inspired by :1,$g/fred/s//WILMA/
while (<>) {
m?(fred)? && s//WILMA $1 WILMA/;
m?(barney)? && s//BETTY $1 BETTY/;
m?(homer)? && s//MARGE $1 MARGE/;
} continue {
print "$ARGV $.: $_";
close ARGV if eof; # reset $.
reset if eof; # reset ?pat?
}
If the word while gets replaced by the word until, the sense of the test is reversed β but the conditional is still tested before the first iteration. πΈ
Loop control statements do not work inside an if or unless, because those aren't loops. You can double up the braces to make them act like one, though:
if (/pattern/) {{
last if /fred/;
next if /barney/; # same effect as "last",
# but doesn't document as well
# do something here
}}
This happens because a block all by itself acts as a loop that executes once. See "Basic BLOCKs". π¦
Warning, bestie: the formwhile/if BLOCK BLOCK, which existed back in Perl 4, is no longer available. Replace any occurrence ofif BLOCKwithif (do BLOCK).
π For Loops
Perl's C-style for loop works just like the corresponding while loop β meaning this:
for ($i = 1; $i < 10; $i++) {
...
}
is the same as this:
$i = 1;
while ($i < 10) {
...
} continue {
$i++;
}
There's one minor difference though: if variables are declared with my in the initialization section of the for, the lexical scope of those variables is exactly the for loop β the body of the loop and the control sections. To illustrate:
my $i = 'samba';
for (my $i = 1; $i <= 4; $i++) {
print "$i\n";
}
print "$i\n";
when executed, gives:
1
2
3
4
samba
As a special case, if the test in the for loop (or the corresponding while loop) is empty, it's treated as true. That is, both
for (;;) {
...
}
and
while () {
...
}
are treated as infinite loops. βΎοΈ
Besides the normal array index looping, for can lend itself to many other interesting applications. Here's one that dodges the problem you get into if you explicitly test for end-of-file on an interactive file descriptor β which causes your program to appear to hang:
$on_a_tty = -t STDIN && -t STDOUT;
sub prompt { print "yes? " if $on_a_tty }
for ( prompt(); <STDIN>; prompt() ) {
# do something
}
The condition expression of a for loop gets the same magic treatment of readline et al that the condition expression of a while loop gets. β¨
π Foreach Loops
The foreach loop iterates over a normal list value and sets the scalar variable VAR to be each element of the list, one at a time, in turn. If the variable is preceded with the keyword my, then it's lexically scoped, and therefore visible only within the loop. Otherwise, the variable is implicitly local to the loop and regains its former value upon exiting the loop. If the variable was previously declared with my, it uses that variable instead of the global one β but it's still localized to the loop. This implicit localization only happens for non C-style loops. π
The foreach keyword is literally just a synonym for the for keyword, so use whichever. If VAR is omitted, $_ gets set to each value. π
If any element of LIST is an lvalue, you can modify it by modifying VAR inside the loop. And conversely, if any element of LIST is not an lvalue, any attempt to modify that element will fail. In other words: the foreach loop index variable is an implicit alias for each item in the list you're looping over. π
Big warning: if the LIST is just a single array,foreachwill get very confused if you add or remove elements within the loop body β for example withspliceorpush. So don't do that. π
my @arr1 = 1 .. 2;
for my $x (@arr1, ()) {
push @arr1, 'a' if $x =~ /[0-9]/;
print $x;
} # Outputs 12
my @arr2 = 1 .. 2;
for my $x (@arr2) {
push @arr2, 'b' if $x =~ /[0-9]/;
print $x;
} # Outputs 12bb
foreach probably won't do what you expect if VAR is a tied or other special variable. Don't do that either. π
As of Perl 5.22, there's an experimental variant of this loop that accepts a variable preceded by a backslash for VAR β in which case the items in the LIST must be references. The backslashed variable becomes an alias to each referenced item in the LIST, which must be of the correct type. The variable needn't be a scalar in this case, and the backslash may be followed by my. To use this form, you have to enable the refaliasing feature via use feature. (See feature. See also "Assigning to References" in perlref.) πͺ
Okay so listen up β as of Perl 5.36, you can iterate over multiple values at a time! Like, a whole little squad of iterator variables, all up in one loop. π β¨
But here's the catch bestie: you can only iterate with lexical scalars as the iterator variables. And unlike list assignment (where you can throw undef in to go "yeah this one's not for me, skip it"), you cannot use undef here to signify a value you don't want. Nope!! That's just a limitation of the current implementation, and it might be changed in the future. (Might. π No promises.)
So okay, what happens if the size of LIST is not an exact multiple of the number of iterator variables? Then on that last iteration, the "excess" iterator variables become aliases to undef β like the LIST had , undef tacked on as many times as needed to make its length a perfect multiple. π
And this happens whether LIST is a literal LIST or an array β meaning arrays do not get extended if their size isn't a multiple of the iteration size. Which, honestly? Consistent with iterating an array one-at-a-time. Makes sense.
But heads up: since those padding elements aren't lvalues, trying to modify them will fail β again, same vibe as iterating a list that has literal undefs in it. If that's not the behaviour you want, then before the loop starts you've gotta either explicitly extend your array so it's an exact multiple, or explicitly throw an exception. Pick your fighter. π₯
Examples, bestie:
for (@ary) { s/foo/bar/ }
for my $elem (@elements) {
$elem *= 2;
}
for $count (reverse(1..10), "BOOM") {
print $count, "\n";
sleep(1);
}
for (1..15) { print "Merry Christmas\n"; }
foreach $item (split(/:[\\\n:]*/, $ENV{TERMCAP})) {
print "Item: $item\n";
}
use feature "refaliasing";
no warnings "experimental::refaliasing";
foreach \my %hash (@array_of_hash_references) {
# do something with each %hash
}
foreach my ($foo, $bar, $baz) (@list) {
# do something three-at-a-time
}
foreach my ($key, $value) (%hash) {
# iterate over the hash
# The hash is immediately copied to a flat list before the loop
# starts. The list contains copies of keys but aliases of values.
# This is the same behaviour as for $var (%hash) {...}
}
Now, here's how a C programmer might code up a particular algorithm in Perl:
for (my $i = 0; $i < @ary1; $i++) {
for (my $j = 0; $j < @ary2; $j++) {
if ($ary1[$i] > $ary2[$j]) {
last; # can't go to outer :-(
}
$ary1[$i] += $ary2[$j];
}
# this is where that last takes me
}
Meanwhile, here's how a Perl programmer who's comfy with the idiom would do it:
OUTER: for my $wid (@ary1) {
INNER: for my $jet (@ary2) {
next OUTER if $wid > $jet;
$wid += $jet;
}
}
See how much easier that is?? π It's cleaner, safer, and faster:
- Cleaner because it's less noisy β no vibe-ruining boilerplate.
- Safer because if someone adds code between the inner and outer loops later on, that new code won't get accidentally executed. Iconic.
- The
nextexplicitly iterates the other loop instead of just terminating the inner one. - And faster, because Perl executes a
foreachstatement more rapidly than it would the equivalent C-styleforloop. β‘
Perceptive Perl hackers may have noticed that a for loop has a return value, and that you can capture it by wrapping the loop in a do block. And the reward for this discovery is this cautionary advice:
The return value of a for loop is unspecified and may change without notice. Do not rely on it. π
π Try Catch Exception Handling π
The try/catch syntax gives you control flow for exception handling. The try keyword introduces a block that gets executed the moment it's encountered, and the catch block hands you code to handle any exception the first one might throw.
But first!! This syntax must be enabled with use feature 'try'.
use feature 'try';
try {
my $x = call_a_function();
$x < 100 or die "Too big";
send_output($x);
}
catch ($e) {
warn "Unable to output a value; $e";
}
print "Finished\n";
So here, the body of the catch block (aka that warn statement) runs if the initial block hits that conditional die, or if either of the functions it calls throws an uncaught exception. The catch block can peek at the lexical variable $e to see what the exception actually was. And if no exception was thrown, the catch block simply doesn't happen. Either way, execution then continues from the next statement β in this example, the print. π¦
The catch keyword must be immediately followed by a variable declaration in parentheses, which introduces a new variable visible to the body of the subsequent block. Inside the block, that variable holds the exception value thrown by the try block's code. You do not need the my keyword to declare it β it's implied (similar to how it works for subroutine signatures).
Both the try and the catch blocks are allowed to contain control-flow expressions, like return, goto, or next/last/redo. In all cases they behave as expected, no warnings. Specifically: a return expression inside the try block makes its entire containing function return β which is not how it works inside an eval block, where it'd only make that block return. π
Like other control-flow syntax, try and catch yield the last evaluated value when placed as the final statement in a function or a do block. Which means you can use this syntax to create a value. But if you do, remember: don't use the return expression, or that'll make the containing function return instead.
my $value = do {
try {
get_thing(@args);
}
catch ($e) {
warn "Unable to get thing - $e";
$DEFAULT_THING;
}
};
And just like other control-flow syntax, try blocks are not visible to caller() β same deal as, say, while or foreach loops. Successive levels of the caller result can see subroutine calls and eval blocks, because those affect the way return would work. Since try blocks don't intercept return, caller simply isn't interested in them. π
Bonus round: the try and catch blocks may optionally be followed by a third block, introduced by the finally keyword. That third block runs after the rest of the construct has finished.
try {
call_a_function();
}
catch ($e) {
warn "Unable to call; $e";
}
finally {
print "Finished\n";
}
The finally block is equivalent to using a defer block and gets invoked in the same situations: not only when the try block completes successfully or throws an exception, but also β out of the ordinary order of execution, so pay attention β immediately before code in the try or catch blocks transfers control elsewhere by using return, a loop control, or goto.
Unlike the try and catch blocks, a finally block is not permitted to return, goto, or use any loop controls. Its final expression value is ignored, and it doesn't affect the return value of the containing function even if it's placed last in that function.
Heads up bestie: use of thisfinallyblock syntax is currently experimental and will emit a warning in theexperimental::trycategory. β¨
πΈ Basic BLOCKs πΈ
A BLOCK by itself (labeled or not) is semantically equivalent to a loop that executes once. So you can use any of the loop control statements inside it to leave or restart the block. π
But note: this is NOT true ineval{},sub{}, or β contrary to popular belief βdo{}blocks. Those do NOT count as loops. Do not come for me about it.
The continue block is optional, btw.
The BLOCK construct can be used to emulate case structures:
SWITCH: {
if (/^abc/) { $abc = 1; last SWITCH; }
if (/^def/) { $def = 1; last SWITCH; }
if (/^xyz/) { $xyz = 1; last SWITCH; }
$nothing = 1;
}
You'll also find that foreach loop used to create a topicalizer and a switch:
SWITCH:
for ($var) {
if (/^abc/) { $abc = 1; last SWITCH; }
if (/^def/) { $def = 1; last SWITCH; }
if (/^xyz/) { $xyz = 1; last SWITCH; }
$nothing = 1;
}
Such constructs are quite frequently used, both because older versions of Perl had no official switch statement, and also because the newer version described immediately below remains experimental and can sometimes be confusing. π The more you know.
π¦ defer blocks π¦
A block prefixed by the defer modifier gives you a section of code that runs at a later time, during scope exit. Lowkey magical. β¨
A defer block can appear at any point where a regular block or other statement is permitted. If the flow of execution reaches this statement, the body of the block is stored for later β but not invoked immediately. When the flow of control leaves the containing block for any reason, that stored block gets executed on the way past. It's a means of deferring execution until a later time. This acts similarly to syntax provided by some other languages, often using keywords named "try / finally".
This syntax is available since Perl 5.36 if enabled by the defer named feature, and it's currently experimental. If experimental warnings are enabled it'll emit a warning when used.
use feature 'defer';
{
say "This happens first";
defer { say "This happens last"; }
say "And this happens inbetween";
}
If multiple defer blocks live in a single scope, they execute in LIFO order β the last one reached is the first one executed. Stack behaviour, bestie. π
The code stored by the defer block gets invoked when control leaves its containing block due to:
- regular fallthrough
- explicit
return - exceptions thrown by
dieor propagated by functions called by it goto- any of the loop control statements
next,last, orredo
Important distinction though: if the flow of control does not reach the defer statement itself, then its body is not stored for later execution. (This is in direct contrast to the code provided by an END phaser block, which is always enqueued by the compiler, regardless of whether execution ever reached the line it was given on. Different vibes entirely.)
use feature 'defer';
{
defer { say "This will run"; }
return;
defer { say "This will not"; }
}
And finally β exceptions thrown by code inside a defer block will propagate to the caller in the same way as any other exception thrown by normal code. No special treatment, no drama. π«Ά
If the defer block is being executed because of a thrown exception and then it goes and throws another one, honestly nobody specified what happens β the only guarantee you get is that the caller will definitely receive an exception. That's it, that's the lore. π
And bestie, besides throwing exceptions, a defer block is not allowed to mess with the control flow of the code around it. Like, it cannot make its containing function return, it cannot goto a label, and it cannot steer a containing loop with next, last or redo. But β plot twist β all of those things are totally permitted inside the body of the defer. π
use feature 'defer';
{
defer {
foreach ( 1 .. 5 ) {
last if $_ == 3; # this is permitted
}
}
}
{
foreach ( 6 .. 10 ) {
defer {
last if $_ == 8; # this is not
}
}
}
β¨ Switch Statements β¨
The switch feature is discouraged for new code and is retained for backward compatibility. So like, it's giving beloved but retired. π«Ά
Starting from Perl 5.10.1 (well, 5.10.0, but it didn't work right), you can literally just say
use feature "switch";
to enable the switch feature. It's loosely based on an old version of a Raku proposal, but ngl it no longer resembles the Raku construct. You also get the switch feature whenever you declare that your code prefers to run under a version of Perl between 5.10 and 5.34. For example:
use v5.14;
Under the switch feature, Perl gains the keywords given, when, default, continue, and break. Starting from Perl 5.16, one can prefix the switch keywords with CORE:: to access the feature without a use feature statement. The keywords given and when are analogous to switch and case in other languages β though continue is not β so the code in the previous section could be rewritten as
use v5.10.1;
for ($var) {
when (/^abc/) { $abc = 1 }
when (/^def/) { $def = 1 }
when (/^xyz/) { $xyz = 1 }
default { $nothing = 1 }
}
The foreach is another way to set a topicalizer. If you wish to use given, that could be written like this:
use v5.10.1;
given ($var) {
when (/^abc/) { $abc = 1 }
when (/^def/) { $def = 1 }
when (/^xyz/) { $xyz = 1 }
default { $nothing = 1 }
}
As of 5.14, that can also be written this way:
use v5.14;
for ($var) {
$abc = 1 when /^abc/;
$def = 1 when /^def/;
$xyz = 1 when /^xyz/;
default { $nothing = 1 }
}
Or if you don't care to play it safe, like this:
use v5.14;
given ($var) {
$abc = 1 when /^abc/;
$def = 1 when /^def/;
$xyz = 1 when /^xyz/;
default { $nothing = 1 }
}
The arguments to given and when are in scalar context, and given assigns the $_ variable its topic value. π
Exactly what the EXPR argument to when does is hard to describe precisely, but in general, it tries to guess what you want done. Sometimes it is interpreted as $_ ~~ EXPR, and sometimes it is not. It also behaves differently when lexically enclosed by a given block than it does when dynamically enclosed by a foreach loop. The rules are far too difficult to understand to be described here. See "Experimental Details on given and when" later on. π
Due to an unfortunate bug in howgivenwas implemented between Perl 5.10 and 5.16, under those implementations the version of$_governed bygivenis merely a lexically scoped copy of the original, not a dynamically scoped alias to the original, as it would be if it were aforeachor under both the original and the current Raku language specification. This bug was fixed in Perl 5.18 (and lexicalized$_itself was removed in Perl 5.24). π
If your code still needs to run on older versions, stick to foreach for your topicalizer and you will be less unhappy. Fr fr, that's the move. β¨
π Goto π
Although not for the faint of heart, Perl does support a goto statement. There are three forms: goto-LABEL, goto-EXPR, and goto-&NAME. A loop's LABEL is not actually a valid target for a goto; it's just the name of the loop. ikyk. π
The goto-LABEL form finds the statement labeled with LABEL and resumes execution there. It may not be used to go into any construct that requires initialization, such as a subroutine or a foreach loop. It also can't be used to go into a construct that is optimized away. It can be used to go almost anywhere else within the dynamic scope, including out of subroutines, but it's usually better to use some other construct such as last or die. The author of Perl has never felt the need to use this form of goto (in Perl, that is--C is another matter). π
The goto-EXPR form expects a label name, whose scope will be resolved dynamically. This allows for computed gotos per FORTRAN, but isn't necessarily recommended if you're optimizing for maintainability:
goto(("FOO", "BAR", "GLARCH")[$i]);
The goto-&NAME form is highly magical, and substitutes a call to the named subroutine for the currently running subroutine. This is used by AUTOLOAD() subroutines that wish to load another subroutine and then pretend that the other subroutine had been called in the first place (except that any modifications to @_ in the current subroutine are propagated to the other subroutine.) After the goto, not even caller() will be able to tell that this routine was called first. π
In almost all cases like this, it's usually a far, far better idea to use the structured control flow mechanisms of next, last, or redo instead of resorting to a goto. For certain applications, the catch and throw pair of eval{} and die() for exception processing can also be a prudent approach. π«Ά
π The Ellipsis Statement π
Beginning in Perl 5.12, Perl accepts an ellipsis, ..., as a placeholder for code that you haven't implemented yet. When Perl 5.12 or later encounters an ellipsis statement, it parses this without error, but if and when you should actually try to execute it, Perl throws an exception with the text Unimplemented:
use v5.12;
sub unimplemented { ... }
eval { unimplemented() };
if ($@ =~ /^Unimplemented at /) {
say "I found an ellipsis!";
}
You can only use the elliptical statement to stand in for a complete statement. Syntactically, ...; is a complete statement, but, as with other kinds of semicolon-terminated statement, the semicolon may be omitted if ... appears immediately before a closing brace. These examples show how the ellipsis works:
use v5.12;
{ ... }
sub foo { ... }
...;
eval { ... };
sub somemeth {
my $self = shift;
...;
}
$x = do {
my $n;
...;
say "Hurrah!";
$n;
};
The elliptical statement cannot stand in for an expression that is part of a larger statement. These examples of attempts to use an ellipsis are syntax errors:
use v5.12;
print ...;
open(my $fh, ">", "/dev/passwd") or ...;
if ($condition && ... ) { say "Howdy" };
... if $x > $y;
say "Cromulent" if ...;
$flub = 5 + ...;
There are some cases where Perl can't immediately tell the difference between an expression and a statement. For instance, the syntax for a block and an anonymous hash reference constructor look the same unless there's something in the braces to give Perl a hint. The ellipsis is a syntax error if Perl doesn't guess that the { ... } is a block. Inside your block, you can use a ; before the ellipsis to denote that the { ... } is a block and not a hash reference constructor. π§
Note: Some folks colloquially refer to this bit of punctuation as a "yada-yada" or "triple-dot", but its true name is actually an ellipsis. π
π PODs: Embedded Documentation π
Perl has a mechanism for intermixing documentation with source code. While it's expecting the beginning of a new statement, if the compiler encounters a line that begins with an equal sign and a word, like this
=head1 Here There Be Pods!
Then that text and all remaining text up through and including a line beginning with =cut will be ignored. The format of the intervening text is described in perlpod. πΈ
This allows you to intermix your source code and your documentation text freely, as in
=item snazzle($)
The snazzle() function will behave in the most spectacular
form that you can possibly imagine, not even excepting
cybernetic pyrotechnics.
=cut back to the compiler, nuff of this pod stuff!
sub snazzle($) {
my $thingie = shift;
.........
}
Note that pod translators should look at only paragraphs beginning with a pod directive (it makes parsing easier), whereas the compiler actually knows to look for pod escapes even in the middle of a paragraph. This means that the following secret stuff will be ignored by both the compiler and the translators. π΅οΈββοΈ
$x=3;
=secret stuff
warn "Neither POD nor CODE!?"
=cut back
print "got $x\n";
You probably shouldn't rely upon the warn() being podded out forever. Not all pod translators are well-behaved in this regard, and perhaps the compiler will become pickier. π
One may also use pod directives to quickly comment out a section of code. Iconic behaviour honestly. β¨
π Plain Old Comments (Not!) π
Perl can process line directives, much like the C preprocessor. Using this, one can control Perl's idea of filenames and line numbers in error or warning messages (especially for strings that are processed with eval()). The syntax for this mechanism is almost the same as for most C preprocessors: it matches the regular expression
# example: '# line 42 "new_filename.plx"'
/^\# \s*
line \s+ (\d+) \s*
(?:\s("?)([^"]+)\g2)? \s*
$/x
with $1 being the line number for the next line, and $3 being the optional filename (specified with or without quotes). Note that no whitespace may precede the #, unlike modern C preprocessors. π€
There is a fairly obvious gotcha included with the line directive: Debuggers and profilers will only show the last source line to appear at a particular line number in a given file. Care should be taken not to cause line number collisions in code you'd like to debug later. π
Here are some examples that you should be able to type into your command shell: π
% perl
# line 200 "bzzzt"
# the '#' on the previous line must be the first char on line
die 'foo';
__END__
foo at bzzzt line 201.
like, look at that line number bestie π bzzzt did not come to play.
now same vibe but with eval in the mix, and the fake line number is 2001 in a file with literally no name:
% perl
# line 200 "bzzzt"
eval qq[\n#line 2001 ""\ndie 'foo']; print $@;
__END__
foo at - line 2001.
and if the fake filename has a space in it, Perl is just gonna report it as-is, no drama:
% perl
eval qq[\n#line 200 "foo bar"\ndie 'foo']; print $@;
__END__
foo at foo bar line 200.
and when you interpolate __LINE__ and __FILE__ in there yourself? chef's kiss:
% perl
# line 345 "goop"
eval "\n#line " . __LINE__ . ' "' . __FILE__ ."\"\ndie 'foo'";
print $@;
__END__
foo at goop line 345.
β¨ Experimental Details on given and when β¨
okay girlies, deep breath π« because as we already said, the "switch" feature is highly experimental (it's also scheduled to be removed in perl 5.42.0), which means it is subject to change with basically zero notice. In particular, when has tricky behaviours that are expected to change to become less tricky in the future. Do not rely upon its current (mis)implementation. And before Perl 5.18, given also had tricky behaviours that you should still beware of if your code must run on older versions of Perl. π
Here's a longer example of given so you can see the whole aesthetic:
use feature ":5.10";
given ($foo) {
when (undef) {
say '$foo is undefined';
}
when ("foo") {
say '$foo is the string "foo"';
}
when ([1,3,5,7,9]) {
say '$foo is an odd digit';
continue; # Fall through
}
when ($_ < 100) {
say '$foo is numerically less than 100';
}
when (\&complicated_check) {
say 'a complicated check for $foo is true';
}
default {
die q(I don't know what to do with $foo);
}
}
Before Perl 5.18, given(EXPR) assigned the value of EXPR to merely a lexically scoped copy (!) of $_, not a dynamically scoped alias the way foreach does. Which made it basically like:
do { my $_ = EXPR; ... }
except that the block was automatically broken out of by a successful when or an explicit break. And because it was only a copy, and because it was only lexically scoped, not dynamically scoped, you could not do the things with it that you're used to in a foreach loop. Specifically: it did not work for arbitrary function calls if those functions might try to access $_. Best stick to foreach for that. fr fr.
Most of the power comes from the implicit smartmatching that can sometimes apply. Most of the time, when(EXPR) is treated as an implicit smartmatch of $_, that is, $_ ~~ EXPR. (peep "Smartmatch Operator" in perlop for more tea on smartmatching, iykyk.) But when EXPR is one of the 10 exceptional cases (or things like them) listed below, it is used directly as a boolean.
- A user-defined subroutine call or a method invocation.
- A regular expression match in the form of
/REGEX/,$foo =~ /REGEX/, or$foo =~ EXPR. Also, a negated regular expression match in the form!/REGEX/,$foo !~ /REGEX/, or$foo !~ EXPR. - A smart match that uses an explicit
~~operator, such asEXPR ~~ EXPR.
NOTE: You will often have to use$c ~~ $_because the default case uses$_ ~~ $c, which is frequently the opposite of what you want. π
- A boolean comparison operator such as
$_ < 10or$x eq "abc". The relational operators that this applies to are the six numeric comparisons (<,>,<=,>=,==, and!=), and the six string comparisons (lt,gt,le,ge,eq, andne). - At least the three builtin functions
defined(...),exists(...), andeof(...). We might someday add more of these later if we think of them. (might, bestie, no promises β¨) - A negated expression, whether
!(EXPR)ornot(EXPR), or a logical exclusive-or,(EXPR1) xor (EXPR2). The bitwise versions (~and^) are not included. - A filetest operator, with exactly 4 exceptions:
-s,-M,-A, and-C, as these return numerical values, not boolean ones. The-zfiletest operator is not included in the exception list. - The
..and...flip-flop operators. Note that the...flip-flop operator is completely different from the...elliptical statement just described.
In those 8 cases above, the value of EXPR is used directly as a boolean, so no smartmatching is done. You may think of when as a smartsmartmatch. π
Furthermore, Perl inspects the operands of logical operators to decide whether to use smartmatching for each one by applying the above test to the operands:
- If EXPR is
EXPR1 && EXPR2orEXPR1 and EXPR2, the test is applied recursively to both EXPR1 and EXPR2. Only if both operands also pass the test, recursively, will the expression be treated as boolean. Otherwise, smartmatching is used. - If EXPR is
EXPR1 || EXPR2,EXPR1 // EXPR2, orEXPR1 or EXPR2, the test is applied recursively to EXPR1 only (which might itself be a higher-precedence AND operator, for example, and thus subject to the previous rule), not to EXPR2. If EXPR1 is to use smartmatching, then EXPR2 also does so, no matter what EXPR2 contains. But if EXPR2 does not get to use smartmatching, then the second argument will not be either. This is quite different from the&&case just described, so be careful. π
These rules are complicated, but the goal is for them to do what you want (even if you don't quite understand why they are doing it). For example:
when (/^\d+$/ && $_ < 75) { ... }
will be treated as a boolean match because the rules say both a regex match and an explicit test on $_ will be treated as boolean.
Also:
when ([qw(foo bar)] && /baz/) { ... }
will use smartmatching because only one of the operands is a boolean: the other uses smartmatching, and that wins. π
Further:
when ([qw(foo bar)] || /^baz/) { ... }
will use smart matching (only the first operand is considered), whereas
when (/^baz/ || [qw(foo bar)]) { ... }
will test only the regex, which causes both operands to be treated as boolean. Watch out for this one, then, because an arrayref is always a true value, which makes it effectively redundant. Not a good idea. π
Tautologous boolean operators are still going to be optimized away. Don't be tempted to write
when ("foo" or "bar") { ... }
This will optimize down to "foo", so "bar" will never be considered (even though the rules say to use a smartmatch on "foo"). For an alternation like this, an array ref will work, because this will instigate smartmatching:
when ([qw(foo bar)] { ... }
This is somewhat equivalent to the C-style switch statement's fallthrough functionality (not to be confused with Perl's fallthrough functionality--see below), wherein the same block is used for several "case" statements.
Another useful shortcut is that, if you use a literal array or hash as the argument to given, it is turned into a reference. So given(@foo) is the same as given(\@foo), for example.
default behaves exactly like when(1 == 1), which is to say that it always matches. β¨
π Breaking out
You can use the break keyword to break out of the enclosing given block. Every when block is implicitly ended with a break.
π Fall-through
You can use the continue keyword to fall through from one case to the next immediate when or default:
given($foo) {
when (/x/) { say '$foo contains an x'; continue }
when (/y/) { say '$foo contains a y' }
default { say '$foo does not contain a y' }
}
π Return value
When a given statement is also a valid expression (for example, when it's the last statement of a block), it evaluates to:
- An empty list as soon as an explicit
breakis encountered. - The value of the last evaluated expression of the successful
when/defaultclause, if there happens to be one. - The value of the last evaluated expression of the
givenblock if no condition is true.
In both last cases, the last expression is evaluated in the context that was applied to the given block.
Note that, unlike if and unless, failed when statements always evaluate to an empty list. π
my $price = do {
given ($item) {
when (["pear", "apple"]) { 1 }
break when "vote"; # My vote cannot be bought
1e10 when /Mona Lisa/;
"unknown";
}
};
Currently, given blocks can't always be used as proper expressions. This may be addressed in a future version of Perl. (bestie we're waiting π°οΈ)
π Switching in a loop
Instead of using given(), you can use a foreach() loop. For example, here's one way to count how many times a particular string occurs in an array:
use v5.10.1;
my $count = 0;
for (@array) {
when ("foo") { ++$count }
}
print "\@array contains $count copies of 'foo'\n";
Or in a more recent version:
use v5.14;
my $count = 0;
for (@array) {
++$count when "foo";
}
print "\@array contains $count copies of 'foo'\n";
At the end of all when blocks, there is an implicit next. You can override that with an explicit last if you're interested in only the first match alone.
This doesn't work if you explicitly specify a loop variable, as in for $item (@array). You have to use the default variable $_.
π Differences from Raku
The Perl 5 smartmatch and given/when constructs are not compatible with their Raku analogues. The most visible difference and least important difference is that, in Perl 5, parentheses are required around the argument to given() and when() (except when this last one is used as a statement modifier). Parentheses in Raku are always optional in a control construct such as if(), while(), or when(); they can't be made optional in Perl 5 without a great deal of potential confusion, because Perl 5 would parse the expression
given $foo {
...
}
as though the argument to given were an element of the hash %foo, interpreting the braces as hash-element syntax.
However, there are many, many other differences. For example, this works in Perl 5:
use v5.12;
my @primary = ("red", "blue", "green");
if (@primary ~~ "red") {
say "primary smartmatches red";
}
if ("red" ~~ @primary) {
say "red smartmatches primary";
}
say "that's all, folks!";
But it doesn't work at all in Raku. Instead, you should use the (parallelizable) any operator:
if any(@primary) eq "red" {
say "primary smartmatches red";
}
if "red" eq any(@primary) {
say "red smartmatches primary";
}
okay so real talk bestie, that table of smartmatches you can go find in "Smartmatch Operator" in perlop? it is not a carbon copy of the one the Raku specification proposes π and the reasons are actually kind of juicy:
- mainly because Raku's data model and Perl 5's data model are just⦠not the same girlies, they're different species of language
- but also because the Raku spec has moved on and changed since Perl 5 kinda rushed into early adoption of it πββοΈπ¨ (we were young, we were excited, it's fine)
and here's the other lil difference that trips people up: in Raku, when() will always do an implicit smartmatch with its argument. no negotiating. periodt. β¨
in Perl 5 though, it's convenient (albeit potentially confusing π) to suppress that implicit smartmatch in various rather loosely-defined situations β as roughly outlined above. rough is the operative word here, she's doing her best π«Ά
the way to think about it: that difference is largely because Perl 5 does not have a boolean type, even internally. like, not even secretly. no true type hiding in the basement. so the whole "should this thing smartmatch or not" question gets answered by vibes and context instead of a type system πΈ
and that's the whole page bestie, you ate it, no crumbs left πβ¨
and that's a wrap on PERLSYN(1perl) β this one's from perl v5.44.0, dated 2026-10-17 π go write something iconic with it, mwah ππ
π¦ where this page comes from
- arch rolling: perl 5.44.0-1 Β· Artistic-1.0-Perl AND GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms