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, abbrevi‐
21       ated DWIM.  It allows programmers to be lazy and to code in a style
22       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 exten‐
27       sions.  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
33       The only things you need to declare in Perl are report formats and sub‐
34       routines (and sometimes not even subroutines).  A variable holds the
35       undefined value ("undef") until it has been assigned a defined value,
36       which is anything other than "undef".  When used as a number, "undef"
37       is treated as 0; when used as a string, it is treated as the empty
38       string, ""; and when used as a reference that isn't being assigned to,
39       it is treated as an error.  If you enable warnings, you'll be notified
40       of an uninitialized value whenever you treat "undef" as a string or a
41       number.  Well, usually.  Boolean contexts, such as:
42
43           my $a;
44           if ($a) {}
45
46       are exempt from warnings (because they care about truth rather than
47       definedness).  Operators such as "++", "--", "+=", "-=", and ".=", that
48       operate on undefined left values such as:
49
50           my $a;
51           $a++;
52
53       are also always exempt from such warnings.
54
55       A declaration can be put anywhere a statement can, but has no effect on
56       the execution of the primary sequence of statements--declarations all
57       take effect at compile time.  Typically all the declarations are put at
58       the beginning or the end of the script.  However, if you're using lexi‐
59       cally-scoped private variables created with "my()", you'll have to make
60       sure your format or subroutine definition is within the same block
61       scope as the my if you expect to be able to access those private vari‐
62       ables.
63
64       Declaring a subroutine allows a subroutine name to be used as if it
65       were a list operator from that point forward in the program.  You can
66       declare a subroutine without defining it by saying "sub name", thus:
67
68           sub myname;
69           $me = myname $0             or die "can't get myname";
70
71       Note that myname() functions as a list operator, not as a unary opera‐
72       tor; so be careful to use "or" instead of "⎪⎪" in this case.  However,
73       if you were to declare the subroutine as "sub myname ($)", then
74       "myname" would function as a unary operator, so either "or" or "⎪⎪"
75       would work.
76
77       Subroutines declarations can also be loaded up with the "require"
78       statement or both loaded and imported into your namespace with a "use"
79       statement.  See perlmod for details on this.
80
81       A statement sequence may contain declarations of lexically-scoped vari‐
82       ables, but apart from declaring a variable name, the declaration acts
83       like an ordinary statement, and is elaborated within the sequence of
84       statements as if it were an ordinary statement.  That means it actually
85       has both compile-time and run-time effects.
86
87       Comments
88
89       Text from a "#" character until the end of the line is a comment, and
90       is ignored.  Exceptions include "#" inside a string or regular expres‐
91       sion.
92
93       Simple Statements
94
95       The only kind of simple statement is an expression evaluated for its
96       side effects.  Every simple statement must be terminated with a semi‐
97       colon, unless it is the final statement in a block, in which case the
98       semicolon is optional.  (A semicolon is still encouraged if the block
99       takes up more than one line, because you may eventually add another
100       line.)  Note that there are some operators like "eval {}" and "do {}"
101       that look like compound statements, but aren't (they're just TERMs in
102       an expression), and thus need an explicit termination if used as the
103       last item in a statement.
104
105       Truth and Falsehood
106
107       The number 0, the strings '0' and '', the empty list "()", and "undef"
108       are all false in a boolean context. All other values are true.  Nega‐
109       tion of a true value by "!" or "not" returns a special false value.
110       When evaluated as a string it is treated as '', but as a number, it is
111       treated as 0.
112
113       Statement Modifiers
114
115       Any simple statement may optionally be followed by a SINGLE modifier,
116       just before the terminating semicolon (or block ending).  The possible
117       modifiers are:
118
119           if EXPR
120           unless EXPR
121           while EXPR
122           until EXPR
123           foreach LIST
124
125       The "EXPR" following the modifier is referred to as the "condition".
126       Its truth or falsehood determines how the modifier will behave.
127
128       "if" executes the statement once if and only if the condition is true.
129       "unless" is the opposite, it executes the statement unless the condi‐
130       tion is true (i.e., if the condition is false).
131
132           print "Basset hounds got long ears" if length $ear >= 10;
133           go_outside() and play() unless $is_raining;
134
135       The "foreach" modifier is an iterator: it executes the statement once
136       for each item in the LIST (with $_ aliased to each item in turn).
137
138           print "Hello $_!\n" foreach qw(world Dolly nurse);
139
140       "while" repeats the statement while the condition is true.  "until"
141       does the opposite, it repeats the statement until the condition is true
142       (or while the condition is false):
143
144           # Both of these count from 0 to 10.
145           print $i++ while $i <= 10;
146           print $j++ until $j >  10;
147
148       The "while" and "until" modifiers have the usual ""while" loop" seman‐
149       tics (conditional evaluated first), except when applied to a "do"-BLOCK
150       (or to the deprecated "do"-SUBROUTINE statement), in which case the
151       block executes once before the conditional is evaluated.  This is so
152       that you can write loops like:
153
154           do {
155               $line = <STDIN>;
156               ...
157           } until $line  eq ".\n";
158
159       See "do" in perlfunc.  Note also that the loop control statements
160       described later will NOT work in this construct, because modifiers
161       don't take loop labels.  Sorry.  You can always put another block
162       inside of it (for "next") or around it (for "last") to do that sort of
163       thing.  For "next", just double the braces:
164
165           do {{
166               next if $x == $y;
167               # do something here
168           }} until $x++ > $z;
169
170       For "last", you have to be more elaborate:
171
172           LOOP: {
173                   do {
174                       last if $x = $y**2;
175                       # do something here
176                   } while $x++ <= $z;
177           }
178
179       NOTE: The behaviour of a "my" statement modified with a statement modi‐
180       fier conditional or loop construct (e.g. "my $x if ...") is undefined.
181       The value of the "my" variable may be "undef", any previously assigned
182       value, or possibly anything else.  Don't rely on it.  Future versions
183       of perl might do something different from the version of perl you try
184       it out on.  Here be dragons.
185
186       Compound Statements
187
188       In Perl, a sequence of statements that defines a scope is called a
189       block.  Sometimes a block is delimited by the file containing it (in
190       the case of a required file, or the program as a whole), and sometimes
191       a block is delimited by the extent of a string (in the case of an
192       eval).
193
194       But generally, a block is delimited by curly brackets, also known as
195       braces.  We will call this syntactic construct a BLOCK.
196
197       The following compound statements may be used to control flow:
198
199           if (EXPR) BLOCK
200           if (EXPR) BLOCK else BLOCK
201           if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
202           LABEL while (EXPR) BLOCK
203           LABEL while (EXPR) BLOCK continue BLOCK
204           LABEL until (EXPR) BLOCK
205           LABEL until (EXPR) BLOCK continue BLOCK
206           LABEL for (EXPR; EXPR; EXPR) BLOCK
207           LABEL foreach VAR (LIST) BLOCK
208           LABEL foreach VAR (LIST) BLOCK continue BLOCK
209           LABEL BLOCK continue BLOCK
210
211       Note that, unlike C and Pascal, these are defined in terms of BLOCKs,
212       not statements.  This means that the curly brackets are required--no
213       dangling statements allowed.  If you want to write conditionals without
214       curly brackets there are several other ways to do it.  The following
215       all do the same thing:
216
217           if (!open(FOO)) { die "Can't open $FOO: $!"; }
218           die "Can't open $FOO: $!" unless open(FOO);
219           open(FOO) or die "Can't open $FOO: $!";     # FOO or bust!
220           open(FOO) ? 'hi mom' : die "Can't open $FOO: $!";
221                               # a bit exotic, that last one
222
223       The "if" statement is straightforward.  Because BLOCKs are always
224       bounded by curly brackets, there is never any ambiguity about which
225       "if" an "else" goes with.  If you use "unless" in place of "if", the
226       sense of the test is reversed.
227
228       The "while" statement executes the block as long as the expression is
229       true (does not evaluate to the null string "" or 0 or "0").  The
230       "until" statement executes the block as long as the expression is
231       false.  The LABEL is optional, and if present, consists of an identi‐
232       fier followed by a colon.  The LABEL identifies the loop for the loop
233       control statements "next", "last", and "redo".  If the LABEL is omit‐
234       ted, the loop control statement refers to the innermost enclosing loop.
235       This may include dynamically looking back your call-stack at run time
236       to find the LABEL.  Such desperate behavior triggers a warning if you
237       use the "use warnings" pragma or the -w flag.
238
239       If there is a "continue" BLOCK, it is always executed just before the
240       conditional is about to be evaluated again.  Thus it can be used to
241       increment a loop variable, even when the loop has been continued via
242       the "next" statement.
243
244       Loop Control
245
246       The "next" command starts the next iteration of the loop:
247
248           LINE: while (<STDIN>) {
249               next LINE if /^#/;      # discard comments
250               ...
251           }
252
253       The "last" command immediately exits the loop in question.  The "con‐
254       tinue" block, if any, is not executed:
255
256           LINE: while (<STDIN>) {
257               last LINE if /^$/;      # exit when done with header
258               ...
259           }
260
261       The "redo" command restarts the loop block without evaluating the con‐
262       ditional again.  The "continue" block, if any, is not executed.  This
263       command is normally used by programs that want to lie to themselves
264       about what was just input.
265
266       For example, when processing a file like /etc/termcap.  If your input
267       lines might end in backslashes to indicate continuation, you want to
268       skip ahead and get the next record.
269
270           while (<>) {
271               chomp;
272               if (s/\\$//) {
273                   $_ .= <>;
274                   redo unless eof();
275               }
276               # now process $_
277           }
278
279       which is Perl short-hand for the more explicitly written version:
280
281           LINE: while (defined($line = <ARGV>)) {
282               chomp($line);
283               if ($line =~ s/\\$//) {
284                   $line .= <ARGV>;
285                   redo LINE unless eof(); # not eof(ARGV)!
286               }
287               # now process $line
288           }
289
290       Note that if there were a "continue" block on the above code, it would
291       get executed only on lines discarded by the regex (since redo skips the
292       continue block). A continue block is often used to reset line counters
293       or "?pat?" one-time matches:
294
295           # inspired by :1,$g/fred/s//WILMA/
296           while (<>) {
297               ?(fred)?    && s//WILMA $1 WILMA/;
298               ?(barney)?  && s//BETTY $1 BETTY/;
299               ?(homer)?   && s//MARGE $1 MARGE/;
300           } continue {
301               print "$ARGV $.: $_";
302               close ARGV  if eof();           # reset $.
303               reset       if eof();           # reset ?pat?
304           }
305
306       If the word "while" is replaced by the word "until", the sense of the
307       test is reversed, but the conditional is still tested before the first
308       iteration.
309
310       The loop control statements don't work in an "if" or "unless", since
311       they aren't loops.  You can double the braces to make them such,
312       though.
313
314           if (/pattern/) {{
315               last if /fred/;
316               next if /barney/; # same effect as "last", but doesn't document as well
317               # do something here
318           }}
319
320       This is caused by the fact that a block by itself acts as a loop that
321       executes once, see "Basic BLOCKs and Switch Statements".
322
323       The form "while/if BLOCK BLOCK", available in Perl 4, is no longer
324       available.   Replace any occurrence of "if BLOCK" by "if (do BLOCK)".
325
326       For Loops
327
328       Perl's C-style "for" loop works like the corresponding "while" loop;
329       that means that this:
330
331           for ($i = 1; $i < 10; $i++) {
332               ...
333           }
334
335       is the same as this:
336
337           $i = 1;
338           while ($i < 10) {
339               ...
340           } continue {
341               $i++;
342           }
343
344       There is one minor difference: if variables are declared with "my" in
345       the initialization section of the "for", the lexical scope of those
346       variables is exactly the "for" loop (the body of the loop and the con‐
347       trol sections).
348
349       Besides the normal array index looping, "for" can lend itself to many
350       other interesting applications.  Here's one that avoids the problem you
351       get into if you explicitly test for end-of-file on an interactive file
352       descriptor causing your program to appear to hang.
353
354           $on_a_tty = -t STDIN && -t STDOUT;
355           sub prompt { print "yes? " if $on_a_tty }
356           for ( prompt(); <STDIN>; prompt() ) {
357               # do something
358           }
359
360       Using "readline" (or the operator form, "<EXPR>") as the conditional of
361       a "for" loop is shorthand for the following.  This behaviour is the
362       same as a "while" loop conditional.
363
364           for ( prompt(); defined( $_ = <STDIN> ); prompt() ) {
365               # do something
366           }
367
368       Foreach Loops
369
370       The "foreach" loop iterates over a normal list value and sets the vari‐
371       able VAR to be each element of the list in turn.  If the variable is
372       preceded with the keyword "my", then it is lexically scoped, and is
373       therefore visible only within the loop.  Otherwise, the variable is
374       implicitly local to the loop and regains its former value upon exiting
375       the loop.  If the variable was previously declared with "my", it uses
376       that variable instead of the global one, but it's still localized to
377       the loop.  This implicit localisation occurs only in a "foreach" loop.
378
379       The "foreach" keyword is actually a synonym for the "for" keyword, so
380       you can use "foreach" for readability or "for" for brevity.  (Or
381       because the Bourne shell is more familiar to you than csh, so writing
382       "for" comes more naturally.)  If VAR is omitted, $_ is set to each
383       value.
384
385       If any element of LIST is an lvalue, you can modify it by modifying VAR
386       inside the loop.  Conversely, if any element of LIST is NOT an lvalue,
387       any attempt to modify that element will fail.  In other words, the
388       "foreach" loop index variable is an implicit alias for each item in the
389       list that you're looping over.
390
391       If any part of LIST is an array, "foreach" will get very confused if
392       you add or remove elements within the loop body, for example with
393       "splice".   So don't do that.
394
395       "foreach" probably won't do what you expect if VAR is a tied or other
396       special variable.   Don't do that either.
397
398       Examples:
399
400           for (@ary) { s/foo/bar/ }
401
402           for my $elem (@elements) {
403               $elem *= 2;
404           }
405
406           for $count (10,9,8,7,6,5,4,3,2,1,'BOOM') {
407               print $count, "\n"; sleep(1);
408           }
409
410           for (1..15) { print "Merry Christmas\n"; }
411
412           foreach $item (split(/:[\\\n:]*/, $ENV{TERMCAP})) {
413               print "Item: $item\n";
414           }
415
416       Here's how a C programmer might code up a particular algorithm in Perl:
417
418           for (my $i = 0; $i < @ary1; $i++) {
419               for (my $j = 0; $j < @ary2; $j++) {
420                   if ($ary1[$i] > $ary2[$j]) {
421                       last; # can't go to outer :-(
422                   }
423                   $ary1[$i] += $ary2[$j];
424               }
425               # this is where that last takes me
426           }
427
428       Whereas here's how a Perl programmer more comfortable with the idiom
429       might do it:
430
431           OUTER: for my $wid (@ary1) {
432           INNER:   for my $jet (@ary2) {
433                       next OUTER if $wid > $jet;
434                       $wid += $jet;
435                    }
436                 }
437
438       See how much easier this is?  It's cleaner, safer, and faster.  It's
439       cleaner because it's less noisy.  It's safer because if code gets added
440       between the inner and outer loops later on, the new code won't be acci‐
441       dentally executed.  The "next" explicitly iterates the other loop
442       rather than merely terminating the inner one.  And it's faster because
443       Perl executes a "foreach" statement more rapidly than it would the
444       equivalent "for" loop.
445
446       Basic BLOCKs and Switch Statements
447
448       A BLOCK by itself (labeled or not) is semantically equivalent to a loop
449       that executes once.  Thus you can use any of the loop control state‐
450       ments in it to leave or restart the block.  (Note that this is NOT true
451       in "eval{}", "sub{}", or contrary to popular belief "do{}" blocks,
452       which do NOT count as loops.)  The "continue" block is optional.
453
454       The BLOCK construct is particularly nice for doing case structures.
455
456           SWITCH: {
457               if (/^abc/) { $abc = 1; last SWITCH; }
458               if (/^def/) { $def = 1; last SWITCH; }
459               if (/^xyz/) { $xyz = 1; last SWITCH; }
460               $nothing = 1;
461           }
462
463       There is no official "switch" statement in Perl, because there are
464       already several ways to write the equivalent.
465
466       However, starting from Perl 5.8 to get switch and case one can use the
467       Switch extension and say:
468
469               use Switch;
470
471       after which one has switch and case.  It is not as fast as it could be
472       because it's not really part of the language (it's done using source
473       filters) but it is available, and it's very flexible.
474
475       In addition to the above BLOCK construct, you could write
476
477           SWITCH: {
478               $abc = 1, last SWITCH  if /^abc/;
479               $def = 1, last SWITCH  if /^def/;
480               $xyz = 1, last SWITCH  if /^xyz/;
481               $nothing = 1;
482           }
483
484       (That's actually not as strange as it looks once you realize that you
485       can use loop control "operators" within an expression.  That's just the
486       binary comma operator in scalar context.  See "Comma Operator" in per‐
487       lop.)
488
489       or
490
491           SWITCH: {
492               /^abc/ && do { $abc = 1; last SWITCH; };
493               /^def/ && do { $def = 1; last SWITCH; };
494               /^xyz/ && do { $xyz = 1; last SWITCH; };
495               $nothing = 1;
496           }
497
498       or formatted so it stands out more as a "proper" "switch" statement:
499
500           SWITCH: {
501               /^abc/      && do {
502                                   $abc = 1;
503                                   last SWITCH;
504                              };
505
506               /^def/      && do {
507                                   $def = 1;
508                                   last SWITCH;
509                              };
510
511               /^xyz/      && do {
512                                   $xyz = 1;
513                                   last SWITCH;
514                               };
515               $nothing = 1;
516           }
517
518       or
519
520           SWITCH: {
521               /^abc/ and $abc = 1, last SWITCH;
522               /^def/ and $def = 1, last SWITCH;
523               /^xyz/ and $xyz = 1, last SWITCH;
524               $nothing = 1;
525           }
526
527       or even, horrors,
528
529           if (/^abc/)
530               { $abc = 1 }
531           elsif (/^def/)
532               { $def = 1 }
533           elsif (/^xyz/)
534               { $xyz = 1 }
535           else
536               { $nothing = 1 }
537
538       A common idiom for a "switch" statement is to use "foreach"'s aliasing
539       to make a temporary assignment to $_ for convenient matching:
540
541           SWITCH: for ($where) {
542                       /In Card Names/     && do { push @flags, '-e'; last; };
543                       /Anywhere/          && do { push @flags, '-h'; last; };
544                       /In Rulings/        && do {                    last; };
545                       die "unknown value for form variable where: `$where'";
546                   }
547
548       Another interesting approach to a switch statement is arrange for a
549       "do" block to return the proper value:
550
551           $amode = do {
552               if     ($flag & O_RDONLY) { "r" }       # XXX: isn't this 0?
553               elsif  ($flag & O_WRONLY) { ($flag & O_APPEND) ? "a" : "w" }
554               elsif  ($flag & O_RDWR)   {
555                   if ($flag & O_CREAT)  { "w+" }
556                   else                  { ($flag & O_APPEND) ? "a+" : "r+" }
557               }
558           };
559
560       Or
561
562               print do {
563                   ($flags & O_WRONLY) ? "write-only"          :
564                   ($flags & O_RDWR)   ? "read-write"          :
565                                         "read-only";
566               };
567
568       Or if you are certain that all the "&&" clauses are true, you can use
569       something like this, which "switches" on the value of the
570       "HTTP_USER_AGENT" environment variable.
571
572           #!/usr/bin/perl
573           # pick out jargon file page based on browser
574           $dir = 'http://www.wins.uva.nl/~mes/jargon';
575           for ($ENV{HTTP_USER_AGENT}) {
576               $page  =    /Mac/            && 'm/Macintrash.html'
577                        ⎪⎪ /Win(dows )?NT/  && 'e/evilandrude.html'
578                        ⎪⎪ /Win⎪MSIE⎪WebTV/ && 'm/MicroslothWindows.html'
579                        ⎪⎪ /Linux/          && 'l/Linux.html'
580                        ⎪⎪ /HP-UX/          && 'h/HP-SUX.html'
581                        ⎪⎪ /SunOS/          && 's/ScumOS.html'
582                        ⎪⎪                     'a/AppendixB.html';
583           }
584           print "Location: $dir/$page\015\012\015\012";
585
586       That kind of switch statement only works when you know the "&&" clauses
587       will be true.  If you don't, the previous "?:" example should be used.
588
589       You might also consider writing a hash of subroutine references instead
590       of synthesizing a "switch" statement.
591
592       Goto
593
594       Although not for the faint of heart, Perl does support a "goto" state‐
595       ment.  There are three forms: "goto"-LABEL, "goto"-EXPR, and
596       "goto"-&NAME.  A loop's LABEL is not actually a valid target for a
597       "goto"; it's just the name of the loop.
598
599       The "goto"-LABEL form finds the statement labeled with LABEL and
600       resumes execution there.  It may not be used to go into any construct
601       that requires initialization, such as a subroutine or a "foreach" loop.
602       It also can't be used to go into a construct that is optimized away.
603       It can be used to go almost anywhere else within the dynamic scope,
604       including out of subroutines, but it's usually better to use some other
605       construct such as "last" or "die".  The author of Perl has never felt
606       the need to use this form of "goto" (in Perl, that is--C is another
607       matter).
608
609       The "goto"-EXPR form expects a label name, whose scope will be resolved
610       dynamically.  This allows for computed "goto"s per FORTRAN, but isn't
611       necessarily recommended if you're optimizing for maintainability:
612
613           goto(("FOO", "BAR", "GLARCH")[$i]);
614
615       The "goto"-&NAME form is highly magical, and substitutes a call to the
616       named subroutine for the currently running subroutine.  This is used by
617       "AUTOLOAD()" subroutines that wish to load another subroutine and then
618       pretend that the other subroutine had been called in the first place
619       (except that any modifications to @_ in the current subroutine are
620       propagated to the other subroutine.)  After the "goto", not even "call‐
621       er()" will be able to tell that this routine was called first.
622
623       In almost all cases like this, it's usually a far, far better idea to
624       use the structured control flow mechanisms of "next", "last", or "redo"
625       instead of resorting to a "goto".  For certain applications, the catch
626       and throw pair of "eval{}" and die() for exception processing can also
627       be a prudent approach.
628
629       PODs: Embedded Documentation
630
631       Perl has a mechanism for intermixing documentation with source code.
632       While it's expecting the beginning of a new statement, if the compiler
633       encounters a line that begins with an equal sign and a word, like this
634
635           =head1 Here There Be Pods!
636
637       Then that text and all remaining text up through and including a line
638       beginning with "=cut" will be ignored.  The format of the intervening
639       text is described in perlpod.
640
641       This allows you to intermix your source code and your documentation
642       text freely, as in
643
644           =item snazzle($)
645
646           The snazzle() function will behave in the most spectacular
647           form that you can possibly imagine, not even excepting
648           cybernetic pyrotechnics.
649
650           =cut back to the compiler, nuff of this pod stuff!
651
652           sub snazzle($) {
653               my $thingie = shift;
654               .........
655           }
656
657       Note that pod translators should look at only paragraphs beginning with
658       a pod directive (it makes parsing easier), whereas the compiler actu‐
659       ally knows to look for pod escapes even in the middle of a paragraph.
660       This means that the following secret stuff will be ignored by both the
661       compiler and the translators.
662
663           $a=3;
664           =secret stuff
665            warn "Neither POD nor CODE!?"
666           =cut back
667           print "got $a\n";
668
669       You probably shouldn't rely upon the "warn()" being podded out forever.
670       Not all pod translators are well-behaved in this regard, and perhaps
671       the compiler will become pickier.
672
673       One may also use pod directives to quickly comment out a section of
674       code.
675
676       Plain Old Comments (Not!)
677
678       Perl can process line directives, much like the C preprocessor.  Using
679       this, one can control Perl's idea of filenames and line numbers in
680       error or warning messages (especially for strings that are processed
681       with "eval()").  The syntax for this mechanism is the same as for most
682       C preprocessors: it matches the regular expression
683
684           # example: '# line 42 "new_filename.plx"'
685           /^\#   \s*
686             line \s+ (\d+)   \s*
687             (?:\s("?)([^"]+)\2)? \s*
688            $/x
689
690       with $1 being the line number for the next line, and $3 being the
691       optional filename (specified with or without quotes).
692
693       There is a fairly obvious gotcha included with the line directive:
694       Debuggers and profilers will only show the last source line to appear
695       at a particular line number in a given file.  Care should be taken not
696       to cause line number collisions in code you'd like to debug later.
697
698       Here are some examples that you should be able to type into your com‐
699       mand shell:
700
701           % perl
702           # line 200 "bzzzt"
703           # the `#' on the previous line must be the first char on line
704           die 'foo';
705           __END__
706           foo at bzzzt line 201.
707
708           % perl
709           # line 200 "bzzzt"
710           eval qq[\n#line 2001 ""\ndie 'foo']; print $@;
711           __END__
712           foo at - line 2001.
713
714           % perl
715           eval qq[\n#line 200 "foo bar"\ndie 'foo']; print $@;
716           __END__
717           foo at foo bar line 200.
718
719           % perl
720           # line 345 "goop"
721           eval "\n#line " . __LINE__ . ' "' . __FILE__ ."\"\ndie 'foo'";
722           print $@;
723           __END__
724           foo at goop line 345.
725
726
727
728perl v5.8.8                       2006-01-07                        PERLSYN(1)
Impressum