Initial commit of OpenSPARC T2 design and verification files.
[OpenSPARC-T2-DV] / tools / perl-5.8.0 / man / man1 / perlfaq7.1
CommitLineData
86530b38
AT
1.\" Automatically generated by Pod::Man v1.34, Pod::Parser v1.13
2.\"
3.\" Standard preamble:
4.\" ========================================================================
5.de Sh \" Subsection heading
6.br
7.if t .Sp
8.ne 5
9.PP
10\fB\\$1\fR
11.PP
12..
13.de Sp \" Vertical space (when we can't use .PP)
14.if t .sp .5v
15.if n .sp
16..
17.de Vb \" Begin verbatim text
18.ft CW
19.nf
20.ne \\$1
21..
22.de Ve \" End verbatim text
23.ft R
24.fi
25..
26.\" Set up some character translations and predefined strings. \*(-- will
27.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
28.\" double quote, and \*(R" will give a right double quote. | will give a
29.\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to
30.\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C'
31.\" expand to `' in nroff, nothing in troff, for use with C<>.
32.tr \(*W-|\(bv\*(Tr
33.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
34.ie n \{\
35. ds -- \(*W-
36. ds PI pi
37. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
38. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
39. ds L" ""
40. ds R" ""
41. ds C` ""
42. ds C' ""
43'br\}
44.el\{\
45. ds -- \|\(em\|
46. ds PI \(*p
47. ds L" ``
48. ds R" ''
49'br\}
50.\"
51.\" If the F register is turned on, we'll generate index entries on stderr for
52.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
53.\" entries marked with X<> in POD. Of course, you'll have to process the
54.\" output yourself in some meaningful fashion.
55.if \nF \{\
56. de IX
57. tm Index:\\$1\t\\n%\t"\\$2"
58..
59. nr % 0
60. rr F
61.\}
62.\"
63.\" For nroff, turn off justification. Always turn off hyphenation; it makes
64.\" way too many mistakes in technical documents.
65.hy 0
66.if n .na
67.\"
68.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
69.\" Fear. Run. Save yourself. No user-serviceable parts.
70. \" fudge factors for nroff and troff
71.if n \{\
72. ds #H 0
73. ds #V .8m
74. ds #F .3m
75. ds #[ \f1
76. ds #] \fP
77.\}
78.if t \{\
79. ds #H ((1u-(\\\\n(.fu%2u))*.13m)
80. ds #V .6m
81. ds #F 0
82. ds #[ \&
83. ds #] \&
84.\}
85. \" simple accents for nroff and troff
86.if n \{\
87. ds ' \&
88. ds ` \&
89. ds ^ \&
90. ds , \&
91. ds ~ ~
92. ds /
93.\}
94.if t \{\
95. ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
96. ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
97. ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
98. ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
99. ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
100. ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
101.\}
102. \" troff and (daisy-wheel) nroff accents
103.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
104.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
105.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
106.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
107.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
108.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
109.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
110.ds ae a\h'-(\w'a'u*4/10)'e
111.ds Ae A\h'-(\w'A'u*4/10)'E
112. \" corrections for vroff
113.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
114.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
115. \" for low resolution devices (crt and lpr)
116.if \n(.H>23 .if \n(.V>19 \
117\{\
118. ds : e
119. ds 8 ss
120. ds o a
121. ds d- d\h'-1'\(ga
122. ds D- D\h'-1'\(hy
123. ds th \o'bp'
124. ds Th \o'LP'
125. ds ae ae
126. ds Ae AE
127.\}
128.rm #[ #] #H #V #F C
129.\" ========================================================================
130.\"
131.IX Title "PERLFAQ7 1"
132.TH PERLFAQ7 1 "2002-06-08" "perl v5.8.0" "Perl Programmers Reference Guide"
133.SH "NAME"
134perlfaq7 \- General Perl Language Issues ($Revision: 1.8 $, $Date: 2002/03/26 15:48:32 $)
135.SH "DESCRIPTION"
136.IX Header "DESCRIPTION"
137This section deals with general Perl language issues that don't
138clearly fit into any of the other sections.
139.Sh "Can I get a BNF/yacc/RE for the Perl language?"
140.IX Subsection "Can I get a BNF/yacc/RE for the Perl language?"
141There is no \s-1BNF\s0, but you can paw your way through the yacc grammar in
142perly.y in the source distribution if you're particularly brave. The
143grammar relies on very smart tokenizing code, so be prepared to
144venture into toke.c as well.
145.PP
146In the words of Chaim Frenkel: \*(L"Perl's grammar can not be reduced to \s-1BNF\s0.
147The work of parsing perl is distributed between yacc, the lexer, smoke
148and mirrors.\*(R"
149.Sh "What are all these $@%&* punctuation signs, and how do I know when to use them?"
150.IX Subsection "What are all these $@%&* punctuation signs, and how do I know when to use them?"
151They are type specifiers, as detailed in perldata:
152.PP
153.Vb 6
154\& $ for scalar values (number, string or reference)
155\& @ for arrays
156\& % for hashes (associative arrays)
157\& & for subroutines (aka functions, procedures, methods)
158\& * for all types of that symbol name. In version 4 you used them like
159\& pointers, but in modern perls you can just use references.
160.Ve
161.PP
162There are couple of other symbols that you're likely to encounter that aren't
163really type specifiers:
164.PP
165.Vb 2
166\& <> are used for inputting a record from a filehandle.
167\& \e takes a reference to something.
168.Ve
169.PP
170Note that <\s-1FILE\s0> is \fIneither\fR the type specifier for files
171nor the name of the handle. It is the \f(CW\*(C`<>\*(C'\fR operator applied
172to the handle \s-1FILE\s0. It reads one line (well, record\*(--see
173\&\*(L"$/\*(R" in perlvar) from the handle \s-1FILE\s0 in scalar context, or \fIall\fR lines
174in list context. When performing open, close, or any other operation
175besides \f(CW\*(C`<>\*(C'\fR on files, or even when talking about the handle, do
176\&\fInot\fR use the brackets. These are correct: \f(CW\*(C`eof(FH)\*(C'\fR, \f(CW\*(C`seek(FH, 0,
1772)\*(C'\fR and \*(L"copying from \s-1STDIN\s0 to \s-1FILE\s0\*(R".
178.Sh "Do I always/never have to quote my strings or use semicolons and commas?"
179.IX Subsection "Do I always/never have to quote my strings or use semicolons and commas?"
180Normally, a bareword doesn't need to be quoted, but in most cases
181probably should be (and must be under \f(CW\*(C`use strict\*(C'\fR). But a hash key
182consisting of a simple word (that isn't the name of a defined
183subroutine) and the left-hand operand to the \f(CW\*(C`=>\*(C'\fR operator both
184count as though they were quoted:
185.PP
186.Vb 4
187\& This is like this
188\& ------------ ---------------
189\& $foo{line} $foo{"line"}
190\& bar => stuff "bar" => stuff
191.Ve
192.PP
193The final semicolon in a block is optional, as is the final comma in a
194list. Good style (see perlstyle) says to put them in except for
195one\-liners:
196.PP
197.Vb 2
198\& if ($whoops) { exit 1 }
199\& @nums = (1, 2, 3);
200.Ve
201.PP
202.Vb 7
203\& if ($whoops) {
204\& exit 1;
205\& }
206\& @lines = (
207\& "There Beren came from mountains cold",
208\& "And lost he wandered under leaves",
209\& );
210.Ve
211.Sh "How do I skip some return values?"
212.IX Subsection "How do I skip some return values?"
213One way is to treat the return values as a list and index into it:
214.PP
215.Vb 1
216\& $dir = (getpwnam($user))[7];
217.Ve
218.PP
219Another way is to use undef as an element on the left\-hand\-side:
220.PP
221.Vb 1
222\& ($dev, $ino, undef, undef, $uid, $gid) = stat($file);
223.Ve
224.Sh "How do I temporarily block warnings?"
225.IX Subsection "How do I temporarily block warnings?"
226If you are running Perl 5.6.0 or better, the \f(CW\*(C`use warnings\*(C'\fR pragma
227allows fine control of what warning are produced.
228See perllexwarn for more details.
229.PP
230.Vb 4
231\& {
232\& no warnings; # temporarily turn off warnings
233\& $a = $b + $c; # I know these might be undef
234\& }
235.Ve
236.PP
237If you have an older version of Perl, the \f(CW$^W\fR variable (documented
238in perlvar) controls runtime warnings for a block:
239.PP
240.Vb 4
241\& {
242\& local $^W = 0; # temporarily turn off warnings
243\& $a = $b + $c; # I know these might be undef
244\& }
245.Ve
246.PP
247Note that like all the punctuation variables, you cannot currently
248use \fImy()\fR on \f(CW$^W\fR, only \fIlocal()\fR.
249.Sh "What's an extension?"
250.IX Subsection "What's an extension?"
251An extension is a way of calling compiled C code from Perl. Reading
252perlxstut is a good place to learn more about extensions.
253.Sh "Why do Perl operators have different precedence than C operators?"
254.IX Subsection "Why do Perl operators have different precedence than C operators?"
255Actually, they don't. All C operators that Perl copies have the same
256precedence in Perl as they do in C. The problem is with operators that C
257doesn't have, especially functions that give a list context to everything
258on their right, eg. print, chmod, exec, and so on. Such functions are
259called \*(L"list operators\*(R" and appear as such in the precedence table in
260perlop.
261.PP
262A common mistake is to write:
263.PP
264.Vb 1
265\& unlink $file || die "snafu";
266.Ve
267.PP
268This gets interpreted as:
269.PP
270.Vb 1
271\& unlink ($file || die "snafu");
272.Ve
273.PP
274To avoid this problem, either put in extra parentheses or use the
275super low precedence \f(CW\*(C`or\*(C'\fR operator:
276.PP
277.Vb 2
278\& (unlink $file) || die "snafu";
279\& unlink $file or die "snafu";
280.Ve
281.PP
282The \*(L"English\*(R" operators (\f(CW\*(C`and\*(C'\fR, \f(CW\*(C`or\*(C'\fR, \f(CW\*(C`xor\*(C'\fR, and \f(CW\*(C`not\*(C'\fR)
283deliberately have precedence lower than that of list operators for
284just such situations as the one above.
285.PP
286Another operator with surprising precedence is exponentiation. It
287binds more tightly even than unary minus, making \f(CW\*(C`\-2**2\*(C'\fR product a
288negative not a positive four. It is also right\-associating, meaning
289that \f(CW\*(C`2**3**2\*(C'\fR is two raised to the ninth power, not eight squared.
290.PP
291Although it has the same precedence as in C, Perl's \f(CW\*(C`?:\*(C'\fR operator
292produces an lvalue. This assigns \f(CW$x\fR to either \f(CW$a\fR or \f(CW$b\fR, depending
293on the trueness of \f(CW$maybe:\fR
294.PP
295.Vb 1
296\& ($maybe ? $a : $b) = $x;
297.Ve
298.Sh "How do I declare/create a structure?"
299.IX Subsection "How do I declare/create a structure?"
300In general, you don't \*(L"declare\*(R" a structure. Just use a (probably
301anonymous) hash reference. See perlref and perldsc for details.
302Here's an example:
303.PP
304.Vb 3
305\& $person = {}; # new anonymous hash
306\& $person->{AGE} = 24; # set field AGE to 24
307\& $person->{NAME} = "Nat"; # set field NAME to "Nat"
308.Ve
309.PP
310If you're looking for something a bit more rigorous, try perltoot.
311.Sh "How do I create a module?"
312.IX Subsection "How do I create a module?"
313A module is a package that lives in a file of the same name. For
314example, the Hello::There module would live in Hello/There.pm. For
315details, read perlmod. You'll also find Exporter helpful. If
316you're writing a C or mixed-language module with both C and Perl, then
317you should study perlxstut.
318.PP
319The \f(CW\*(C`h2xs\*(C'\fR program will create stubs for all the important stuff for you:
320.PP
321.Vb 1
322\& % h2xs -XA -n My::Module
323.Ve
324.PP
325The \f(CW\*(C`\-X\*(C'\fR switch tells \f(CW\*(C`h2xs\*(C'\fR that you are not using \f(CW\*(C`XS\*(C'\fR extension
326code. The \f(CW\*(C`\-A\*(C'\fR switch tells \f(CW\*(C`h2xs\*(C'\fR that you are not using the
327AutoLoader, and the \f(CW\*(C`\-n\*(C'\fR switch specifies the name of the module.
328See h2xs for more details.
329.Sh "How do I create a class?"
330.IX Subsection "How do I create a class?"
331See perltoot for an introduction to classes and objects, as well as
332perlobj and perlbot.
333.Sh "How can I tell if a variable is tainted?"
334.IX Subsection "How can I tell if a variable is tainted?"
335You can use the \fItainted()\fR function of the Scalar::Util module, available
336from \s-1CPAN\s0 (or included with Perl since release 5.8.0).
337See also \*(L"Laundering and Detecting Tainted Data\*(R" in perlsec.
338.Sh "What's a closure?"
339.IX Subsection "What's a closure?"
340Closures are documented in perlref.
341.PP
342\&\fIClosure\fR is a computer science term with a precise but
343hard-to-explain meaning. Closures are implemented in Perl as anonymous
344subroutines with lasting references to lexical variables outside their
345own scopes. These lexicals magically refer to the variables that were
346around when the subroutine was defined (deep binding).
347.PP
348Closures make sense in any programming language where you can have the
349return value of a function be itself a function, as you can in Perl.
350Note that some languages provide anonymous functions but are not
351capable of providing proper closures: the Python language, for
352example. For more information on closures, check out any textbook on
353functional programming. Scheme is a language that not only supports
354but encourages closures.
355.PP
356Here's a classic function-generating function:
357.PP
358.Vb 3
359\& sub add_function_generator {
360\& return sub { shift + shift };
361\& }
362.Ve
363.PP
364.Vb 2
365\& $add_sub = add_function_generator();
366\& $sum = $add_sub->(4,5); # $sum is 9 now.
367.Ve
368.PP
369The closure works as a \fIfunction template\fR with some customization
370slots left out to be filled later. The anonymous subroutine returned
371by \fIadd_function_generator()\fR isn't technically a closure because it
372refers to no lexicals outside its own scope.
373.PP
374Contrast this with the following \fImake_adder()\fR function, in which the
375returned anonymous function contains a reference to a lexical variable
376outside the scope of that function itself. Such a reference requires
377that Perl return a proper closure, thus locking in for all time the
378value that the lexical had when the function was created.
379.PP
380.Vb 4
381\& sub make_adder {
382\& my $addpiece = shift;
383\& return sub { shift + $addpiece };
384\& }
385.Ve
386.PP
387.Vb 2
388\& $f1 = make_adder(20);
389\& $f2 = make_adder(555);
390.Ve
391.PP
392Now \f(CW\*(C`&$f1($n)\*(C'\fR is always 20 plus whatever \f(CW$n\fR you pass in, whereas
393\&\f(CW\*(C`&$f2($n)\*(C'\fR is always 555 plus whatever \f(CW$n\fR you pass in. The \f(CW$addpiece\fR
394in the closure sticks around.
395.PP
396Closures are often used for less esoteric purposes. For example, when
397you want to pass in a bit of code into a function:
398.PP
399.Vb 2
400\& my $line;
401\& timeout( 30, sub { $line = <STDIN> } );
402.Ve
403.PP
404If the code to execute had been passed in as a string,
405\&\f(CW'$line = <STDIN>'\fR, there would have been no way for the
406hypothetical \fItimeout()\fR function to access the lexical variable
407\&\f(CW$line\fR back in its caller's scope.
408.Sh "What is variable suicide and how can I prevent it?"
409.IX Subsection "What is variable suicide and how can I prevent it?"
410Variable suicide is when you (temporarily or permanently) lose the
411value of a variable. It is caused by scoping through \fImy()\fR and \fIlocal()\fR
412interacting with either closures or aliased \fIforeach()\fR iterator
413variables and subroutine arguments. It used to be easy to
414inadvertently lose a variable's value this way, but now it's much
415harder. Take this code:
416.PP
417.Vb 6
418\& my $f = "foo";
419\& sub T {
420\& while ($i++ < 3) { my $f = $f; $f .= "bar"; print $f, "\en" }
421\& }
422\& T;
423\& print "Finally $f\en";
424.Ve
425.PP
426The \f(CW$f\fR that has \*(L"bar\*(R" added to it three times should be a new \f(CW$f\fR
427(\f(CW\*(C`my $f\*(C'\fR should create a new local variable each time through the loop).
428It isn't, however. This was a bug, now fixed in the latest releases
429(tested against 5.004_05, 5.005_03, and 5.005_56).
430.Sh "How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?"
431.IX Subsection "How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?"
432With the exception of regexes, you need to pass references to these
433objects. See \*(L"Pass by Reference\*(R" in perlsub for this particular
434question, and perlref for information on references.
435.PP
436See ``Passing Regexes'', below, for information on passing regular
437expressions.
438.IP "Passing Variables and Functions" 4
439.IX Item "Passing Variables and Functions"
440Regular variables and functions are quite easy to pass: just pass in a
441reference to an existing or anonymous variable or function:
442.Sp
443.Vb 1
444\& func( \e$some_scalar );
445.Ve
446.Sp
447.Vb 2
448\& func( \e@some_array );
449\& func( [ 1 .. 10 ] );
450.Ve
451.Sp
452.Vb 2
453\& func( \e%some_hash );
454\& func( { this => 10, that => 20 } );
455.Ve
456.Sp
457.Vb 2
458\& func( \e&some_func );
459\& func( sub { $_[0] ** $_[1] } );
460.Ve
461.IP "Passing Filehandles" 4
462.IX Item "Passing Filehandles"
463To pass filehandles to subroutines, use the \f(CW*FH\fR or \f(CW\*(C`\e*FH\*(C'\fR notations.
464These are \*(L"typeglobs\*(R"\-\-see \*(L"Typeglobs and Filehandles\*(R" in perldata
465and especially \*(L"Pass by Reference\*(R" in perlsub for more information.
466.Sp
467Here's an excerpt:
468.Sp
469If you're passing around filehandles, you could usually just use the bare
470typeglob, like *STDOUT, but typeglobs references would be better because
471they'll still work properly under \f(CW\*(C`use strict 'refs'\*(C'\fR. For example:
472.Sp
473.Vb 5
474\& splutter(\e*STDOUT);
475\& sub splutter {
476\& my $fh = shift;
477\& print $fh "her um well a hmmm\en";
478\& }
479.Ve
480.Sp
481.Vb 5
482\& $rec = get_rec(\e*STDIN);
483\& sub get_rec {
484\& my $fh = shift;
485\& return scalar <$fh>;
486\& }
487.Ve
488.Sp
489If you're planning on generating new filehandles, you could do this:
490.Sp
491.Vb 7
492\& sub openit {
493\& my $path = shift;
494\& local *FH;
495\& return open (FH, $path) ? *FH : undef;
496\& }
497\& $fh = openit('< /etc/motd');
498\& print <$fh>;
499.Ve
500.IP "Passing Regexes" 4
501.IX Item "Passing Regexes"
502To pass regexes around, you'll need to be using a release of Perl
503sufficiently recent as to support the \f(CW\*(C`qr//\*(C'\fR construct, pass around
504strings and use an exception-trapping eval, or else be very, very clever.
505.Sp
506Here's an example of how to pass in a string to be regex compared
507using \f(CW\*(C`qr//\*(C'\fR:
508.Sp
509.Vb 6
510\& sub compare($$) {
511\& my ($val1, $regex) = @_;
512\& my $retval = $val1 =~ /$regex/;
513\& return $retval;
514\& }
515\& $match = compare("old McDonald", qr/d.*D/i);
516.Ve
517.Sp
518Notice how \f(CW\*(C`qr//\*(C'\fR allows flags at the end. That pattern was compiled
519at compile time, although it was executed later. The nifty \f(CW\*(C`qr//\*(C'\fR
520notation wasn't introduced until the 5.005 release. Before that, you
521had to approach this problem much less intuitively. For example, here
522it is again if you don't have \f(CW\*(C`qr//\*(C'\fR:
523.Sp
524.Vb 6
525\& sub compare($$) {
526\& my ($val1, $regex) = @_;
527\& my $retval = eval { $val1 =~ /$regex/ };
528\& die if $@;
529\& return $retval;
530\& }
531.Ve
532.Sp
533.Vb 1
534\& $match = compare("old McDonald", q/($?i)d.*D/);
535.Ve
536.Sp
537Make sure you never say something like this:
538.Sp
539.Vb 1
540\& return eval "\e$val =~ /$regex/"; # WRONG
541.Ve
542.Sp
543or someone can sneak shell escapes into the regex due to the double
544interpolation of the eval and the double-quoted string. For example:
545.Sp
546.Vb 1
547\& $pattern_of_evil = 'danger ${ system("rm -rf * &") } danger';
548.Ve
549.Sp
550.Vb 1
551\& eval "\e$string =~ /$pattern_of_evil/";
552.Ve
553.Sp
554Those preferring to be very, very clever might see the O'Reilly book,
555\&\fIMastering Regular Expressions\fR, by Jeffrey Friedl. Page 273's
556\&\fIBuild_MatchMany_Function()\fR is particularly interesting. A complete
557citation of this book is given in perlfaq2.
558.IP "Passing Methods" 4
559.IX Item "Passing Methods"
560To pass an object method into a subroutine, you can do this:
561.Sp
562.Vb 7
563\& call_a_lot(10, $some_obj, "methname")
564\& sub call_a_lot {
565\& my ($count, $widget, $trick) = @_;
566\& for (my $i = 0; $i < $count; $i++) {
567\& $widget->$trick();
568\& }
569\& }
570.Ve
571.Sp
572Or, you can use a closure to bundle up the object, its
573method call, and arguments:
574.Sp
575.Vb 6
576\& my $whatnot = sub { $some_obj->obfuscate(@args) };
577\& func($whatnot);
578\& sub func {
579\& my $code = shift;
580\& &$code();
581\& }
582.Ve
583.Sp
584You could also investigate the \fIcan()\fR method in the \s-1UNIVERSAL\s0 class
585(part of the standard perl distribution).
586.Sh "How do I create a static variable?"
587.IX Subsection "How do I create a static variable?"
588As with most things in Perl, \s-1TMTOWTDI\s0. What is a \*(L"static variable\*(R" in
589other languages could be either a function-private variable (visible
590only within a single function, retaining its value between calls to
591that function), or a file-private variable (visible only to functions
592within the file it was declared in) in Perl.
593.PP
594Here's code to implement a function-private variable:
595.PP
596.Vb 5
597\& BEGIN {
598\& my $counter = 42;
599\& sub prev_counter { return --$counter }
600\& sub next_counter { return $counter++ }
601\& }
602.Ve
603.PP
604Now \fIprev_counter()\fR and \fInext_counter()\fR share a private variable \f(CW$counter\fR
605that was initialized at compile time.
606.PP
607To declare a file-private variable, you'll still use a \fImy()\fR, putting
608the declaration at the outer scope level at the top of the file.
609Assume this is in file Pax.pm:
610.PP
611.Vb 2
612\& package Pax;
613\& my $started = scalar(localtime(time()));
614.Ve
615.PP
616.Vb 1
617\& sub begun { return $started }
618.Ve
619.PP
620When \f(CW\*(C`use Pax\*(C'\fR or \f(CW\*(C`require Pax\*(C'\fR loads this module, the variable will
621be initialized. It won't get garbage-collected the way most variables
622going out of scope do, because the \fIbegun()\fR function cares about it,
623but no one else can get it. It is not called \f(CW$Pax::started\fR because
624its scope is unrelated to the package. It's scoped to the file. You
625could conceivably have several packages in that same file all
626accessing the same private variable, but another file with the same
627package couldn't get to it.
628.PP
629See \*(L"Persistent Private Variables\*(R" in perlsub for details.
630.Sh "What's the difference between dynamic and lexical (static) scoping? Between \fIlocal()\fP and \fImy()\fP?"
631.IX Subsection "What's the difference between dynamic and lexical (static) scoping? Between local() and my()?"
632\&\f(CW\*(C`local($x)\*(C'\fR saves away the old value of the global variable \f(CW$x\fR
633and assigns a new value for the duration of the subroutine \fIwhich is
634visible in other functions called from that subroutine\fR. This is done
635at run\-time, so is called dynamic scoping. \fIlocal()\fR always affects global
636variables, also called package variables or dynamic variables.
637.PP
638\&\f(CW\*(C`my($x)\*(C'\fR creates a new variable that is only visible in the current
639subroutine. This is done at compile\-time, so it is called lexical or
640static scoping. \fImy()\fR always affects private variables, also called
641lexical variables or (improperly) static(ly scoped) variables.
642.PP
643For instance:
644.PP
645.Vb 3
646\& sub visible {
647\& print "var has value $var\en";
648\& }
649.Ve
650.PP
651.Vb 4
652\& sub dynamic {
653\& local $var = 'local'; # new temporary value for the still-global
654\& visible(); # variable called $var
655\& }
656.Ve
657.PP
658.Vb 4
659\& sub lexical {
660\& my $var = 'private'; # new private variable, $var
661\& visible(); # (invisible outside of sub scope)
662\& }
663.Ve
664.PP
665.Vb 1
666\& $var = 'global';
667.Ve
668.PP
669.Vb 3
670\& visible(); # prints global
671\& dynamic(); # prints local
672\& lexical(); # prints global
673.Ve
674.PP
675Notice how at no point does the value \*(L"private\*(R" get printed. That's
676because \f(CW$var\fR only has that value within the block of the \fIlexical()\fR
677function, and it is hidden from called subroutine.
678.PP
679In summary, \fIlocal()\fR doesn't make what you think of as private, local
680variables. It gives a global variable a temporary value. \fImy()\fR is
681what you're looking for if you want private variables.
682.PP
683See \*(L"Private Variables via \fImy()\fR\*(R" in perlsub and
684\&\*(L"Temporary Values via \fIlocal()\fR\*(R" in perlsub for excruciating details.
685.Sh "How can I access a dynamic variable while a similarly named lexical is in scope?"
686.IX Subsection "How can I access a dynamic variable while a similarly named lexical is in scope?"
687You can do this via symbolic references, provided you haven't set
688\&\f(CW\*(C`use strict "refs"\*(C'\fR. So instead of \f(CW$var\fR, use \f(CW\*(C`${'var'}\*(C'\fR.
689.PP
690.Vb 2
691\& local $var = "global";
692\& my $var = "lexical";
693.Ve
694.PP
695.Vb 1
696\& print "lexical is $var\en";
697.Ve
698.PP
699.Vb 2
700\& no strict 'refs';
701\& print "global is ${'var'}\en";
702.Ve
703.PP
704If you know your package, you can just mention it explicitly, as in
705\&\f(CW$Some_Pack::var\fR. Note that the notation \f(CW$::var\fR is \fInot\fR the dynamic
706\&\f(CW$var\fR in the current package, but rather the one in the \f(CW\*(C`main\*(C'\fR
707package, as though you had written \f(CW$main::var\fR. Specifying the package
708directly makes you hard-code its name, but it executes faster and
709avoids running afoul of \f(CW\*(C`use strict "refs"\*(C'\fR.
710.Sh "What's the difference between deep and shallow binding?"
711.IX Subsection "What's the difference between deep and shallow binding?"
712In deep binding, lexical variables mentioned in anonymous subroutines
713are the same ones that were in scope when the subroutine was created.
714In shallow binding, they are whichever variables with the same names
715happen to be in scope when the subroutine is called. Perl always uses
716deep binding of lexical variables (i.e., those created with \fImy()\fR).
717However, dynamic variables (aka global, local, or package variables)
718are effectively shallowly bound. Consider this just one more reason
719not to use them. See the answer to \*(L"What's a closure?\*(R".
720.ie n .Sh "Why doesn't ""my($foo) = <\s-1FILE\s0>;"" work right?"
721.el .Sh "Why doesn't ``my($foo) = <\s-1FILE\s0>;'' work right?"
722.IX Subsection "Why doesn't my($foo) = <FILE>; work right?"
723\&\f(CW\*(C`my()\*(C'\fR and \f(CW\*(C`local()\*(C'\fR give list context to the right hand side
724of \f(CW\*(C`=\*(C'\fR. The <\s-1FH\s0> read operation, like so many of Perl's
725functions and operators, can tell which context it was called in and
726behaves appropriately. In general, the \fIscalar()\fR function can help.
727This function does nothing to the data itself (contrary to popular myth)
728but rather tells its argument to behave in whatever its scalar fashion is.
729If that function doesn't have a defined scalar behavior, this of course
730doesn't help you (such as with \fIsort()\fR).
731.PP
732To enforce scalar context in this particular case, however, you need
733merely omit the parentheses:
734.PP
735.Vb 3
736\& local($foo) = <FILE>; # WRONG
737\& local($foo) = scalar(<FILE>); # ok
738\& local $foo = <FILE>; # right
739.Ve
740.PP
741You should probably be using lexical variables anyway, although the
742issue is the same here:
743.PP
744.Vb 2
745\& my($foo) = <FILE>; # WRONG
746\& my $foo = <FILE>; # right
747.Ve
748.Sh "How do I redefine a builtin function, operator, or method?"
749.IX Subsection "How do I redefine a builtin function, operator, or method?"
750Why do you want to do that? :\-)
751.PP
752If you want to override a predefined function, such as \fIopen()\fR,
753then you'll have to import the new definition from a different
754module. See \*(L"Overriding Built-in Functions\*(R" in perlsub. There's
755also an example in \*(L"Class::Template\*(R" in perltoot.
756.PP
757If you want to overload a Perl operator, such as \f(CW\*(C`+\*(C'\fR or \f(CW\*(C`**\*(C'\fR,
758then you'll want to use the \f(CW\*(C`use overload\*(C'\fR pragma, documented
759in overload.
760.PP
761If you're talking about obscuring method calls in parent classes,
762see \*(L"Overridden Methods\*(R" in perltoot.
763.Sh "What's the difference between calling a function as &foo and \fIfoo()\fP?"
764.IX Subsection "What's the difference between calling a function as &foo and foo()?"
765When you call a function as \f(CW&foo\fR, you allow that function access to
766your current \f(CW@_\fR values, and you bypass prototypes.
767The function doesn't get an empty \f(CW@_\fR\-\-it gets yours! While not
768strictly speaking a bug (it's documented that way in perlsub), it
769would be hard to consider this a feature in most cases.
770.PP
771When you call your function as \f(CW\*(C`&foo()\*(C'\fR, then you \fIdo\fR get a new \f(CW@_\fR,
772but prototyping is still circumvented.
773.PP
774Normally, you want to call a function using \f(CW\*(C`foo()\*(C'\fR. You may only
775omit the parentheses if the function is already known to the compiler
776because it already saw the definition (\f(CW\*(C`use\*(C'\fR but not \f(CW\*(C`require\*(C'\fR),
777or via a forward reference or \f(CW\*(C`use subs\*(C'\fR declaration. Even in this
778case, you get a clean \f(CW@_\fR without any of the old values leaking through
779where they don't belong.
780.Sh "How do I create a switch or case statement?"
781.IX Subsection "How do I create a switch or case statement?"
782This is explained in more depth in the perlsyn. Briefly, there's
783no official case statement, because of the variety of tests possible
784in Perl (numeric comparison, string comparison, glob comparison,
785regex matching, overloaded comparisons, ...).
786Larry couldn't decide how best to do this, so he left it out, even
787though it's been on the wish list since perl1.
788.PP
789Starting from Perl 5.8 to get switch and case one can use the
790Switch extension and say:
791.PP
792.Vb 1
793\& use Switch;
794.Ve
795.PP
796after which one has switch and case. It is not as fast as it could be
797because it's not really part of the language (it's done using source
798filters) but it is available, and it's very flexible.
799.PP
800But if one wants to use pure Perl, the general answer is to write a
801construct like this:
802.PP
803.Vb 6
804\& for ($variable_to_test) {
805\& if (/pat1/) { } # do something
806\& elsif (/pat2/) { } # do something else
807\& elsif (/pat3/) { } # do something else
808\& else { } # default
809\& }
810.Ve
811.PP
812Here's a simple example of a switch based on pattern matching, this
813time lined up in a way to make it look more like a switch statement.
814We'll do a multiway conditional based on the type of reference stored
815in \f(CW$whatchamacallit:\fR
816.PP
817.Vb 1
818\& SWITCH: for (ref $whatchamacallit) {
819.Ve
820.PP
821.Vb 1
822\& /^$/ && die "not a reference";
823.Ve
824.PP
825.Vb 4
826\& /SCALAR/ && do {
827\& print_scalar($$ref);
828\& last SWITCH;
829\& };
830.Ve
831.PP
832.Vb 4
833\& /ARRAY/ && do {
834\& print_array(@$ref);
835\& last SWITCH;
836\& };
837.Ve
838.PP
839.Vb 4
840\& /HASH/ && do {
841\& print_hash(%$ref);
842\& last SWITCH;
843\& };
844.Ve
845.PP
846.Vb 4
847\& /CODE/ && do {
848\& warn "can't print function ref";
849\& last SWITCH;
850\& };
851.Ve
852.PP
853.Vb 1
854\& # DEFAULT
855.Ve
856.PP
857.Vb 1
858\& warn "User defined type skipped";
859.Ve
860.PP
861.Vb 1
862\& }
863.Ve
864.PP
865See \f(CW\*(C`perlsyn/"Basic BLOCKs and Switch Statements"\*(C'\fR for many other
866examples in this style.
867.PP
868Sometimes you should change the positions of the constant and the variable.
869For example, let's say you wanted to test which of many answers you were
870given, but in a case-insensitive way that also allows abbreviations.
871You can use the following technique if the strings all start with
872different characters or if you want to arrange the matches so that
873one takes precedence over another, as \f(CW"SEND"\fR has precedence over
874\&\f(CW"STOP"\fR here:
875.PP
876.Vb 6
877\& chomp($answer = <>);
878\& if ("SEND" =~ /^\eQ$answer/i) { print "Action is send\en" }
879\& elsif ("STOP" =~ /^\eQ$answer/i) { print "Action is stop\en" }
880\& elsif ("ABORT" =~ /^\eQ$answer/i) { print "Action is abort\en" }
881\& elsif ("LIST" =~ /^\eQ$answer/i) { print "Action is list\en" }
882\& elsif ("EDIT" =~ /^\eQ$answer/i) { print "Action is edit\en" }
883.Ve
884.PP
885A totally different approach is to create a hash of function references.
886.PP
887.Vb 6
888\& my %commands = (
889\& "happy" => \e&joy,
890\& "sad", => \e&sullen,
891\& "done" => sub { die "See ya!" },
892\& "mad" => \e&angry,
893\& );
894.Ve
895.PP
896.Vb 7
897\& print "How are you? ";
898\& chomp($string = <STDIN>);
899\& if ($commands{$string}) {
900\& $commands{$string}->();
901\& } else {
902\& print "No such command: $string\en";
903\& }
904.Ve
905.Sh "How can I catch accesses to undefined variables/functions/methods?"
906.IX Subsection "How can I catch accesses to undefined variables/functions/methods?"
907The \s-1AUTOLOAD\s0 method, discussed in \*(L"Autoloading\*(R" in perlsub and
908\&\*(L"\s-1AUTOLOAD:\s0 Proxy Methods\*(R" in perltoot, lets you capture calls to
909undefined functions and methods.
910.PP
911When it comes to undefined variables that would trigger a warning
912under \f(CW\*(C`\-w\*(C'\fR, you can use a handler to trap the pseudo-signal
913\&\f(CW\*(C`_\|_WARN_\|_\*(C'\fR like this:
914.PP
915.Vb 1
916\& $SIG{__WARN__} = sub {
917.Ve
918.PP
919.Vb 1
920\& for ( $_[0] ) { # voici un switch statement
921.Ve
922.PP
923.Vb 4
924\& /Use of uninitialized value/ && do {
925\& # promote warning to a fatal
926\& die $_;
927\& };
928.Ve
929.PP
930.Vb 1
931\& # other warning cases to catch could go here;
932.Ve
933.PP
934.Vb 2
935\& warn $_;
936\& }
937.Ve
938.PP
939.Vb 1
940\& };
941.Ve
942.Sh "Why can't a method included in this same file be found?"
943.IX Subsection "Why can't a method included in this same file be found?"
944Some possible reasons: your inheritance is getting confused, you've
945misspelled the method name, or the object is of the wrong type. Check
946out perltoot for details about any of the above cases. You may
947also use \f(CW\*(C`print ref($object)\*(C'\fR to find out the class \f(CW$object\fR was
948blessed into.
949.PP
950Another possible reason for problems is because you've used the
951indirect object syntax (eg, \f(CW\*(C`find Guru "Samy"\*(C'\fR) on a class name
952before Perl has seen that such a package exists. It's wisest to make
953sure your packages are all defined before you start using them, which
954will be taken care of if you use the \f(CW\*(C`use\*(C'\fR statement instead of
955\&\f(CW\*(C`require\*(C'\fR. If not, make sure to use arrow notation (eg.,
956\&\f(CW\*(C`Guru\->find("Samy")\*(C'\fR) instead. Object notation is explained in
957perlobj.
958.PP
959Make sure to read about creating modules in perlmod and
960the perils of indirect objects in \*(L"Method Invocation\*(R" in perlobj.
961.Sh "How can I find out my current package?"
962.IX Subsection "How can I find out my current package?"
963If you're just a random program, you can do this to find
964out what the currently compiled package is:
965.PP
966.Vb 1
967\& my $packname = __PACKAGE__;
968.Ve
969.PP
970But, if you're a method and you want to print an error message
971that includes the kind of object you were called on (which is
972not necessarily the same as the one in which you were compiled):
973.PP
974.Vb 5
975\& sub amethod {
976\& my $self = shift;
977\& my $class = ref($self) || $self;
978\& warn "called me from a $class object";
979\& }
980.Ve
981.Sh "How can I comment out a large block of perl code?"
982.IX Subsection "How can I comment out a large block of perl code?"
983You can use embedded \s-1POD\s0 to discard it. The =for directive
984lasts until the next paragraph (two consecutive newlines).
985.PP
986.Vb 1
987\& # program is here
988.Ve
989.PP
990.Vb 2
991\& =for nobody
992\& This paragraph is commented out
993.Ve
994.PP
995.Vb 1
996\& # program continues
997.Ve
998.PP
999The =begin and =end directives can contain multiple
1000paragraphs.
1001.PP
1002.Vb 1
1003\& =begin comment text
1004.Ve
1005.PP
1006.Vb 1
1007\& all of this stuff
1008.Ve
1009.PP
1010.Vb 2
1011\& here will be ignored
1012\& by everyone
1013.Ve
1014.PP
1015.Vb 1
1016\& =end comment text
1017.Ve
1018.PP
1019The pod directives cannot go just anywhere. You must put a
1020pod directive where the parser is expecting a new statement,
1021not just in the middle of an expression or some other
1022arbitrary s grammar production.
1023.PP
1024See perlpod for more details.
1025.Sh "How do I clear a package?"
1026.IX Subsection "How do I clear a package?"
1027Use this code, provided by Mark-Jason Dominus:
1028.PP
1029.Vb 17
1030\& sub scrub_package {
1031\& no strict 'refs';
1032\& my $pack = shift;
1033\& die "Shouldn't delete main package"
1034\& if $pack eq "" || $pack eq "main";
1035\& my $stash = *{$pack . '::'}{HASH};
1036\& my $name;
1037\& foreach $name (keys %$stash) {
1038\& my $fullname = $pack . '::' . $name;
1039\& # Get rid of everything with that name.
1040\& undef $$fullname;
1041\& undef @$fullname;
1042\& undef %$fullname;
1043\& undef &$fullname;
1044\& undef *$fullname;
1045\& }
1046\& }
1047.Ve
1048.PP
1049Or, if you're using a recent release of Perl, you can
1050just use the \fISymbol::delete_package()\fR function instead.
1051.Sh "How can I use a variable as a variable name?"
1052.IX Subsection "How can I use a variable as a variable name?"
1053Beginners often think they want to have a variable contain the name
1054of a variable.
1055.PP
1056.Vb 3
1057\& $fred = 23;
1058\& $varname = "fred";
1059\& ++$$varname; # $fred now 24
1060.Ve
1061.PP
1062This works \fIsometimes\fR, but it is a very bad idea for two reasons.
1063.PP
1064The first reason is that this technique \fIonly works on global
1065variables\fR. That means that if \f(CW$fred\fR is a lexical variable created
1066with \fImy()\fR in the above example, the code wouldn't work at all: you'd
1067accidentally access the global and skip right over the private lexical
1068altogether. Global variables are bad because they can easily collide
1069accidentally and in general make for non-scalable and confusing code.
1070.PP
1071Symbolic references are forbidden under the \f(CW\*(C`use strict\*(C'\fR pragma.
1072They are not true references and consequently are not reference counted
1073or garbage collected.
1074.PP
1075The other reason why using a variable to hold the name of another
1076variable is a bad idea is that the question often stems from a lack of
1077understanding of Perl data structures, particularly hashes. By using
1078symbolic references, you are just using the package's symbol-table hash
1079(like \f(CW%main::\fR) instead of a user-defined hash. The solution is to
1080use your own hash or a real reference instead.
1081.PP
1082.Vb 3
1083\& $fred = 23;
1084\& $varname = "fred";
1085\& $USER_VARS{$varname}++; # not $$varname++
1086.Ve
1087.PP
1088There we're using the \f(CW%USER_VARS\fR hash instead of symbolic references.
1089Sometimes this comes up in reading strings from the user with variable
1090references and wanting to expand them to the values of your perl
1091program's variables. This is also a bad idea because it conflates the
1092program-addressable namespace and the user-addressable one. Instead of
1093reading a string and expanding it to the actual contents of your program's
1094own variables:
1095.PP
1096.Vb 2
1097\& $str = 'this has a $fred and $barney in it';
1098\& $str =~ s/(\e$\ew+)/$1/eeg; # need double eval
1099.Ve
1100.PP
1101it would be better to keep a hash around like \f(CW%USER_VARS\fR and have
1102variable references actually refer to entries in that hash:
1103.PP
1104.Vb 1
1105\& $str =~ s/\e$(\ew+)/$USER_VARS{$1}/g; # no /e here at all
1106.Ve
1107.PP
1108That's faster, cleaner, and safer than the previous approach. Of course,
1109you don't need to use a dollar sign. You could use your own scheme to
1110make it less confusing, like bracketed percent symbols, etc.
1111.PP
1112.Vb 2
1113\& $str = 'this has a %fred% and %barney% in it';
1114\& $str =~ s/%(\ew+)%/$USER_VARS{$1}/g; # no /e here at all
1115.Ve
1116.PP
1117Another reason that folks sometimes think they want a variable to
1118contain the name of a variable is because they don't know how to build
1119proper data structures using hashes. For example, let's say they
1120wanted two hashes in their program: \f(CW%fred\fR and \f(CW%barney\fR, and that they
1121wanted to use another scalar variable to refer to those by name.
1122.PP
1123.Vb 2
1124\& $name = "fred";
1125\& $$name{WIFE} = "wilma"; # set %fred
1126.Ve
1127.PP
1128.Vb 2
1129\& $name = "barney";
1130\& $$name{WIFE} = "betty"; # set %barney
1131.Ve
1132.PP
1133This is still a symbolic reference, and is still saddled with the
1134problems enumerated above. It would be far better to write:
1135.PP
1136.Vb 2
1137\& $folks{"fred"}{WIFE} = "wilma";
1138\& $folks{"barney"}{WIFE} = "betty";
1139.Ve
1140.PP
1141And just use a multilevel hash to start with.
1142.PP
1143The only times that you absolutely \fImust\fR use symbolic references are
1144when you really must refer to the symbol table. This may be because it's
1145something that can't take a real reference to, such as a format name.
1146Doing so may also be important for method calls, since these always go
1147through the symbol table for resolution.
1148.PP
1149In those cases, you would turn off \f(CW\*(C`strict 'refs'\*(C'\fR temporarily so you
1150can play around with the symbol table. For example:
1151.PP
1152.Vb 5
1153\& @colors = qw(red blue green yellow orange purple violet);
1154\& for my $name (@colors) {
1155\& no strict 'refs'; # renege for the block
1156\& *$name = sub { "<FONT COLOR='$name'>@_</FONT>" };
1157\& }
1158.Ve
1159.PP
1160All those functions (\fIred()\fR, \fIblue()\fR, \fIgreen()\fR, etc.) appear to be separate,
1161but the real code in the closure actually was compiled only once.
1162.PP
1163So, sometimes you might want to use symbolic references to directly
1164manipulate the symbol table. This doesn't matter for formats, handles, and
1165subroutines, because they are always global\*(--you can't use \fImy()\fR on them.
1166For scalars, arrays, and hashes, though\*(--and usually for subroutines\*(--
1167you probably only want to use hard references.
1168.SH "AUTHOR AND COPYRIGHT"
1169.IX Header "AUTHOR AND COPYRIGHT"
1170Copyright (c) 1997\-2002 Tom Christiansen and Nathan Torkington.
1171All rights reserved.
1172.PP
1173This documentation is free; you can redistribute it and/or modify it
1174under the same terms as Perl itself.
1175.PP
1176Irrespective of its distribution, all code examples in this file
1177are hereby placed into the public domain. You are permitted and
1178encouraged to use this code in your own programs for fun
1179or for profit as you see fit. A simple comment in the code giving
1180credit would be courteous but is not required.