Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

846 lines
28 KiB

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