Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

617 lines
21 KiB

  1. =head1 NAME
  2. perlsyn - Perl syntax
  3. =head1 DESCRIPTION
  4. A Perl script consists of a sequence of declarations and statements.
  5. The only things that need to be declared in Perl are report formats
  6. and subroutines. See the sections below for more information on those
  7. declarations. All uninitialized user-created objects are assumed to
  8. start with a C<null> or C<0> value until they are defined by some explicit
  9. operation such as assignment. (Though you can get warnings about the
  10. use of undefined values if you like.) The sequence of statements is
  11. executed just once, unlike in B<sed> and B<awk> scripts, where the
  12. sequence of statements is executed for each input line. While this means
  13. that you must explicitly loop over the lines of your input file (or
  14. files), it also means you have much more control over which files and
  15. which lines you look at. (Actually, I'm lying--it is possible to do an
  16. implicit loop with either the B<-n> or B<-p> switch. It's just not the
  17. mandatory default like it is in B<sed> and B<awk>.)
  18. =head2 Declarations
  19. Perl is, for the most part, a free-form language. (The only exception
  20. to this is format declarations, for obvious reasons.) Text from a
  21. C<"#"> character until the end of the line is a comment, and is
  22. ignored. If you attempt to use C</* */> C-style comments, it will be
  23. interpreted either as division or pattern matching, depending on the
  24. context, and C++ C<//> comments just look like a null regular
  25. expression, so don't do that.
  26. A declaration can be put anywhere a statement can, but has no effect on
  27. the execution of the primary sequence of statements--declarations all
  28. take effect at compile time. Typically all the declarations are put at
  29. the beginning or the end of the script. However, if you're using
  30. lexically-scoped private variables created with C<my()>, you'll have to make sure
  31. your format or subroutine definition is within the same block scope
  32. as the my if you expect to be able to access those private variables.
  33. Declaring a subroutine allows a subroutine name to be used as if it were a
  34. list operator from that point forward in the program. You can declare a
  35. subroutine without defining it by saying C<sub name>, thus:
  36. sub myname;
  37. $me = myname $0 or die "can't get myname";
  38. Note that it functions as a list operator, not as a unary operator; so
  39. be careful to use C<or> instead of C<||> in this case. However, if
  40. you were to declare the subroutine as C<sub myname ($)>, then
  41. C<myname> would function as a unary operator, so either C<or> or
  42. C<||> would work.
  43. Subroutines declarations can also be loaded up with the C<require> statement
  44. or both loaded and imported into your namespace with a C<use> statement.
  45. See L<perlmod> for details on this.
  46. A statement sequence may contain declarations of lexically-scoped
  47. variables, but apart from declaring a variable name, the declaration acts
  48. like an ordinary statement, and is elaborated within the sequence of
  49. statements as if it were an ordinary statement. That means it actually
  50. has both compile-time and run-time effects.
  51. =head2 Simple statements
  52. The only kind of simple statement is an expression evaluated for its
  53. side effects. Every simple statement must be terminated with a
  54. semicolon, unless it is the final statement in a block, in which case
  55. the semicolon is optional. (A semicolon is still encouraged there if the
  56. block takes up more than one line, because you may eventually add another line.)
  57. Note that there are some operators like C<eval {}> and C<do {}> that look
  58. like compound statements, but aren't (they're just TERMs in an expression),
  59. and thus need an explicit termination if used as the last item in a statement.
  60. Any simple statement may optionally be followed by a I<SINGLE> modifier,
  61. just before the terminating semicolon (or block ending). The possible
  62. modifiers are:
  63. if EXPR
  64. unless EXPR
  65. while EXPR
  66. until EXPR
  67. foreach EXPR
  68. The C<if> and C<unless> modifiers have the expected semantics,
  69. presuming you're a speaker of English. The C<foreach> modifier is an
  70. iterator: For each value in EXPR, it aliases C<$_> to the value and
  71. executes the statement. The C<while> and C<until> modifiers have the
  72. usual "C<while> loop" semantics (conditional evaluated first), except
  73. when applied to a C<do>-BLOCK (or to the now-deprecated C<do>-SUBROUTINE
  74. statement), in which case the block executes once before the
  75. conditional is evaluated. This is so that you can write loops like:
  76. do {
  77. $line = <STDIN>;
  78. ...
  79. } until $line eq ".\n";
  80. See L<perlfunc/do>. Note also that the loop control statements described
  81. later will I<NOT> work in this construct, because modifiers don't take
  82. loop labels. Sorry. You can always put another block inside of it
  83. (for C<next>) or around it (for C<last>) to do that sort of thing.
  84. For C<next>, just double the braces:
  85. do {{
  86. next if $x == $y;
  87. # do something here
  88. }} until $x++ > $z;
  89. For C<last>, you have to be more elaborate:
  90. LOOP: {
  91. do {
  92. last if $x = $y**2;
  93. # do something here
  94. } while $x++ <= $z;
  95. }
  96. =head2 Compound statements
  97. In Perl, a sequence of statements that defines a scope is called a block.
  98. Sometimes a block is delimited by the file containing it (in the case
  99. of a required file, or the program as a whole), and sometimes a block
  100. is delimited by the extent of a string (in the case of an eval).
  101. But generally, a block is delimited by curly brackets, also known as braces.
  102. We will call this syntactic construct a BLOCK.
  103. The following compound statements may be used to control flow:
  104. if (EXPR) BLOCK
  105. if (EXPR) BLOCK else BLOCK
  106. if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
  107. LABEL while (EXPR) BLOCK
  108. LABEL while (EXPR) BLOCK continue BLOCK
  109. LABEL for (EXPR; EXPR; EXPR) BLOCK
  110. LABEL foreach VAR (LIST) BLOCK
  111. LABEL BLOCK continue BLOCK
  112. Note that, unlike C and Pascal, these are defined in terms of BLOCKs,
  113. not statements. This means that the curly brackets are I<required>--no
  114. dangling statements allowed. If you want to write conditionals without
  115. curly brackets there are several other ways to do it. The following
  116. all do the same thing:
  117. if (!open(FOO)) { die "Can't open $FOO: $!"; }
  118. die "Can't open $FOO: $!" unless open(FOO);
  119. open(FOO) or die "Can't open $FOO: $!"; # FOO or bust!
  120. open(FOO) ? 'hi mom' : die "Can't open $FOO: $!";
  121. # a bit exotic, that last one
  122. The C<if> statement is straightforward. Because BLOCKs are always
  123. bounded by curly brackets, there is never any ambiguity about which
  124. C<if> an C<else> goes with. If you use C<unless> in place of C<if>,
  125. the sense of the test is reversed.
  126. The C<while> statement executes the block as long as the expression is
  127. true (does not evaluate to the null string (C<"">) or C<0> or C<"0")>. The LABEL is
  128. optional, and if present, consists of an identifier followed by a colon.
  129. The LABEL identifies the loop for the loop control statements C<next>,
  130. C<last>, and C<redo>. If the LABEL is omitted, the loop control statement
  131. refers to the innermost enclosing loop. This may include dynamically
  132. looking back your call-stack at run time to find the LABEL. Such
  133. desperate behavior triggers a warning if you use the B<-w> flag.
  134. If there is a C<continue> BLOCK, it is always executed just before the
  135. conditional is about to be evaluated again, just like the third part of a
  136. C<for> loop in C. Thus it can be used to increment a loop variable, even
  137. when the loop has been continued via the C<next> statement (which is
  138. similar to the C C<continue> statement).
  139. =head2 Loop Control
  140. The C<next> command is like the C<continue> statement in C; it starts
  141. the next iteration of the loop:
  142. LINE: while (<STDIN>) {
  143. next LINE if /^#/; # discard comments
  144. ...
  145. }
  146. The C<last> command is like the C<break> statement in C (as used in
  147. loops); it immediately exits the loop in question. The
  148. C<continue> block, if any, is not executed:
  149. LINE: while (<STDIN>) {
  150. last LINE if /^$/; # exit when done with header
  151. ...
  152. }
  153. The C<redo> command restarts the loop block without evaluating the
  154. conditional again. The C<continue> block, if any, is I<not> executed.
  155. This command is normally used by programs that want to lie to themselves
  156. about what was just input.
  157. For example, when processing a file like F</etc/termcap>.
  158. If your input lines might end in backslashes to indicate continuation, you
  159. want to skip ahead and get the next record.
  160. while (<>) {
  161. chomp;
  162. if (s/\\$//) {
  163. $_ .= <>;
  164. redo unless eof();
  165. }
  166. # now process $_
  167. }
  168. which is Perl short-hand for the more explicitly written version:
  169. LINE: while (defined($line = <ARGV>)) {
  170. chomp($line);
  171. if ($line =~ s/\\$//) {
  172. $line .= <ARGV>;
  173. redo LINE unless eof(); # not eof(ARGV)!
  174. }
  175. # now process $line
  176. }
  177. Note that if there were a C<continue> block on the above code, it would get
  178. executed even on discarded lines. This is often used to reset line counters
  179. or C<?pat?> one-time matches.
  180. # inspired by :1,$g/fred/s//WILMA/
  181. while (<>) {
  182. ?(fred)? && s//WILMA $1 WILMA/;
  183. ?(barney)? && s//BETTY $1 BETTY/;
  184. ?(homer)? && s//MARGE $1 MARGE/;
  185. } continue {
  186. print "$ARGV $.: $_";
  187. close ARGV if eof(); # reset $.
  188. reset if eof(); # reset ?pat?
  189. }
  190. If the word C<while> is replaced by the word C<until>, the sense of the
  191. test is reversed, but the conditional is still tested before the first
  192. iteration.
  193. The loop control statements don't work in an C<if> or C<unless>, since
  194. they aren't loops. You can double the braces to make them such, though.
  195. if (/pattern/) {{
  196. next if /fred/;
  197. next if /barney/;
  198. # so something here
  199. }}
  200. The form C<while/if BLOCK BLOCK>, available in Perl 4, is no longer
  201. available. Replace any occurrence of C<if BLOCK> by C<if (do BLOCK)>.
  202. =head2 For Loops
  203. Perl's C-style C<for> loop works exactly like the corresponding C<while> loop;
  204. that means that this:
  205. for ($i = 1; $i < 10; $i++) {
  206. ...
  207. }
  208. is the same as this:
  209. $i = 1;
  210. while ($i < 10) {
  211. ...
  212. } continue {
  213. $i++;
  214. }
  215. (There is one minor difference: The first form implies a lexical scope
  216. for variables declared with C<my> in the initialization expression.)
  217. Besides the normal array index looping, C<for> can lend itself
  218. to many other interesting applications. Here's one that avoids the
  219. problem you get into if you explicitly test for end-of-file on
  220. an interactive file descriptor causing your program to appear to
  221. hang.
  222. $on_a_tty = -t STDIN && -t STDOUT;
  223. sub prompt { print "yes? " if $on_a_tty }
  224. for ( prompt(); <STDIN>; prompt() ) {
  225. # do something
  226. }
  227. =head2 Foreach Loops
  228. The C<foreach> loop iterates over a normal list value and sets the
  229. variable VAR to be each element of the list in turn. If the variable
  230. is preceded with the keyword C<my>, then it is lexically scoped, and
  231. is therefore visible only within the loop. Otherwise, the variable is
  232. implicitly local to the loop and regains its former value upon exiting
  233. the loop. If the variable was previously declared with C<my>, it uses
  234. that variable instead of the global one, but it's still localized to
  235. the loop. (Note that a lexically scoped variable can cause problems
  236. if you have subroutine or format declarations within the loop which
  237. refer to it.)
  238. The C<foreach> keyword is actually a synonym for the C<for> keyword, so
  239. you can use C<foreach> for readability or C<for> for brevity. (Or because
  240. the Bourne shell is more familiar to you than I<csh>, so writing C<for>
  241. comes more naturally.) If VAR is omitted, C<$_> is set to each value.
  242. If any element of LIST is an lvalue, you can modify it by modifying VAR
  243. inside the loop. That's because the C<foreach> loop index variable is
  244. an implicit alias for each item in the list that you're looping over.
  245. If any part of LIST is an array, C<foreach> will get very confused if
  246. you add or remove elements within the loop body, for example with
  247. C<splice>. So don't do that.
  248. C<foreach> probably won't do what you expect if VAR is a tied or other
  249. special variable. Don't do that either.
  250. Examples:
  251. for (@ary) { s/foo/bar/ }
  252. foreach my $elem (@elements) {
  253. $elem *= 2;
  254. }
  255. for $count (10,9,8,7,6,5,4,3,2,1,'BOOM') {
  256. print $count, "\n"; sleep(1);
  257. }
  258. for (1..15) { print "Merry Christmas\n"; }
  259. foreach $item (split(/:[\\\n:]*/, $ENV{TERMCAP})) {
  260. print "Item: $item\n";
  261. }
  262. Here's how a C programmer might code up a particular algorithm in Perl:
  263. for (my $i = 0; $i < @ary1; $i++) {
  264. for (my $j = 0; $j < @ary2; $j++) {
  265. if ($ary1[$i] > $ary2[$j]) {
  266. last; # can't go to outer :-(
  267. }
  268. $ary1[$i] += $ary2[$j];
  269. }
  270. # this is where that last takes me
  271. }
  272. Whereas here's how a Perl programmer more comfortable with the idiom might
  273. do it:
  274. OUTER: foreach my $wid (@ary1) {
  275. INNER: foreach my $jet (@ary2) {
  276. next OUTER if $wid > $jet;
  277. $wid += $jet;
  278. }
  279. }
  280. See how much easier this is? It's cleaner, safer, and faster. It's
  281. cleaner because it's less noisy. It's safer because if code gets added
  282. between the inner and outer loops later on, the new code won't be
  283. accidentally executed. The C<next> explicitly iterates the other loop
  284. rather than merely terminating the inner one. And it's faster because
  285. Perl executes a C<foreach> statement more rapidly than it would the
  286. equivalent C<for> loop.
  287. =head2 Basic BLOCKs and Switch Statements
  288. A BLOCK by itself (labeled or not) is semantically equivalent to a
  289. loop that executes once. Thus you can use any of the loop control
  290. statements in it to leave or restart the block. (Note that this is
  291. I<NOT> true in C<eval{}>, C<sub{}>, or contrary to popular belief
  292. C<do{}> blocks, which do I<NOT> count as loops.) The C<continue>
  293. block is optional.
  294. The BLOCK construct is particularly nice for doing case
  295. structures.
  296. SWITCH: {
  297. if (/^abc/) { $abc = 1; last SWITCH; }
  298. if (/^def/) { $def = 1; last SWITCH; }
  299. if (/^xyz/) { $xyz = 1; last SWITCH; }
  300. $nothing = 1;
  301. }
  302. There is no official C<switch> statement in Perl, because there are
  303. already several ways to write the equivalent. In addition to the
  304. above, you could write
  305. SWITCH: {
  306. $abc = 1, last SWITCH if /^abc/;
  307. $def = 1, last SWITCH if /^def/;
  308. $xyz = 1, last SWITCH if /^xyz/;
  309. $nothing = 1;
  310. }
  311. (That's actually not as strange as it looks once you realize that you can
  312. use loop control "operators" within an expression, That's just the normal
  313. C comma operator.)
  314. or
  315. SWITCH: {
  316. /^abc/ && do { $abc = 1; last SWITCH; };
  317. /^def/ && do { $def = 1; last SWITCH; };
  318. /^xyz/ && do { $xyz = 1; last SWITCH; };
  319. $nothing = 1;
  320. }
  321. or formatted so it stands out more as a "proper" C<switch> statement:
  322. SWITCH: {
  323. /^abc/ && do {
  324. $abc = 1;
  325. last SWITCH;
  326. };
  327. /^def/ && do {
  328. $def = 1;
  329. last SWITCH;
  330. };
  331. /^xyz/ && do {
  332. $xyz = 1;
  333. last SWITCH;
  334. };
  335. $nothing = 1;
  336. }
  337. or
  338. SWITCH: {
  339. /^abc/ and $abc = 1, last SWITCH;
  340. /^def/ and $def = 1, last SWITCH;
  341. /^xyz/ and $xyz = 1, last SWITCH;
  342. $nothing = 1;
  343. }
  344. or even, horrors,
  345. if (/^abc/)
  346. { $abc = 1 }
  347. elsif (/^def/)
  348. { $def = 1 }
  349. elsif (/^xyz/)
  350. { $xyz = 1 }
  351. else
  352. { $nothing = 1 }
  353. A common idiom for a C<switch> statement is to use C<foreach>'s aliasing to make
  354. a temporary assignment to C<$_> for convenient matching:
  355. SWITCH: for ($where) {
  356. /In Card Names/ && do { push @flags, '-e'; last; };
  357. /Anywhere/ && do { push @flags, '-h'; last; };
  358. /In Rulings/ && do { last; };
  359. die "unknown value for form variable where: `$where'";
  360. }
  361. Another interesting approach to a switch statement is arrange
  362. for a C<do> block to return the proper value:
  363. $amode = do {
  364. if ($flag & O_RDONLY) { "r" } # XXX: isn't this 0?
  365. elsif ($flag & O_WRONLY) { ($flag & O_APPEND) ? "a" : "w" }
  366. elsif ($flag & O_RDWR) {
  367. if ($flag & O_CREAT) { "w+" }
  368. else { ($flag & O_APPEND) ? "a+" : "r+" }
  369. }
  370. };
  371. Or
  372. print do {
  373. ($flags & O_WRONLY) ? "write-only" :
  374. ($flags & O_RDWR) ? "read-write" :
  375. "read-only";
  376. };
  377. Or if you are certainly that all the C<&&> clauses are true, you can use
  378. something like this, which "switches" on the value of the
  379. C<HTTP_USER_AGENT> envariable.
  380. #!/usr/bin/perl
  381. # pick out jargon file page based on browser
  382. $dir = 'http://www.wins.uva.nl/~mes/jargon';
  383. for ($ENV{HTTP_USER_AGENT}) {
  384. $page = /Mac/ && 'm/Macintrash.html'
  385. || /Win(dows )?NT/ && 'e/evilandrude.html'
  386. || /Win|MSIE|WebTV/ && 'm/MicroslothWindows.html'
  387. || /Linux/ && 'l/Linux.html'
  388. || /HP-UX/ && 'h/HP-SUX.html'
  389. || /SunOS/ && 's/ScumOS.html'
  390. || 'a/AppendixB.html';
  391. }
  392. print "Location: $dir/$page\015\012\015\012";
  393. That kind of switch statement only works when you know the C<&&> clauses
  394. will be true. If you don't, the previous C<?:> example should be used.
  395. You might also consider writing a hash instead of synthesizing a C<switch>
  396. statement.
  397. =head2 Goto
  398. Although not for the faint of heart, Perl does support a C<goto> statement.
  399. A loop's LABEL is not actually a valid target for a C<goto>;
  400. it's just the name of the loop. There are three forms: C<goto>-LABEL,
  401. C<goto>-EXPR, and C<goto>-&NAME.
  402. The C<goto>-LABEL form finds the statement labeled with LABEL and resumes
  403. execution there. It may not be used to go into any construct that
  404. requires initialization, such as a subroutine or a C<foreach> loop. It
  405. also can't be used to go into a construct that is optimized away. It
  406. can be used to go almost anywhere else within the dynamic scope,
  407. including out of subroutines, but it's usually better to use some other
  408. construct such as C<last> or C<die>. The author of Perl has never felt the
  409. need to use this form of C<goto> (in Perl, that is--C is another matter).
  410. The C<goto>-EXPR form expects a label name, whose scope will be resolved
  411. dynamically. This allows for computed C<goto>s per FORTRAN, but isn't
  412. necessarily recommended if you're optimizing for maintainability:
  413. goto ("FOO", "BAR", "GLARCH")[$i];
  414. The C<goto>-&NAME form is highly magical, and substitutes a call to the
  415. named subroutine for the currently running subroutine. This is used by
  416. C<AUTOLOAD()> subroutines that wish to load another subroutine and then
  417. pretend that the other subroutine had been called in the first place
  418. (except that any modifications to C<@_> in the current subroutine are
  419. propagated to the other subroutine.) After the C<goto>, not even C<caller()>
  420. will be able to tell that this routine was called first.
  421. In almost all cases like this, it's usually a far, far better idea to use the
  422. structured control flow mechanisms of C<next>, C<last>, or C<redo> instead of
  423. resorting to a C<goto>. For certain applications, the catch and throw pair of
  424. C<eval{}> and die() for exception processing can also be a prudent approach.
  425. =head2 PODs: Embedded Documentation
  426. Perl has a mechanism for intermixing documentation with source code.
  427. While it's expecting the beginning of a new statement, if the compiler
  428. encounters a line that begins with an equal sign and a word, like this
  429. =head1 Here There Be Pods!
  430. Then that text and all remaining text up through and including a line
  431. beginning with C<=cut> will be ignored. The format of the intervening
  432. text is described in L<perlpod>.
  433. This allows you to intermix your source code
  434. and your documentation text freely, as in
  435. =item snazzle($)
  436. The snazzle() function will behave in the most spectacular
  437. form that you can possibly imagine, not even excepting
  438. cybernetic pyrotechnics.
  439. =cut back to the compiler, nuff of this pod stuff!
  440. sub snazzle($) {
  441. my $thingie = shift;
  442. .........
  443. }
  444. Note that pod translators should look at only paragraphs beginning
  445. with a pod directive (it makes parsing easier), whereas the compiler
  446. actually knows to look for pod escapes even in the middle of a
  447. paragraph. This means that the following secret stuff will be
  448. ignored by both the compiler and the translators.
  449. $a=3;
  450. =secret stuff
  451. warn "Neither POD nor CODE!?"
  452. =cut back
  453. print "got $a\n";
  454. You probably shouldn't rely upon the C<warn()> being podded out forever.
  455. Not all pod translators are well-behaved in this regard, and perhaps
  456. the compiler will become pickier.
  457. One may also use pod directives to quickly comment out a section
  458. of code.
  459. =head2 Plain Old Comments (Not!)
  460. Much like the C preprocessor, Perl can process line directives. Using
  461. this, one can control Perl's idea of filenames and line numbers in
  462. error or warning messages (especially for strings that are processed
  463. with C<eval()>). The syntax for this mechanism is the same as for most
  464. C preprocessors: it matches the regular expression
  465. C</^#\s*line\s+(\d+)\s*(?:\s"([^"]*)")?/> with C<$1> being the line
  466. number for the next line, and C<$2> being the optional filename
  467. (specified within quotes).
  468. Here are some examples that you should be able to type into your command
  469. shell:
  470. % perl
  471. # line 200 "bzzzt"
  472. # the `#' on the previous line must be the first char on line
  473. die 'foo';
  474. __END__
  475. foo at bzzzt line 201.
  476. % perl
  477. # line 200 "bzzzt"
  478. eval qq[\n#line 2001 ""\ndie 'foo']; print $@;
  479. __END__
  480. foo at - line 2001.
  481. % perl
  482. eval qq[\n#line 200 "foo bar"\ndie 'foo']; print $@;
  483. __END__
  484. foo at foo bar line 200.
  485. % perl
  486. # line 345 "goop"
  487. eval "\n#line " . __LINE__ . ' "' . __FILE__ ."\"\ndie 'foo'";
  488. print $@;
  489. __END__
  490. foo at goop line 345.
  491. =cut