Leaked source code of windows server 2003
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.

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