pods for subroutine argument autovivication
[p5sagit/p5-mst-13.2.git] / pod / perlfaq7.pod
CommitLineData
68dc0745 1=head1 NAME
2
3perlfaq7 - Perl Language Issues ($Revision: 1.15 $)
4
5=head1 DESCRIPTION
6
7This section deals with general Perl language issues that don't
8clearly fit into any of the other sections.
9
10=head2 Can I get a BNF/yacc/RE for the Perl language?
11
12No, in the words of Chaim Frenkel: "Perl's grammar can not be reduced
13to BNF. The work of parsing perl is distributed between yacc, the
14lexer, smoke and mirrors."
15
16=head2 What are all these $@%* punctuation signs, and how do I know when to use them?
17
18They are type specifiers, as detailed in L<perldata>:
19
20 $ for scalar values (number, string or reference)
21 @ for arrays
22 % for hashes (associative arrays)
23 * for all types of that symbol name. In version 4 you used them like
24 pointers, but in modern perls you can just use references.
25
26While there are a few places where you don't actually need these type
27specifiers, you should always use them.
28
29A couple of others that you're likely to encounter that aren't
30really type specifiers are:
31
32 <> are used for inputting a record from a filehandle.
33 \ takes a reference to something.
34
35Note that E<lt>FILEE<gt> is I<neither> the type specifier for files
36nor the name of the handle. It is the C<E<lt>E<gt>> operator applied
37to the handle FILE. It reads one line (well, record - see
38L<perlvar/$/>) from the handle FILE in scalar context, or I<all> lines
39in list context. When performing open, close, or any other operation
40besides C<E<lt>E<gt>> on files, or even talking about the handle, do
41I<not> use the brackets. These are correct: C<eof(FH)>, C<seek(FH, 0,
422)> and "copying from STDIN to FILE".
43
44=head2 Do I always/never have to quote my strings or use semicolons and commas?
45
46Normally, a bareword doesn't need to be quoted, but in most cases
47probably should be (and must be under C<use strict>). But a hash key
48consisting of a simple word (that isn't the name of a defined
49subroutine) and the left-hand operand to the C<=E<gt>> operator both
50count as though they were quoted:
51
52 This is like this
53 ------------ ---------------
54 $foo{line} $foo{"line"}
55 bar => stuff "bar" => stuff
56
57The final semicolon in a block is optional, as is the final comma in a
58list. Good style (see L<perlstyle>) says to put them in except for
59one-liners:
60
61 if ($whoops) { exit 1 }
62 @nums = (1, 2, 3);
63
64 if ($whoops) {
65 exit 1;
66 }
67 @lines = (
68 "There Beren came from mountains cold",
69 "And lost he wandered under leaves",
70 );
71
72=head2 How do I skip some return values?
73
74One way is to treat the return values as a list and index into it:
75
76 $dir = (getpwnam($user))[7];
77
78Another way is to use undef as an element on the left-hand-side:
79
80 ($dev, $ino, undef, undef, $uid, $gid) = stat($file);
81
82=head2 How do I temporarily block warnings?
83
84The C<$^W> variable (documented in L<perlvar>) controls
85runtime warnings for a block:
86
87 {
88 local $^W = 0; # temporarily turn off warnings
89 $a = $b + $c; # I know these might be undef
90 }
91
92Note that like all the punctuation variables, you cannot currently
93use my() on C<$^W>, only local().
94
95A new C<use warnings> pragma is in the works to provide finer control
96over all this. The curious should check the perl5-porters mailing list
97archives for details.
98
99=head2 What's an extension?
100
101A way of calling compiled C code from Perl. Reading L<perlxstut>
102is a good place to learn more about extensions.
103
104=head2 Why do Perl operators have different precedence than C operators?
105
106Actually, they don't. All C operators that Perl copies have the same
107precedence in Perl as they do in C. The problem is with operators that C
108doesn't have, especially functions that give a list context to everything
109on their right, eg print, chmod, exec, and so on. Such functions are
110called "list operators" and appear as such in the precedence table in
111L<perlop>.
112
113A common mistake is to write:
114
115 unlink $file || die "snafu";
116
117This gets interpreted as:
118
119 unlink ($file || die "snafu");
120
121To avoid this problem, either put in extra parentheses or use the
122super low precedence C<or> operator:
123
124 (unlink $file) || die "snafu";
125 unlink $file or die "snafu";
126
127The "English" operators (C<and>, C<or>, C<xor>, and C<not>)
128deliberately have precedence lower than that of list operators for
129just such situations as the one above.
130
131Another operator with surprising precedence is exponentiation. It
132binds more tightly even than unary minus, making C<-2**2> product a
133negative not a positive four. It is also right-associating, meaning
134that C<2**3**2> is two raised to the ninth power, not eight squared.
135
136=head2 How do I declare/create a structure?
137
138In general, you don't "declare" a structure. Just use a (probably
139anonymous) hash reference. See L<perlref> and L<perldsc> for details.
140Here's an example:
141
142 $person = {}; # new anonymous hash
143 $person->{AGE} = 24; # set field AGE to 24
144 $person->{NAME} = "Nat"; # set field NAME to "Nat"
145
146If you're looking for something a bit more rigorous, try L<perltoot>.
147
148=head2 How do I create a module?
149
150A module is a package that lives in a file of the same name. For
151example, the Hello::There module would live in Hello/There.pm. For
152details, read L<perlmod>. You'll also find L<Exporter> helpful. If
153you're writing a C or mixed-language module with both C and Perl, then
154you should study L<perlxstut>.
155
156Here's a convenient template you might wish you use when starting your
157own module. Make sure to change the names appropriately.
158
159 package Some::Module; # assumes Some/Module.pm
160
161 use strict;
162
163 BEGIN {
164 use Exporter ();
165 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
166
167 ## set the version for version checking; uncomment to use
168 ## $VERSION = 1.00;
169
170 # if using RCS/CVS, this next line may be preferred,
171 # but beware two-digit versions.
172 $VERSION = do{my@r=q$Revision: 1.15 $=~/\d+/g;sprintf '%d.'.'%02d'x$#r,@r};
173
174 @ISA = qw(Exporter);
175 @EXPORT = qw(&func1 &func2 &func3);
176 %EXPORT_TAGS = ( ); # eg: TAG => [ qw!name1 name2! ],
177
178 # your exported package globals go here,
179 # as well as any optionally exported functions
180 @EXPORT_OK = qw($Var1 %Hashit);
181 }
182 use vars @EXPORT_OK;
183
184 # non-exported package globals go here
185 use vars qw( @more $stuff );
186
187 # initialize package globals, first exported ones
188 $Var1 = '';
189 %Hashit = ();
190
191 # then the others (which are still accessible as $Some::Module::stuff)
192 $stuff = '';
193 @more = ();
194
195 # all file-scoped lexicals must be created before
196 # the functions below that use them.
197
198 # file-private lexicals go here
199 my $priv_var = '';
200 my %secret_hash = ();
201
202 # here's a file-private function as a closure,
203 # callable as &$priv_func; it cannot be prototyped.
204 my $priv_func = sub {
205 # stuff goes here.
206 };
207
208 # make all your functions, whether exported or not;
209 # remember to put something interesting in the {} stubs
210 sub func1 {} # no prototype
211 sub func2() {} # proto'd void
212 sub func3($$) {} # proto'd to 2 scalars
213
214 # this one isn't exported, but could be called!
215 sub func4(\%) {} # proto'd to 1 hash ref
216
217 END { } # module clean-up code here (global destructor)
218
219 1; # modules must return true
220
221=head2 How do I create a class?
222
223See L<perltoot> for an introduction to classes and objects, as well as
224L<perlobj> and L<perlbot>.
225
226=head2 How can I tell if a variable is tainted?
227
228See L<perlsec/"Laundering and Detecting Tainted Data">. Here's an
229example (which doesn't use any system calls, because the kill()
230is given no processes to signal):
231
232 sub is_tainted {
233 return ! eval { join('',@_), kill 0; 1; };
234 }
235
236This is not C<-w> clean, however. There is no C<-w> clean way to
237detect taintedness - take this as a hint that you should untaint
238all possibly-tainted data.
239
240=head2 What's a closure?
241
242Closures are documented in L<perlref>.
243
244I<Closure> is a computer science term with a precise but
245hard-to-explain meaning. Closures are implemented in Perl as anonymous
246subroutines with lasting references to lexical variables outside their
247own scopes. These lexicals magically refer to the variables that were
248around when the subroutine was defined (deep binding).
249
250Closures make sense in any programming language where you can have the
251return value of a function be itself a function, as you can in Perl.
252Note that some languages provide anonymous functions but are not
253capable of providing proper closures; the Python language, for
254example. For more information on closures, check out any textbook on
255functional programming. Scheme is a language that not only supports
256but encourages closures.
257
258Here's a classic function-generating function:
259
260 sub add_function_generator {
261 return sub { shift + shift };
262 }
263
264 $add_sub = add_function_generator();
265 $sum = &$add_sub(4,5); # $sum is 9 now.
266
267The closure works as a I<function template> with some customization
268slots left out to be filled later. The anonymous subroutine returned
269by add_function_generator() isn't technically a closure because it
270refers to no lexicals outside its own scope.
271
272Contrast this with the following make_adder() function, in which the
273returned anonymous function contains a reference to a lexical variable
274outside the scope of that function itself. Such a reference requires
275that Perl return a proper closure, thus locking in for all time the
276value that the lexical had when the function was created.
277
278 sub make_adder {
279 my $addpiece = shift;
280 return sub { shift + $addpiece };
281 }
282
283 $f1 = make_adder(20);
284 $f2 = make_adder(555);
285
286Now C<&$f1($n)> is always 20 plus whatever $n you pass in, whereas
287C<&$f2($n)> is always 555 plus whatever $n you pass in. The $addpiece
288in the closure sticks around.
289
290Closures are often used for less esoteric purposes. For example, when
291you want to pass in a bit of code into a function:
292
293 my $line;
294 timeout( 30, sub { $line = <STDIN> } );
295
296If the code to execute had been passed in as a string, C<'$line =
297E<lt>STDINE<gt>'>, there would have been no way for the hypothetical
298timeout() function to access the lexical variable $line back in its
299caller's scope.
300
301=head2 How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regexp}?
302
303With the exception of regexps, you need to pass references to these
304objects. See L<perlsub/"Pass by Reference"> for this particular
305question, and L<perlref> for information on references.
306
307=over 4
308
309=item Passing Variables and Functions
310
311Regular variables and functions are quite easy: just pass in a
312reference to an existing or anonymous variable or function:
313
314 func( \$some_scalar );
315
316 func( \$some_array );
317 func( [ 1 .. 10 ] );
318
319 func( \%some_hash );
320 func( { this => 10, that => 20 } );
321
322 func( \&some_func );
323 func( sub { $_[0] ** $_[1] } );
324
325=item Passing Filehandles
326
327To create filehandles you can pass to subroutines, you can use C<*FH>
328or C<\*FH> notation ("typeglobs" - see L<perldata> for more information),
329or create filehandles dynamically using the old FileHandle or the new
330IO::File modules, both part of the standard Perl distribution.
331
332 use Fcntl;
333 use IO::File;
334 my $fh = new IO::File $filename, O_WRONLY|O_APPEND;
335 or die "Can't append to $filename: $!";
336 func($fh);
337
338=item Passing Regexps
339
340To pass regexps around, you'll need to either use one of the highly
341experimental regular expression modules from CPAN (Nick Ing-Simmons's
342Regexp or Ilya Zakharevich's Devel::Regexp), pass around strings
343and use an exception-trapping eval, or else be be very, very clever.
344Here's an example of how to pass in a string to be regexp compared:
345
346 sub compare($$) {
347 my ($val1, $regexp) = @_;
348 my $retval = eval { $val =~ /$regexp/ };
349 die if $@;
350 return $retval;
351 }
352
353 $match = compare("old McDonald", q/d.*D/);
354
355Make sure you never say something like this:
356
357 return eval "\$val =~ /$regexp/"; # WRONG
358
359or someone can sneak shell escapes into the regexp due to the double
360interpolation of the eval and the double-quoted string. For example:
361
362 $pattern_of_evil = 'danger ${ system("rm -rf * &") } danger';
363
364 eval "\$string =~ /$pattern_of_evil/";
365
366Those preferring to be very, very clever might see the O'Reilly book,
367I<Mastering Regular Expressions>, by Jeffrey Friedl. Page 273's
368Build_MatchMany_Function() is particularly interesting. A complete
369citation of this book is given in L<perlfaq2>.
370
371=item Passing Methods
372
373To pass an object method into a subroutine, you can do this:
374
375 call_a_lot(10, $some_obj, "methname")
376 sub call_a_lot {
377 my ($count, $widget, $trick) = @_;
378 for (my $i = 0; $i < $count; $i++) {
379 $widget->$trick();
380 }
381 }
382
383or you can use a closure to bundle up the object and its method call
384and arguments:
385
386 my $whatnot = sub { $some_obj->obfuscate(@args) };
387 func($whatnot);
388 sub func {
389 my $code = shift;
390 &$code();
391 }
392
393You could also investigate the can() method in the UNIVERSAL class
394(part of the standard perl distribution).
395
396=back
397
398=head2 How do I create a static variable?
399
400As with most things in Perl, TMTOWTDI. What is a "static variable" in
401other languages could be either a function-private variable (visible
402only within a single function, retaining its value between calls to
403that function), or a file-private variable (visible only to functions
404within the file it was declared in) in Perl.
405
406Here's code to implement a function-private variable:
407
408 BEGIN {
409 my $counter = 42;
410 sub prev_counter { return --$counter }
411 sub next_counter { return $counter++ }
412 }
413
414Now prev_counter() and next_counter() share a private variable $counter
415that was initialized at compile time.
416
417To declare a file-private variable, you'll still use a my(), putting
418it at the outer scope level at the top of the file. Assume this is in
419file Pax.pm:
420
421 package Pax;
422 my $started = scalar(localtime(time()));
423
424 sub begun { return $started }
425
426When C<use Pax> or C<require Pax> loads this module, the variable will
427be initialized. It won't get garbage-collected the way most variables
428going out of scope do, because the begun() function cares about it,
429but no one else can get it. It is not called $Pax::started because
430its scope is unrelated to the package. It's scoped to the file. You
431could conceivably have several packages in that same file all
432accessing the same private variable, but another file with the same
433package couldn't get to it.
434
435=head2 What's the difference between dynamic and lexical (static) scoping? Between local() and my()?
436
437C<local($x)> saves away the old value of the global variable C<$x>,
438and assigns a new value for the duration of the subroutine, I<which is
439visible in other functions called from that subroutine>. This is done
440at run-time, so is called dynamic scoping. local() always affects global
441variables, also called package variables or dynamic variables.
442
443C<my($x)> creates a new variable that is only visible in the current
444subroutine. This is done at compile-time, so is called lexical or
445static scoping. my() always affects private variables, also called
446lexical variables or (improperly) static(ly scoped) variables.
447
448For instance:
449
450 sub visible {
451 print "var has value $var\n";
452 }
453
454 sub dynamic {
455 local $var = 'local'; # new temporary value for the still-global
456 visible(); # variable called $var
457 }
458
459 sub lexical {
460 my $var = 'private'; # new private variable, $var
461 visible(); # (invisible outside of sub scope)
462 }
463
464 $var = 'global';
465
466 visible(); # prints global
467 dynamic(); # prints local
468 lexical(); # prints global
469
470Notice how at no point does the value "private" get printed. That's
471because $var only has that value within the block of the lexical()
472function, and it is hidden from called subroutine.
473
474In summary, local() doesn't make what you think of as private, local
475variables. It gives a global variable a temporary value. my() is
476what you're looking for if you want private variables.
477
478See also L<perlsub>, which explains this all in more detail.
479
480=head2 How can I access a dynamic variable while a similarly named lexical is in scope?
481
482You can do this via symbolic references, provided you haven't set
483C<use strict "refs">. So instead of $var, use C<${'var'}>.
484
485 local $var = "global";
486 my $var = "lexical";
487
488 print "lexical is $var\n";
489
490 no strict 'refs';
491 print "global is ${'var'}\n";
492
493If you know your package, you can just mention it explicitly, as in
494$Some_Pack::var. Note that the notation $::var is I<not> the dynamic
495$var in the current package, but rather the one in the C<main>
496package, as though you had written $main::var. Specifying the package
497directly makes you hard-code its name, but it executes faster and
498avoids running afoul of C<use strict "refs">.
499
500=head2 What's the difference between deep and shallow binding?
501
502In deep binding, lexical variables mentioned in anonymous subroutines
503are the same ones that were in scope when the subroutine was created.
504In shallow binding, they are whichever variables with the same names
505happen to be in scope when the subroutine is called. Perl always uses
506deep binding of lexical variables (i.e., those created with my()).
507However, dynamic variables (aka global, local, or package variables)
508are effectively shallowly bound. Consider this just one more reason
509not to use them. See the answer to L<"What's a closure?">.
510
511=head2 Why doesn't "local($foo) = <FILE>;" work right?
512
513C<local()> gives list context to the right hand side of C<=>. The
514E<lt>FHE<gt> read operation, like so many of Perl's functions and
515operators, can tell which context it was called in and behaves
516appropriately. In general, the scalar() function can help. This
517function does nothing to the data itself (contrary to popular myth)
518but rather tells its argument to behave in whatever its scalar fashion
519is. If that function doesn't have a defined scalar behavior, this of
520course doesn't help you (such as with sort()).
521
522To enforce scalar context in this particular case, however, you need
523merely omit the parentheses:
524
525 local($foo) = <FILE>; # WRONG
526 local($foo) = scalar(<FILE>); # ok
527 local $foo = <FILE>; # right
528
529You should probably be using lexical variables anyway, although the
530issue is the same here:
531
532 my($foo) = <FILE>; # WRONG
533 my $foo = <FILE>; # right
534
535=head2 How do I redefine a built-in function, operator, or method?
536
537Why do you want to do that? :-)
538
539If you want to override a predefined function, such as open(),
540then you'll have to import the new definition from a different
541module. See L<perlsub/"Overriding Builtin Functions">. There's
542also an example in L<perltoot/"Class::Template">.
543
544If you want to overload a Perl operator, such as C<+> or C<**>,
545then you'll want to use the C<use overload> pragma, documented
546in L<overload>.
547
548If you're talking about obscuring method calls in parent classes,
549see L<perltoot/"Overridden Methods">.
550
551=head2 What's the difference between calling a function as &foo and foo()?
552
553When you call a function as C<&foo>, you allow that function access to
554your current @_ values, and you by-pass prototypes. That means that
555the function doesn't get an empty @_, it gets yours! While not
556strictly speaking a bug (it's documented that way in L<perlsub>), it
557would be hard to consider this a feature in most cases.
558
559When you call your function as C<&foo()>, then you do get a new @_,
560but prototyping is still circumvented.
561
562Normally, you want to call a function using C<foo()>. You may only
563omit the parentheses if the function is already known to the compiler
564because it already saw the definition (C<use> but not C<require>),
565or via a forward reference or C<use subs> declaration. Even in this
566case, you get a clean @_ without any of the old values leaking through
567where they don't belong.
568
569=head2 How do I create a switch or case statement?
570
571This is explained in more depth in the L<perlsyn>. Briefly, there's
572no official case statement, because of the variety of tests possible
573in Perl (numeric comparison, string comparison, glob comparison,
574regexp matching, overloaded comparisons, ...). Larry couldn't decide
575how best to do this, so he left it out, even though it's been on the
576wish list since perl1.
577
578Here's a simple example of a switch based on pattern matching. We'll
579do a multi-way conditional based on the type of reference stored in
580$whatchamacallit:
581
582 SWITCH:
583 for (ref $whatchamacallit) {
584
585 /^$/ && die "not a reference";
586
587 /SCALAR/ && do {
588 print_scalar($$ref);
589 last SWITCH;
590 };
591
592 /ARRAY/ && do {
593 print_array(@$ref);
594 last SWITCH;
595 };
596
597 /HASH/ && do {
598 print_hash(%$ref);
599 last SWITCH;
600 };
601
602 /CODE/ && do {
603 warn "can't print function ref";
604 last SWITCH;
605 };
606
607 # DEFAULT
608
609 warn "User defined type skipped";
610
611 }
612
613=head2 How can I catch accesses to undefined variables/functions/methods?
614
615The AUTOLOAD method, discussed in L<perlsub/"Autoloading"> and
616L<perltoot/"AUTOLOAD: Proxy Methods">, lets you capture calls to
617undefined functions and methods.
618
619When it comes to undefined variables that would trigger a warning
620under C<-w>, you can use a handler to trap the pseudo-signal
621C<__WARN__> like this:
622
623 $SIG{__WARN__} = sub {
624
625 for ( $_[0] ) {
626
627 /Use of uninitialized value/ && do {
628 # promote warning to a fatal
629 die $_;
630 };
631
632 # other warning cases to catch could go here;
633
634 warn $_;
635 }
636
637 };
638
639=head2 Why can't a method included in this same file be found?
640
641Some possible reasons: your inheritance is getting confused, you've
642misspelled the method name, or the object is of the wrong type. Check
643out L<perltoot> for details on these. You may also use C<print
644ref($object)> to find out the class C<$object> was blessed into.
645
646Another possible reason for problems is because you've used the
647indirect object syntax (eg, C<find Guru "Samy">) on a class name
648before Perl has seen that such a package exists. It's wisest to make
649sure your packages are all defined before you start using them, which
650will be taken care of if you use the C<use> statement instead of
651C<require>. If not, make sure to use arrow notation (eg,
652C<Guru->find("Samy")>) instead. Object notation is explained in
653L<perlobj>.
654
655=head2 How can I find out my current package?
656
657If you're just a random program, you can do this to find
658out what the currently compiled package is:
659
660 my $packname = ref bless [];
661
662But if you're a method and you want to print an error message
663that includes the kind of object you were called on (which is
664not necessarily the same as the one in which you were compiled):
665
666 sub amethod {
667 my $self = shift;
668 my $class = ref($self) || $self;
669 warn "called me from a $class object";
670 }
671
672=head1 AUTHOR AND COPYRIGHT
673
674Copyright (c) 1997 Tom Christiansen and Nathan Torkington.
675All rights reserved. See L<perlfaq> for distribution information.