1PERLSYN(1)             Perl Programmers Reference Guide             PERLSYN(1)
2
3
4

NAME

6       perlsyn - Perl syntax
7

DESCRIPTION

9       A Perl program consists of a sequence of declarations and statements
10       which run from the top to the bottom.  Loops, subroutines and other
11       control structures allow you to jump around within the code.
12
13       Perl is a free-form language, you can format and indent it however you
14       like.  Whitespace mostly serves to separate tokens, unlike languages
15       like Python where it is an important part of the syntax.
16
17       Many of Perl's syntactic elements are optional.  Rather than requiring
18       you to put parentheses around every function call and declare every
19       variable, you can often leave such explicit elements off and Perl will
20       figure out what you meant.  This is known as Do What I Mean,
21       abbreviated DWIM.  It allows programmers to be lazy and to code in a
22       style with which they are comfortable.
23
24       Perl borrows syntax and concepts from many languages: awk, sed, C,
25       Bourne Shell, Smalltalk, Lisp and even English.  Other languages have
26       borrowed syntax from Perl, particularly its regular expression
27       extensions.  So if you have programmed in another language you will see
28       familiar pieces in Perl.  They often work the same, but see perltrap
29       for information about how they differ.
30
31   Declarations
32       The only things you need to declare in Perl are report formats and
33       subroutines (and sometimes not even subroutines).  A variable holds the
34       undefined value ("undef") until it has been assigned a defined value,
35       which is anything other than "undef".  When used as a number, "undef"
36       is treated as 0; when used as a string, it is treated as the empty
37       string, ""; and when used as a reference that isn't being assigned to,
38       it is treated as an error.  If you enable warnings, you'll be notified
39       of an uninitialized value whenever you treat "undef" as a string or a
40       number.  Well, usually.  Boolean contexts, such as:
41
42           my $a;
43           if ($a) {}
44
45       are exempt from warnings (because they care about truth rather than
46       definedness).  Operators such as "++", "--", "+=", "-=", and ".=", that
47       operate on undefined left values such as:
48
49           my $a;
50           $a++;
51
52       are also always exempt from such warnings.
53
54       A declaration can be put anywhere a statement can, but has no effect on
55       the execution of the primary sequence of statements--declarations all
56       take effect at compile time.  Typically all the declarations are put at
57       the beginning or the end of the script.  However, if you're using
58       lexically-scoped private variables created with "my()", you'll have to
59       make sure your format or subroutine definition is within the same block
60       scope as the my if you expect to be able to access those private
61       variables.
62
63       Declaring a subroutine allows a subroutine name to be used as if it
64       were a list operator from that point forward in the program.  You can
65       declare a subroutine without defining it by saying "sub name", thus:
66
67           sub myname;
68           $me = myname $0             or die "can't get myname";
69
70       Note that myname() functions as a list operator, not as a unary
71       operator; so be careful to use "or" instead of "||" in this case.
72       However, if you were to declare the subroutine as "sub myname ($)",
73       then "myname" would function as a unary operator, so either "or" or
74       "||" would work.
75
76       Subroutines declarations can also be loaded up with the "require"
77       statement or both loaded and imported into your namespace with a "use"
78       statement.  See perlmod for details on this.
79
80       A statement sequence may contain declarations of lexically-scoped
81       variables, but apart from declaring a variable name, the declaration
82       acts like an ordinary statement, and is elaborated within the sequence
83       of statements as if it were an ordinary statement.  That means it
84       actually has both compile-time and run-time effects.
85
86   Comments
87       Text from a "#" character until the end of the line is a comment, and
88       is ignored.  Exceptions include "#" inside a string or regular
89       expression.
90
91   Simple Statements
92       The only kind of simple statement is an expression evaluated for its
93       side effects.  Every simple statement must be terminated with a
94       semicolon, unless it is the final statement in a block, in which case
95       the semicolon is optional.  (A semicolon is still encouraged if the
96       block takes up more than one line, because you may eventually add
97       another line.)  Note that there are some operators like "eval {}" and
98       "do {}" that look like compound statements, but aren't (they're just
99       TERMs in an expression), and thus need an explicit termination if used
100       as the last item in a statement.
101
102   Truth and Falsehood
103       The number 0, the strings '0' and '', the empty list "()", and "undef"
104       are all false in a boolean context. All other values are true.
105       Negation of a true value by "!" or "not" returns a special false value.
106       When evaluated as a string it is treated as '', but as a number, it is
107       treated as 0.
108
109   Statement Modifiers
110       Any simple statement may optionally be followed by a SINGLE modifier,
111       just before the terminating semicolon (or block ending).  The possible
112       modifiers are:
113
114           if EXPR
115           unless EXPR
116           while EXPR
117           until EXPR
118           foreach LIST
119
120       The "EXPR" following the modifier is referred to as the "condition".
121       Its truth or falsehood determines how the modifier will behave.
122
123       "if" executes the statement once if and only if the condition is true.
124       "unless" is the opposite, it executes the statement unless the
125       condition is true (i.e., if the condition is false).
126
127           print "Basset hounds got long ears" if length $ear >= 10;
128           go_outside() and play() unless $is_raining;
129
130       The "foreach" modifier is an iterator: it executes the statement once
131       for each item in the LIST (with $_ aliased to each item in turn).
132
133           print "Hello $_!\n" foreach qw(world Dolly nurse);
134
135       "while" repeats the statement while the condition is true.  "until"
136       does the opposite, it repeats the statement until the condition is true
137       (or while the condition is false):
138
139           # Both of these count from 0 to 10.
140           print $i++ while $i <= 10;
141           print $j++ until $j >  10;
142
143       The "while" and "until" modifiers have the usual ""while" loop"
144       semantics (conditional evaluated first), except when applied to a
145       "do"-BLOCK (or to the deprecated "do"-SUBROUTINE statement), in which
146       case the block executes once before the conditional is evaluated.  This
147       is so that you can write loops like:
148
149           do {
150               $line = <STDIN>;
151               ...
152           } until $line  eq ".\n";
153
154       See "do" in perlfunc.  Note also that the loop control statements
155       described later will NOT work in this construct, because modifiers
156       don't take loop labels.  Sorry.  You can always put another block
157       inside of it (for "next") or around it (for "last") to do that sort of
158       thing.  For "next", just double the braces:
159
160           do {{
161               next if $x == $y;
162               # do something here
163           }} until $x++ > $z;
164
165       For "last", you have to be more elaborate:
166
167           LOOP: {
168                   do {
169                       last if $x = $y**2;
170                       # do something here
171                   } while $x++ <= $z;
172           }
173
174       NOTE: The behaviour of a "my" statement modified with a statement
175       modifier conditional or loop construct (e.g. "my $x if ...") is
176       undefined.  The value of the "my" variable may be "undef", any
177       previously assigned value, or possibly anything else.  Don't rely on
178       it.  Future versions of perl might do something different from the
179       version of perl you try it out on.  Here be dragons.
180
181   Compound Statements
182       In Perl, a sequence of statements that defines a scope is called a
183       block.  Sometimes a block is delimited by the file containing it (in
184       the case of a required file, or the program as a whole), and sometimes
185       a block is delimited by the extent of a string (in the case of an
186       eval).
187
188       But generally, a block is delimited by curly brackets, also known as
189       braces.  We will call this syntactic construct a BLOCK.
190
191       The following compound statements may be used to control flow:
192
193           if (EXPR) BLOCK
194           if (EXPR) BLOCK else BLOCK
195           if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
196           LABEL while (EXPR) BLOCK
197           LABEL while (EXPR) BLOCK continue BLOCK
198           LABEL until (EXPR) BLOCK
199           LABEL until (EXPR) BLOCK continue BLOCK
200           LABEL for (EXPR; EXPR; EXPR) BLOCK
201           LABEL foreach VAR (LIST) BLOCK
202           LABEL foreach VAR (LIST) BLOCK continue BLOCK
203           LABEL BLOCK continue BLOCK
204
205       Note that, unlike C and Pascal, these are defined in terms of BLOCKs,
206       not statements.  This means that the curly brackets are required--no
207       dangling statements allowed.  If you want to write conditionals without
208       curly brackets there are several other ways to do it.  The following
209       all do the same thing:
210
211           if (!open(FOO)) { die "Can't open $FOO: $!"; }
212           die "Can't open $FOO: $!" unless open(FOO);
213           open(FOO) or die "Can't open $FOO: $!";     # FOO or bust!
214           open(FOO) ? 'hi mom' : die "Can't open $FOO: $!";
215                               # a bit exotic, that last one
216
217       The "if" statement is straightforward.  Because BLOCKs are always
218       bounded by curly brackets, there is never any ambiguity about which
219       "if" an "else" goes with.  If you use "unless" in place of "if", the
220       sense of the test is reversed.
221
222       The "while" statement executes the block as long as the expression is
223       true.  The "until" statement executes the block as long as the
224       expression is false.  The LABEL is optional, and if present, consists
225       of an identifier followed by a colon.  The LABEL identifies the loop
226       for the loop control statements "next", "last", and "redo".  If the
227       LABEL is omitted, the loop control statement refers to the innermost
228       enclosing loop.  This may include dynamically looking back your call-
229       stack at run time to find the LABEL.  Such desperate behavior triggers
230       a warning if you use the "use warnings" pragma or the -w flag.
231
232       If there is a "continue" BLOCK, it is always executed just before the
233       conditional is about to be evaluated again.  Thus it can be used to
234       increment a loop variable, even when the loop has been continued via
235       the "next" statement.
236
237   Loop Control
238       The "next" command starts the next iteration of the loop:
239
240           LINE: while (<STDIN>) {
241               next LINE if /^#/;      # discard comments
242               ...
243           }
244
245       The "last" command immediately exits the loop in question.  The
246       "continue" block, if any, is not executed:
247
248           LINE: while (<STDIN>) {
249               last LINE if /^$/;      # exit when done with header
250               ...
251           }
252
253       The "redo" command restarts the loop block without evaluating the
254       conditional again.  The "continue" block, if any, is not executed.
255       This command is normally used by programs that want to lie to
256       themselves about what was just input.
257
258       For example, when processing a file like /etc/termcap.  If your input
259       lines might end in backslashes to indicate continuation, you want to
260       skip ahead and get the next record.
261
262           while (<>) {
263               chomp;
264               if (s/\\$//) {
265                   $_ .= <>;
266                   redo unless eof();
267               }
268               # now process $_
269           }
270
271       which is Perl short-hand for the more explicitly written version:
272
273           LINE: while (defined($line = <ARGV>)) {
274               chomp($line);
275               if ($line =~ s/\\$//) {
276                   $line .= <ARGV>;
277                   redo LINE unless eof(); # not eof(ARGV)!
278               }
279               # now process $line
280           }
281
282       Note that if there were a "continue" block on the above code, it would
283       get executed only on lines discarded by the regex (since redo skips the
284       continue block). A continue block is often used to reset line counters
285       or "?pat?" one-time matches:
286
287           # inspired by :1,$g/fred/s//WILMA/
288           while (<>) {
289               ?(fred)?    && s//WILMA $1 WILMA/;
290               ?(barney)?  && s//BETTY $1 BETTY/;
291               ?(homer)?   && s//MARGE $1 MARGE/;
292           } continue {
293               print "$ARGV $.: $_";
294               close ARGV  if eof();           # reset $.
295               reset       if eof();           # reset ?pat?
296           }
297
298       If the word "while" is replaced by the word "until", the sense of the
299       test is reversed, but the conditional is still tested before the first
300       iteration.
301
302       The loop control statements don't work in an "if" or "unless", since
303       they aren't loops.  You can double the braces to make them such,
304       though.
305
306           if (/pattern/) {{
307               last if /fred/;
308               next if /barney/; # same effect as "last", but doesn't document as well
309               # do something here
310           }}
311
312       This is caused by the fact that a block by itself acts as a loop that
313       executes once, see "Basic BLOCKs".
314
315       The form "while/if BLOCK BLOCK", available in Perl 4, is no longer
316       available.   Replace any occurrence of "if BLOCK" by "if (do BLOCK)".
317
318   For Loops
319       Perl's C-style "for" loop works like the corresponding "while" loop;
320       that means that this:
321
322           for ($i = 1; $i < 10; $i++) {
323               ...
324           }
325
326       is the same as this:
327
328           $i = 1;
329           while ($i < 10) {
330               ...
331           } continue {
332               $i++;
333           }
334
335       There is one minor difference: if variables are declared with "my" in
336       the initialization section of the "for", the lexical scope of those
337       variables is exactly the "for" loop (the body of the loop and the
338       control sections).
339
340       Besides the normal array index looping, "for" can lend itself to many
341       other interesting applications.  Here's one that avoids the problem you
342       get into if you explicitly test for end-of-file on an interactive file
343       descriptor causing your program to appear to hang.
344
345           $on_a_tty = -t STDIN && -t STDOUT;
346           sub prompt { print "yes? " if $on_a_tty }
347           for ( prompt(); <STDIN>; prompt() ) {
348               # do something
349           }
350
351       Using "readline" (or the operator form, "<EXPR>") as the conditional of
352       a "for" loop is shorthand for the following.  This behaviour is the
353       same as a "while" loop conditional.
354
355           for ( prompt(); defined( $_ = <STDIN> ); prompt() ) {
356               # do something
357           }
358
359   Foreach Loops
360       The "foreach" loop iterates over a normal list value and sets the
361       variable VAR to be each element of the list in turn.  If the variable
362       is preceded with the keyword "my", then it is lexically scoped, and is
363       therefore visible only within the loop.  Otherwise, the variable is
364       implicitly local to the loop and regains its former value upon exiting
365       the loop.  If the variable was previously declared with "my", it uses
366       that variable instead of the global one, but it's still localized to
367       the loop.  This implicit localisation occurs only in a "foreach" loop.
368
369       The "foreach" keyword is actually a synonym for the "for" keyword, so
370       you can use "foreach" for readability or "for" for brevity.  (Or
371       because the Bourne shell is more familiar to you than csh, so writing
372       "for" comes more naturally.)  If VAR is omitted, $_ is set to each
373       value.
374
375       If any element of LIST is an lvalue, you can modify it by modifying VAR
376       inside the loop.  Conversely, if any element of LIST is NOT an lvalue,
377       any attempt to modify that element will fail.  In other words, the
378       "foreach" loop index variable is an implicit alias for each item in the
379       list that you're looping over.
380
381       If any part of LIST is an array, "foreach" will get very confused if
382       you add or remove elements within the loop body, for example with
383       "splice".   So don't do that.
384
385       "foreach" probably won't do what you expect if VAR is a tied or other
386       special variable.   Don't do that either.
387
388       Examples:
389
390           for (@ary) { s/foo/bar/ }
391
392           for my $elem (@elements) {
393               $elem *= 2;
394           }
395
396           for $count (10,9,8,7,6,5,4,3,2,1,'BOOM') {
397               print $count, "\n"; sleep(1);
398           }
399
400           for (1..15) { print "Merry Christmas\n"; }
401
402           foreach $item (split(/:[\\\n:]*/, $ENV{TERMCAP})) {
403               print "Item: $item\n";
404           }
405
406       Here's how a C programmer might code up a particular algorithm in Perl:
407
408           for (my $i = 0; $i < @ary1; $i++) {
409               for (my $j = 0; $j < @ary2; $j++) {
410                   if ($ary1[$i] > $ary2[$j]) {
411                       last; # can't go to outer :-(
412                   }
413                   $ary1[$i] += $ary2[$j];
414               }
415               # this is where that last takes me
416           }
417
418       Whereas here's how a Perl programmer more comfortable with the idiom
419       might do it:
420
421           OUTER: for my $wid (@ary1) {
422           INNER:   for my $jet (@ary2) {
423                       next OUTER if $wid > $jet;
424                       $wid += $jet;
425                    }
426                 }
427
428       See how much easier this is?  It's cleaner, safer, and faster.  It's
429       cleaner because it's less noisy.  It's safer because if code gets added
430       between the inner and outer loops later on, the new code won't be
431       accidentally executed.  The "next" explicitly iterates the other loop
432       rather than merely terminating the inner one.  And it's faster because
433       Perl executes a "foreach" statement more rapidly than it would the
434       equivalent "for" loop.
435
436   Basic BLOCKs
437       A BLOCK by itself (labeled or not) is semantically equivalent to a loop
438       that executes once.  Thus you can use any of the loop control
439       statements in it to leave or restart the block.  (Note that this is NOT
440       true in "eval{}", "sub{}", or contrary to popular belief "do{}" blocks,
441       which do NOT count as loops.)  The "continue" block is optional.
442
443       The BLOCK construct can be used to emulate case structures.
444
445           SWITCH: {
446               if (/^abc/) { $abc = 1; last SWITCH; }
447               if (/^def/) { $def = 1; last SWITCH; }
448               if (/^xyz/) { $xyz = 1; last SWITCH; }
449               $nothing = 1;
450           }
451
452       Such constructs are quite frequently used, because older versions of
453       Perl had no official "switch" statement.
454
455   Switch statements
456       Starting from Perl 5.10, you can say
457
458           use feature "switch";
459
460       which enables a switch feature that is closely based on the Perl 6
461       proposal.
462
463       The keywords "given" and "when" are analogous to "switch" and "case" in
464       other languages, so the code above could be written as
465
466           given($_) {
467               when (/^abc/) { $abc = 1; }
468               when (/^def/) { $def = 1; }
469               when (/^xyz/) { $xyz = 1; }
470               default { $nothing = 1; }
471           }
472
473       This construct is very flexible and powerful. For example:
474
475           use feature ":5.10";
476           given($foo) {
477               when (undef) {
478                   say '$foo is undefined';
479               }
480               when ("foo") {
481                   say '$foo is the string "foo"';
482               }
483               when ([1,3,5,7,9]) {
484                   say '$foo is an odd digit';
485                   continue; # Fall through
486               }
487               when ($_ < 100) {
488                   say '$foo is numerically less than 100';
489               }
490               when (\&complicated_check) {
491                   say 'a complicated check for $foo is true';
492               }
493               default {
494                   die q(I don't know what to do with $foo);
495               }
496           }
497
498       "given(EXPR)" will assign the value of EXPR to $_ within the lexical
499       scope of the block, so it's similar to
500
501               do { my $_ = EXPR; ... }
502
503       except that the block is automatically broken out of by a successful
504       "when" or an explicit "break".
505
506       Most of the power comes from implicit smart matching:
507
508               when($foo)
509
510       is exactly equivalent to
511
512               when($_ ~~ $foo)
513
514       Most of the time, "when(EXPR)" is treated as an implicit smart match of
515       $_, i.e. "$_ ~~ EXPR". (See "Smart matching in detail" for more
516       information on smart matching.) But when EXPR is one of the below
517       exceptional cases, it is used directly as a boolean:
518
519       ·   a subroutine or method call
520
521       ·   a regular expression match, i.e. "/REGEX/" or "$foo =~ /REGEX/", or
522           a negated regular expression match ("!/REGEX/" or "$foo !~
523           /REGEX/").
524
525       ·   a comparison such as "$_ < 10" or "$x eq "abc"" (or of course "$_
526           ~~ $c")
527
528       ·   "defined(...)", "exists(...)", or "eof(...)"
529
530       ·   a negated expression "!(...)" or "not (...)", or a logical
531           exclusive-or "(...) xor (...)".
532
533       ·   a filetest operator, with the exception of "-s", "-M", "-A", and
534           "-C", that return numerical values, not boolean ones.
535
536       ·   the ".." and "..." flip-flop operators.
537
538       In those cases the value of EXPR is used directly as a boolean.
539
540       Furthermore:
541
542       ·   If EXPR is "... && ..." or "... and ...", the test is applied
543           recursively to both arguments. If both arguments pass the test,
544           then the argument is treated as boolean.
545
546       ·   If EXPR is "... || ...", "... // ..." or "... or ...", the test is
547           applied recursively to the first argument.
548
549       These rules look complicated, but usually they will do what you want.
550       For example you could write:
551
552           when (/^\d+$/ && $_ < 75) { ... }
553
554       Another useful shortcut is that, if you use a literal array or hash as
555       the argument to "given", it is turned into a reference. So
556       "given(@foo)" is the same as "given(\@foo)", for example.
557
558       "default" behaves exactly like "when(1 == 1)", which is to say that it
559       always matches.
560
561       Breaking out
562
563       You can use the "break" keyword to break out of the enclosing "given"
564       block.  Every "when" block is implicitly ended with a "break".
565
566       Fall-through
567
568       You can use the "continue" keyword to fall through from one case to the
569       next:
570
571           given($foo) {
572               when (/x/) { say '$foo contains an x'; continue }
573               when (/y/) { say '$foo contains a y' }
574               default    { say '$foo does not contain a y' }
575           }
576
577       Switching in a loop
578
579       Instead of using "given()", you can use a "foreach()" loop.  For
580       example, here's one way to count how many times a particular string
581       occurs in an array:
582
583           my $count = 0;
584           for (@array) {
585               when ("foo") { ++$count }
586           }
587           print "\@array contains $count copies of 'foo'\n";
588
589       On exit from the "when" block, there is an implicit "next".  You can
590       override that with an explicit "last" if you're only interested in the
591       first match.
592
593       This doesn't work if you explicitly specify a loop variable, as in "for
594       $item (@array)". You have to use the default variable $_. (You can use
595       "for my $_ (@array)".)
596
597       Smart matching in detail
598
599       The behaviour of a smart match depends on what type of thing its
600       arguments are. The behaviour is determined by the following table: the
601       first row that applies determines the match behaviour (which is thus
602       mostly determined by the type of the right operand). Note that the
603       smart match implicitly dereferences any non-blessed hash or array ref,
604       so the "Hash" and "Array" entries apply in those cases. (For blessed
605       references, the "Object" entries apply.)
606
607       Note that the "Matching Code" column is not always an exact rendition.
608       For example, the smart match operator short-circuits whenever possible,
609       but "grep" does not.
610
611           $a      $b        Type of Match Implied    Matching Code
612           ======  =====     =====================    =============
613           Any     undef     undefined                !defined $a
614
615           Any     Object    invokes ~~ overloading on $object, or dies
616
617           Hash    CodeRef   sub truth for each key[1] !grep { !$b->($_) } keys %$a
618           Array   CodeRef   sub truth for each elt[1] !grep { !$b->($_) } @$a
619           Any     CodeRef   scalar sub truth          $b->($a)
620
621           Hash    Hash      hash keys identical (every key is found in both hashes)
622           Array   Hash      hash slice existence     grep { exists $b->{$_} } @$a
623           Regex   Hash      hash key grep            grep /$a/, keys %$b
624           undef   Hash      always false (undef can't be a key)
625           Any     Hash      hash entry existence     exists $b->{$a}
626
627           Hash    Array     hash slice existence     grep { exists $a->{$_} } @$b
628           Array   Array     arrays are comparable[2]
629           Regex   Array     array grep               grep /$a/, @$b
630           undef   Array     array contains undef     grep !defined, @$b
631           Any     Array     match against an array element[3]
632                                                      grep $a ~~ $_, @$b
633
634           Hash    Regex     hash key grep            grep /$b/, keys %$a
635           Array   Regex     array grep               grep /$b/, @$a
636           Any     Regex     pattern match            $a =~ /$b/
637
638           Object  Any       invokes ~~ overloading on $object, or falls back:
639           Any     Num       numeric equality         $a == $b
640           Num     numish[4] numeric equality         $a == $b
641           undef   Any       undefined                !defined($b)
642           Any     Any       string equality          $a eq $b
643
644        1 - empty hashes or arrays will match.
645        2 - that is, each element smart-matches the element of same index in the
646            other array. [3]
647        3 - If a circular reference is found, we fall back to referential equality.
648        4 - either a real number, or a string that looks like a number
649
650       Custom matching via overloading
651
652       You can change the way that an object is matched by overloading the
653       "~~" operator. This may alter the usual smart match semantics.
654
655       It should be noted that "~~" will refuse to work on objects that don't
656       overload it (in order to avoid relying on the object's underlying
657       structure).
658
659       Note also that smart match's matching rules take precedence over
660       overloading, so if $obj has smart match overloading, then
661
662           $obj ~~ X
663
664       will not automatically invoke the overload method with X as an
665       argument; instead the table above is consulted as normal, and based in
666       the type of X, overloading may or may not be invoked.
667
668       See overload.
669
670       Differences from Perl 6
671
672       The Perl 5 smart match and "given"/"when" constructs are not absolutely
673       identical to their Perl 6 analogues. The most visible difference is
674       that, in Perl 5, parentheses are required around the argument to
675       "given()" and "when()". Parentheses in Perl 6 are always optional in a
676       control construct such as "if()", "while()", or "when()"; they can't be
677       made optional in Perl 5 without a great deal of potential confusion,
678       because Perl 5 would parse the expression
679
680         given $foo {
681           ...
682         }
683
684       as though the argument to "given" were an element of the hash %foo,
685       interpreting the braces as hash-element syntax.
686
687       The table of smart matches is not identical to that proposed by the
688       Perl 6 specification, mainly due to the differences between Perl 6's
689       and Perl 5's data models.
690
691       In Perl 6, "when()" will always do an implicit smart match with its
692       argument, whilst it is convenient in Perl 5 to suppress this implicit
693       smart match in certain situations, as documented above. (The difference
694       is largely because Perl 5 does not, even internally, have a boolean
695       type.)
696
697   Goto
698       Although not for the faint of heart, Perl does support a "goto"
699       statement.  There are three forms: "goto"-LABEL, "goto"-EXPR, and
700       "goto"-&NAME.  A loop's LABEL is not actually a valid target for a
701       "goto"; it's just the name of the loop.
702
703       The "goto"-LABEL form finds the statement labeled with LABEL and
704       resumes execution there.  It may not be used to go into any construct
705       that requires initialization, such as a subroutine or a "foreach" loop.
706       It also can't be used to go into a construct that is optimized away.
707       It can be used to go almost anywhere else within the dynamic scope,
708       including out of subroutines, but it's usually better to use some other
709       construct such as "last" or "die".  The author of Perl has never felt
710       the need to use this form of "goto" (in Perl, that is--C is another
711       matter).
712
713       The "goto"-EXPR form expects a label name, whose scope will be resolved
714       dynamically.  This allows for computed "goto"s per FORTRAN, but isn't
715       necessarily recommended if you're optimizing for maintainability:
716
717           goto(("FOO", "BAR", "GLARCH")[$i]);
718
719       The "goto"-&NAME form is highly magical, and substitutes a call to the
720       named subroutine for the currently running subroutine.  This is used by
721       "AUTOLOAD()" subroutines that wish to load another subroutine and then
722       pretend that the other subroutine had been called in the first place
723       (except that any modifications to @_ in the current subroutine are
724       propagated to the other subroutine.)  After the "goto", not even
725       "caller()" will be able to tell that this routine was called first.
726
727       In almost all cases like this, it's usually a far, far better idea to
728       use the structured control flow mechanisms of "next", "last", or "redo"
729       instead of resorting to a "goto".  For certain applications, the catch
730       and throw pair of "eval{}" and die() for exception processing can also
731       be a prudent approach.
732
733   PODs: Embedded Documentation
734       Perl has a mechanism for intermixing documentation with source code.
735       While it's expecting the beginning of a new statement, if the compiler
736       encounters a line that begins with an equal sign and a word, like this
737
738           =head1 Here There Be Pods!
739
740       Then that text and all remaining text up through and including a line
741       beginning with "=cut" will be ignored.  The format of the intervening
742       text is described in perlpod.
743
744       This allows you to intermix your source code and your documentation
745       text freely, as in
746
747           =item snazzle($)
748
749           The snazzle() function will behave in the most spectacular
750           form that you can possibly imagine, not even excepting
751           cybernetic pyrotechnics.
752
753           =cut back to the compiler, nuff of this pod stuff!
754
755           sub snazzle($) {
756               my $thingie = shift;
757               .........
758           }
759
760       Note that pod translators should look at only paragraphs beginning with
761       a pod directive (it makes parsing easier), whereas the compiler
762       actually knows to look for pod escapes even in the middle of a
763       paragraph.  This means that the following secret stuff will be ignored
764       by both the compiler and the translators.
765
766           $a=3;
767           =secret stuff
768            warn "Neither POD nor CODE!?"
769           =cut back
770           print "got $a\n";
771
772       You probably shouldn't rely upon the "warn()" being podded out forever.
773       Not all pod translators are well-behaved in this regard, and perhaps
774       the compiler will become pickier.
775
776       One may also use pod directives to quickly comment out a section of
777       code.
778
779   Plain Old Comments (Not!)
780       Perl can process line directives, much like the C preprocessor.  Using
781       this, one can control Perl's idea of filenames and line numbers in
782       error or warning messages (especially for strings that are processed
783       with "eval()").  The syntax for this mechanism is the same as for most
784       C preprocessors: it matches the regular expression
785
786           # example: '# line 42 "new_filename.plx"'
787           /^\#   \s*
788             line \s+ (\d+)   \s*
789             (?:\s("?)([^"]+)\2)? \s*
790            $/x
791
792       with $1 being the line number for the next line, and $3 being the
793       optional filename (specified with or without quotes).
794
795       There is a fairly obvious gotcha included with the line directive:
796       Debuggers and profilers will only show the last source line to appear
797       at a particular line number in a given file.  Care should be taken not
798       to cause line number collisions in code you'd like to debug later.
799
800       Here are some examples that you should be able to type into your
801       command shell:
802
803           % perl
804           # line 200 "bzzzt"
805           # the `#' on the previous line must be the first char on line
806           die 'foo';
807           __END__
808           foo at bzzzt line 201.
809
810           % perl
811           # line 200 "bzzzt"
812           eval qq[\n#line 2001 ""\ndie 'foo']; print $@;
813           __END__
814           foo at - line 2001.
815
816           % perl
817           eval qq[\n#line 200 "foo bar"\ndie 'foo']; print $@;
818           __END__
819           foo at foo bar line 200.
820
821           % perl
822           # line 345 "goop"
823           eval "\n#line " . __LINE__ . ' "' . __FILE__ ."\"\ndie 'foo'";
824           print $@;
825           __END__
826           foo at goop line 345.
827
828
829
830perl v5.10.1                      2009-08-22                        PERLSYN(1)
Impressum