{
    "content": [
        {
            "type": "text",
            "text": "# perlsyn (man)\n\n## NAME\n\nperlsyn - Perl syntax\n\n## DESCRIPTION\n\nA Perl program consists of a sequence of declarations and statements which run from the top\nto the bottom.  Loops, subroutines, and other control structures allow you to jump around\nwithin the code.\n\n## Sections\n\n- **NAME**\n- **DESCRIPTION** (16 subsections)\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "perlsyn",
        "section": "",
        "mode": "man",
        "summary": "perlsyn - Perl syntax",
        "synopsis": null,
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "DESCRIPTION",
                "lines": 20,
                "subsections": [
                    {
                        "name": "Declarations",
                        "lines": 53
                    },
                    {
                        "name": "Comments",
                        "lines": 3
                    },
                    {
                        "name": "Simple Statements",
                        "lines": 8
                    },
                    {
                        "name": "Statement Modifiers",
                        "lines": 95
                    },
                    {
                        "name": "Compound Statements",
                        "lines": 103
                    },
                    {
                        "name": "Loop Control",
                        "lines": 76
                    },
                    {
                        "name": "For Loops",
                        "lines": 61
                    },
                    {
                        "name": "Foreach Loops",
                        "lines": 86
                    },
                    {
                        "name": "Try Catch Exception Handling",
                        "lines": 56
                    },
                    {
                        "name": "Basic BLOCKs",
                        "lines": 28
                    },
                    {
                        "name": "Switch Statements",
                        "lines": 74
                    },
                    {
                        "name": "Goto",
                        "lines": 30
                    },
                    {
                        "name": "The Ellipsis Statement",
                        "lines": 55
                    },
                    {
                        "name": "PODs: Embedded Documentation",
                        "lines": 40
                    },
                    {
                        "name": "Plain Old Comments (Not!)",
                        "lines": 46
                    },
                    {
                        "name": "Experimental Details on given and when",
                        "lines": 269
                    }
                ]
            }
        ],
        "sections": {
            "NAME": {
                "content": "perlsyn - Perl syntax\n",
                "subsections": []
            },
            "DESCRIPTION": {
                "content": "A Perl program consists of a sequence of declarations and statements which run from the top\nto the bottom.  Loops, subroutines, and other control structures allow you to jump around\nwithin the code.\n\nPerl is a free-form language: you can format and indent it however you like.  Whitespace\nserves mostly to separate tokens, unlike languages like Python where it is an important part\nof the syntax, or Fortran where it is immaterial.\n\nMany of Perl's syntactic elements are optional.  Rather than requiring you to put parentheses\naround every function call and declare every variable, you can often leave such explicit\nelements off and Perl will figure out what you meant.  This is known as Do What I Mean,\nabbreviated DWIM.  It allows programmers to be lazy and to code in a style with which they\nare comfortable.\n\nPerl borrows syntax and concepts from many languages: awk, sed, C, Bourne Shell, Smalltalk,\nLisp and even English.  Other languages have borrowed syntax from Perl, particularly its\nregular expression extensions.  So if you have programmed in another language you will see\nfamiliar pieces in Perl.  They often work the same, but see perltrap for information about\nhow they differ.\n",
                "subsections": [
                    {
                        "name": "Declarations",
                        "content": "The only things you need to declare in Perl are report formats and subroutines (and sometimes\nnot even subroutines).  A scalar variable holds the undefined value (\"undef\") until it has\nbeen assigned a defined value, which is anything other than \"undef\".  When used as a number,\n\"undef\" is treated as 0; when used as a string, it is treated as the empty string, \"\"; and\nwhen used as a reference that isn't being assigned to, it is treated as an error.  If you\nenable warnings, you'll be notified of an uninitialized value whenever you treat \"undef\" as a\nstring or a number.  Well, usually.  Boolean contexts, such as:\n\nif ($a) {}\n\nare exempt from warnings (because they care about truth rather than definedness).  Operators\nsuch as \"++\", \"--\", \"+=\", \"-=\", and \".=\", that operate on undefined variables such as:\n\nundef $a;\n$a++;\n\nare also always exempt from such warnings.\n\nA declaration can be put anywhere a statement can, but has no effect on the execution of the\nprimary sequence of statements: declarations all take effect at compile time.  All\ndeclarations are typically put at the beginning or the end of the script.  However, if you're\nusing lexically-scoped private variables created with \"my()\", \"state()\", or \"our()\", you'll\nhave to make sure your format or subroutine definition is within the same block scope as the\nmy if you expect to be able to access those private variables.\n\nDeclaring a subroutine allows a subroutine name to be used as if it were a list operator from\nthat point forward in the program.  You can declare a subroutine without defining it by\nsaying \"sub name\", thus:\n\nsub myname;\n$me = myname $0             or die \"can't get myname\";\n\nA bare declaration like that declares the function to be a list operator, not a unary\noperator, so you have to be careful to use parentheses (or \"or\" instead of \"||\".)  The \"||\"\noperator binds too tightly to use after list operators; it becomes part of the last element.\nYou can always use parentheses around the list operators arguments to turn the list operator\nback into something that behaves more like a function call.  Alternatively, you can use the\nprototype \"($)\" to turn the subroutine into a unary operator:\n\nsub myname ($);\n$me = myname $0             || die \"can't get myname\";\n\nThat now parses as you'd expect, but you still ought to get in the habit of using parentheses\nin that situation.  For more on prototypes, see perlsub.\n\nSubroutines declarations can also be loaded up with the \"require\" statement or both loaded\nand imported into your namespace with a \"use\" statement.  See perlmod for details on this.\n\nA statement sequence may contain declarations of lexically-scoped variables, but apart from\ndeclaring a variable name, the declaration acts like an ordinary statement, and is elaborated\nwithin the sequence of statements as if it were an ordinary statement.  That means it\nactually has both compile-time and run-time effects.\n"
                    },
                    {
                        "name": "Comments",
                        "content": "Text from a \"#\" character until the end of the line is a comment, and is ignored.  Exceptions\ninclude \"#\" inside a string or regular expression.\n"
                    },
                    {
                        "name": "Simple Statements",
                        "content": "The only kind of simple statement is an expression evaluated for its side-effects.  Every\nsimple statement must be terminated with a semicolon, unless it is the final statement in a\nblock, in which case the semicolon is optional.  But put the semicolon in anyway if the block\ntakes up more than one line, because you may eventually add another line.  Note that there\nare operators like \"eval {}\", \"sub {}\", and \"do {}\" that look like compound statements, but\naren't--they're just TERMs in an expression--and thus need an explicit termination when used\nas the last item in a statement.\n"
                    },
                    {
                        "name": "Statement Modifiers",
                        "content": "Any simple statement may optionally be followed by a SINGLE modifier, just before the\nterminating semicolon (or block ending).  The possible modifiers are:\n\nif EXPR\nunless EXPR\nwhile EXPR\nuntil EXPR\nfor LIST\nforeach LIST\nwhen EXPR\n\nThe \"EXPR\" following the modifier is referred to as the \"condition\".  Its truth or falsehood\ndetermines how the modifier will behave.\n\n\"if\" executes the statement once if and only if the condition is true.  \"unless\" is the\nopposite, it executes the statement unless the condition is true (that is, if the condition\nis false).  See \"Scalar values\" in perldata for definitions of true and false.\n\nprint \"Basset hounds got long ears\" if length $ear >= 10;\ngooutside() and play() unless $israining;\n\nThe \"for(each)\" modifier is an iterator: it executes the statement once for each item in the\nLIST (with $ aliased to each item in turn).  There is no syntax to specify a C-style for\nloop or a lexically scoped iteration variable in this form.\n\nprint \"Hello $!\\n\" for qw(world Dolly nurse);\n\n\"while\" repeats the statement while the condition is true.  Postfix \"while\" has the same\nmagic treatment of some kinds of condition that prefix \"while\" has.  \"until\" does the\nopposite, it repeats the statement until the condition is true (or while the condition is\nfalse):\n\n# Both of these count from 0 to 10.\nprint $i++ while $i <= 10;\nprint $j++ until $j >  10;\n\nThe \"while\" and \"until\" modifiers have the usual \"\"while\" loop\" semantics (conditional\nevaluated first), except when applied to a \"do\"-BLOCK (or to the Perl4 \"do\"-SUBROUTINE\nstatement), in which case the block executes once before the conditional is evaluated.\n\nThis is so that you can write loops like:\n\ndo {\n$line = <STDIN>;\n...\n} until !defined($line) || $line eq \".\\n\"\n\nSee \"do\" in perlfunc.  Note also that the loop control statements described later will NOT\nwork in this construct, because modifiers don't take loop labels.  Sorry.  You can always put\nanother block inside of it (for \"next\"/\"redo\") or around it (for \"last\") to do that sort of\nthing.\n\nFor \"next\" or \"redo\", just double the braces:\n\ndo {{\nnext if $x == $y;\n# do something here\n}} until $x++ > $z;\n\nFor \"last\", you have to be more elaborate and put braces around it:\n\n{\ndo {\nlast if $x == $y2;\n# do something here\n} while $x++ <= $z;\n}\n\nIf you need both \"next\" and \"last\", you have to do both and also use a loop label:\n\nLOOP: {\ndo {{\nnext if $x == $y;\nlast LOOP if $x == $y2;\n# do something here\n}} until $x++ > $z;\n}\n\nNOTE: The behaviour of a \"my\", \"state\", or \"our\" modified with a statement modifier\nconditional or loop construct (for example, \"my $x if ...\") is undefined.  The value of the\n\"my\" variable may be \"undef\", any previously assigned value, or possibly anything else.\nDon't rely on it.  Future versions of perl might do something different from the version of\nperl you try it out on.  Here be dragons.\n\nThe \"when\" modifier is an experimental feature that first appeared in Perl 5.14.  To use it,\nyou should include a \"use v5.14\" declaration.  (Technically, it requires only the \"switch\"\nfeature, but that aspect of it was not available before 5.14.)  Operative only from within a\n\"foreach\" loop or a \"given\" block, it executes the statement only if the smartmatch \"$ ~~\nEXPR\" is true.  If the statement executes, it is followed by a \"next\" from inside a \"foreach\"\nand \"break\" from inside a \"given\".\n\nUnder the current implementation, the \"foreach\" loop can be anywhere within the \"when\"\nmodifier's dynamic scope, but must be within the \"given\" block's lexical scope.  This\nrestriction may be relaxed in a future release.  See \"Switch Statements\" below.\n"
                    },
                    {
                        "name": "Compound Statements",
                        "content": "In Perl, a sequence of statements that defines a scope is called a block.  Sometimes a block\nis delimited by the file containing it (in the case of a required file, or the program as a\nwhole), and sometimes a block is delimited by the extent of a string (in the case of an\neval).\n\nBut generally, a block is delimited by curly brackets, also known as braces.  We will call\nthis syntactic construct a BLOCK.  Because enclosing braces are also the syntax for hash\nreference constructor expressions (see perlref), you may occasionally need to disambiguate by\nplacing a \";\" immediately after an opening brace so that Perl realises the brace is the start\nof a block.  You will more frequently need to disambiguate the other way, by placing a \"+\"\nimmediately before an opening brace to force it to be interpreted as a hash reference\nconstructor expression.  It is considered good style to use these disambiguating mechanisms\nliberally, not only when Perl would otherwise guess incorrectly.\n\nThe following compound statements may be used to control flow:\n\nif (EXPR) BLOCK\nif (EXPR) BLOCK else BLOCK\nif (EXPR) BLOCK elsif (EXPR) BLOCK ...\nif (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK\n\nunless (EXPR) BLOCK\nunless (EXPR) BLOCK else BLOCK\nunless (EXPR) BLOCK elsif (EXPR) BLOCK ...\nunless (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK\n\ngiven (EXPR) BLOCK\n\nLABEL while (EXPR) BLOCK\nLABEL while (EXPR) BLOCK continue BLOCK\n\nLABEL until (EXPR) BLOCK\nLABEL until (EXPR) BLOCK continue BLOCK\n\nLABEL for (EXPR; EXPR; EXPR) BLOCK\nLABEL for VAR (LIST) BLOCK\nLABEL for VAR (LIST) BLOCK continue BLOCK\n\nLABEL foreach (EXPR; EXPR; EXPR) BLOCK\nLABEL foreach VAR (LIST) BLOCK\nLABEL foreach VAR (LIST) BLOCK continue BLOCK\n\nLABEL BLOCK\nLABEL BLOCK continue BLOCK\n\nPHASE BLOCK\n\nIf enabled by the experimental \"try\" feature, the following may also be used\n\ntry BLOCK catch (VAR) BLOCK\n\nThe experimental \"given\" statement is not automatically enabled; see \"Switch Statements\"\nbelow for how to do so, and the attendant caveats.\n\nUnlike in C and Pascal, in Perl these are all defined in terms of BLOCKs, not statements.\nThis means that the curly brackets are required--no dangling statements allowed.  If you want\nto write conditionals without curly brackets, there are several other ways to do it.  The\nfollowing all do the same thing:\n\nif (!open(FOO)) { die \"Can't open $FOO: $!\" }\ndie \"Can't open $FOO: $!\" unless open(FOO);\nopen(FOO)  || die \"Can't open $FOO: $!\";\nopen(FOO) ? () : die \"Can't open $FOO: $!\";\n# a bit exotic, that last one\n\nThe \"if\" statement is straightforward.  Because BLOCKs are always bounded by curly brackets,\nthere is never any ambiguity about which \"if\" an \"else\" goes with.  If you use \"unless\" in\nplace of \"if\", the sense of the test is reversed.  Like \"if\", \"unless\" can be followed by\n\"else\".  \"unless\" can even be followed by one or more \"elsif\" statements, though you may want\nto think twice before using that particular language construct, as everyone reading your code\nwill have to think at least twice before they can understand what's going on.\n\nThe \"while\" statement executes the block as long as the expression is true.  The \"until\"\nstatement executes the block as long as the expression is false.  The LABEL is optional, and\nif present, consists of an identifier followed by a colon.  The LABEL identifies the loop for\nthe loop control statements \"next\", \"last\", and \"redo\".  If the LABEL is omitted, the loop\ncontrol statement refers to the innermost enclosing loop.  This may include dynamically\nsearching through your call-stack at run time to find the LABEL.  Such desperate behavior\ntriggers a warning if you use the \"use warnings\" pragma or the -w flag.\n\nIf the condition expression of a \"while\" statement is based on any of a group of iterative\nexpression types then it gets some magic treatment.  The affected iterative expression types\nare \"readline\", the \"<FILEHANDLE>\" input operator, \"readdir\", \"glob\", the \"<PATTERN>\"\nglobbing operator, and \"each\".  If the condition expression is one of these expression types,\nthen the value yielded by the iterative operator will be implicitly assigned to $.  If the\ncondition expression is one of these expression types or an explicit assignment of one of\nthem to a scalar, then the condition actually tests for definedness of the expression's\nvalue, not for its regular truth value.\n\nIf there is a \"continue\" BLOCK, it is always executed just before the conditional is about to\nbe evaluated again.  Thus it can be used to increment a loop variable, even when the loop has\nbeen continued via the \"next\" statement.\n\nWhen a block is preceded by a compilation phase keyword such as \"BEGIN\", \"END\", \"INIT\",\n\"CHECK\", or \"UNITCHECK\", then the block will run only during the corresponding phase of\nexecution.  See perlmod for more details.\n\nExtension modules can also hook into the Perl parser to define new kinds of compound\nstatements.  These are introduced by a keyword which the extension recognizes, and the syntax\nfollowing the keyword is defined entirely by the extension.  If you are an implementor, see\n\"PLkeywordplugin\" in perlapi for the mechanism.  If you are using such a module, see the\nmodule's documentation for details of the syntax that it defines.\n"
                    },
                    {
                        "name": "Loop Control",
                        "content": "The \"next\" command starts the next iteration of the loop:\n\nLINE: while (<STDIN>) {\nnext LINE if /^#/;      # discard comments\n...\n}\n\nThe \"last\" command immediately exits the loop in question.  The \"continue\" block, if any, is\nnot executed:\n\nLINE: while (<STDIN>) {\nlast LINE if /^$/;      # exit when done with header\n...\n}\n\nThe \"redo\" command restarts the loop block without evaluating the conditional again.  The\n\"continue\" block, if any, is not executed.  This command is normally used by programs that\nwant to lie to themselves about what was just input.\n\nFor example, when processing a file like /etc/termcap.  If your input lines might end in\nbackslashes to indicate continuation, you want to skip ahead and get the next record.\n\nwhile (<>) {\nchomp;\nif (s/\\\\$//) {\n$ .= <>;\nredo unless eof();\n}\n# now process $\n}\n\nwhich is Perl shorthand for the more explicitly written version:\n\nLINE: while (defined($line = <ARGV>)) {\nchomp($line);\nif ($line =~ s/\\\\$//) {\n$line .= <ARGV>;\nredo LINE unless eof(); # not eof(ARGV)!\n}\n# now process $line\n}\n\nNote that if there were a \"continue\" block on the above code, it would get executed only on\nlines discarded by the regex (since redo skips the continue block).  A continue block is\noften used to reset line counters or \"m?pat?\" one-time matches:\n\n# inspired by :1,$g/fred/s//WILMA/\nwhile (<>) {\nm?(fred)?    && s//WILMA $1 WILMA/;\nm?(barney)?  && s//BETTY $1 BETTY/;\nm?(homer)?   && s//MARGE $1 MARGE/;\n} continue {\nprint \"$ARGV $.: $\";\nclose ARGV  if eof;             # reset $.\nreset       if eof;             # reset ?pat?\n}\n\nIf the word \"while\" is replaced by the word \"until\", the sense of the test is reversed, but\nthe conditional is still tested before the first iteration.\n\nLoop control statements don't work in an \"if\" or \"unless\", since they aren't loops.  You can\ndouble the braces to make them such, though.\n\nif (/pattern/) {{\nlast if /fred/;\nnext if /barney/; # same effect as \"last\",\n# but doesn't document as well\n# do something here\n}}\n\nThis is caused by the fact that a block by itself acts as a loop that executes once, see\n\"Basic BLOCKs\".\n\nThe form \"while/if BLOCK BLOCK\", available in Perl 4, is no longer available.   Replace any\noccurrence of \"if BLOCK\" by \"if (do BLOCK)\".\n"
                    },
                    {
                        "name": "For Loops",
                        "content": "Perl's C-style \"for\" loop works like the corresponding \"while\" loop; that means that this:\n\nfor ($i = 1; $i < 10; $i++) {\n...\n}\n\nis the same as this:\n\n$i = 1;\nwhile ($i < 10) {\n...\n} continue {\n$i++;\n}\n\nThere is one minor difference: if variables are declared with \"my\" in the initialization\nsection of the \"for\", the lexical scope of those variables is exactly the \"for\" loop (the\nbody of the loop and the control sections).  To illustrate:\n\nmy $i = 'samba';\nfor (my $i = 1; $i <= 4; $i++) {\nprint \"$i\\n\";\n}\nprint \"$i\\n\";\n\nwhen executed, gives:\n\n1\n2\n3\n4\nsamba\n\nAs a special case, if the test in the \"for\" loop (or the corresponding \"while\" loop) is\nempty, it is treated as true.  That is, both\n\nfor (;;) {\n...\n}\n\nand\n\nwhile () {\n...\n}\n\nare treated as infinite loops.\n\nBesides the normal array index looping, \"for\" can lend itself to many other interesting\napplications.  Here's one that avoids the problem you get into if you explicitly test for\nend-of-file on an interactive file descriptor causing your program to appear to hang.\n\n$onatty = -t STDIN && -t STDOUT;\nsub prompt { print \"yes? \" if $onatty }\nfor ( prompt(); <STDIN>; prompt() ) {\n# do something\n}\n\nThe condition expression of a \"for\" loop gets the same magic treatment of \"readline\" et al\nthat the condition expression of a \"while\" loop gets.\n"
                    },
                    {
                        "name": "Foreach Loops",
                        "content": "The \"foreach\" loop iterates over a normal list value and sets the scalar variable VAR to be\neach element of the list in turn.  If the variable is preceded with the keyword \"my\", then it\nis lexically scoped, and is therefore visible only within the loop.  Otherwise, the variable\nis implicitly local to the loop and regains its former value upon exiting the loop.  If the\nvariable was previously declared with \"my\", it uses that variable instead of the global one,\nbut it's still localized to the loop.  This implicit localization occurs only in a \"foreach\"\nloop.\n\nThe \"foreach\" keyword is actually a synonym for the \"for\" keyword, so you can use either.  If\nVAR is omitted, $ is set to each value.\n\nIf any element of LIST is an lvalue, you can modify it by modifying VAR inside the loop.\nConversely, if any element of LIST is NOT an lvalue, any attempt to modify that element will\nfail.  In other words, the \"foreach\" loop index variable is an implicit alias for each item\nin the list that you're looping over.\n\nIf any part of LIST is an array, \"foreach\" will get very confused if you add or remove\nelements within the loop body, for example with \"splice\".   So don't do that.\n\n\"foreach\" probably won't do what you expect if VAR is a tied or other special variable.\nDon't do that either.\n\nAs of Perl 5.22, there is an experimental variant of this loop that accepts a variable\npreceded by a backslash for VAR, in which case the items in the LIST must be references.  The\nbackslashed variable will become an alias to each referenced item in the LIST, which must be\nof the correct type.  The variable needn't be a scalar in this case, and the backslash may be\nfollowed by \"my\".  To use this form, you must enable the \"refaliasing\" feature via \"use\nfeature\".  (See feature.  See also \"Assigning to References\" in perlref.)\n\nExamples:\n\nfor (@ary) { s/foo/bar/ }\n\nfor my $elem (@elements) {\n$elem *= 2;\n}\n\nfor $count (reverse(1..10), \"BOOM\") {\nprint $count, \"\\n\";\nsleep(1);\n}\n\nfor (1..15) { print \"Merry Christmas\\n\"; }\n\nforeach $item (split(/:[\\\\\\n:]*/, $ENV{TERMCAP})) {\nprint \"Item: $item\\n\";\n}\n\nuse feature \"refaliasing\";\nno warnings \"experimental::refaliasing\";\nforeach \\my %hash (@arrayofhashreferences) {\n# do something which each %hash\n}\n\nHere's how a C programmer might code up a particular algorithm in Perl:\n\nfor (my $i = 0; $i < @ary1; $i++) {\nfor (my $j = 0; $j < @ary2; $j++) {\nif ($ary1[$i] > $ary2[$j]) {\nlast; # can't go to outer :-(\n}\n$ary1[$i] += $ary2[$j];\n}\n# this is where that last takes me\n}\n\nWhereas here's how a Perl programmer more comfortable with the idiom might do it:\n\nOUTER: for my $wid (@ary1) {\nINNER:   for my $jet (@ary2) {\nnext OUTER if $wid > $jet;\n$wid += $jet;\n}\n}\n\nSee how much easier this is?  It's cleaner, safer, and faster.  It's cleaner because it's\nless noisy.  It's safer because if code gets added between the inner and outer loops later\non, the new code won't be accidentally executed.  The \"next\" explicitly iterates the other\nloop rather than merely terminating the inner one.  And it's faster because Perl executes a\n\"foreach\" statement more rapidly than it would the equivalent C-style \"for\" loop.\n\nPerceptive Perl hackers may have noticed that a \"for\" loop has a return value, and that this\nvalue can be captured by wrapping the loop in a \"do\" block.  The reward for this discovery is\nthis cautionary advice:  The return value of a \"for\" loop is unspecified and may change\nwithout notice.  Do not rely on it.\n"
                    },
                    {
                        "name": "Try Catch Exception Handling",
                        "content": "The \"try\"/\"catch\" syntax provides control flow relating to exception handling. The \"try\"\nkeyword introduces a block which will be executed when it is encountered, and the \"catch\"\nblock provides code to handle any exception that may be thrown by the first.\n\ntry {\nmy $x = callafunction();\n$x < 100 or die \"Too big\";\nsendoutput($x);\n}\ncatch ($e) {\nwarn \"Unable to output a value; $e\";\n}\nprint \"Finished\\n\";\n\nHere, the body of the \"catch\" block (i.e. the \"warn\" statement) will be executed if the\ninitial block invokes the conditional \"die\", or if either of the functions it invokes throws\nan uncaught exception. The \"catch\" block can inspect the $e lexical variable in this case to\nsee what the exception was.  If no exception was thrown then the \"catch\" block does not\nhappen. In either case, execution will then continue from the following statement - in this\nexample the \"print\".\n\nThe \"catch\" keyword must be immediately followed by a variable declaration in parentheses,\nwhich introduces a new variable visible to the body of the subsequent block. Inside the block\nthis variable will contain the exception value that was thrown by the code in the \"try\"\nblock. It is not necessary to use the \"my\" keyword to declare this variable; this is implied\n(similar as it is for subroutine signatures).\n\nBoth the \"try\" and the \"catch\" blocks are permitted to contain control-flow expressions, such\nas \"return\", \"goto\", or \"next\"/\"last\"/\"redo\". In all cases they behave as expected without\nwarnings. In particular, a \"return\" expression inside the \"try\" block will make its entire\ncontaining function return - this is in contrast to its behaviour inside an \"eval\" block,\nwhere it would only make that block return.\n\nLike other control-flow syntax, \"try\" and \"catch\" will yield the last evaluated value when\nplaced as the final statement in a function or a \"do\" block. This permits the syntax to be\nused to create a value. In this case remember not to use the \"return\" expression, or that\nwill cause the containing function to return.\n\nmy $value = do {\ntry {\ngetthing(@args);\n}\ncatch ($e) {\nwarn \"Unable to get thing - $e\";\n$DEFAULTTHING;\n}\n};\n\nAs with other control-flow syntax, \"try\" blocks are not visible to \"caller()\" (just as for\nexample, \"while\" or \"foreach\" loops are not).  Successive levels of the \"caller\" result can\nsee subroutine calls and \"eval\" blocks, because those affect the way that \"return\" would\nwork. Since \"try\" blocks do not intercept \"return\", they are not of interest to \"caller\".\n\nThis syntax is currently experimental and must be enabled with \"use feature 'try'\". It emits\na warning in the \"experimental::try\" category.\n"
                    },
                    {
                        "name": "Basic BLOCKs",
                        "content": "A BLOCK by itself (labeled or not) is semantically equivalent to a loop that executes once.\nThus you can use any of the loop control statements in it to leave or restart the block.\n(Note that this is NOT true in \"eval{}\", \"sub{}\", or contrary to popular belief \"do{}\"\nblocks, which do NOT count as loops.)  The \"continue\" block is optional.\n\nThe BLOCK construct can be used to emulate case structures.\n\nSWITCH: {\nif (/^abc/) { $abc = 1; last SWITCH; }\nif (/^def/) { $def = 1; last SWITCH; }\nif (/^xyz/) { $xyz = 1; last SWITCH; }\n$nothing = 1;\n}\n\nYou'll also find that \"foreach\" loop used to create a topicalizer and a switch:\n\nSWITCH:\nfor ($var) {\nif (/^abc/) { $abc = 1; last SWITCH; }\nif (/^def/) { $def = 1; last SWITCH; }\nif (/^xyz/) { $xyz = 1; last SWITCH; }\n$nothing = 1;\n}\n\nSuch constructs are quite frequently used, both because older versions of Perl had no\nofficial \"switch\" statement, and also because the new version described immediately below\nremains experimental and can sometimes be confusing.\n"
                    },
                    {
                        "name": "Switch Statements",
                        "content": "Starting from Perl 5.10.1 (well, 5.10.0, but it didn't work right), you can say\n\nuse feature \"switch\";\n\nto enable an experimental switch feature.  This is loosely based on an old version of a Raku\nproposal, but it no longer resembles the Raku construct.   You also get the switch feature\nwhenever you declare that your code prefers to run under a version of Perl that is 5.10 or\nlater.  For example:\n\nuse v5.14;\n\nUnder the \"switch\" feature, Perl gains the experimental keywords \"given\", \"when\", \"default\",\n\"continue\", and \"break\".  Starting from Perl 5.16, one can prefix the switch keywords with\n\"CORE::\" to access the feature without a \"use feature\" statement.  The keywords \"given\" and\n\"when\" are analogous to \"switch\" and \"case\" in other languages -- though \"continue\" is not --\nso the code in the previous section could be rewritten as\n\nuse v5.10.1;\nfor ($var) {\nwhen (/^abc/) { $abc = 1 }\nwhen (/^def/) { $def = 1 }\nwhen (/^xyz/) { $xyz = 1 }\ndefault       { $nothing = 1 }\n}\n\nThe \"foreach\" is the non-experimental way to set a topicalizer.  If you wish to use the\nhighly experimental \"given\", that could be written like this:\n\nuse v5.10.1;\ngiven ($var) {\nwhen (/^abc/) { $abc = 1 }\nwhen (/^def/) { $def = 1 }\nwhen (/^xyz/) { $xyz = 1 }\ndefault       { $nothing = 1 }\n}\n\nAs of 5.14, that can also be written this way:\n\nuse v5.14;\nfor ($var) {\n$abc = 1 when /^abc/;\n$def = 1 when /^def/;\n$xyz = 1 when /^xyz/;\ndefault { $nothing = 1 }\n}\n\nOr if you don't care to play it safe, like this:\n\nuse v5.14;\ngiven ($var) {\n$abc = 1 when /^abc/;\n$def = 1 when /^def/;\n$xyz = 1 when /^xyz/;\ndefault { $nothing = 1 }\n}\n\nThe arguments to \"given\" and \"when\" are in scalar context, and \"given\" assigns the $\nvariable its topic value.\n\nExactly what the EXPR argument to \"when\" does is hard to describe precisely, but in general,\nit tries to guess what you want done.  Sometimes it is interpreted as \"$ ~~ EXPR\", and\nsometimes it is not.  It also behaves differently when lexically enclosed by a \"given\" block\nthan it does when dynamically enclosed by a \"foreach\" loop.  The rules are far too difficult\nto understand to be described here.  See \"Experimental Details on given and when\" later on.\n\nDue to an unfortunate bug in how \"given\" was implemented between Perl 5.10 and 5.16, under\nthose implementations the version of $ governed by \"given\" is merely a lexically scoped copy\nof the original, not a dynamically scoped alias to the original, as it would be if it were a\n\"foreach\" or under both the original and the current Raku language specification.  This bug\nwas fixed in Perl 5.18 (and lexicalized $ itself was removed in Perl 5.24).\n\nIf your code still needs to run on older versions, stick to \"foreach\" for your topicalizer\nand you will be less unhappy.\n"
                    },
                    {
                        "name": "Goto",
                        "content": "Although not for the faint of heart, Perl does support a \"goto\" statement.  There are three\nforms: \"goto\"-LABEL, \"goto\"-EXPR, and \"goto\"-&NAME.  A loop's LABEL is not actually a valid\ntarget for a \"goto\"; it's just the name of the loop.\n\nThe \"goto\"-LABEL form finds the statement labeled with LABEL and resumes execution there.  It\nmay not be used to go into any construct that requires initialization, such as a subroutine\nor a \"foreach\" loop.  It also can't be used to go into a construct that is optimized away.\nIt can be used to go almost anywhere else within the dynamic scope, including out of\nsubroutines, but it's usually better to use some other construct such as \"last\" or \"die\".\nThe author of Perl has never felt the need to use this form of \"goto\" (in Perl, that is--C is\nanother matter).\n\nThe \"goto\"-EXPR form expects a label name, whose scope will be resolved dynamically.  This\nallows for computed \"goto\"s per FORTRAN, but isn't necessarily recommended if you're\noptimizing for maintainability:\n\ngoto((\"FOO\", \"BAR\", \"GLARCH\")[$i]);\n\nThe \"goto\"-&NAME form is highly magical, and substitutes a call to the named subroutine for\nthe currently running subroutine.  This is used by \"AUTOLOAD()\" subroutines that wish to load\nanother subroutine and then pretend that the other subroutine had been called in the first\nplace (except that any modifications to @ in the current subroutine are propagated to the\nother subroutine.)  After the \"goto\", not even \"caller()\" will be able to tell that this\nroutine was called first.\n\nIn almost all cases like this, it's usually a far, far better idea to use the structured\ncontrol flow mechanisms of \"next\", \"last\", or \"redo\" instead of resorting to a \"goto\".  For\ncertain applications, the catch and throw pair of \"eval{}\" and die() for exception processing\ncan also be a prudent approach.\n"
                    },
                    {
                        "name": "The Ellipsis Statement",
                        "content": "Beginning in Perl 5.12, Perl accepts an ellipsis, \"\"...\"\", as a placeholder for code that you\nhaven't implemented yet.  When Perl 5.12 or later encounters an ellipsis statement, it parses\nthis without error, but if and when you should actually try to execute it, Perl throws an\nexception with the text \"Unimplemented\":\n\nuse v5.12;\nsub unimplemented { ... }\neval { unimplemented() };\nif ($@ =~ /^Unimplemented at /) {\nsay \"I found an ellipsis!\";\n}\n\nYou can only use the elliptical statement to stand in for a complete statement.\nSyntactically, \"\"...;\"\" is a complete statement, but, as with other kinds of semicolon-\nterminated statement, the semicolon may be omitted if \"\"...\"\" appears immediately before a\nclosing brace.  These examples show how the ellipsis works:\n\nuse v5.12;\n{ ... }\nsub foo { ... }\n...;\neval { ... };\nsub somemeth {\nmy $self = shift;\n...;\n}\n$x = do {\nmy $n;\n...;\nsay \"Hurrah!\";\n$n;\n};\n\nThe elliptical statement cannot stand in for an expression that is part of a larger\nstatement.  These examples of attempts to use an ellipsis are syntax errors:\n\nuse v5.12;\n\nprint ...;\nopen(my $fh, \">\", \"/dev/passwd\") or ...;\nif ($condition && ... ) { say \"Howdy\" };\n... if $a > $b;\nsay \"Cromulent\" if ...;\n$flub = 5 + ...;\n\nThere are some cases where Perl can't immediately tell the difference between an expression\nand a statement.  For instance, the syntax for a block and an anonymous hash reference\nconstructor look the same unless there's something in the braces to give Perl a hint.  The\nellipsis is a syntax error if Perl doesn't guess that the \"{ ... }\" is a block.  Inside your\nblock, you can use a \";\" before the ellipsis to denote that the \"{ ... }\" is a block and not\na hash reference constructor.\n\nNote: Some folks colloquially refer to this bit of punctuation as a \"yada-yada\" or \"triple-\ndot\", but its true name is actually an ellipsis.\n"
                    },
                    {
                        "name": "PODs: Embedded Documentation",
                        "content": "Perl has a mechanism for intermixing documentation with source code.  While it's expecting\nthe beginning of a new statement, if the compiler encounters a line that begins with an equal\nsign and a word, like this\n\n=head1 Here There Be Pods!\n\nThen that text and all remaining text up through and including a line beginning with \"=cut\"\nwill be ignored.  The format of the intervening text is described in perlpod.\n\nThis allows you to intermix your source code and your documentation text freely, as in\n\n=item snazzle($)\n\nThe snazzle() function will behave in the most spectacular\nform that you can possibly imagine, not even excepting\ncybernetic pyrotechnics.\n\n=cut back to the compiler, nuff of this pod stuff!\n\nsub snazzle($) {\nmy $thingie = shift;\n.........\n}\n\nNote that pod translators should look at only paragraphs beginning with a pod directive (it\nmakes parsing easier), whereas the compiler actually knows to look for pod escapes even in\nthe middle of a paragraph.  This means that the following secret stuff will be ignored by\nboth the compiler and the translators.\n\n$a=3;\n=secret stuff\nwarn \"Neither POD nor CODE!?\"\n=cut back\nprint \"got $a\\n\";\n\nYou probably shouldn't rely upon the \"warn()\" being podded out forever.  Not all pod\ntranslators are well-behaved in this regard, and perhaps the compiler will become pickier.\n\nOne may also use pod directives to quickly comment out a section of code.\n"
                    },
                    {
                        "name": "Plain Old Comments (Not!)",
                        "content": "Perl can process line directives, much like the C preprocessor.  Using this, one can control\nPerl's idea of filenames and line numbers in error or warning messages (especially for\nstrings that are processed with \"eval()\").  The syntax for this mechanism is almost the same\nas for most C preprocessors: it matches the regular expression\n\n# example: '# line 42 \"newfilename.plx\"'\n/^\\#   \\s*\nline \\s+ (\\d+)   \\s*\n(?:\\s(\"?)([^\"]+)\\g2)? \\s*\n$/x\n\nwith $1 being the line number for the next line, and $3 being the optional filename\n(specified with or without quotes).  Note that no whitespace may precede the \"#\", unlike\nmodern C preprocessors.\n\nThere is a fairly obvious gotcha included with the line directive: Debuggers and profilers\nwill only show the last source line to appear at a particular line number in a given file.\nCare should be taken not to cause line number collisions in code you'd like to debug later.\n\nHere are some examples that you should be able to type into your command shell:\n\n% perl\n# line 200 \"bzzzt\"\n# the '#' on the previous line must be the first char on line\ndie 'foo';\nEND\nfoo at bzzzt line 201.\n\n% perl\n# line 200 \"bzzzt\"\neval qq[\\n#line 2001 \"\"\\ndie 'foo']; print $@;\nEND\nfoo at - line 2001.\n\n% perl\neval qq[\\n#line 200 \"foo bar\"\\ndie 'foo']; print $@;\nEND\nfoo at foo bar line 200.\n\n% perl\n# line 345 \"goop\"\neval \"\\n#line \" . LINE . ' \"' . FILE .\"\\\"\\ndie 'foo'\";\nprint $@;\nEND\nfoo at goop line 345.\n"
                    },
                    {
                        "name": "Experimental Details on given and when",
                        "content": "As previously mentioned, the \"switch\" feature is considered highly experimental; it is\nsubject to change with little notice.  In particular, \"when\" has tricky behaviours that are\nexpected to change to become less tricky in the future.  Do not rely upon its current\n(mis)implementation.  Before Perl 5.18, \"given\" also had tricky behaviours that you should\nstill beware of if your code must run on older versions of Perl.\n\nHere is a longer example of \"given\":\n\nuse feature \":5.10\";\ngiven ($foo) {\nwhen (undef) {\nsay '$foo is undefined';\n}\nwhen (\"foo\") {\nsay '$foo is the string \"foo\"';\n}\nwhen ([1,3,5,7,9]) {\nsay '$foo is an odd digit';\ncontinue; # Fall through\n}\nwhen ($ < 100) {\nsay '$foo is numerically less than 100';\n}\nwhen (\\&complicatedcheck) {\nsay 'a complicated check for $foo is true';\n}\ndefault {\ndie q(I don't know what to do with $foo);\n}\n}\n\nBefore Perl 5.18, \"given(EXPR)\" assigned the value of EXPR to merely a lexically scoped ccooppyy\n(!) of $, not a dynamically scoped alias the way \"foreach\" does.  That made it similar to\n\ndo { my $ = EXPR; ... }\n\nexcept that the block was automatically broken out of by a successful \"when\" or an explicit\n\"break\".  Because it was only a copy, and because it was only lexically scoped, not\ndynamically scoped, you could not do the things with it that you are used to in a \"foreach\"\nloop.  In particular, it did not work for arbitrary function calls if those functions might\ntry to access $.  Best stick to \"foreach\" for that.\n\nMost of the power comes from the implicit smartmatching that can sometimes apply.  Most of\nthe time, \"when(EXPR)\" is treated as an implicit smartmatch of $, that is, \"$ ~~ EXPR\".\n(See \"Smartmatch Operator\" in perlop for more information on smartmatching.)  But when EXPR\nis one of the 10 exceptional cases (or things like them) listed below, it is used directly as\na boolean.\n\n1.  A user-defined subroutine call or a method invocation.\n\n2.  A regular expression match in the form of \"/REGEX/\", \"$foo =~ /REGEX/\", or \"$foo =~\nEXPR\".  Also, a negated regular expression match in the form \"!/REGEX/\", \"$foo !~\n/REGEX/\", or \"$foo !~ EXPR\".\n\n3.  A smart match that uses an explicit \"~~\" operator, such as \"EXPR ~~ EXPR\".\n\nNOTE: You will often have to use \"$c ~~ $\" because the default case uses \"$ ~~ $c\" ,\nwhich is frequently the opposite of what you want.\n\n4.  A boolean comparison operator such as \"$ < 10\" or \"$x eq \"abc\"\".  The relational\noperators that this applies to are the six numeric comparisons (\"<\", \">\", \"<=\", \">=\",\n\"==\", and \"!=\"), and the six string comparisons (\"lt\", \"gt\", \"le\", \"ge\", \"eq\", and \"ne\").\n\n5.  At least the three builtin functions \"defined(...)\", \"exists(...)\", and \"eof(...)\".  We\nmight someday add more of these later if we think of them.\n\n6.  A negated expression, whether \"!(EXPR)\" or \"not(EXPR)\", or a logical exclusive-or,\n\"(EXPR1) xor (EXPR2)\".  The bitwise versions (\"~\" and \"^\") are not included.\n\n7.  A filetest operator, with exactly 4 exceptions: \"-s\", \"-M\", \"-A\", and \"-C\", as these\nreturn numerical values, not boolean ones.  The \"-z\" filetest operator is not included in\nthe exception list.\n\n8.  The \"..\" and \"...\" flip-flop operators.  Note that the \"...\" flip-flop operator is\ncompletely different from the \"...\" elliptical statement just described.\n\nIn those 8 cases above, the value of EXPR is used directly as a boolean, so no smartmatching\nis done.  You may think of \"when\" as a smartsmartmatch.\n\nFurthermore, Perl inspects the operands of logical operators to decide whether to use\nsmartmatching for each one by applying the above test to the operands:\n\n9.  If EXPR is \"EXPR1 && EXPR2\" or \"EXPR1 and EXPR2\", the test is applied recursively to both\nEXPR1 and EXPR2.  Only if both operands also pass the test, recursively, will the\nexpression be treated as boolean.  Otherwise, smartmatching is used.\n\n10. If EXPR is \"EXPR1 || EXPR2\", \"EXPR1 // EXPR2\", or \"EXPR1 or EXPR2\", the test is applied\nrecursively to EXPR1 only (which might itself be a higher-precedence AND operator, for\nexample, and thus subject to the previous rule), not to EXPR2.  If EXPR1 is to use\nsmartmatching, then EXPR2 also does so, no matter what EXPR2 contains.  But if EXPR2 does\nnot get to use smartmatching, then the second argument will not be either.  This is quite\ndifferent from the \"&&\" case just described, so be careful.\n\nThese rules are complicated, but the goal is for them to do what you want (even if you don't\nquite understand why they are doing it).  For example:\n\nwhen (/^\\d+$/ && $ < 75) { ... }\n\nwill be treated as a boolean match because the rules say both a regex match and an explicit\ntest on $ will be treated as boolean.\n\nAlso:\n\nwhen ([qw(foo bar)] && /baz/) { ... }\n\nwill use smartmatching because only one of the operands is a boolean: the other uses\nsmartmatching, and that wins.\n\nFurther:\n\nwhen ([qw(foo bar)] || /^baz/) { ... }\n\nwill use smart matching (only the first operand is considered), whereas\n\nwhen (/^baz/ || [qw(foo bar)]) { ... }\n\nwill test only the regex, which causes both operands to be treated as boolean.  Watch out for\nthis one, then, because an arrayref is always a true value, which makes it effectively\nredundant.  Not a good idea.\n\nTautologous boolean operators are still going to be optimized away.  Don't be tempted to\nwrite\n\nwhen (\"foo\" or \"bar\") { ... }\n\nThis will optimize down to \"foo\", so \"bar\" will never be considered (even though the rules\nsay to use a smartmatch on \"foo\").  For an alternation like this, an array ref will work,\nbecause this will instigate smartmatching:\n\nwhen ([qw(foo bar)] { ... }\n\nThis is somewhat equivalent to the C-style switch statement's fallthrough functionality (not\nto be confused with Perl's fallthrough functionality--see below), wherein the same block is\nused for several \"case\" statements.\n\nAnother useful shortcut is that, if you use a literal array or hash as the argument to\n\"given\", it is turned into a reference.  So \"given(@foo)\" is the same as \"given(\\@foo)\", for\nexample.\n\n\"default\" behaves exactly like \"when(1 == 1)\", which is to say that it always matches.\n\nBreaking out\n\nYou can use the \"break\" keyword to break out of the enclosing \"given\" block.  Every \"when\"\nblock is implicitly ended with a \"break\".\n\nFall-through\n\nYou can use the \"continue\" keyword to fall through from one case to the next immediate \"when\"\nor \"default\":\n\ngiven($foo) {\nwhen (/x/) { say '$foo contains an x'; continue }\nwhen (/y/) { say '$foo contains a y'            }\ndefault    { say '$foo does not contain a y'    }\n}\n\nReturn value\n\nWhen a \"given\" statement is also a valid expression (for example, when it's the last\nstatement of a block), it evaluates to:\n\n•   An empty list as soon as an explicit \"break\" is encountered.\n\n•   The value of the last evaluated expression of the successful \"when\"/\"default\" clause, if\nthere happens to be one.\n\n•   The value of the last evaluated expression of the \"given\" block if no condition is true.\n\nIn both last cases, the last expression is evaluated in the context that was applied to the\n\"given\" block.\n\nNote that, unlike \"if\" and \"unless\", failed \"when\" statements always evaluate to an empty\nlist.\n\nmy $price = do {\ngiven ($item) {\nwhen ([\"pear\", \"apple\"]) { 1 }\nbreak when \"vote\";      # My vote cannot be bought\n1e10  when /Mona Lisa/;\n\"unknown\";\n}\n};\n\nCurrently, \"given\" blocks can't always be used as proper expressions.  This may be addressed\nin a future version of Perl.\n\nSwitching in a loop\n\nInstead of using \"given()\", you can use a \"foreach()\" loop.  For example, here's one way to\ncount how many times a particular string occurs in an array:\n\nuse v5.10.1;\nmy $count = 0;\nfor (@array) {\nwhen (\"foo\") { ++$count }\n}\nprint \"\\@array contains $count copies of 'foo'\\n\";\n\nOr in a more recent version:\n\nuse v5.14;\nmy $count = 0;\nfor (@array) {\n++$count when \"foo\";\n}\nprint \"\\@array contains $count copies of 'foo'\\n\";\n\nAt the end of all \"when\" blocks, there is an implicit \"next\".  You can override that with an\nexplicit \"last\" if you're interested in only the first match alone.\n\nThis doesn't work if you explicitly specify a loop variable, as in \"for $item (@array)\".  You\nhave to use the default variable $.\n\nDifferences from Raku\n\nThe Perl 5 smartmatch and \"given\"/\"when\" constructs are not compatible with their Raku\nanalogues.  The most visible difference and least important difference is that, in Perl 5,\nparentheses are required around the argument to \"given()\" and \"when()\" (except when this last\none is used as a statement modifier).  Parentheses in Raku are always optional in a control\nconstruct such as \"if()\", \"while()\", or \"when()\"; they can't be made optional in Perl 5\nwithout a great deal of potential confusion, because Perl 5 would parse the expression\n\ngiven $foo {\n...\n}\n\nas though the argument to \"given\" were an element of the hash %foo, interpreting the braces\nas hash-element syntax.\n\nHowever, their are many, many other differences.  For example, this works in Perl 5:\n\nuse v5.12;\nmy @primary = (\"red\", \"blue\", \"green\");\n\nif (@primary ~~ \"red\") {\nsay \"primary smartmatches red\";\n}\n\nif (\"red\" ~~ @primary) {\nsay \"red smartmatches primary\";\n}\n\nsay \"that's all, folks!\";\n\nBut it doesn't work at all in Raku.  Instead, you should use the (parallelizable) \"any\"\noperator:\n\nif any(@primary) eq \"red\" {\nsay \"primary smartmatches red\";\n}\n\nif \"red\" eq any(@primary) {\nsay \"red smartmatches primary\";\n}\n\nThe table of smartmatches in \"Smartmatch Operator\" in perlop is not identical to that\nproposed by the Raku specification, mainly due to differences between Raku's and Perl 5's\ndata models, but also because the Raku spec has changed since Perl 5 rushed into early\nadoption.\n\nIn Raku, \"when()\" will always do an implicit smartmatch with its argument, while in Perl 5 it\nis convenient (albeit potentially confusing) to suppress this implicit smartmatch in various\nrather loosely-defined situations, as roughly outlined above.  (The difference is largely\nbecause Perl 5 does not have, even internally, a boolean type.)\n\n\n\nperl v5.34.0                                 2025-07-25                                   PERLSYN(1)"
                    }
                ]
            }
        }
    }
}