1 .\" Automatically generated by Pod::Man v1.37, Pod::Parser v1.14
4 .\" ========================================================================
5 .de Sh \" Subsection heading
13 .de Sp \" Vertical space (when we can't use .PP)
17 .de Vb \" Begin verbatim text
22 .de Ve \" End verbatim text
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<>.
33 .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
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
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.
57 . tm Index:\\$1\t\\n%\t"\\$2"
63 .\" For nroff, turn off justification. Always turn off hyphenation; it makes
64 .\" way too many mistakes in technical documents.
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
79 . ds #H ((1u-(\\\\n(.fu%2u))*.13m)
85 . \" simple accents for nroff and troff
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'
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 \
129 .\" ========================================================================
131 .IX Title "PERLFAQ7 1"
132 .TH PERLFAQ7 1 "2003-11-25" "perl v5.8.3" "Perl Programmers Reference Guide"
134 perlfaq7 \- General Perl Language Issues ($Revision: 1.1 $, $Date: 2004/06/16 12:41:53 $)
136 .IX Header "DESCRIPTION"
137 This section deals with general Perl language issues that don't
138 clearly 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?"
141 There is no \s-1BNF\s0, but you can paw your way through the yacc grammar in
142 perly.y in the source distribution if you're particularly brave. The
143 grammar relies on very smart tokenizing code, so be prepared to
144 venture into toke.c as well.
146 In the words of Chaim Frenkel: \*(L"Perl's grammar can not be reduced to \s-1BNF\s0.
147 The work of parsing perl is distributed between yacc, the lexer, smoke
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?"
151 They are type specifiers, as detailed in perldata:
154 \& $ for scalar values (number, string or reference)
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.
162 There are couple of other symbols that you're likely to encounter that aren't
163 really type specifiers:
166 \& <> are used for inputting a record from a filehandle.
167 \& \e takes a reference to something.
170 Note that <\s-1FILE\s0> is \fIneither\fR the type specifier for files
171 nor the name of the handle. It is the \f(CW\*(C`<>\*(C'\fR operator applied
172 to the handle \s-1FILE\s0. It reads one line (well, record\*(--see
173 "$/" in perlvar) from the handle \s-1FILE\s0 in scalar context, or \fIall\fR lines
174 in list context. When performing open, close, or any other operation
175 besides \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,
177 2)\*(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?"
180 Normally, a bareword doesn't need to be quoted, but in most cases
181 probably should be (and must be under \f(CW\*(C`use strict\*(C'\fR). But a hash key
182 consisting of a simple word (that isn't the name of a defined
183 subroutine) and the left-hand operand to the \f(CW\*(C`=>\*(C'\fR operator both
184 count as though they were quoted:
188 \& ------------ ---------------
189 \& $foo{line} $foo{"line"}
190 \& bar => stuff "bar" => stuff
193 The final semicolon in a block is optional, as is the final comma in a
194 list. Good style (see perlstyle) says to put them in except for
198 \& if ($whoops) { exit 1 }
199 \& @nums = (1, 2, 3);
207 \& "There Beren came from mountains cold",
208 \& "And lost he wandered under leaves",
211 .Sh "How do I skip some return values?"
212 .IX Subsection "How do I skip some return values?"
213 One way is to treat the return values as a list and index into it:
216 \& $dir = (getpwnam($user))[7];
219 Another way is to use undef as an element on the left\-hand\-side:
222 \& ($dev, $ino, undef, undef, $uid, $gid) = stat($file);
225 You can also use a list slice to select only the elements that
229 \& ($dev, $ino, $uid, $gid) = ( stat($file) )[0,1,4,5];
231 .Sh "How do I temporarily block warnings?"
232 .IX Subsection "How do I temporarily block warnings?"
233 If you are running Perl 5.6.0 or better, the \f(CW\*(C`use warnings\*(C'\fR pragma
234 allows fine control of what warning are produced.
235 See perllexwarn for more details.
239 \& no warnings; # temporarily turn off warnings
240 \& $a = $b + $c; # I know these might be undef
244 If you have an older version of Perl, the \f(CW$^W\fR variable (documented
245 in perlvar) controls runtime warnings for a block:
249 \& local $^W = 0; # temporarily turn off warnings
250 \& $a = $b + $c; # I know these might be undef
254 Note that like all the punctuation variables, you cannot currently
255 use \fImy()\fR on \f(CW$^W\fR, only \fIlocal()\fR.
256 .Sh "What's an extension?"
257 .IX Subsection "What's an extension?"
258 An extension is a way of calling compiled C code from Perl. Reading
259 perlxstut is a good place to learn more about extensions.
260 .Sh "Why do Perl operators have different precedence than C operators?"
261 .IX Subsection "Why do Perl operators have different precedence than C operators?"
262 Actually, they don't. All C operators that Perl copies have the same
263 precedence in Perl as they do in C. The problem is with operators that C
264 doesn't have, especially functions that give a list context to everything
265 on their right, eg. print, chmod, exec, and so on. Such functions are
266 called \*(L"list operators\*(R" and appear as such in the precedence table in
269 A common mistake is to write:
272 \& unlink $file || die "snafu";
275 This gets interpreted as:
278 \& unlink ($file || die "snafu");
281 To avoid this problem, either put in extra parentheses or use the
282 super low precedence \f(CW\*(C`or\*(C'\fR operator:
285 \& (unlink $file) || die "snafu";
286 \& unlink $file or die "snafu";
289 The \*(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)
290 deliberately have precedence lower than that of list operators for
291 just such situations as the one above.
293 Another operator with surprising precedence is exponentiation. It
294 binds more tightly even than unary minus, making \f(CW\*(C`\-2**2\*(C'\fR product a
295 negative not a positive four. It is also right\-associating, meaning
296 that \f(CW\*(C`2**3**2\*(C'\fR is two raised to the ninth power, not eight squared.
298 Although it has the same precedence as in C, Perl's \f(CW\*(C`?:\*(C'\fR operator
299 produces an lvalue. This assigns \f(CW$x\fR to either \f(CW$a\fR or \f(CW$b\fR, depending
300 on the trueness of \f(CW$maybe:\fR
303 \& ($maybe ? $a : $b) = $x;
305 .Sh "How do I declare/create a structure?"
306 .IX Subsection "How do I declare/create a structure?"
307 In general, you don't \*(L"declare\*(R" a structure. Just use a (probably
308 anonymous) hash reference. See perlref and perldsc for details.
312 \& $person = {}; # new anonymous hash
313 \& $person->{AGE} = 24; # set field AGE to 24
314 \& $person->{NAME} = "Nat"; # set field NAME to "Nat"
317 If you're looking for something a bit more rigorous, try perltoot.
318 .Sh "How do I create a module?"
319 .IX Subsection "How do I create a module?"
320 A module is a package that lives in a file of the same name. For
321 example, the Hello::There module would live in Hello/There.pm. For
322 details, read perlmod. You'll also find Exporter helpful. If
323 you're writing a C or mixed-language module with both C and Perl, then
324 you should study perlxstut.
326 The \f(CW\*(C`h2xs\*(C'\fR program will create stubs for all the important stuff for you:
329 \& % h2xs -XA -n My::Module
332 The \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
333 code. The \f(CW\*(C`\-A\*(C'\fR switch tells \f(CW\*(C`h2xs\*(C'\fR that you are not using the
334 AutoLoader, and the \f(CW\*(C`\-n\*(C'\fR switch specifies the name of the module.
335 See h2xs for more details.
336 .Sh "How do I create a class?"
337 .IX Subsection "How do I create a class?"
338 See perltoot for an introduction to classes and objects, as well as
340 .Sh "How can I tell if a variable is tainted?"
341 .IX Subsection "How can I tell if a variable is tainted?"
342 You can use the \fItainted()\fR function of the Scalar::Util module, available
343 from \s-1CPAN\s0 (or included with Perl since release 5.8.0).
344 See also \*(L"Laundering and Detecting Tainted Data\*(R" in perlsec.
345 .Sh "What's a closure?"
346 .IX Subsection "What's a closure?"
347 Closures are documented in perlref.
349 \&\fIClosure\fR is a computer science term with a precise but
350 hard-to-explain meaning. Closures are implemented in Perl as anonymous
351 subroutines with lasting references to lexical variables outside their
352 own scopes. These lexicals magically refer to the variables that were
353 around when the subroutine was defined (deep binding).
355 Closures make sense in any programming language where you can have the
356 return value of a function be itself a function, as you can in Perl.
357 Note that some languages provide anonymous functions but are not
358 capable of providing proper closures: the Python language, for
359 example. For more information on closures, check out any textbook on
360 functional programming. Scheme is a language that not only supports
361 but encourages closures.
363 Here's a classic function-generating function:
366 \& sub add_function_generator {
367 \& return sub { shift + shift };
372 \& $add_sub = add_function_generator();
373 \& $sum = $add_sub->(4,5); # $sum is 9 now.
376 The closure works as a \fIfunction template\fR with some customization
377 slots left out to be filled later. The anonymous subroutine returned
378 by \fIadd_function_generator()\fR isn't technically a closure because it
379 refers to no lexicals outside its own scope.
381 Contrast this with the following \fImake_adder()\fR function, in which the
382 returned anonymous function contains a reference to a lexical variable
383 outside the scope of that function itself. Such a reference requires
384 that Perl return a proper closure, thus locking in for all time the
385 value that the lexical had when the function was created.
389 \& my $addpiece = shift;
390 \& return sub { shift + $addpiece };
395 \& $f1 = make_adder(20);
396 \& $f2 = make_adder(555);
399 Now \f(CW\*(C`&$f1($n)\*(C'\fR is always 20 plus whatever \f(CW$n\fR you pass in, whereas
400 \&\f(CW\*(C`&$f2($n)\*(C'\fR is always 555 plus whatever \f(CW$n\fR you pass in. The \f(CW$addpiece\fR
401 in the closure sticks around.
403 Closures are often used for less esoteric purposes. For example, when
404 you want to pass in a bit of code into a function:
408 \& timeout( 30, sub { $line = <STDIN> } );
411 If the code to execute had been passed in as a string,
412 \&\f(CW'$line = <STDIN>'\fR, there would have been no way for the
413 hypothetical \fItimeout()\fR function to access the lexical variable
414 \&\f(CW$line\fR back in its caller's scope.
415 .Sh "What is variable suicide and how can I prevent it?"
416 .IX Subsection "What is variable suicide and how can I prevent it?"
417 Variable suicide is when you (temporarily or permanently) lose the
418 value of a variable. It is caused by scoping through \fImy()\fR and \fIlocal()\fR
419 interacting with either closures or aliased \fIforeach()\fR iterator
420 variables and subroutine arguments. It used to be easy to
421 inadvertently lose a variable's value this way, but now it's much
422 harder. Take this code:
427 \& while ($i++ < 3) { my $f = $f; $f .= "bar"; print $f, "\en" }
430 \& print "Finally $f\en";
433 The \f(CW$f\fR that has \*(L"bar\*(R" added to it three times should be a new \f(CW$f\fR
434 (\f(CW\*(C`my $f\*(C'\fR should create a new local variable each time through the loop).
435 It isn't, however. This was a bug, now fixed in the latest releases
436 (tested against 5.004_05, 5.005_03, and 5.005_56).
437 .Sh "How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?"
438 .IX Subsection "How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?"
439 With the exception of regexes, you need to pass references to these
440 objects. See \*(L"Pass by Reference\*(R" in perlsub for this particular
441 question, and perlref for information on references.
443 See ``Passing Regexes'', below, for information on passing regular
445 .IP "Passing Variables and Functions" 4
446 .IX Item "Passing Variables and Functions"
447 Regular variables and functions are quite easy to pass: just pass in a
448 reference to an existing or anonymous variable or function:
451 \& func( \e$some_scalar );
455 \& func( \e@some_array );
456 \& func( [ 1 .. 10 ] );
460 \& func( \e%some_hash );
461 \& func( { this => 10, that => 20 } );
465 \& func( \e&some_func );
466 \& func( sub { $_[0] ** $_[1] } );
468 .IP "Passing Filehandles" 4
469 .IX Item "Passing Filehandles"
470 As of Perl 5.6, you can represent filehandles with scalar variables
471 which you treat as any other scalar.
474 \& open my $fh, $filename or die "Cannot open $filename! $!";
480 \& my $passed_fh = shift;
488 Before Perl 5.6, you had to use the \f(CW*FH\fR or \f(CW\*(C`\e*FH\*(C'\fR notations.
489 These are \*(L"typeglobs\*(R"\-\-see \*(L"Typeglobs and Filehandles\*(R" in perldata
490 and especially \*(L"Pass by Reference\*(R" in perlsub for more information.
491 .IP "Passing Regexes" 4
492 .IX Item "Passing Regexes"
493 To pass regexes around, you'll need to be using a release of Perl
494 sufficiently recent as to support the \f(CW\*(C`qr//\*(C'\fR construct, pass around
495 strings and use an exception-trapping eval, or else be very, very clever.
497 Here's an example of how to pass in a string to be regex compared
498 using \f(CW\*(C`qr//\*(C'\fR:
502 \& my ($val1, $regex) = @_;
503 \& my $retval = $val1 =~ /$regex/;
506 \& $match = compare("old McDonald", qr/d.*D/i);
509 Notice how \f(CW\*(C`qr//\*(C'\fR allows flags at the end. That pattern was compiled
510 at compile time, although it was executed later. The nifty \f(CW\*(C`qr//\*(C'\fR
511 notation wasn't introduced until the 5.005 release. Before that, you
512 had to approach this problem much less intuitively. For example, here
513 it is again if you don't have \f(CW\*(C`qr//\*(C'\fR:
517 \& my ($val1, $regex) = @_;
518 \& my $retval = eval { $val1 =~ /$regex/ };
525 \& $match = compare("old McDonald", q/($?i)d.*D/);
528 Make sure you never say something like this:
531 \& return eval "\e$val =~ /$regex/"; # WRONG
534 or someone can sneak shell escapes into the regex due to the double
535 interpolation of the eval and the double-quoted string. For example:
538 \& $pattern_of_evil = 'danger ${ system("rm -rf * &") } danger';
542 \& eval "\e$string =~ /$pattern_of_evil/";
545 Those preferring to be very, very clever might see the O'Reilly book,
546 \&\fIMastering Regular Expressions\fR, by Jeffrey Friedl. Page 273's
547 \&\fIBuild_MatchMany_Function()\fR is particularly interesting. A complete
548 citation of this book is given in perlfaq2.
549 .IP "Passing Methods" 4
550 .IX Item "Passing Methods"
551 To pass an object method into a subroutine, you can do this:
554 \& call_a_lot(10, $some_obj, "methname")
556 \& my ($count, $widget, $trick) = @_;
557 \& for (my $i = 0; $i < $count; $i++) {
558 \& $widget->$trick();
563 Or, you can use a closure to bundle up the object, its
564 method call, and arguments:
567 \& my $whatnot = sub { $some_obj->obfuscate(@args) };
575 You could also investigate the \fIcan()\fR method in the \s-1UNIVERSAL\s0 class
576 (part of the standard perl distribution).
577 .Sh "How do I create a static variable?"
578 .IX Subsection "How do I create a static variable?"
579 As with most things in Perl, \s-1TMTOWTDI\s0. What is a \*(L"static variable\*(R" in
580 other languages could be either a function-private variable (visible
581 only within a single function, retaining its value between calls to
582 that function), or a file-private variable (visible only to functions
583 within the file it was declared in) in Perl.
585 Here's code to implement a function-private variable:
590 \& sub prev_counter { return --$counter }
591 \& sub next_counter { return $counter++ }
595 Now \fIprev_counter()\fR and \fInext_counter()\fR share a private variable \f(CW$counter\fR
596 that was initialized at compile time.
598 To declare a file-private variable, you'll still use a \fImy()\fR, putting
599 the declaration at the outer scope level at the top of the file.
600 Assume this is in file Pax.pm:
604 \& my $started = scalar(localtime(time()));
608 \& sub begun { return $started }
611 When \f(CW\*(C`use Pax\*(C'\fR or \f(CW\*(C`require Pax\*(C'\fR loads this module, the variable will
612 be initialized. It won't get garbage-collected the way most variables
613 going out of scope do, because the \fIbegun()\fR function cares about it,
614 but no one else can get it. It is not called \f(CW$Pax::started\fR because
615 its scope is unrelated to the package. It's scoped to the file. You
616 could conceivably have several packages in that same file all
617 accessing the same private variable, but another file with the same
618 package couldn't get to it.
620 See \*(L"Persistent Private Variables\*(R" in perlsub for details.
621 .Sh "What's the difference between dynamic and lexical (static) scoping? Between \fIlocal()\fP and \fImy()\fP?"
622 .IX Subsection "What's the difference between dynamic and lexical (static) scoping? Between local() and my()?"
623 \&\f(CW\*(C`local($x)\*(C'\fR saves away the old value of the global variable \f(CW$x\fR
624 and assigns a new value for the duration of the subroutine \fIwhich is
625 visible in other functions called from that subroutine\fR. This is done
626 at run\-time, so is called dynamic scoping. \fIlocal()\fR always affects global
627 variables, also called package variables or dynamic variables.
629 \&\f(CW\*(C`my($x)\*(C'\fR creates a new variable that is only visible in the current
630 subroutine. This is done at compile\-time, so it is called lexical or
631 static scoping. \fImy()\fR always affects private variables, also called
632 lexical variables or (improperly) static(ly scoped) variables.
638 \& print "var has value $var\en";
644 \& local $var = 'local'; # new temporary value for the still-global
645 \& visible(); # variable called $var
651 \& my $var = 'private'; # new private variable, $var
652 \& visible(); # (invisible outside of sub scope)
661 \& visible(); # prints global
662 \& dynamic(); # prints local
663 \& lexical(); # prints global
666 Notice how at no point does the value \*(L"private\*(R" get printed. That's
667 because \f(CW$var\fR only has that value within the block of the \fIlexical()\fR
668 function, and it is hidden from called subroutine.
670 In summary, \fIlocal()\fR doesn't make what you think of as private, local
671 variables. It gives a global variable a temporary value. \fImy()\fR is
672 what you're looking for if you want private variables.
674 See \*(L"Private Variables via \fImy()\fR\*(R" in perlsub and
675 \&\*(L"Temporary Values via \fIlocal()\fR\*(R" in perlsub for excruciating details.
676 .Sh "How can I access a dynamic variable while a similarly named lexical is in scope?"
677 .IX Subsection "How can I access a dynamic variable while a similarly named lexical is in scope?"
678 If you know your package, you can just mention it explicitly, as in
679 \&\f(CW$Some_Pack::var\fR. Note that the notation \f(CW$::var\fR is \fBnot\fR the dynamic \f(CW$var\fR
680 in the current package, but rather the one in the \*(L"main\*(R" package, as
681 though you had written \f(CW$main::var\fR.
685 \& local $var = "global";
686 \& my $var = "lexical";
690 \& print "lexical is $var\en";
691 \& print "global is $main::var\en";
694 Alternatively you can use the compiler directive \fIour()\fR to bring a
695 dynamic variable into the current lexical scope.
698 \& require 5.006; # our() did not exist before 5.6
703 \& local $var = "global";
704 \& my $var = "lexical";
708 \& print "lexical is $var\en";
714 \& print "global is $var\en";
717 .Sh "What's the difference between deep and shallow binding?"
718 .IX Subsection "What's the difference between deep and shallow binding?"
719 In deep binding, lexical variables mentioned in anonymous subroutines
720 are the same ones that were in scope when the subroutine was created.
721 In shallow binding, they are whichever variables with the same names
722 happen to be in scope when the subroutine is called. Perl always uses
723 deep binding of lexical variables (i.e., those created with \fImy()\fR).
724 However, dynamic variables (aka global, local, or package variables)
725 are effectively shallowly bound. Consider this just one more reason
726 not to use them. See the answer to \*(L"What's a closure?\*(R".
727 .ie n .Sh "Why doesn't ""my($foo) = <\s-1FILE\s0>;"" work right?"
728 .el .Sh "Why doesn't ``my($foo) = <\s-1FILE\s0>;'' work right?"
729 .IX Subsection "Why doesn't ""my($foo) = <FILE>;"" work right?"
730 \&\f(CW\*(C`my()\*(C'\fR and \f(CW\*(C`local()\*(C'\fR give list context to the right hand side
731 of \f(CW\*(C`=\*(C'\fR. The <\s-1FH\s0> read operation, like so many of Perl's
732 functions and operators, can tell which context it was called in and
733 behaves appropriately. In general, the \fIscalar()\fR function can help.
734 This function does nothing to the data itself (contrary to popular myth)
735 but rather tells its argument to behave in whatever its scalar fashion is.
736 If that function doesn't have a defined scalar behavior, this of course
737 doesn't help you (such as with \fIsort()\fR).
739 To enforce scalar context in this particular case, however, you need
740 merely omit the parentheses:
743 \& local($foo) = <FILE>; # WRONG
744 \& local($foo) = scalar(<FILE>); # ok
745 \& local $foo = <FILE>; # right
748 You should probably be using lexical variables anyway, although the
749 issue is the same here:
752 \& my($foo) = <FILE>; # WRONG
753 \& my $foo = <FILE>; # right
755 .Sh "How do I redefine a builtin function, operator, or method?"
756 .IX Subsection "How do I redefine a builtin function, operator, or method?"
757 Why do you want to do that? :\-)
759 If you want to override a predefined function, such as \fIopen()\fR,
760 then you'll have to import the new definition from a different
761 module. See \*(L"Overriding Built-in Functions\*(R" in perlsub. There's
762 also an example in \*(L"Class::Template\*(R" in perltoot.
764 If you want to overload a Perl operator, such as \f(CW\*(C`+\*(C'\fR or \f(CW\*(C`**\*(C'\fR,
765 then you'll want to use the \f(CW\*(C`use overload\*(C'\fR pragma, documented
768 If you're talking about obscuring method calls in parent classes,
769 see \*(L"Overridden Methods\*(R" in perltoot.
770 .Sh "What's the difference between calling a function as &foo and \fIfoo()\fP?"
771 .IX Subsection "What's the difference between calling a function as &foo and foo()?"
772 When you call a function as \f(CW&foo\fR, you allow that function access to
773 your current \f(CW@_\fR values, and you bypass prototypes.
774 The function doesn't get an empty \f(CW@_\fR\-\-it gets yours! While not
775 strictly speaking a bug (it's documented that way in perlsub), it
776 would be hard to consider this a feature in most cases.
778 When you call your function as \f(CW\*(C`&foo()\*(C'\fR, then you \fIdo\fR get a new \f(CW@_\fR,
779 but prototyping is still circumvented.
781 Normally, you want to call a function using \f(CW\*(C`foo()\*(C'\fR. You may only
782 omit the parentheses if the function is already known to the compiler
783 because it already saw the definition (\f(CW\*(C`use\*(C'\fR but not \f(CW\*(C`require\*(C'\fR),
784 or via a forward reference or \f(CW\*(C`use subs\*(C'\fR declaration. Even in this
785 case, you get a clean \f(CW@_\fR without any of the old values leaking through
786 where they don't belong.
787 .Sh "How do I create a switch or case statement?"
788 .IX Subsection "How do I create a switch or case statement?"
789 This is explained in more depth in the perlsyn. Briefly, there's
790 no official case statement, because of the variety of tests possible
791 in Perl (numeric comparison, string comparison, glob comparison,
792 regex matching, overloaded comparisons, ...).
793 Larry couldn't decide how best to do this, so he left it out, even
794 though it's been on the wish list since perl1.
796 Starting from Perl 5.8 to get switch and case one can use the
797 Switch extension and say:
803 after which one has switch and case. It is not as fast as it could be
804 because it's not really part of the language (it's done using source
805 filters) but it is available, and it's very flexible.
807 But if one wants to use pure Perl, the general answer is to write a
811 \& for ($variable_to_test) {
812 \& if (/pat1/) { } # do something
813 \& elsif (/pat2/) { } # do something else
814 \& elsif (/pat3/) { } # do something else
815 \& else { } # default
819 Here's a simple example of a switch based on pattern matching, this
820 time lined up in a way to make it look more like a switch statement.
821 We'll do a multiway conditional based on the type of reference stored
822 in \f(CW$whatchamacallit:\fR
825 \& SWITCH: for (ref $whatchamacallit) {
829 \& /^$/ && die "not a reference";
834 \& print_scalar($$ref);
841 \& print_array(@$ref);
848 \& print_hash(%$ref);
855 \& warn "can't print function ref";
865 \& warn "User defined type skipped";
872 See \f(CW\*(C`perlsyn/"Basic BLOCKs and Switch Statements"\*(C'\fR for many other
873 examples in this style.
875 Sometimes you should change the positions of the constant and the variable.
876 For example, let's say you wanted to test which of many answers you were
877 given, but in a case-insensitive way that also allows abbreviations.
878 You can use the following technique if the strings all start with
879 different characters or if you want to arrange the matches so that
880 one takes precedence over another, as \f(CW"SEND"\fR has precedence over
881 \&\f(CW"STOP"\fR here:
884 \& chomp($answer = <>);
885 \& if ("SEND" =~ /^\eQ$answer/i) { print "Action is send\en" }
886 \& elsif ("STOP" =~ /^\eQ$answer/i) { print "Action is stop\en" }
887 \& elsif ("ABORT" =~ /^\eQ$answer/i) { print "Action is abort\en" }
888 \& elsif ("LIST" =~ /^\eQ$answer/i) { print "Action is list\en" }
889 \& elsif ("EDIT" =~ /^\eQ$answer/i) { print "Action is edit\en" }
892 A totally different approach is to create a hash of function references.
896 \& "happy" => \e&joy,
897 \& "sad", => \e&sullen,
898 \& "done" => sub { die "See ya!" },
899 \& "mad" => \e&angry,
904 \& print "How are you? ";
905 \& chomp($string = <STDIN>);
906 \& if ($commands{$string}) {
907 \& $commands{$string}->();
909 \& print "No such command: $string\en";
912 .Sh "How can I catch accesses to undefined variables, functions, or methods?"
913 .IX Subsection "How can I catch accesses to undefined variables, functions, or methods?"
914 The \s-1AUTOLOAD\s0 method, discussed in \*(L"Autoloading\*(R" in perlsub and
915 \&\*(L"\s-1AUTOLOAD:\s0 Proxy Methods\*(R" in perltoot, lets you capture calls to
916 undefined functions and methods.
918 When it comes to undefined variables that would trigger a warning
919 under \f(CW\*(C`use warnings\*(C'\fR, you can promote the warning to an error.
922 \& use warnings FATAL => qw(uninitialized);
924 .Sh "Why can't a method included in this same file be found?"
925 .IX Subsection "Why can't a method included in this same file be found?"
926 Some possible reasons: your inheritance is getting confused, you've
927 misspelled the method name, or the object is of the wrong type. Check
928 out perltoot for details about any of the above cases. You may
929 also use \f(CW\*(C`print ref($object)\*(C'\fR to find out the class \f(CW$object\fR was
932 Another possible reason for problems is because you've used the
933 indirect object syntax (eg, \f(CW\*(C`find Guru "Samy"\*(C'\fR) on a class name
934 before Perl has seen that such a package exists. It's wisest to make
935 sure your packages are all defined before you start using them, which
936 will be taken care of if you use the \f(CW\*(C`use\*(C'\fR statement instead of
937 \&\f(CW\*(C`require\*(C'\fR. If not, make sure to use arrow notation (eg.,
938 \&\f(CW\*(C`Guru\->find("Samy")\*(C'\fR) instead. Object notation is explained in
941 Make sure to read about creating modules in perlmod and
942 the perils of indirect objects in \*(L"Method Invocation\*(R" in perlobj.
943 .Sh "How can I find out my current package?"
944 .IX Subsection "How can I find out my current package?"
945 If you're just a random program, you can do this to find
946 out what the currently compiled package is:
949 \& my $packname = __PACKAGE__;
952 But, if you're a method and you want to print an error message
953 that includes the kind of object you were called on (which is
954 not necessarily the same as the one in which you were compiled):
959 \& my $class = ref($self) || $self;
960 \& warn "called me from a $class object";
963 .Sh "How can I comment out a large block of perl code?"
964 .IX Subsection "How can I comment out a large block of perl code?"
965 You can use embedded \s-1POD\s0 to discard it. Enclose the blocks you want
966 to comment out in \s-1POD\s0 markers, for example \f(CW\*(C`=for nobody\*(C'\fR and \f(CW\*(C`=cut\*(C'\fR
967 (which marks ends of \s-1POD\s0 blocks).
982 \& here will be ignored
991 \& # program continues
994 The pod directives cannot go just anywhere. You must put a
995 pod directive where the parser is expecting a new statement,
996 not just in the middle of an expression or some other
997 arbitrary grammar production.
999 See perlpod for more details.
1000 .Sh "How do I clear a package?"
1001 .IX Subsection "How do I clear a package?"
1002 Use this code, provided by Mark-Jason Dominus:
1005 \& sub scrub_package {
1006 \& no strict 'refs';
1007 \& my $pack = shift;
1008 \& die "Shouldn't delete main package"
1009 \& if $pack eq "" || $pack eq "main";
1010 \& my $stash = *{$pack . '::'}{HASH};
1012 \& foreach $name (keys %$stash) {
1013 \& my $fullname = $pack . '::' . $name;
1014 \& # Get rid of everything with that name.
1015 \& undef $$fullname;
1016 \& undef @$fullname;
1017 \& undef %$fullname;
1018 \& undef &$fullname;
1019 \& undef *$fullname;
1024 Or, if you're using a recent release of Perl, you can
1025 just use the \fISymbol::delete_package()\fR function instead.
1026 .Sh "How can I use a variable as a variable name?"
1027 .IX Subsection "How can I use a variable as a variable name?"
1028 Beginners often think they want to have a variable contain the name
1033 \& $varname = "fred";
1034 \& ++$$varname; # $fred now 24
1037 This works \fIsometimes\fR, but it is a very bad idea for two reasons.
1039 The first reason is that this technique \fIonly works on global
1040 variables\fR. That means that if \f(CW$fred\fR is a lexical variable created
1041 with \fImy()\fR in the above example, the code wouldn't work at all: you'd
1042 accidentally access the global and skip right over the private lexical
1043 altogether. Global variables are bad because they can easily collide
1044 accidentally and in general make for non-scalable and confusing code.
1046 Symbolic references are forbidden under the \f(CW\*(C`use strict\*(C'\fR pragma.
1047 They are not true references and consequently are not reference counted
1048 or garbage collected.
1050 The other reason why using a variable to hold the name of another
1051 variable is a bad idea is that the question often stems from a lack of
1052 understanding of Perl data structures, particularly hashes. By using
1053 symbolic references, you are just using the package's symbol-table hash
1054 (like \f(CW%main::\fR) instead of a user-defined hash. The solution is to
1055 use your own hash or a real reference instead.
1058 \& $USER_VARS{"fred"} = 23;
1059 \& $varname = "fred";
1060 \& $USER_VARS{$varname}++; # not $$varname++
1063 There we're using the \f(CW%USER_VARS\fR hash instead of symbolic references.
1064 Sometimes this comes up in reading strings from the user with variable
1065 references and wanting to expand them to the values of your perl
1066 program's variables. This is also a bad idea because it conflates the
1067 program-addressable namespace and the user-addressable one. Instead of
1068 reading a string and expanding it to the actual contents of your program's
1072 \& $str = 'this has a $fred and $barney in it';
1073 \& $str =~ s/(\e$\ew+)/$1/eeg; # need double eval
1076 it would be better to keep a hash around like \f(CW%USER_VARS\fR and have
1077 variable references actually refer to entries in that hash:
1080 \& $str =~ s/\e$(\ew+)/$USER_VARS{$1}/g; # no /e here at all
1083 That's faster, cleaner, and safer than the previous approach. Of course,
1084 you don't need to use a dollar sign. You could use your own scheme to
1085 make it less confusing, like bracketed percent symbols, etc.
1088 \& $str = 'this has a %fred% and %barney% in it';
1089 \& $str =~ s/%(\ew+)%/$USER_VARS{$1}/g; # no /e here at all
1092 Another reason that folks sometimes think they want a variable to
1093 contain the name of a variable is because they don't know how to build
1094 proper data structures using hashes. For example, let's say they
1095 wanted two hashes in their program: \f(CW%fred\fR and \f(CW%barney\fR, and that they
1096 wanted to use another scalar variable to refer to those by name.
1100 \& $$name{WIFE} = "wilma"; # set %fred
1104 \& $name = "barney";
1105 \& $$name{WIFE} = "betty"; # set %barney
1108 This is still a symbolic reference, and is still saddled with the
1109 problems enumerated above. It would be far better to write:
1112 \& $folks{"fred"}{WIFE} = "wilma";
1113 \& $folks{"barney"}{WIFE} = "betty";
1116 And just use a multilevel hash to start with.
1118 The only times that you absolutely \fImust\fR use symbolic references are
1119 when you really must refer to the symbol table. This may be because it's
1120 something that can't take a real reference to, such as a format name.
1121 Doing so may also be important for method calls, since these always go
1122 through the symbol table for resolution.
1124 In those cases, you would turn off \f(CW\*(C`strict 'refs'\*(C'\fR temporarily so you
1125 can play around with the symbol table. For example:
1128 \& @colors = qw(red blue green yellow orange purple violet);
1129 \& for my $name (@colors) {
1130 \& no strict 'refs'; # renege for the block
1131 \& *$name = sub { "<FONT COLOR='$name'>@_</FONT>" };
1135 All those functions (\fIred()\fR, \fIblue()\fR, \fIgreen()\fR, etc.) appear to be separate,
1136 but the real code in the closure actually was compiled only once.
1138 So, sometimes you might want to use symbolic references to directly
1139 manipulate the symbol table. This doesn't matter for formats, handles, and
1140 subroutines, because they are always global\*(--you can't use \fImy()\fR on them.
1141 For scalars, arrays, and hashes, though\*(--and usually for subroutines\*(--
1142 you probably only want to use hard references.
1143 .ie n .Sh "What does ""bad interpreter"" mean?"
1144 .el .Sh "What does ``bad interpreter'' mean?"
1145 .IX Subsection "What does bad interpreter mean?"
1146 The \*(L"bad interpreter\*(R" message comes from the shell, not perl. The
1147 actual message may vary depending on your platform, shell, and locale
1150 If you see \*(L"bad interpreter \- no such file or directory\*(R", the first
1151 line in your perl script (the \*(L"shebang\*(R" line) does not contain the
1152 right path to perl (or any other program capable of running scripts).
1153 Sometimes this happens when you move the script from one machine to
1154 another and each machine has a different path to perl\-\-\-/usr/bin/perl
1155 versus /usr/local/bin/perl for instance.
1157 If you see \*(L"bad interpreter: Permission denied\*(R", you need to make your
1160 In either case, you should still be able to run the scripts with perl
1167 If you get a message like \*(L"perl: command not found\*(R", perl is not in
1168 your \s-1PATH\s0, which might also mean that the location of perl is not
1169 where you expect it so you need to adjust your shebang line.
1170 .SH "AUTHOR AND COPYRIGHT"
1171 .IX Header "AUTHOR AND COPYRIGHT"
1172 Copyright (c) 1997\-2002 Tom Christiansen and Nathan Torkington.
1173 All rights reserved.
1175 This documentation is free; you can redistribute it and/or modify it
1176 under the same terms as Perl itself.
1178 Irrespective of its distribution, all code examples in this file
1179 are hereby placed into the public domain. You are permitted and
1180 encouraged to use this code in your own programs for fun
1181 or for profit as you see fit. A simple comment in the code giving
1182 credit would be courteous but is not required.