Leaked source code of windows server 2003
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.

974 lines
34 KiB

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