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.

1174 lines
43 KiB

  1. =head1 NAME
  2. perlsub - Perl subroutines
  3. =head1 SYNOPSIS
  4. To declare subroutines:
  5. sub NAME; # A "forward" declaration.
  6. sub NAME(PROTO); # ditto, but with prototypes
  7. sub NAME BLOCK # A declaration and a definition.
  8. sub NAME(PROTO) BLOCK # ditto, but with prototypes
  9. To define an anonymous subroutine at runtime:
  10. $subref = sub BLOCK; # no proto
  11. $subref = sub (PROTO) BLOCK; # with proto
  12. To import subroutines:
  13. use PACKAGE qw(NAME1 NAME2 NAME3);
  14. To call subroutines:
  15. NAME(LIST); # & is optional with parentheses.
  16. NAME LIST; # Parentheses optional if predeclared/imported.
  17. &NAME; # Makes current @_ visible to called subroutine.
  18. =head1 DESCRIPTION
  19. Like many languages, Perl provides for user-defined subroutines. These
  20. may be located anywhere in the main program, loaded in from other files
  21. via the C<do>, C<require>, or C<use> keywords, or even generated on the
  22. fly using C<eval> or anonymous subroutines (closures). You can even call
  23. a function indirectly using a variable containing its name or a CODE reference
  24. to it.
  25. The Perl model for function call and return values is simple: all
  26. functions are passed as parameters one single flat list of scalars, and
  27. all functions likewise return to their caller one single flat list of
  28. scalars. Any arrays or hashes in these call and return lists will
  29. collapse, losing their identities--but you may always use
  30. pass-by-reference instead to avoid this. Both call and return lists may
  31. contain as many or as few scalar elements as you'd like. (Often a
  32. function without an explicit return statement is called a subroutine, but
  33. there's really no difference from the language's perspective.)
  34. Any arguments passed to the routine come in as the array C<@_>. Thus if you
  35. called a function with two arguments, those would be stored in C<$_[0]>
  36. and C<$_[1]>. The array C<@_> is a local array, but its elements are
  37. aliases for the actual scalar parameters. In particular, if an element
  38. C<$_[0]> is updated, the corresponding argument is updated (or an error
  39. occurs if it is not updatable). If an argument is an array or hash
  40. element which did not exist when the function was called, that element is
  41. created only when (and if) it is modified or if a reference to it is
  42. taken. (Some earlier versions of Perl created the element whether or not
  43. it was assigned to.) Note that assigning to the whole array C<@_> removes
  44. the aliasing, and does not update any arguments.
  45. The return value of the subroutine is the value of the last expression
  46. evaluated. Alternatively, a C<return> statement may be used to exit the
  47. subroutine, optionally specifying the returned value, which will be
  48. evaluated in the appropriate context (list, scalar, or void) depending
  49. on the context of the subroutine call. If you specify no return value,
  50. the subroutine will return an empty list in a list context, an undefined
  51. value in a scalar context, or nothing in a void context. If you return
  52. one or more arrays and/or hashes, these will be flattened together into
  53. one large indistinguishable list.
  54. Perl does not have named formal parameters, but in practice all you do is
  55. assign to a C<my()> list of these. Any variables you use in the function
  56. that aren't declared private are global variables. For the gory details
  57. on creating private variables, see
  58. L<"Private Variables via my()"> and L<"Temporary Values via local()">.
  59. To create protected environments for a set of functions in a separate
  60. package (and probably a separate file), see L<perlmod/"Packages">.
  61. Example:
  62. sub max {
  63. my $max = shift(@_);
  64. foreach $foo (@_) {
  65. $max = $foo if $max < $foo;
  66. }
  67. return $max;
  68. }
  69. $bestday = max($mon,$tue,$wed,$thu,$fri);
  70. Example:
  71. # get a line, combining continuation lines
  72. # that start with whitespace
  73. sub get_line {
  74. $thisline = $lookahead; # GLOBAL VARIABLES!!
  75. LINE: while (defined($lookahead = <STDIN>)) {
  76. if ($lookahead =~ /^[ \t]/) {
  77. $thisline .= $lookahead;
  78. }
  79. else {
  80. last LINE;
  81. }
  82. }
  83. $thisline;
  84. }
  85. $lookahead = <STDIN>; # get first line
  86. while ($_ = get_line()) {
  87. ...
  88. }
  89. Use array assignment to a local list to name your formal arguments:
  90. sub maybeset {
  91. my($key, $value) = @_;
  92. $Foo{$key} = $value unless $Foo{$key};
  93. }
  94. This also has the effect of turning call-by-reference into call-by-value,
  95. because the assignment copies the values. Otherwise a function is free to
  96. do in-place modifications of C<@_> and change its caller's values.
  97. upcase_in($v1, $v2); # this changes $v1 and $v2
  98. sub upcase_in {
  99. for (@_) { tr/a-z/A-Z/ }
  100. }
  101. You aren't allowed to modify constants in this way, of course. If an
  102. argument were actually literal and you tried to change it, you'd take a
  103. (presumably fatal) exception. For example, this won't work:
  104. upcase_in("frederick");
  105. It would be much safer if the C<upcase_in()> function
  106. were written to return a copy of its parameters instead
  107. of changing them in place:
  108. ($v3, $v4) = upcase($v1, $v2); # this doesn't
  109. sub upcase {
  110. return unless defined wantarray; # void context, do nothing
  111. my @parms = @_;
  112. for (@parms) { tr/a-z/A-Z/ }
  113. return wantarray ? @parms : $parms[0];
  114. }
  115. Notice how this (unprototyped) function doesn't care whether it was passed
  116. real scalars or arrays. Perl will see everything as one big long flat C<@_>
  117. parameter list. This is one of the ways where Perl's simple
  118. argument-passing style shines. The C<upcase()> function would work perfectly
  119. well without changing the C<upcase()> definition even if we fed it things
  120. like this:
  121. @newlist = upcase(@list1, @list2);
  122. @newlist = upcase( split /:/, $var );
  123. Do not, however, be tempted to do this:
  124. (@a, @b) = upcase(@list1, @list2);
  125. Because like its flat incoming parameter list, the return list is also
  126. flat. So all you have managed to do here is stored everything in C<@a> and
  127. made C<@b> an empty list. See L<Pass by Reference> for alternatives.
  128. A subroutine may be called using the "C<&>" prefix. The "C<&>" is optional
  129. in modern Perls, and so are the parentheses if the subroutine has been
  130. predeclared. (Note, however, that the "C<&>" is I<NOT> optional when
  131. you're just naming the subroutine, such as when it's used as an
  132. argument to C<defined()> or C<undef()>. Nor is it optional when you want to
  133. do an indirect subroutine call with a subroutine name or reference
  134. using the C<&$subref()> or C<&{$subref}()> constructs. See L<perlref>
  135. for more on that.)
  136. Subroutines may be called recursively. If a subroutine is called using
  137. the "C<&>" form, the argument list is optional, and if omitted, no C<@_> array is
  138. set up for the subroutine: the C<@_> array at the time of the call is
  139. visible to subroutine instead. This is an efficiency mechanism that
  140. new users may wish to avoid.
  141. &foo(1,2,3); # pass three arguments
  142. foo(1,2,3); # the same
  143. foo(); # pass a null list
  144. &foo(); # the same
  145. &foo; # foo() get current args, like foo(@_) !!
  146. foo; # like foo() IFF sub foo predeclared, else "foo"
  147. Not only does the "C<&>" form make the argument list optional, but it also
  148. disables any prototype checking on the arguments you do provide. This
  149. is partly for historical reasons, and partly for having a convenient way
  150. to cheat if you know what you're doing. See the section on Prototypes below.
  151. Function whose names are in all upper case are reserved to the Perl core,
  152. just as are modules whose names are in all lower case. A function in
  153. all capitals is a loosely-held convention meaning it will be called
  154. indirectly by the run-time system itself. Functions that do special,
  155. pre-defined things are C<BEGIN>, C<END>, C<AUTOLOAD>, and C<DESTROY>--plus all the
  156. functions mentioned in L<perltie>. The 5.005 release adds C<INIT>
  157. to this list.
  158. =head2 Private Variables via my()
  159. Synopsis:
  160. my $foo; # declare $foo lexically local
  161. my (@wid, %get); # declare list of variables local
  162. my $foo = "flurp"; # declare $foo lexical, and init it
  163. my @oof = @bar; # declare @oof lexical, and init it
  164. A "C<my>" declares the listed variables to be confined (lexically) to the
  165. enclosing block, conditional (C<if/unless/elsif/else>), loop
  166. (C<for/foreach/while/until/continue>), subroutine, C<eval>, or
  167. C<do/require/use>'d file. If more than one value is listed, the list
  168. must be placed in parentheses. All listed elements must be legal lvalues.
  169. Only alphanumeric identifiers may be lexically scoped--magical
  170. builtins like C<$/> must currently be C<local>ize with "C<local>" instead.
  171. Unlike dynamic variables created by the "C<local>" operator, lexical
  172. variables declared with "C<my>" are totally hidden from the outside world,
  173. including any called subroutines (even if it's the same subroutine called
  174. from itself or elsewhere--every call gets its own copy).
  175. This doesn't mean that a C<my()> variable declared in a statically
  176. I<enclosing> lexical scope would be invisible. Only the dynamic scopes
  177. are cut off. For example, the C<bumpx()> function below has access to the
  178. lexical C<$x> variable because both the my and the sub occurred at the same
  179. scope, presumably the file scope.
  180. my $x = 10;
  181. sub bumpx { $x++ }
  182. (An C<eval()>, however, can see the lexical variables of the scope it is
  183. being evaluated in so long as the names aren't hidden by declarations within
  184. the C<eval()> itself. See L<perlref>.)
  185. The parameter list to C<my()> may be assigned to if desired, which allows you
  186. to initialize your variables. (If no initializer is given for a
  187. particular variable, it is created with the undefined value.) Commonly
  188. this is used to name the parameters to a subroutine. Examples:
  189. $arg = "fred"; # "global" variable
  190. $n = cube_root(27);
  191. print "$arg thinks the root is $n\n";
  192. fred thinks the root is 3
  193. sub cube_root {
  194. my $arg = shift; # name doesn't matter
  195. $arg **= 1/3;
  196. return $arg;
  197. }
  198. The "C<my>" is simply a modifier on something you might assign to. So when
  199. you do assign to the variables in its argument list, the "C<my>" doesn't
  200. change whether those variables are viewed as a scalar or an array. So
  201. my ($foo) = <STDIN>; # WRONG?
  202. my @FOO = <STDIN>;
  203. both supply a list context to the right-hand side, while
  204. my $foo = <STDIN>;
  205. supplies a scalar context. But the following declares only one variable:
  206. my $foo, $bar = 1; # WRONG
  207. That has the same effect as
  208. my $foo;
  209. $bar = 1;
  210. The declared variable is not introduced (is not visible) until after
  211. the current statement. Thus,
  212. my $x = $x;
  213. can be used to initialize the new $x with the value of the old C<$x>, and
  214. the expression
  215. my $x = 123 and $x == 123
  216. is false unless the old C<$x> happened to have the value C<123>.
  217. Lexical scopes of control structures are not bounded precisely by the
  218. braces that delimit their controlled blocks; control expressions are
  219. part of the scope, too. Thus in the loop
  220. while (defined(my $line = <>)) {
  221. $line = lc $line;
  222. } continue {
  223. print $line;
  224. }
  225. the scope of C<$line> extends from its declaration throughout the rest of
  226. the loop construct (including the C<continue> clause), but not beyond
  227. it. Similarly, in the conditional
  228. if ((my $answer = <STDIN>) =~ /^yes$/i) {
  229. user_agrees();
  230. } elsif ($answer =~ /^no$/i) {
  231. user_disagrees();
  232. } else {
  233. chomp $answer;
  234. die "'$answer' is neither 'yes' nor 'no'";
  235. }
  236. the scope of C<$answer> extends from its declaration throughout the rest
  237. of the conditional (including C<elsif> and C<else> clauses, if any),
  238. but not beyond it.
  239. (None of the foregoing applies to C<if/unless> or C<while/until>
  240. modifiers appended to simple statements. Such modifiers are not
  241. control structures and have no effect on scoping.)
  242. The C<foreach> loop defaults to scoping its index variable dynamically
  243. (in the manner of C<local>; see below). However, if the index
  244. variable is prefixed with the keyword "C<my>", then it is lexically
  245. scoped instead. Thus in the loop
  246. for my $i (1, 2, 3) {
  247. some_function();
  248. }
  249. the scope of C<$i> extends to the end of the loop, but not beyond it, and
  250. so the value of C<$i> is unavailable in C<some_function()>.
  251. Some users may wish to encourage the use of lexically scoped variables.
  252. As an aid to catching implicit references to package variables,
  253. if you say
  254. use strict 'vars';
  255. then any variable reference from there to the end of the enclosing
  256. block must either refer to a lexical variable, or must be fully
  257. qualified with the package name. A compilation error results
  258. otherwise. An inner block may countermand this with S<"C<no strict 'vars'>">.
  259. A C<my()> has both a compile-time and a run-time effect. At compile time,
  260. the compiler takes notice of it; the principle usefulness of this is to
  261. quiet S<"C<use strict 'vars'>">. The actual initialization is delayed until
  262. run time, so it gets executed appropriately; every time through a loop,
  263. for example.
  264. Variables declared with "C<my>" are not part of any package and are therefore
  265. never fully qualified with the package name. In particular, you're not
  266. allowed to try to make a package variable (or other global) lexical:
  267. my $pack::var; # ERROR! Illegal syntax
  268. my $_; # also illegal (currently)
  269. In fact, a dynamic variable (also known as package or global variables)
  270. are still accessible using the fully qualified C<::> notation even while a
  271. lexical of the same name is also visible:
  272. package main;
  273. local $x = 10;
  274. my $x = 20;
  275. print "$x and $::x\n";
  276. That will print out C<20> and C<10>.
  277. You may declare "C<my>" variables at the outermost scope of a file to hide
  278. any such identifiers totally from the outside world. This is similar
  279. to C's static variables at the file level. To do this with a subroutine
  280. requires the use of a closure (anonymous function with lexical access).
  281. If a block (such as an C<eval()>, function, or C<package>) wants to create
  282. a private subroutine that cannot be called from outside that block,
  283. it can declare a lexical variable containing an anonymous sub reference:
  284. my $secret_version = '1.001-beta';
  285. my $secret_sub = sub { print $secret_version };
  286. &$secret_sub();
  287. As long as the reference is never returned by any function within the
  288. module, no outside module can see the subroutine, because its name is not in
  289. any package's symbol table. Remember that it's not I<REALLY> called
  290. C<$some_pack::secret_version> or anything; it's just C<$secret_version>,
  291. unqualified and unqualifiable.
  292. This does not work with object methods, however; all object methods have
  293. to be in the symbol table of some package to be found.
  294. =head2 Persistent Private Variables
  295. Just because a lexical variable is lexically (also called statically)
  296. scoped to its enclosing block, C<eval>, or C<do> FILE, this doesn't mean that
  297. within a function it works like a C static. It normally works more
  298. like a C auto, but with implicit garbage collection.
  299. Unlike local variables in C or C++, Perl's lexical variables don't
  300. necessarily get recycled just because their scope has exited.
  301. If something more permanent is still aware of the lexical, it will
  302. stick around. So long as something else references a lexical, that
  303. lexical won't be freed--which is as it should be. You wouldn't want
  304. memory being free until you were done using it, or kept around once you
  305. were done. Automatic garbage collection takes care of this for you.
  306. This means that you can pass back or save away references to lexical
  307. variables, whereas to return a pointer to a C auto is a grave error.
  308. It also gives us a way to simulate C's function statics. Here's a
  309. mechanism for giving a function private variables with both lexical
  310. scoping and a static lifetime. If you do want to create something like
  311. C's static variables, just enclose the whole function in an extra block,
  312. and put the static variable outside the function but in the block.
  313. {
  314. my $secret_val = 0;
  315. sub gimme_another {
  316. return ++$secret_val;
  317. }
  318. }
  319. # $secret_val now becomes unreachable by the outside
  320. # world, but retains its value between calls to gimme_another
  321. If this function is being sourced in from a separate file
  322. via C<require> or C<use>, then this is probably just fine. If it's
  323. all in the main program, you'll need to arrange for the C<my()>
  324. to be executed early, either by putting the whole block above
  325. your main program, or more likely, placing merely a C<BEGIN>
  326. sub around it to make sure it gets executed before your program
  327. starts to run:
  328. sub BEGIN {
  329. my $secret_val = 0;
  330. sub gimme_another {
  331. return ++$secret_val;
  332. }
  333. }
  334. See L<perlmod/"Package Constructors and Destructors"> about the C<BEGIN> function.
  335. If declared at the outermost scope, the file scope, then lexicals work
  336. someone like C's file statics. They are available to all functions in
  337. that same file declared below them, but are inaccessible from outside of
  338. the file. This is sometimes used in modules to create private variables
  339. for the whole module.
  340. =head2 Temporary Values via local()
  341. B<NOTE>: In general, you should be using "C<my>" instead of "C<local>", because
  342. it's faster and safer. Exceptions to this include the global punctuation
  343. variables, filehandles and formats, and direct manipulation of the Perl
  344. symbol table itself. Format variables often use "C<local>" though, as do
  345. other variables whose current value must be visible to called
  346. subroutines.
  347. Synopsis:
  348. local $foo; # declare $foo dynamically local
  349. local (@wid, %get); # declare list of variables local
  350. local $foo = "flurp"; # declare $foo dynamic, and init it
  351. local @oof = @bar; # declare @oof dynamic, and init it
  352. local *FH; # localize $FH, @FH, %FH, &FH ...
  353. local *merlyn = *randal; # now $merlyn is really $randal, plus
  354. # @merlyn is really @randal, etc
  355. local *merlyn = 'randal'; # SAME THING: promote 'randal' to *randal
  356. local *merlyn = \$randal; # just alias $merlyn, not @merlyn etc
  357. A C<local()> modifies its listed variables to be "local" to the enclosing
  358. block, C<eval>, or C<do FILE>--and to I<any subroutine called from within that block>.
  359. A C<local()> just gives temporary values to global (meaning package)
  360. variables. It does B<not> create a local variable. This is known as
  361. dynamic scoping. Lexical scoping is done with "C<my>", which works more
  362. like C's auto declarations.
  363. If more than one variable is given to C<local()>, they must be placed in
  364. parentheses. All listed elements must be legal lvalues. This operator works
  365. by saving the current values of those variables in its argument list on a
  366. hidden stack and restoring them upon exiting the block, subroutine, or
  367. eval. This means that called subroutines can also reference the local
  368. variable, but not the global one. The argument list may be assigned to if
  369. desired, which allows you to initialize your local variables. (If no
  370. initializer is given for a particular variable, it is created with an
  371. undefined value.) Commonly this is used to name the parameters to a
  372. subroutine. Examples:
  373. for $i ( 0 .. 9 ) {
  374. $digits{$i} = $i;
  375. }
  376. # assume this function uses global %digits hash
  377. parse_num();
  378. # now temporarily add to %digits hash
  379. if ($base12) {
  380. # (NOTE: not claiming this is efficient!)
  381. local %digits = (%digits, 't' => 10, 'e' => 11);
  382. parse_num(); # parse_num gets this new %digits!
  383. }
  384. # old %digits restored here
  385. Because C<local()> is a run-time command, it gets executed every time
  386. through a loop. In releases of Perl previous to 5.0, this used more stack
  387. storage each time until the loop was exited. Perl now reclaims the space
  388. each time through, but it's still more efficient to declare your variables
  389. outside the loop.
  390. A C<local> is simply a modifier on an lvalue expression. When you assign to
  391. a C<local>ized variable, the C<local> doesn't change whether its list is viewed
  392. as a scalar or an array. So
  393. local($foo) = <STDIN>;
  394. local @FOO = <STDIN>;
  395. both supply a list context to the right-hand side, while
  396. local $foo = <STDIN>;
  397. supplies a scalar context.
  398. A note about C<local()> and composite types is in order. Something
  399. like C<local(%foo)> works by temporarily placing a brand new hash in
  400. the symbol table. The old hash is left alone, but is hidden "behind"
  401. the new one.
  402. This means the old variable is completely invisible via the symbol
  403. table (i.e. the hash entry in the C<*foo> typeglob) for the duration
  404. of the dynamic scope within which the C<local()> was seen. This
  405. has the effect of allowing one to temporarily occlude any magic on
  406. composite types. For instance, this will briefly alter a tied
  407. hash to some other implementation:
  408. tie %ahash, 'APackage';
  409. [...]
  410. {
  411. local %ahash;
  412. tie %ahash, 'BPackage';
  413. [..called code will see %ahash tied to 'BPackage'..]
  414. {
  415. local %ahash;
  416. [..%ahash is a normal (untied) hash here..]
  417. }
  418. }
  419. [..%ahash back to its initial tied self again..]
  420. As another example, a custom implementation of C<%ENV> might look
  421. like this:
  422. {
  423. local %ENV;
  424. tie %ENV, 'MyOwnEnv';
  425. [..do your own fancy %ENV manipulation here..]
  426. }
  427. [..normal %ENV behavior here..]
  428. It's also worth taking a moment to explain what happens when you
  429. C<local>ize a member of a composite type (i.e. an array or hash element).
  430. In this case, the element is C<local>ized I<by name>. This means that
  431. when the scope of the C<local()> ends, the saved value will be
  432. restored to the hash element whose key was named in the C<local()>, or
  433. the array element whose index was named in the C<local()>. If that
  434. element was deleted while the C<local()> was in effect (e.g. by a
  435. C<delete()> from a hash or a C<shift()> of an array), it will spring
  436. back into existence, possibly extending an array and filling in the
  437. skipped elements with C<undef>. For instance, if you say
  438. %hash = ( 'This' => 'is', 'a' => 'test' );
  439. @ary = ( 0..5 );
  440. {
  441. local($ary[5]) = 6;
  442. local($hash{'a'}) = 'drill';
  443. while (my $e = pop(@ary)) {
  444. print "$e . . .\n";
  445. last unless $e > 3;
  446. }
  447. if (@ary) {
  448. $hash{'only a'} = 'test';
  449. delete $hash{'a'};
  450. }
  451. }
  452. print join(' ', map { "$_ $hash{$_}" } sort keys %hash),".\n";
  453. print "The array has ",scalar(@ary)," elements: ",
  454. join(', ', map { defined $_ ? $_ : 'undef' } @ary),"\n";
  455. Perl will print
  456. 6 . . .
  457. 4 . . .
  458. 3 . . .
  459. This is a test only a test.
  460. The array has 6 elements: 0, 1, 2, undef, undef, 5
  461. Note also that when you C<local>ize a member of a composite type that
  462. B<does not exist previously>, the value is treated as though it were
  463. in an lvalue context, i.e., it is first created and then C<local>ized.
  464. The consequence of this is that the hash or array is in fact permanently
  465. modified. For instance, if you say
  466. %hash = ( 'This' => 'is', 'a' => 'test' );
  467. @ary = ( 0..5 );
  468. {
  469. local($ary[8]) = 0;
  470. local($hash{'b'}) = 'whatever';
  471. }
  472. printf "%%hash has now %d keys, \@ary %d elements.\n",
  473. scalar(keys(%hash)), scalar(@ary);
  474. Perl will print
  475. %hash has now 3 keys, @ary 9 elements.
  476. The above behavior of local() on non-existent members of composite
  477. types is subject to change in future.
  478. =head2 Passing Symbol Table Entries (typeglobs)
  479. [Note: The mechanism described in this section was originally the only
  480. way to simulate pass-by-reference in older versions of Perl. While it
  481. still works fine in modern versions, the new reference mechanism is
  482. generally easier to work with. See below.]
  483. Sometimes you don't want to pass the value of an array to a subroutine
  484. but rather the name of it, so that the subroutine can modify the global
  485. copy of it rather than working with a local copy. In perl you can
  486. refer to all objects of a particular name by prefixing the name
  487. with a star: C<*foo>. This is often known as a "typeglob", because the
  488. star on the front can be thought of as a wildcard match for all the
  489. funny prefix characters on variables and subroutines and such.
  490. When evaluated, the typeglob produces a scalar value that represents
  491. all the objects of that name, including any filehandle, format, or
  492. subroutine. When assigned to, it causes the name mentioned to refer to
  493. whatever "C<*>" value was assigned to it. Example:
  494. sub doubleary {
  495. local(*someary) = @_;
  496. foreach $elem (@someary) {
  497. $elem *= 2;
  498. }
  499. }
  500. doubleary(*foo);
  501. doubleary(*bar);
  502. Note that scalars are already passed by reference, so you can modify
  503. scalar arguments without using this mechanism by referring explicitly
  504. to C<$_[0]> etc. You can modify all the elements of an array by passing
  505. all the elements as scalars, but you have to use the C<*> mechanism (or
  506. the equivalent reference mechanism) to C<push>, C<pop>, or change the size of
  507. an array. It will certainly be faster to pass the typeglob (or reference).
  508. Even if you don't want to modify an array, this mechanism is useful for
  509. passing multiple arrays in a single LIST, because normally the LIST
  510. mechanism will merge all the array values so that you can't extract out
  511. the individual arrays. For more on typeglobs, see
  512. L<perldata/"Typeglobs and Filehandles">.
  513. =head2 When to Still Use local()
  514. Despite the existence of C<my()>, there are still three places where the
  515. C<local()> operator still shines. In fact, in these three places, you
  516. I<must> use C<local> instead of C<my>.
  517. =over
  518. =item 1. You need to give a global variable a temporary value, especially C<$_>.
  519. The global variables, like C<@ARGV> or the punctuation variables, must be
  520. C<local>ized with C<local()>. This block reads in F</etc/motd>, and splits
  521. it up into chunks separated by lines of equal signs, which are placed
  522. in C<@Fields>.
  523. {
  524. local @ARGV = ("/etc/motd");
  525. local $/ = undef;
  526. local $_ = <>;
  527. @Fields = split /^\s*=+\s*$/;
  528. }
  529. It particular, it's important to C<local>ize C<$_> in any routine that assigns
  530. to it. Look out for implicit assignments in C<while> conditionals.
  531. =item 2. You need to create a local file or directory handle or a local function.
  532. A function that needs a filehandle of its own must use C<local()> uses
  533. C<local()> on complete typeglob. This can be used to create new symbol
  534. table entries:
  535. sub ioqueue {
  536. local (*READER, *WRITER); # not my!
  537. pipe (READER, WRITER); or die "pipe: $!";
  538. return (*READER, *WRITER);
  539. }
  540. ($head, $tail) = ioqueue();
  541. See the Symbol module for a way to create anonymous symbol table
  542. entries.
  543. Because assignment of a reference to a typeglob creates an alias, this
  544. can be used to create what is effectively a local function, or at least,
  545. a local alias.
  546. {
  547. local *grow = \&shrink; # only until this block exists
  548. grow(); # really calls shrink()
  549. move(); # if move() grow()s, it shrink()s too
  550. }
  551. grow(); # get the real grow() again
  552. See L<perlref/"Function Templates"> for more about manipulating
  553. functions by name in this way.
  554. =item 3. You want to temporarily change just one element of an array or hash.
  555. You can C<local>ize just one element of an aggregate. Usually this
  556. is done on dynamics:
  557. {
  558. local $SIG{INT} = 'IGNORE';
  559. funct(); # uninterruptible
  560. }
  561. # interruptibility automatically restored here
  562. But it also works on lexically declared aggregates. Prior to 5.005,
  563. this operation could on occasion misbehave.
  564. =back
  565. =head2 Pass by Reference
  566. If you want to pass more than one array or hash into a function--or
  567. return them from it--and have them maintain their integrity, then
  568. you're going to have to use an explicit pass-by-reference. Before you
  569. do that, you need to understand references as detailed in L<perlref>.
  570. This section may not make much sense to you otherwise.
  571. Here are a few simple examples. First, let's pass in several
  572. arrays to a function and have it C<pop> all of then, return a new
  573. list of all their former last elements:
  574. @tailings = popmany ( \@a, \@b, \@c, \@d );
  575. sub popmany {
  576. my $aref;
  577. my @retlist = ();
  578. foreach $aref ( @_ ) {
  579. push @retlist, pop @$aref;
  580. }
  581. return @retlist;
  582. }
  583. Here's how you might write a function that returns a
  584. list of keys occurring in all the hashes passed to it:
  585. @common = inter( \%foo, \%bar, \%joe );
  586. sub inter {
  587. my ($k, $href, %seen); # locals
  588. foreach $href (@_) {
  589. while ( $k = each %$href ) {
  590. $seen{$k}++;
  591. }
  592. }
  593. return grep { $seen{$_} == @_ } keys %seen;
  594. }
  595. So far, we're using just the normal list return mechanism.
  596. What happens if you want to pass or return a hash? Well,
  597. if you're using only one of them, or you don't mind them
  598. concatenating, then the normal calling convention is ok, although
  599. a little expensive.
  600. Where people get into trouble is here:
  601. (@a, @b) = func(@c, @d);
  602. or
  603. (%a, %b) = func(%c, %d);
  604. That syntax simply won't work. It sets just C<@a> or C<%a> and clears the C<@b> or
  605. C<%b>. Plus the function didn't get passed into two separate arrays or
  606. hashes: it got one long list in C<@_>, as always.
  607. If you can arrange for everyone to deal with this through references, it's
  608. cleaner code, although not so nice to look at. Here's a function that
  609. takes two array references as arguments, returning the two array elements
  610. in order of how many elements they have in them:
  611. ($aref, $bref) = func(\@c, \@d);
  612. print "@$aref has more than @$bref\n";
  613. sub func {
  614. my ($cref, $dref) = @_;
  615. if (@$cref > @$dref) {
  616. return ($cref, $dref);
  617. } else {
  618. return ($dref, $cref);
  619. }
  620. }
  621. It turns out that you can actually do this also:
  622. (*a, *b) = func(\@c, \@d);
  623. print "@a has more than @b\n";
  624. sub func {
  625. local (*c, *d) = @_;
  626. if (@c > @d) {
  627. return (\@c, \@d);
  628. } else {
  629. return (\@d, \@c);
  630. }
  631. }
  632. Here we're using the typeglobs to do symbol table aliasing. It's
  633. a tad subtle, though, and also won't work if you're using C<my()>
  634. variables, because only globals (well, and C<local()>s) are in the symbol table.
  635. If you're passing around filehandles, you could usually just use the bare
  636. typeglob, like C<*STDOUT>, but typeglobs references would be better because
  637. they'll still work properly under S<C<use strict 'refs'>>. For example:
  638. splutter(\*STDOUT);
  639. sub splutter {
  640. my $fh = shift;
  641. print $fh "her um well a hmmm\n";
  642. }
  643. $rec = get_rec(\*STDIN);
  644. sub get_rec {
  645. my $fh = shift;
  646. return scalar <$fh>;
  647. }
  648. Another way to do this is using C<*HANDLE{IO}>, see L<perlref> for usage
  649. and caveats.
  650. If you're planning on generating new filehandles, you could do this:
  651. sub openit {
  652. my $name = shift;
  653. local *FH;
  654. return open (FH, $path) ? *FH : undef;
  655. }
  656. Although that will actually produce a small memory leak. See the bottom
  657. of L<perlfunc/open()> for a somewhat cleaner way using the C<IO::Handle>
  658. package.
  659. =head2 Prototypes
  660. As of the 5.002 release of perl, if you declare
  661. sub mypush (\@@)
  662. then C<mypush()> takes arguments exactly like C<push()> does. The declaration
  663. of the function to be called must be visible at compile time. The prototype
  664. affects only the interpretation of new-style calls to the function, where
  665. new-style is defined as not using the C<&> character. In other words,
  666. if you call it like a builtin function, then it behaves like a builtin
  667. function. If you call it like an old-fashioned subroutine, then it
  668. behaves like an old-fashioned subroutine. It naturally falls out from
  669. this rule that prototypes have no influence on subroutine references
  670. like C<\&foo> or on indirect subroutine calls like C<&{$subref}> or
  671. C<$subref-E<gt>()>.
  672. Method calls are not influenced by prototypes either, because the
  673. function to be called is indeterminate at compile time, because it depends
  674. on inheritance.
  675. Because the intent is primarily to let you define subroutines that work
  676. like builtin commands, here are the prototypes for some other functions
  677. that parse almost exactly like the corresponding builtins.
  678. Declared as Called as
  679. sub mylink ($$) mylink $old, $new
  680. sub myvec ($$$) myvec $var, $offset, 1
  681. sub myindex ($$;$) myindex &getstring, "substr"
  682. sub mysyswrite ($$$;$) mysyswrite $buf, 0, length($buf) - $off, $off
  683. sub myreverse (@) myreverse $a, $b, $c
  684. sub myjoin ($@) myjoin ":", $a, $b, $c
  685. sub mypop (\@) mypop @array
  686. sub mysplice (\@$$@) mysplice @array, @array, 0, @pushme
  687. sub mykeys (\%) mykeys %{$hashref}
  688. sub myopen (*;$) myopen HANDLE, $name
  689. sub mypipe (**) mypipe READHANDLE, WRITEHANDLE
  690. sub mygrep (&@) mygrep { /foo/ } $a, $b, $c
  691. sub myrand ($) myrand 42
  692. sub mytime () mytime
  693. Any backslashed prototype character represents an actual argument
  694. that absolutely must start with that character. The value passed
  695. to the subroutine (as part of C<@_>) will be a reference to the
  696. actual argument given in the subroutine call, obtained by applying
  697. C<\> to that argument.
  698. Unbackslashed prototype characters have special meanings. Any
  699. unbackslashed C<@> or C<%> eats all the rest of the arguments, and forces
  700. list context. An argument represented by C<$> forces scalar context. An
  701. C<&> requires an anonymous subroutine, which, if passed as the first
  702. argument, does not require the "C<sub>" keyword or a subsequent comma. A
  703. C<*> allows the subroutine to accept a bareword, constant, scalar expression,
  704. typeglob, or a reference to a typeglob in that slot. The value will be
  705. available to the subroutine either as a simple scalar, or (in the latter
  706. two cases) as a reference to the typeglob.
  707. A semicolon separates mandatory arguments from optional arguments.
  708. (It is redundant before C<@> or C<%>.)
  709. Note how the last three examples above are treated specially by the parser.
  710. C<mygrep()> is parsed as a true list operator, C<myrand()> is parsed as a
  711. true unary operator with unary precedence the same as C<rand()>, and
  712. C<mytime()> is truly without arguments, just like C<time()>. That is, if you
  713. say
  714. mytime +2;
  715. you'll get C<mytime() + 2>, not C<mytime(2)>, which is how it would be parsed
  716. without the prototype.
  717. The interesting thing about C<&> is that you can generate new syntax with it:
  718. sub try (&@) {
  719. my($try,$catch) = @_;
  720. eval { &$try };
  721. if ($@) {
  722. local $_ = $@;
  723. &$catch;
  724. }
  725. }
  726. sub catch (&) { $_[0] }
  727. try {
  728. die "phooey";
  729. } catch {
  730. /phooey/ and print "unphooey\n";
  731. };
  732. That prints C<"unphooey">. (Yes, there are still unresolved
  733. issues having to do with the visibility of C<@_>. I'm ignoring that
  734. question for the moment. (But note that if we make C<@_> lexically
  735. scoped, those anonymous subroutines can act like closures... (Gee,
  736. is this sounding a little Lispish? (Never mind.))))
  737. And here's a reimplementation of C<grep>:
  738. sub mygrep (&@) {
  739. my $code = shift;
  740. my @result;
  741. foreach $_ (@_) {
  742. push(@result, $_) if &$code;
  743. }
  744. @result;
  745. }
  746. Some folks would prefer full alphanumeric prototypes. Alphanumerics have
  747. been intentionally left out of prototypes for the express purpose of
  748. someday in the future adding named, formal parameters. The current
  749. mechanism's main goal is to let module writers provide better diagnostics
  750. for module users. Larry feels the notation quite understandable to Perl
  751. programmers, and that it will not intrude greatly upon the meat of the
  752. module, nor make it harder to read. The line noise is visually
  753. encapsulated into a small pill that's easy to swallow.
  754. It's probably best to prototype new functions, not retrofit prototyping
  755. into older ones. That's because you must be especially careful about
  756. silent impositions of differing list versus scalar contexts. For example,
  757. if you decide that a function should take just one parameter, like this:
  758. sub func ($) {
  759. my $n = shift;
  760. print "you gave me $n\n";
  761. }
  762. and someone has been calling it with an array or expression
  763. returning a list:
  764. func(@foo);
  765. func( split /:/ );
  766. Then you've just supplied an automatic C<scalar()> in front of their
  767. argument, which can be more than a bit surprising. The old C<@foo>
  768. which used to hold one thing doesn't get passed in. Instead,
  769. the C<func()> now gets passed in C<1>, that is, the number of elements
  770. in C<@foo>. And the C<split()> gets called in a scalar context and
  771. starts scribbling on your C<@_> parameter list.
  772. This is all very powerful, of course, and should be used only in moderation
  773. to make the world a better place.
  774. =head2 Constant Functions
  775. Functions with a prototype of C<()> are potential candidates for
  776. inlining. If the result after optimization and constant folding is
  777. either a constant or a lexically-scoped scalar which has no other
  778. references, then it will be used in place of function calls made
  779. without C<&> or C<do>. Calls made using C<&> or C<do> are never
  780. inlined. (See F<constant.pm> for an easy way to declare most
  781. constants.)
  782. The following functions would all be inlined:
  783. sub pi () { 3.14159 } # Not exact, but close.
  784. sub PI () { 4 * atan2 1, 1 } # As good as it gets,
  785. # and it's inlined, too!
  786. sub ST_DEV () { 0 }
  787. sub ST_INO () { 1 }
  788. sub FLAG_FOO () { 1 << 8 }
  789. sub FLAG_BAR () { 1 << 9 }
  790. sub FLAG_MASK () { FLAG_FOO | FLAG_BAR }
  791. sub OPT_BAZ () { not (0x1B58 & FLAG_MASK) }
  792. sub BAZ_VAL () {
  793. if (OPT_BAZ) {
  794. return 23;
  795. }
  796. else {
  797. return 42;
  798. }
  799. }
  800. sub N () { int(BAZ_VAL) / 3 }
  801. BEGIN {
  802. my $prod = 1;
  803. for (1..N) { $prod *= $_ }
  804. sub N_FACTORIAL () { $prod }
  805. }
  806. If you redefine a subroutine that was eligible for inlining, you'll get
  807. a mandatory warning. (You can use this warning to tell whether or not a
  808. particular subroutine is considered constant.) The warning is
  809. considered severe enough not to be optional because previously compiled
  810. invocations of the function will still be using the old value of the
  811. function. If you need to be able to redefine the subroutine you need to
  812. ensure that it isn't inlined, either by dropping the C<()> prototype
  813. (which changes the calling semantics, so beware) or by thwarting the
  814. inlining mechanism in some other way, such as
  815. sub not_inlined () {
  816. 23 if $];
  817. }
  818. =head2 Overriding Builtin Functions
  819. Many builtin functions may be overridden, though this should be tried
  820. only occasionally and for good reason. Typically this might be
  821. done by a package attempting to emulate missing builtin functionality
  822. on a non-Unix system.
  823. Overriding may be done only by importing the name from a
  824. module--ordinary predeclaration isn't good enough. However, the
  825. C<subs> pragma (compiler directive) lets you, in effect, predeclare subs
  826. via the import syntax, and these names may then override the builtin ones:
  827. use subs 'chdir', 'chroot', 'chmod', 'chown';
  828. chdir $somewhere;
  829. sub chdir { ... }
  830. To unambiguously refer to the builtin form, one may precede the
  831. builtin name with the special package qualifier C<CORE::>. For example,
  832. saying C<CORE::open()> will always refer to the builtin C<open()>, even
  833. if the current package has imported some other subroutine called
  834. C<&open()> from elsewhere.
  835. Library modules should not in general export builtin names like "C<open>"
  836. or "C<chdir>" as part of their default C<@EXPORT> list, because these may
  837. sneak into someone else's namespace and change the semantics unexpectedly.
  838. Instead, if the module adds the name to the C<@EXPORT_OK> list, then it's
  839. possible for a user to import the name explicitly, but not implicitly.
  840. That is, they could say
  841. use Module 'open';
  842. and it would import the C<open> override, but if they said
  843. use Module;
  844. they would get the default imports without the overrides.
  845. The foregoing mechanism for overriding builtins is restricted, quite
  846. deliberately, to the package that requests the import. There is a second
  847. method that is sometimes applicable when you wish to override a builtin
  848. everywhere, without regard to namespace boundaries. This is achieved by
  849. importing a sub into the special namespace C<CORE::GLOBAL::>. Here is an
  850. example that quite brazenly replaces the C<glob> operator with something
  851. that understands regular expressions.
  852. package REGlob;
  853. require Exporter;
  854. @ISA = 'Exporter';
  855. @EXPORT_OK = 'glob';
  856. sub import {
  857. my $pkg = shift;
  858. return unless @_;
  859. my $sym = shift;
  860. my $where = ($sym =~ s/^GLOBAL_// ? 'CORE::GLOBAL' : caller(0));
  861. $pkg->export($where, $sym, @_);
  862. }
  863. sub glob {
  864. my $pat = shift;
  865. my @got;
  866. local(*D);
  867. if (opendir D, '.') { @got = grep /$pat/, readdir D; closedir D; }
  868. @got;
  869. }
  870. 1;
  871. And here's how it could be (ab)used:
  872. #use REGlob 'GLOBAL_glob'; # override glob() in ALL namespaces
  873. package Foo;
  874. use REGlob 'glob'; # override glob() in Foo:: only
  875. print for <^[a-z_]+\.pm\$>; # show all pragmatic modules
  876. Note that the initial comment shows a contrived, even dangerous example.
  877. By overriding C<glob> globally, you would be forcing the new (and
  878. subversive) behavior for the C<glob> operator for B<every> namespace,
  879. without the complete cognizance or cooperation of the modules that own
  880. those namespaces. Naturally, this should be done with extreme caution--if
  881. it must be done at all.
  882. The C<REGlob> example above does not implement all the support needed to
  883. cleanly override perl's C<glob> operator. The builtin C<glob> has
  884. different behaviors depending on whether it appears in a scalar or list
  885. context, but our C<REGlob> doesn't. Indeed, many perl builtins have such
  886. context sensitive behaviors, and these must be adequately supported by
  887. a properly written override. For a fully functional example of overriding
  888. C<glob>, study the implementation of C<File::DosGlob> in the standard
  889. library.
  890. =head2 Autoloading
  891. If you call a subroutine that is undefined, you would ordinarily get an
  892. immediate fatal error complaining that the subroutine doesn't exist.
  893. (Likewise for subroutines being used as methods, when the method
  894. doesn't exist in any base class of the class package.) If,
  895. however, there is an C<AUTOLOAD> subroutine defined in the package or
  896. packages that were searched for the original subroutine, then that
  897. C<AUTOLOAD> subroutine is called with the arguments that would have been
  898. passed to the original subroutine. The fully qualified name of the
  899. original subroutine magically appears in the C<$AUTOLOAD> variable in the
  900. same package as the C<AUTOLOAD> routine. The name is not passed as an
  901. ordinary argument because, er, well, just because, that's why...
  902. Most C<AUTOLOAD> routines will load in a definition for the subroutine in
  903. question using eval, and then execute that subroutine using a special
  904. form of "goto" that erases the stack frame of the C<AUTOLOAD> routine
  905. without a trace. (See the standard C<AutoLoader> module, for example.)
  906. But an C<AUTOLOAD> routine can also just emulate the routine and never
  907. define it. For example, let's pretend that a function that wasn't defined
  908. should just call C<system()> with those arguments. All you'd do is this:
  909. sub AUTOLOAD {
  910. my $program = $AUTOLOAD;
  911. $program =~ s/.*:://;
  912. system($program, @_);
  913. }
  914. date();
  915. who('am', 'i');
  916. ls('-l');
  917. In fact, if you predeclare the functions you want to call that way, you don't
  918. even need the parentheses:
  919. use subs qw(date who ls);
  920. date;
  921. who "am", "i";
  922. ls -l;
  923. A more complete example of this is the standard Shell module, which
  924. can treat undefined subroutine calls as calls to Unix programs.
  925. Mechanisms are available for modules writers to help split the modules
  926. up into autoloadable files. See the standard AutoLoader module
  927. described in L<AutoLoader> and in L<AutoSplit>, the standard
  928. SelfLoader modules in L<SelfLoader>, and the document on adding C
  929. functions to perl code in L<perlxs>.
  930. =head1 SEE ALSO
  931. See L<perlref> for more about references and closures. See L<perlxs> if
  932. you'd like to learn about calling C subroutines from perl. See L<perlmod>
  933. to learn about bundling up your functions in separate files.