home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / perlref.zip / perlref.inf (.txt) < prev    next >
OS/2 Help File  |  1996-08-07  |  685KB  |  27,154 lines

  1.  
  2. ΓòÉΓòÉΓòÉ 1. About Perl 5.02 Information Retrieval ΓòÉΓòÉΓòÉ
  3.  
  4. Purpose 
  5.  
  6. The Perl Language and Interpreter provide an easy to use and concise method for 
  7. processing text files.  The utility of the OS/2 version was hampered by the 
  8. need to refer either to the manual or the man pages while coding. This 
  9. IPF-based information file will be preferable for OS/2 Perl developers.  The 
  10. important tables have been fully indexed and the search and print features of 
  11. IPF are available. 
  12.  
  13. Acknowledgments 
  14.  
  15. Perl 5.02B manual pages and textual information, all copyrights reserved by 
  16. Larry Wall <lwall@sems.com> and the GNU Project. 
  17.  
  18. OS/2 Warp version of the Perl 5.02B manual pages, prepared by Tully M. Steward 
  19. <71231.1173@compuserve.com>. 
  20.  
  21. Produced using Perl 5.02B, the Rimstar Programmers Editor, IBM IPFC compiler 
  22. and IBM Hyperwise 2.01. 
  23.  
  24. Caveats and deviations 
  25.  
  26.      The perltoc, and perlovl pods are not included.  The perltoc pod has been 
  27.       replaced by the IPF table-of-contents and index. 
  28.  
  29.      The perlfunc, perlvar, perlguts, and perldiag pods have been indexed by 
  30.       sub-topic, making them easier to access. 
  31.  
  32.      Not all links have been indexed, only the module level links.  Use the 
  33.       IPF search feature to locate other keywords.  Other links are 
  34.       unimplemented and will appear with their original control codes. 
  35.  
  36.      If you find any problems, or would like to suggest improvements send 
  37.       email to <71231.1173@compuserve.com> 
  38.  
  39.  Note:  In keeping with the spirit of GNU, the Perl Script used to prepare this 
  40.  file is included in an appendix at the end.  Be advised however, that I can't 
  41.  distribute all the tools needed to reproduce it, and therefore it's not a 
  42.  GNU-compliant module. 
  43.  
  44.  
  45. ΓòÉΓòÉΓòÉ 2. Version Information ΓòÉΓòÉΓòÉ
  46.  
  47. Version 1.0517, OS/2 Warp Perl Manual Page Information, to accompany Perl 
  48. 5.02B. 
  49.  
  50. Compiled: Wed Aug  7 10:15:21 1996 
  51.  
  52.  
  53. ΓòÉΓòÉΓòÉ 3. Section - perl ΓòÉΓòÉΓòÉ
  54.  
  55. NAME 
  56.  
  57. perl - Practical Extraction and Report Language 
  58.  
  59. SYNOPSIS 
  60.  
  61. perl [ -acdhnpPsSTuUvw ] [ -0[octal] ] [ -Dnumber/list] ] [ -Fstring ] [ 
  62. -i[extension] ] [ -Idir ] [ -loctal ] [ -xdir ] [ programfile | -e command ] [ 
  63. argument ... ] 
  64.  
  65. For ease of access, the Perl manual has been split up into a number of 
  66. sections: 
  67.  
  68.     perl        Perl overview (this section)
  69.     perltoc     Perl documentation table of contents
  70.     perldata    Perl data structures
  71.     perlsyn     Perl syntax
  72.     perlop      Perl operators and precedence
  73.     perlre      Perl regular expressions
  74.     perlrun     Perl execution and options
  75.     perlfunc    Perl builtin functions
  76.     perlvar     Perl predefined variables
  77.     perlsub     Perl subroutines
  78.     perlmod     Perl modules
  79.     perlref     Perl references
  80.     perldsc     Perl data structures intro
  81.     perllol     Perl data structures: lists of lists
  82.     perlobj     Perl objects
  83.     perltie     Perl objects hidden behind simple variables
  84.     perlbot     Perl OO tricks and examples
  85.     perldebug   Perl debugging
  86.     perldiag    Perl diagnostic messages
  87.     perlform    Perl formats
  88.     perlipc     Perl interprocess communication
  89.     perlsec     Perl security
  90.     perltrap    Perl traps for the unwary
  91.     perlstyle   Perl style guide
  92.     perlxs      Perl XS application programming interface
  93.     perlxstut   Perl XS tutorial
  94.     perlguts    Perl internal functions for those doing extensions
  95.     perlcall    Perl calling conventions from C
  96.     perlembed   Perl how to embed perl in your C or C++ app
  97.     perlpod     Perl plain old documentation
  98.     perlbook    Perl book information
  99.  
  100. (If you're intending to read these straight through for the first time, the 
  101. suggested order will tend to reduce the number of forward references.) 
  102.  
  103. Additional documentation for Perl modules is available in the /usr/local/man/ 
  104. directory.  Some of this is distributed standard with Perl, but you'll also 
  105. find third-party modules there.  You should be able to view this with your 
  106. man(1) program by including the proper directories in the appropriate start-up 
  107. files.  To find out where these are, type: 
  108.  
  109.     perl -le 'use Config; print "@Config{man1dir,man3dir}"'
  110.  
  111. If the directories were /usr/local/man/man1 and /usr/local/man/man3, you would 
  112. only need to add /usr/local/man to your MANPATH.  If they are different, you'll 
  113. have to add both stems. 
  114.  
  115. If that doesn't work for some reason, you can still use the supplied perldoc 
  116. script to view module information.  You might also look into getting a 
  117. replacement man program. 
  118.  
  119. If something strange has gone wrong with your program and you're not sure where 
  120. you should look for help, try the -w switch first.  It will often point out 
  121. exactly where the trouble is. 
  122.  
  123. DESCRIPTION 
  124.  
  125. Perl is an interpreted language optimized for scanning arbitrary text files, 
  126. extracting information from those text files, and printing reports based on 
  127. that information.  It's also a good language for many system management tasks. 
  128. The language is intended to be practical (easy to use, efficient, complete) 
  129. rather than beautiful (tiny, elegant, minimal).  It combines (in the author's 
  130. opinion, anyway) some of the best features of C, sed, awk, and sh, so people 
  131. familiar with those languages should have little difficulty with it. (Language 
  132. historians will also note some vestiges of csh, Pascal, and even BASIC-PLUS.) 
  133. Expression syntax corresponds quite closely to C expression syntax.  Unlike 
  134. most Unix utilities, Perl does not arbitrarily limit the size of your data--if 
  135. you've got the memory, Perl can slurp in your whole file as a single string. 
  136. Recursion is of unlimited depth.  And the hash tables used by associative 
  137. arrays grow as necessary to prevent degraded performance.  Perl uses 
  138. sophisticated pattern matching techniques to scan large amounts of data very 
  139. quickly.  Although optimized for scanning text, Perl can also deal with binary 
  140. data, and can make dbm files look like associative arrays.  Setuid Perl scripts 
  141. are safer than C programs through a dataflow tracing mechanism which prevents 
  142. many stupid security holes.  If you have a problem that would ordinarily use 
  143. sed or awk or sh, but it exceeds their capabilities or must run a little 
  144. faster, and you don't want to write the silly thing in C, then Perl may be for 
  145. you.  There are also translators to turn your sed and awk scripts into Perl 
  146. scripts. 
  147.  
  148. But wait, there's more... 
  149.  
  150. Perl version 5 is nearly a complete rewrite, and provides the following 
  151. additional benefits: 
  152.  
  153. * Many usability enhancements 
  154.  
  155. It is now possible to write much more readable Perl code (even within regular 
  156. expressions).  Formerly cryptic variable names can be replaced by mnemonic 
  157. identifiers.  Error messages are more informative, and the optional warnings 
  158. will catch many of the mistakes a novice might make. This cannot be stressed 
  159. enough.  Whenever you get mysterious behavior, try the -w switch!!!  Whenever 
  160. you don't get mysterious behavior, try using -w anyway. 
  161.  
  162. * Simplified grammar 
  163.  
  164. The new yacc grammar is one half the size of the old one.  Many of the 
  165. arbitrary grammar rules have been regularized.  The number of reserved words 
  166. has been cut by 2/3.  Despite this, nearly all old Perl scripts will continue 
  167. to work unchanged. 
  168.  
  169. * Lexical scoping 
  170.  
  171. Perl variables may now be declared within a lexical scope, like "auto" 
  172. variables in C.  Not only is this more efficient, but it contributes to better 
  173. privacy for "programming in the large". 
  174.  
  175. * Arbitrarily nested data structures 
  176.  
  177. Any scalar value, including any array element, may now contain a reference to 
  178. any other variable or subroutine.  You can easily create anonymous variables 
  179. and subroutines.  Perl manages your reference counts for you. 
  180.  
  181. * Modularity and reusability 
  182.  
  183. The Perl library is now defined in terms of modules which can be easily shared 
  184. among various packages.  A package may choose to import all or a portion of a 
  185. module's published interface.  Pragmas (that is, compiler directives) are 
  186. defined and used by the same mechanism. 
  187.  
  188. * Object-oriented programming 
  189.  
  190. A package can function as a class.  Dynamic multiple inheritance and virtual 
  191. methods are supported in a straightforward manner and with very little new 
  192. syntax.  Filehandles may now be treated as objects. 
  193.  
  194. * Embeddable and Extensible 
  195.  
  196. Perl may now be embedded easily in your C or C++ application, and can either 
  197. call or be called by your routines through a documented interface.  The XS 
  198. preprocessor is provided to make it easy to glue your C or C++ routines into 
  199. Perl.  Dynamic loading of modules is supported. 
  200.  
  201. * POSIX compliant 
  202.  
  203. A major new module is the POSIX module, which provides access to all available 
  204. POSIX routines and definitions, via object classes where appropriate. 
  205.  
  206. * Package constructors and destructors 
  207.  
  208. The new BEGIN and END blocks provide means to capture control as a package is 
  209. being compiled, and after the program exits.  As a degenerate case they work 
  210. just like awk's BEGIN and END when you use the -p or -n switches. 
  211.  
  212. * Multiple simultaneous DBM implementations 
  213.  
  214. A Perl program may now access DBM, NDBM, SDBM, GDBM, and Berkeley DB files from 
  215. the same script simultaneously.  In fact, the old dbmopen interface has been 
  216. generalized to allow any variable to be tied to an object class which defines 
  217. its access methods. 
  218.  
  219. * Subroutine definitions may now be autoloaded 
  220.  
  221. In fact, the AUTOLOAD mechanism also allows you to define any arbitrary 
  222. semantics for undefined subroutine calls.  It's not just for autoloading. 
  223.  
  224. * Regular expression enhancements 
  225.  
  226. You can now specify non-greedy quantifiers.  You can now do grouping without 
  227. creating a backreference.  You can now write regular expressions with embedded 
  228. whitespace and comments for readability.  A consistent extensibility mechanism 
  229. has been added that is upwardly compatible with all old regular expressions. 
  230.  
  231. Ok, that's definitely enough hype. 
  232.  
  233. ENVIRONMENT 
  234.  
  235. HOME 
  236.  
  237. Used if chdir has no argument. 
  238.  
  239. LOGDIR 
  240.  
  241. Used if chdir has no argument and HOME is not set. 
  242.  
  243. PATH 
  244.  
  245. Used in executing subprocesses, and in finding the script if -S is used. 
  246.  
  247. PERL5LIB 
  248.  
  249. A colon-separated list of directories in which to look for Perl library files 
  250. before looking in the standard library and the current directory.  If PERL5LIB 
  251. is not defined, PERLLIB is used.  When running taint checks (because the script 
  252. was running setuid or setgid, or the -T switch was used), neither variable is 
  253. used.  The script should instead say 
  254.  
  255.     use lib "/my/directory";
  256.  
  257. PERL5DB 
  258.  
  259. The command used to get the debugger code.  If unset, uses 
  260.  
  261.         BEGIN { require 'perl5db.pl' }
  262.  
  263. PERLLIB 
  264.  
  265. A colon-separated list of directories in which to look for Perl library files 
  266. before looking in the standard library and the current directory.  If PERL5LIB 
  267. is defined, PERLLIB is not used. 
  268.  
  269. Apart from these, Perl uses no other environment variables, except to make them 
  270. available to the script being executed, and to child processes.  However, 
  271. scripts running setuid would do well to execute the following lines before 
  272. doing anything else, just to keep people honest: 
  273.  
  274.     $ENV{'PATH'} = '/bin:/usr/bin';    # or whatever you need
  275.     $ENV{'SHELL'} = '/bin/sh' if defined $ENV{'SHELL'};
  276.     $ENV{'IFS'} = ''          if defined $ENV{'IFS'};
  277.  
  278. AUTHOR 
  279.  
  280. Larry Wall <<lwall@sems.com>, with the help of oodles of other folks. 
  281.  
  282. FILES 
  283.  
  284.  "/tmp/perl-e$$"        temporary file for -e commands
  285.  "@INC"                 locations of perl 5 libraries
  286.  
  287. SEE ALSO 
  288.  
  289.  a2p    awk to perl translator
  290.  
  291.  s2p    sed to perl translator
  292.  
  293. DIAGNOSTICS 
  294.  
  295. The -w switch produces some lovely diagnostics. 
  296.  
  297. See perldiag for explanations of all Perl's diagnostics. 
  298.  
  299. Compilation errors will tell you the line number of the error, with an 
  300. indication of the next token or token type that was to be examined. (In the 
  301. case of a script passed to Perl via -e switches, each -e is counted as one 
  302. line.) 
  303.  
  304. Setuid scripts have additional constraints that can produce error messages such 
  305. as "Insecure dependency".  See perlsec. 
  306.  
  307. Did we mention that you should definitely consider using the -w switch? 
  308.  
  309. BUGS 
  310.  
  311. The -w switch is not mandatory. 
  312.  
  313. Perl is at the mercy of your machine's definitions of various operations such 
  314. as type casting, atof() and sprintf().  The latter can even trigger a coredump 
  315. when passed ludicrous input values. 
  316.  
  317. If your stdio requires a seek or eof between reads and writes on a particular 
  318. stream, so does Perl.  (This doesn't apply to sysread() and syswrite().) 
  319.  
  320. While none of the built-in data types have any arbitrary size limits (apart 
  321. from memory size), there are still a few arbitrary limits:  a given identifier 
  322. may not be longer than 255 characters, and no component of your PATH may be 
  323. longer than 255 if you use -S.  A regular expression may not compile to more 
  324. than 32767 bytes internally. 
  325.  
  326. See the perl bugs database at http://perl.com/perl/bugs/.  You may mail your 
  327. bug reports (be sure to include full configuration information as output by the 
  328. myconfig program in the perl source tree) to perlbug@perl.com. If you've 
  329. succeeded in compiling perl, the perlbug script in the utils/ subdirectory can 
  330. be used to help mail in a bug report. 
  331.  
  332. Perl actually stands for Pathologically Eclectic Rubbish Lister, but don't tell 
  333. anyone I said that. 
  334.  
  335. NOTES 
  336.  
  337. The Perl motto is "There's more than one way to do it."  Divining how many more 
  338. is left as an exercise to the reader. 
  339.  
  340. The three principal virtues of a programmer are Laziness, Impatience, and 
  341. Hubris.  See the Camel Book for why. 
  342.  
  343.  
  344. ΓòÉΓòÉΓòÉ 4. Section - perldata ΓòÉΓòÉΓòÉ
  345.  
  346. NAME 
  347.  
  348. perldata - Perl data types 
  349.  
  350. DESCRIPTION 
  351.  
  352. Variable names 
  353.  
  354. Perl has three data structures: scalars, arrays of scalars, and associative 
  355. arrays of scalars, known as "hashes".  Normal arrays are indexed by number, 
  356. starting with 0.  (Negative subscripts count from the end.)  Hash arrays are 
  357. indexed by string. 
  358.  
  359. Scalar values are always named with '$', even when referring to a scalar that 
  360. is part of an array.  It works like the English word "the".  Thus we have: 
  361.  
  362.     $days               # the simple scalar value "days"
  363.     $days[28]           # the 29th element of array @days
  364.     $days{'Feb'}        # the 'Feb' value from hash %days
  365.     $#days              # the last index of array @days
  366.  
  367. but entire arrays or array slices are denoted by '@', which works much like the 
  368. word "these" or "those": 
  369.  
  370.     @days               # ($days[0], $days[1],... $days[n])
  371.     @days[3,4,5]        # same as @days[3..5]
  372.     @days{'a','c'}      # same as ($days{'a'},$days{'c'})
  373.  
  374. and entire hashes are denoted by '%': 
  375.  
  376.     %days               # (key1, val1, key2, val2 ...)
  377.  
  378. In addition, subroutines are named with an initial '&', though this is optional 
  379. when it's otherwise unambiguous (just as "do" is often redundant in English). 
  380. Symbol table entries can be named with an initial '*', but you don't really 
  381. care about that yet. 
  382.  
  383. Every variable type has its own namespace.  You can, without fear of conflict, 
  384. use the same name for a scalar variable, an array, or a hash (or, for that 
  385. matter, a filehandle, a subroutine name, or a label). This means that $foo and 
  386. @foo are two different variables.  It also means that $foo[1] is a part of 
  387. @foo, not a part of $foo.  This may seem a bit weird, but that's okay, because 
  388. it is weird. 
  389.  
  390. Since variable and array references always start with '$', '@', or '%', the 
  391. "reserved" words aren't in fact reserved with respect to variable names.  (They 
  392. ARE reserved with respect to labels and filehandles, however, which don't have 
  393. an initial special character.  You can't have a filehandle named "log", for 
  394. instance.  Hint: you could say open(LOG,'logfile') rather than 
  395. open(log,'logfile').  Using uppercase filehandles also improves readability and 
  396. protects you from conflict with future reserved words.)  Case IS 
  397. significant--"FOO", "Foo" and "foo" are all different names.  Names that start 
  398. with a letter or underscore may also contain digits and underscores. 
  399.  
  400. It is possible to replace such an alphanumeric name with an expression that 
  401. returns a reference to an object of that type.  For a description of this, see 
  402. perlref. 
  403.  
  404. Names that start with a digit may only contain more digits.  Names which do not 
  405. start with a letter, underscore,  or digit are limited to one character, e.g. 
  406. $% or $$.  (Most of these one character names have a predefined significance to 
  407. Perl.  For instance, $$ is the current process id.) 
  408.  
  409. Context 
  410.  
  411. The interpretation of operations and values in Perl sometimes depends on the 
  412. requirements of the context around the operation or value. There are two major 
  413. contexts: scalar and list.  Certain operations return list values in contexts 
  414. wanting a list, and scalar values otherwise.  (If this is true of an operation 
  415. it will be mentioned in the documentation for that operation.)  In other words, 
  416. Perl overloads certain operations based on whether the expected return value is 
  417. singular or plural.  (Some words in English work this way, like "fish" and 
  418. "sheep".) 
  419.  
  420. In a reciprocal fashion, an operation provides either a scalar or a list 
  421. context to each of its arguments.  For example, if you say 
  422.  
  423.     int( <STDIN> )
  424.  
  425. the integer operation provides a scalar context for the <STDIN> operator, which 
  426. responds by reading one line from STDIN and passing it back to the integer 
  427. operation, which will then find the integer value of that line and return that. 
  428. If, on the other hand, you say 
  429.  
  430.     sort( <STDIN> )
  431.  
  432. then the sort operation provides a list context for <STDIN>, which will proceed 
  433. to read every line available up to the end of file, and pass that list of lines 
  434. back to the sort routine, which will then sort those lines and return them as a 
  435. list to whatever the context of the sort was. 
  436.  
  437. Assignment is a little bit special in that it uses its left argument to 
  438. determine the context for the right argument.  Assignment to a scalar evaluates 
  439. the righthand side in a scalar context, while assignment to an array or array 
  440. slice evaluates the righthand side in a list context.  Assignment to a list 
  441. also evaluates the righthand side in a list context. 
  442.  
  443. User defined subroutines may choose to care whether they are being called in a 
  444. scalar or list context, but most subroutines do not need to care, because 
  445. scalars are automatically interpolated into lists.  See perlfunc/wantarray. 
  446.  
  447. Scalar values 
  448.  
  449. All data in Perl is a scalar or an array of scalars or a hash of scalars. 
  450. Scalar variables may contain various kinds of singular data, such as numbers, 
  451. strings, and references.  In general, conversion from one form to another is 
  452. transparent.  (A scalar may not contain multiple values, but may contain a 
  453. reference to an array or hash containing multiple values.) Because of the 
  454. automatic conversion of scalars, operations and functions that return scalars 
  455. don't need to care (and, in fact, can't care) whether the context is looking 
  456. for a string or a number. 
  457.  
  458. Scalars aren't necessarily one thing or another.  There's no place to declare a 
  459. scalar variable to be of type "string", or of type "number", or type 
  460. "filehandle", or anything else.  Perl is a contextually polymorphic language 
  461. whose scalars can be strings, numbers, or references (which includes objects). 
  462. While strings and numbers are considered the pretty much same thing for nearly 
  463. all purposes, references are strongly-typed uncastable pointers with built-in 
  464. reference-counting and destructor invocation. 
  465.  
  466. A scalar value is interpreted as TRUE in the Boolean sense if it is not the 
  467. null string or the number 0 (or its string equivalent, "0").  The Boolean 
  468. context is just a special kind of scalar context. 
  469.  
  470. There are actually two varieties of null scalars: defined and undefined. 
  471. Undefined null scalars are returned when there is no real value for something, 
  472. such as when there was an error, or at end of file, or when you refer to an 
  473. uninitialized variable or element of an array.  An undefined null scalar may 
  474. become defined the first time you use it as if it were defined, but prior to 
  475. that you can use the defined() operator to determine whether the value is 
  476. defined or not. 
  477.  
  478. To find out whether a given string is a valid non-zero number, it's usually 
  479. enough to test it against both numeric 0 and also lexical "0" (although this 
  480. will cause -w noises).  That's because strings that aren't numbers count as 0, 
  481. just as the do in awk: 
  482.  
  483.     if ($str == 0 && $str ne "0")  {
  484.         warn "That doesn't look like a number";
  485.     }
  486.  
  487. That's usually preferable because otherwise you won't treat IEEE notations like 
  488. NaN or Infinity properly.  At other times you might prefer to use a regular 
  489. expression to check whether data is numeric.  See perlre for details on regular 
  490. expressions. 
  491.  
  492.     warn "has nondigits"        if     /\D/;
  493.     warn "not a whole number"   unless /^\d+$/;
  494.     warn "not an integer"       unless /^[+-]?\d+$/
  495.     warn "not a decimal number" unless /^[+-]?\d+\.?\d*$/
  496.     warn "not a C float"
  497.         unless /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/;
  498.  
  499. The length of an array is a scalar value.  You may find the length of array 
  500. @days by evaluating $#days, as in csh.  (Actually, it's not the length of the 
  501. array, it's the subscript of the last element, since there is (ordinarily) a 
  502. 0th element.)  Assigning to $#days changes the length of the array.  Shortening 
  503. an array by this method destroys intervening values.  Lengthening an array that 
  504. was previously shortened NO LONGER recovers the values that were in those 
  505. elements.  (It used to in Perl 4, but we had to break this make to make sure 
  506. destructors were called when expected.)  You can also gain some measure of 
  507. efficiency by preextending an array that is going to get big.  (You can also 
  508. extend an array by assigning to an element that is off the end of the array.) 
  509. You can truncate an array down to nothing by assigning the null list () to it. 
  510. The following are equivalent: 
  511.  
  512.     @whatever = ();
  513.     $#whatever = $[ - 1;
  514.  
  515. If you evaluate a named array in a scalar context, it returns the length of the 
  516. array.  (Note that this is not true of lists, which return the last value, like 
  517. the C comma operator.)  The following is always true: 
  518.  
  519.     scalar(@whatever) == $#whatever - $[ + 1;
  520.  
  521. Version 5 of Perl changed the semantics of $[: files that don't set the value 
  522. of $[ no longer need to worry about whether another file changed its value. 
  523. (In other words, use of $[ is deprecated.) So in general you can just assume 
  524. that 
  525.  
  526.     scalar(@whatever) == $#whatever + 1;
  527.  
  528. Some programmer choose to use an explcit conversion so nothing's left to doubt: 
  529.  
  530.     $element_count = scalar(@whatever);
  531.  
  532. If you evaluate a hash in a scalar context, it returns a value which is true if 
  533. and only if the hash contains any key/value pairs.  (If there are any key/value 
  534. pairs, the value returned is a string consisting of the number of used buckets 
  535. and the number of allocated buckets, separated by a slash.  This is pretty much 
  536. only useful to find out whether Perl's (compiled in) hashing algorithm is 
  537. performing poorly on your data set. For example, you stick 10,000 things in a 
  538. hash, but evaluating %HASH in scalar context reveals "1/16", which means only 
  539. one out of sixteen buckets has been touched, and presumably contains all 10,000 
  540. of your items.  This isn't supposed to happen.) 
  541.  
  542. Scalar value constructors 
  543.  
  544. Numeric literals are specified in any of the customary floating point or 
  545. integer formats: 
  546.  
  547.     12345
  548.     12345.67
  549.     .23E-10
  550.     0xffff              # hex
  551.     0377                # octal
  552.     4_294_967_296       # underline for legibility
  553.  
  554. String literals are usually delimited by either single or double quotes.  They 
  555. work much like shell quotes:  double-quoted string literals are subject to 
  556. backslash and variable substitution; single-quoted strings are not (except for 
  557. "\'" and "\\").  The usual Unix backslash rules apply for making characters 
  558. such as newline, tab, etc., as well as some more exotic forms.  See perlop/qq 
  559. for a list. 
  560.  
  561. You can also embed newlines directly in your strings, i.e. they can end on a 
  562. different line than they begin.  This is nice, but if you forget your trailing 
  563. quote, the error will not be reported until Perl finds another line containing 
  564. the quote character, which may be much further on in the script.  Variable 
  565. substitution inside strings is limited to scalar variables, arrays, and array 
  566. slices.  (In other words, identifiers beginning with $ or @, followed by an 
  567. optional bracketed expression as a subscript.)  The following code segment 
  568. prints out "The price is $100." 
  569.  
  570.     $Price = '$100';    # not interpreted
  571.     print "The price is $Price.\n";     # interpreted
  572.  
  573. As in some shells, you can put curly brackets around the identifier to delimit 
  574. it from following alphanumerics.  In fact, an identifier within such curlies is 
  575. forced to be a string, as is any single identifier within a hash subscript. 
  576. Our earlier example, 
  577.  
  578.     $days{'Feb'}
  579.  
  580. can be written as 
  581.  
  582.     $days{Feb}
  583.  
  584. and the quotes will be assumed automatically.  But anything more complicated in 
  585. the subscript will be interpreted as an expression. 
  586.  
  587. Note that a single-quoted string must be separated from a preceding word by a 
  588. space, since single quote is a valid (though deprecated) character in an 
  589. identifier (see perlmod/Packages). 
  590.  
  591. Two special literals are __LINE__ and __FILE__, which represent the current 
  592. line number and filename at that point in your program.  They may only be used 
  593. as separate tokens; they will not be interpolated into strings.  In addition, 
  594. the token __END__ may be used to indicate the logical end of the script before 
  595. the actual end of file.  Any following text is ignored, but may be read via the 
  596. DATA filehandle.  (The DATA filehandle may read data only from the main script, 
  597. but not from any required file or evaluated string.)  The two control 
  598. characters ^D and ^Z are synonyms for __END__ (or __DATA__ in a module; see 
  599. L<SelfLoader> for details on __DATA__). 
  600.  
  601. A word that has no other interpretation in the grammar will be treated as if it 
  602. were a quoted string.  These are known as "barewords".  As with filehandles and 
  603. labels, a bareword that consists entirely of lowercase letters risks conflict 
  604. with future reserved words, and if you use the -w switch, Perl will warn you 
  605. about any such words.  Some people may wish to outlaw barewords entirely.  If 
  606. you say 
  607.  
  608.     use strict 'subs';
  609.  
  610. then any bareword that would NOT be interpreted as a subroutine call produces a 
  611. compile-time error instead.  The restriction lasts to the end of the enclosing 
  612. block.  An inner block may countermand this by saying no strict 'subs'. 
  613.  
  614. Array variables are interpolated into double-quoted strings by joining all the 
  615. elements of the array with the delimiter specified in the $" variable 
  616. ($LIST_SEPARATOR in English), space by default.  The following are equivalent: 
  617.  
  618.     $temp = join($",@ARGV);
  619.     system "echo $temp";
  620.  
  621.     system "echo @ARGV";
  622.  
  623. Within search patterns (which also undergo double-quotish substitution) there 
  624. is a bad ambiguity:  Is /$foo[bar]/ to be interpreted as /${foo}[bar]/ (where 
  625. [bar] is a character class for the regular expression) or as /${foo[bar]}/ 
  626. (where [bar] is the subscript to array @foo)?  If @foo doesn't otherwise exist, 
  627. then it's obviously a character class.  If @foo exists, Perl takes a good guess 
  628. about [bar], and is almost always right.  If it does guess wrong, or if you're 
  629. just plain paranoid, you can force the correct interpretation with curly 
  630. brackets as above. 
  631.  
  632. A line-oriented form of quoting is based on the shell "here-doc" syntax. 
  633. Following a << you specify a string to terminate the quoted material, and all 
  634. lines following the current line down to the terminating string are the value 
  635. of the item.  The terminating string may be either an identifier (a word), or 
  636. some quoted text.  If quoted, the type of quotes you use determines the 
  637. treatment of the text, just as in regular quoting.  An unquoted identifier 
  638. works like double quotes.  There must be no space between the << and the 
  639. identifier.  (If you put a space it will be treated as a null identifier, which 
  640. is valid, and matches the first blank line--see the Merry Christmas example 
  641. below.)  The terminating string must appear by itself (unquoted and with no 
  642. surrounding whitespace) on the terminating line. 
  643.  
  644.         print <<EOF;
  645.     The price is $Price.
  646.     EOF
  647.  
  648.         print <<"EOF";  # same as above
  649.     The price is $Price.
  650.     EOF
  651.  
  652.         print <<`EOC`;  # execute commands
  653.     echo hi there
  654.     echo lo there
  655.     EOC
  656.  
  657.         print <<"foo", <<"bar"; # you can stack them
  658.     I said foo.
  659.     foo
  660.     I said bar.
  661.     bar
  662.  
  663.         myfunc(<<"THIS", 23, <<'THAT'');
  664.     Here's a line
  665.     or two.
  666.     THIS
  667.     and here another.
  668.     THAT
  669.  
  670. Just don't forget that you have to put a semicolon on the end to finish the 
  671. statement, as Perl doesn't know you're not going to try to do this: 
  672.  
  673.         print <<ABC
  674.     179231
  675.     ABC
  676.         + 20;
  677.  
  678. List value constructors 
  679.  
  680. List values are denoted by separating individual values by commas (and 
  681. enclosing the list in parentheses where precedence requires it): 
  682.  
  683.     (LIST)
  684.  
  685. In a context not requiring a list value, the value of the list literal is the 
  686. value of the final element, as with the C comma operator. For example, 
  687.  
  688.     @foo = ('cc', '-E', $bar);
  689.  
  690. assigns the entire list value to array foo, but 
  691.  
  692.     $foo = ('cc', '-E', $bar);
  693.  
  694. assigns the value of variable bar to variable foo.  Note that the value of an 
  695. actual array in a scalar context is the length of the array; the following 
  696. assigns to $foo the value 3: 
  697.  
  698.     @foo = ('cc', '-E', $bar);
  699.     $foo = @foo;                # $foo gets 3
  700.  
  701. You may have an optional comma before the closing parenthesis of an list 
  702. literal, so that you can say: 
  703.  
  704.     @foo = (
  705.         1,
  706.         2,
  707.         3,
  708.     );
  709.  
  710. LISTs do automatic interpolation of sublists.  That is, when a LIST is 
  711. evaluated, each element of the list is evaluated in a list context, and the 
  712. resulting list value is interpolated into LIST just as if each individual 
  713. element were a member of LIST.  Thus arrays lose their identity in a LIST--the 
  714. list 
  715.  
  716.     (@foo,@bar,&SomeSub)
  717.  
  718. contains all the elements of @foo followed by all the elements of @bar, 
  719. followed by all the elements returned by the subroutine named SomeSub when it's 
  720. called in a list context. To make a list reference that does NOT interpolate, 
  721. see perlref. 
  722.  
  723. The null list is represented by ().  Interpolating it in a list has no effect. 
  724. Thus ((),(),()) is equivalent to ().  Similarly, interpolating an array with no 
  725. elements is the same as if no array had been interpolated at that point. 
  726.  
  727. A list value may also be subscripted like a normal array.  You must put the 
  728. list in parentheses to avoid ambiguity.  Examples: 
  729.  
  730.     # Stat returns list value.
  731.     $time = (stat($file))[8];
  732.  
  733.     # SYNTAX ERROR HERE.
  734.     $time = stat($file)[8];  # OOPS, FORGOT PARENS
  735.  
  736.     # Find a hex digit.
  737.     $hexdigit = ('a','b','c','d','e','f')[$digit-10];
  738.  
  739.     # A "reverse comma operator".
  740.     return (pop(@foo),pop(@foo))[0];
  741.  
  742. Lists may be assigned to if and only if each element of the list is legal to 
  743. assign to: 
  744.  
  745.     ($a, $b, $c) = (1, 2, 3);
  746.  
  747.     ($map{'red'}, $map{'blue'}, $map{'green'}) = (0x00f, 0x0f0, 0xf00);
  748.  
  749. Array assignment in a scalar context returns the number of elements produced by 
  750. the expression on the right side of the assignment: 
  751.  
  752.     $x = (($foo,$bar) = (3,2,1));       # set $x to 3, not 2
  753.     $x = (($foo,$bar) = f());           # set $x to f()'s return count
  754.  
  755. This is very handy when you want to do a list assignment in a Boolean context, 
  756. since most list functions return a null list when finished, which when assigned 
  757. produces a 0, which is interpreted as FALSE. 
  758.  
  759. The final element may be an array or a hash: 
  760.  
  761.     ($a, $b, @rest) = split;
  762.     local($a, $b, %rest) = @_;
  763.  
  764. You can actually put an array or hash anywhere in the list, but the first one 
  765. in the list will soak up all the values, and anything after it will get a null 
  766. value.  This may be useful in a local() or my(). 
  767.  
  768. A hash literal contains pairs of values to be interpreted as a key and a value: 
  769.  
  770.     # same as map assignment above
  771.     %map = ('red',0x00f,'blue',0x0f0,'green',0xf00);
  772.  
  773. While literal lists and named arrays are usually interchangeable, that's not 
  774. the case for hashes.  Just because you can subscript a list value like a normal 
  775. array does not mean that you can subscript a list value as a hash.  Likewise, 
  776. hashes included as parts of other lists (including parameters lists and return 
  777. lists from functions) always flatten out into key/value pairs.  That's why it's 
  778. good to use references sometimes. 
  779.  
  780. It is often more readable to use the => operator between key/value pairs.  The 
  781. => operator is mostly just a more visually distinctive synonym for a comma, but 
  782. it also quotes its left-hand operand, which makes it nice for initializing 
  783. hashes: 
  784.  
  785.     %map = (
  786.                  red   => 0x00f,
  787.                  blue  => 0x0f0,
  788.                  green => 0xf00,
  789.    );
  790.  
  791. or for initializing hash references to be used as records: 
  792.  
  793.     $rec = {
  794.                 witch => 'Mable the Merciless',
  795.                 cat   => 'Fluffy the Ferocious',
  796.                 date  => '10/31/1776',
  797.     };
  798.  
  799. or for using call-by-named-parameter to complicated functions: 
  800.  
  801.    $field = $query->radio_group(
  802.                name      => 'group_name',
  803.                values    => ['eenie','meenie','minie'],
  804.                default   => 'meenie',
  805.                linebreak => 'true',
  806.                labels    => \%labels
  807.    );
  808.  
  809. Note that just because a hash is initialized in that order doesn't mean that it 
  810. comes out in that order.  See perlfunc/sort for examples of how to arrange for 
  811. an output ordering. 
  812.  
  813. Typeglobs and FileHandles 
  814.  
  815. Perl uses an internal type called a typeglob to hold an entire symbol table 
  816. entry.  The type prefix of a typeglob is a *, because it represents all types. 
  817. This used to be the preferred way to pass arrays and hashes by reference into a 
  818. function, but now that we have real references, this is seldom needed. 
  819.  
  820. One place where you still use typeglobs (or references thereto) is for passing 
  821. or storing filehandles.  If you want to save away a filehandle, do it this way: 
  822.  
  823.     $fh = *STDOUT;
  824.  
  825. or perhaps as a real reference, like this: 
  826.  
  827.     $fh = \*STDOUT;
  828.  
  829. This is also the way to create a local filehandle.  For example: 
  830.  
  831.     sub newopen {
  832.         my $path = shift;
  833.         local *FH;  # not my!
  834.         open (FH, $path) || return undef;
  835.         return \*FH;
  836.     }
  837.     $fh = newopen('/etc/passwd');
  838.  
  839. See perlref, perlsub, and perlmod/"Symbols Tables" for more discussion on 
  840. typeglobs.  See perlfunc/open for other ways of generating filehandles. 
  841.  
  842.  
  843. ΓòÉΓòÉΓòÉ 5. Section - perlsyn ΓòÉΓòÉΓòÉ
  844.  
  845. NAME 
  846.  
  847. perlsyn - Perl syntax 
  848.  
  849. DESCRIPTION 
  850.  
  851. A Perl script consists of a sequence of declarations and statements. The only 
  852. things that need to be declared in Perl are report formats and subroutines. 
  853. See the sections below for more information on those declarations.  All 
  854. uninitialized user-created objects are assumed to start with a null or 0 value 
  855. until they are defined by some explicit operation such as assignment.  (Though 
  856. you can get warnings about the use of undefined values if you like.)  The 
  857. sequence of statements is executed just once, unlike in sed and awk scripts, 
  858. where the sequence of statements is executed for each input line.  While this 
  859. means that you must explicitly loop over the lines of your input file (or 
  860. files), it also means you have much more control over which files and which 
  861. lines you look at.  (Actually, I'm lying--it is possible to do an implicit loop 
  862. with either the -n or -p switch.  It's just not the mandatory default like it 
  863. is in sed and awk.) 
  864.  
  865. Declarations 
  866.  
  867. Perl is, for the most part, a free-form language.  (The only exception to this 
  868. is format declarations, for obvious reasons.) Comments are indicated by the "#" 
  869. character, and extend to the end of the line.  If you attempt to use /* */ 
  870. C-style comments, it will be interpreted either as division or pattern 
  871. matching, depending on the context, and C++ // comments just look like a null 
  872. regular expression, so don't do that. 
  873.  
  874. A declaration can be put anywhere a statement can, but has no effect on the 
  875. execution of the primary sequence of statements--declarations all take effect 
  876. at compile time.  Typically all the declarations are put at the beginning or 
  877. the end of the script.  However, if you're using lexically-scoped private 
  878. variables created with my(), you'll have to make sure your format or subroutine 
  879. definition is within the same block scope as the my if you expect to to be able 
  880. to access those private variables. 
  881.  
  882. Declaring a subroutine allows a subroutine name to be used as if it were a list 
  883. operator from that point forward in the program.  You can declare a subroutine 
  884. (prototyped to take one scalar parameter) without defining it by saying just: 
  885.  
  886.     sub myname ($);
  887.     $me = myname $0             or die "can't get myname";
  888.  
  889. Note that it functions as a list operator though, not as a unary operator, so 
  890. be careful to use or instead of || there. 
  891.  
  892. Subroutines declarations can also be loaded up with the require statement or 
  893. both loaded and imported into your namespace with a use statement. See perlmod 
  894. for details on this. 
  895.  
  896. A statement sequence may contain declarations of lexically-scoped variables, 
  897. but apart from declaring a variable name, the declaration acts like an ordinary 
  898. statement, and is elaborated within the sequence of statements as if it were an 
  899. ordinary statement.  That means it actually has both compile-time and run-time 
  900. effects. 
  901.  
  902. Simple statements 
  903.  
  904. The only kind of simple statement is an expression evaluated for its side 
  905. effects.  Every simple statement must be terminated with a semicolon, unless it 
  906. is the final statement in a block, in which case the semicolon is optional.  (A 
  907. semicolon is still encouraged there if the block takes up more than one line, 
  908. since you may eventually add another line.) Note that there are some operators 
  909. like eval {} and do {} that look like compound statements, but aren't (they're 
  910. just TERMs in an expression), and thus need an explicit termination if used as 
  911. the last item in a statement. 
  912.  
  913. Any simple statement may optionally be followed by a SINGLE modifier, just 
  914. before the terminating semicolon (or block ending).  The possible modifiers 
  915. are: 
  916.  
  917.     if EXPR
  918.     unless EXPR
  919.     while EXPR
  920.     until EXPR
  921.  
  922. The if and unless modifiers have the expected semantics, presuming you're a 
  923. speaker of English.  The while and until modifiers also have the usual "while 
  924. loop" semantics (conditional evaluated first), except when applied to a 
  925. do-BLOCK (or to the now-deprecated do-SUBROUTINE statement), in which case the 
  926. block executes once before the conditional is evaluated.  This is so that you 
  927. can write loops like: 
  928.  
  929.     do {
  930.         $line = <STDIN>;
  931.         ...
  932.     } until $line  eq ".\n";
  933.  
  934. See perlfunc/do.  Note also that the loop control statements described later 
  935. will NOT work in this construct, since modifiers don't take loop labels. 
  936. Sorry.  You can always wrap another block around it to do that sort of thing. 
  937.  
  938. Compound statements 
  939.  
  940. In Perl, a sequence of statements that defines a scope is called a block. 
  941. Sometimes a block is delimited by the file containing it (in the case of a 
  942. required file, or the program as a whole), and sometimes a block is delimited 
  943. by the extent of a string (in the case of an eval). 
  944.  
  945. But generally, a block is delimited by curly brackets, also known as braces. We 
  946. will call this syntactic construct a BLOCK. 
  947.  
  948. The following compound statements may be used to control flow: 
  949.  
  950.     if (EXPR) BLOCK
  951.     if (EXPR) BLOCK else BLOCK
  952.     if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
  953.     LABEL while (EXPR) BLOCK
  954.     LABEL while (EXPR) BLOCK continue BLOCK
  955.     LABEL for (EXPR; EXPR; EXPR) BLOCK
  956.     LABEL foreach VAR (LIST) BLOCK
  957.     LABEL BLOCK continue BLOCK
  958.  
  959. Note that, unlike C and Pascal, these are defined in terms of BLOCKs, not 
  960. statements.  This means that the curly brackets are required--no dangling 
  961. statements allowed.  If you want to write conditionals without curly brackets 
  962. there are several other ways to do it.  The following all do the same thing: 
  963.  
  964.     if (!open(FOO)) { die "Can't open $FOO: $!"; }
  965.     die "Can't open $FOO: $!" unless open(FOO);
  966.     open(FOO) or die "Can't open $FOO: $!";     # FOO or bust!
  967.     open(FOO) ? 'hi mom' : die "Can't open $FOO: $!";
  968.                         # a bit exotic, that last one
  969.  
  970. The if statement is straightforward.  Since BLOCKs are always bounded by curly 
  971. brackets, there is never any ambiguity about which if an else goes with.  If 
  972. you use unless in place of if, the sense of the test is reversed. 
  973.  
  974. The while statement executes the block as long as the expression is true (does 
  975. not evaluate to the null string or 0 or "0").  The LABEL is optional, and if 
  976. present, consists of an identifier followed by a colon. The LABEL identifies 
  977. the loop for the loop control statements next, last, and redo.  If the LABEL is 
  978. omitted, the loop control statement refers to the innermost enclosing loop. 
  979. This may include dynamically looking back your call-stack at run time to find 
  980. the LABEL.  Such desperate behavior triggers a warning if you use the -w flag. 
  981.  
  982. If there is a continue BLOCK, it is always executed just before the conditional 
  983. is about to be evaluated again, just like the third part of a for loop in C. 
  984. Thus it can be used to increment a loop variable, even when the loop has been 
  985. continued via the next statement (which is similar to the C continue 
  986. statement). 
  987.  
  988. Loop Control 
  989.  
  990. The next command is like the continue statement in C; it starts the next 
  991. iteration of the loop: 
  992.  
  993.     LINE: while (<STDIN>) {
  994.         next LINE if /^#/;      # discard comments
  995.         ...
  996.     }
  997.  
  998. The last command is like the break statement in C (as used in loops); it 
  999. immediately exits the loop in question.  The continue block, if any, is not 
  1000. executed: 
  1001.  
  1002.     LINE: while (<STDIN>) {
  1003.         last LINE if /^$/;      # exit when done with header
  1004.         ...
  1005.     }
  1006.  
  1007. The redo command restarts the loop block without evaluating the conditional 
  1008. again.  The continue block, if any, is not executed. This command is normally 
  1009. used by programs that want to lie to themselves about what was just input. 
  1010.  
  1011. For example, when processing a file like /etc/termcap. If your input lines 
  1012. might end in backslashes to indicate continuation, you want to skip ahead and 
  1013. get the next record. 
  1014.  
  1015.     while (<>) {
  1016.         chomp;
  1017.         if (s/\\$//) {
  1018.             $_ .= <>;
  1019.             redo unless eof();
  1020.         }
  1021.         # now process $_
  1022.     }
  1023.  
  1024. which is Perl short-hand for the more explicitly written version: 
  1025.  
  1026.     LINE: while ($line = <ARGV>) {
  1027.         chomp($line);
  1028.         if ($line =~ s/\\$//) {
  1029.             $line .= <ARGV>;
  1030.             redo LINE unless eof(); # not eof(ARGV)!
  1031.         }
  1032.         # now process $line
  1033.     }
  1034.  
  1035. Or here's a a simpleminded Pascal comment stripper (warning: assumes no { or } 
  1036. in strings) 
  1037.  
  1038.     LINE: while (<STDIN>) {
  1039.         while (s|({.*}.*){.*}|$1 |) {}
  1040.         s|{.*}| |;
  1041.         if (s|{.*| |) {
  1042.             $front = $_;
  1043.             while (<STDIN>) {
  1044.                 if (/}/) {      # end of comment?
  1045.                     s|^|$front{|;
  1046.                     redo LINE;
  1047.                 }
  1048.             }
  1049.         }
  1050.         print;
  1051.     }
  1052.  
  1053. Note that if there were a continue block on the above code, it would get 
  1054. executed even on discarded lines. 
  1055.  
  1056. If the word while is replaced by the word until, the sense of the test is 
  1057. reversed, but the conditional is still tested before the first iteration. 
  1058.  
  1059. In either the if or the while statement, you may replace "(EXPR)" with a BLOCK, 
  1060. and the conditional is true if the value of the last statement in that block is 
  1061. true.  While this "feature" continues to work in version 5, it has been 
  1062. deprecated, so please change any occurrences of "if BLOCK" to "if (do BLOCK)". 
  1063.  
  1064. For Loops 
  1065.  
  1066. Perl's C-style for loop works exactly like the corresponding while loop; that 
  1067. means that this: 
  1068.  
  1069.     for ($i = 1; $i < 10; $i++) {
  1070.         ...
  1071.     }
  1072.  
  1073. is the same as this: 
  1074.  
  1075.     $i = 1;
  1076.     while ($i < 10) {
  1077.         ...
  1078.     } continue {
  1079.         $i++;
  1080.     }
  1081.  
  1082. Besides the normal array index looping, for can lend itself to many other 
  1083. interesting applications.  Here's one that avoids the problem you get into if 
  1084. you explicitly test for end-of-file on an interactive file descriptor causing 
  1085. your program to appear to hang. 
  1086.  
  1087.     $on_a_tty = -t STDIN && -t STDOUT;
  1088.     sub prompt { print "yes? " if $on_a_tty }
  1089.     for ( prompt(); <STDIN>; prompt() ) {
  1090.         # do something
  1091.     }
  1092.  
  1093. Foreach Loops 
  1094.  
  1095. The foreach loop iterates over a normal list value and sets the variable VAR to 
  1096. be each element of the list in turn.  The variable is implicitly local to the 
  1097. loop and regains its former value upon exiting the loop.  If the variable was 
  1098. previously declared with my, it uses that variable instead of the global one, 
  1099. but it's still localized to the loop. This can cause problems if you have 
  1100. subroutine or format declarations within that block's scope. 
  1101.  
  1102. The foreach keyword is actually a synonym for the for keyword, so you can use 
  1103. foreach for readability or for for brevity.  If VAR is omitted, $_ is set to 
  1104. each value.  If LIST is an actual array (as opposed to an expression returning 
  1105. a list value), you can modify each element of the array by modifying VAR inside 
  1106. the loop.  That's because the foreach loop index variable is an implicit alias 
  1107. for each item in the list that you're looping over. 
  1108.  
  1109. Examples: 
  1110.  
  1111.     for (@ary) { s/foo/bar/ }
  1112.  
  1113.     foreach $elem (@elements) {
  1114.         $elem *= 2;
  1115.     }
  1116.  
  1117.     for $count (10,9,8,7,6,5,4,3,2,1,'BOOM') {
  1118.         print $count, "\n"; sleep(1);
  1119.     }
  1120.  
  1121.     for (1..15) { print "Merry Christmas\n"; }
  1122.  
  1123.     foreach $item (split(/:[\\\n:]*/, $ENV{TERMCAP})) {
  1124.         print "Item: $item\n";
  1125.     }
  1126.  
  1127. Here's how a C programmer might code up a particular algorithm in Perl: 
  1128.  
  1129.     for ($i = 0; $i < @ary1; $i++) {
  1130.         for ($j = 0; $j < @ary2; $j++) {
  1131.             if ($ary1[$i] > $ary2[$j]) {
  1132.                 last; # can't go to outer :-(
  1133.             }
  1134.             $ary1[$i] += $ary2[$j];
  1135.         }
  1136.         # this is where that last takes me
  1137.     }
  1138.  
  1139. Whereas here's how a Perl programmer more confortable with the idiom might do 
  1140. it: 
  1141.  
  1142.     OUTER: foreach $wid (@ary1) {
  1143.     INNER:   foreach $jet (@ary2) {
  1144.                 next OUTER if $wid > $jet;
  1145.                 $wid += $jet;
  1146.              }
  1147.           }
  1148.  
  1149. See how much easier this is?  It's cleaner, safer, and faster.  It's cleaner 
  1150. because it's less noisy.  It's safer because if code gets added between the 
  1151. inner and outer loops later on, the new code won't be accidentally excecuted: 
  1152. the next explicitly iterates the other loop rather than merely terminating the 
  1153. inner one.  And it's faster because Perl executes a foreach statement more 
  1154. rapidly than it would the equivalent for loop. 
  1155.  
  1156. Basic BLOCKs and Switch Statements 
  1157.  
  1158. A BLOCK by itself (labeled or not) is semantically equivalent to a loop that 
  1159. executes once.  Thus you can use any of the loop control statements in it to 
  1160. leave or restart the block.  (Note that this is NOT true in eval{}, sub{}, or 
  1161. contrary to popular belief do{} blocks, which do NOT count as loops.)  The 
  1162. continue block is optional. 
  1163.  
  1164. The BLOCK construct is particularly nice for doing case structures. 
  1165.  
  1166.     SWITCH: {
  1167.         if (/^abc/) { $abc = 1; last SWITCH; }
  1168.         if (/^def/) { $def = 1; last SWITCH; }
  1169.         if (/^xyz/) { $xyz = 1; last SWITCH; }
  1170.         $nothing = 1;
  1171.     }
  1172.  
  1173. There is no official switch statement in Perl, because there are already 
  1174. several ways to write the equivalent.  In addition to the above, you could 
  1175. write 
  1176.  
  1177.     SWITCH: {
  1178.         $abc = 1, last SWITCH  if /^abc/;
  1179.         $def = 1, last SWITCH  if /^def/;
  1180.         $xyz = 1, last SWITCH  if /^xyz/;
  1181.         $nothing = 1;
  1182.     }
  1183.  
  1184. (That's actually not as strange as it looks once you realize that you can use 
  1185. loop control "operators" within an expression,  That's just the normal C comma 
  1186. operator.) 
  1187.  
  1188. or 
  1189.  
  1190.     SWITCH: {
  1191.         /^abc/ && do { $abc = 1; last SWITCH; };
  1192.         /^def/ && do { $def = 1; last SWITCH; };
  1193.         /^xyz/ && do { $xyz = 1; last SWITCH; };
  1194.         $nothing = 1;
  1195.     }
  1196.  
  1197. or formatted so it stands out more as a "proper" switch statement: 
  1198.  
  1199.     SWITCH: {
  1200.         /^abc/      && do {
  1201.                             $abc = 1;
  1202.                             last SWITCH;
  1203.                        };
  1204.  
  1205.         /^def/      && do {
  1206.                             $def = 1;
  1207.                             last SWITCH;
  1208.                        };
  1209.  
  1210.         /^xyz/      && do {
  1211.                             $xyz = 1;
  1212.                             last SWITCH;
  1213.                         };
  1214.         $nothing = 1;
  1215.     }
  1216.  
  1217. or 
  1218.  
  1219.     SWITCH: {
  1220.         /^abc/ and $abc = 1, last SWITCH;
  1221.         /^def/ and $def = 1, last SWITCH;
  1222.         /^xyz/ and $xyz = 1, last SWITCH;
  1223.         $nothing = 1;
  1224.     }
  1225.  
  1226. or even, horrors, 
  1227.  
  1228.     if (/^abc/)
  1229.         { $abc = 1 }
  1230.     elsif (/^def/)
  1231.         { $def = 1 }
  1232.     elsif (/^xyz/)
  1233.         { $xyz = 1 }
  1234.     else
  1235.         { $nothing = 1 }
  1236.  
  1237. A common idiom for a switch statement is to use foreach's aliasing to make a 
  1238. temporary assignment to $_ for convenient matching: 
  1239.  
  1240.     SWITCH: for ($where) {
  1241.                 /In Card Names/     && do { push @flags, '-e'; last; };
  1242.                 /Anywhere/          && do { push @flags, '-h'; last; };
  1243.                 /In Rulings/        && do {                    last; };
  1244.                 die "unknown value for form variable where: `$where'";
  1245.             }
  1246.  
  1247. Another interesting approach to a switch statement is arrange for a do block to 
  1248. return the proper value: 
  1249.  
  1250.     $amode = do {
  1251.         if     ($flag & O_RDONLY) { "r" }
  1252.         elsif  ($flag & O_WRONLY) { ($flag & O_APPEND) ? "a" : "w" }
  1253.         elsif  ($flag & O_RDWR)   {
  1254.             if ($flag & O_CREAT)  { "w+" }
  1255.             else                  { ($flag & O_APPEND) ? "a+" : "r+" }
  1256.         }
  1257.     };
  1258.  
  1259. Goto 
  1260.  
  1261. Although not for the faint of heart, Perl does support a goto statement. A 
  1262. loop's LABEL is not actually a valid target for a goto; it's just the name of 
  1263. the loop.  There are three forms: goto-LABEL, goto-EXPR, and goto-&NAME. 
  1264.  
  1265. The goto-LABEL form finds the statement labeled with LABEL and resumes 
  1266. execution there.  It may not be used to go into any construct that requires 
  1267. initialization, such as a subroutine or a foreach loop.  It also can't be used 
  1268. to go into a construct that is optimized away.  It can be used to go almost 
  1269. anywhere else within the dynamic scope, including out of subroutines, but it's 
  1270. usually better to use some other construct such as last or die.  The author of 
  1271. Perl has never felt the need to use this form of goto (in Perl, that is--C is 
  1272. another matter). 
  1273.  
  1274. The goto-EXPR form expects a label name, whose scope will be resolved 
  1275. dynamically.  This allows for computed gotos per FORTRAN, but isn't necessarily 
  1276. recommended if you're optimizing for maintainability: 
  1277.  
  1278.     goto ("FOO", "BAR", "GLARCH")[$i];
  1279.  
  1280. The goto-&NAME form is highly magical, and substitutes a call to the named 
  1281. subroutine for the currently running subroutine.  This is used by AUTOLOAD() 
  1282. subroutines that wish to load another subroutine and then pretend that the 
  1283. other subroutine had been called in the first place (except that any 
  1284. modifications to @_ in the current subroutine are propagated to the other 
  1285. subroutine.)  After the goto, not even caller() will be able to tell that this 
  1286. routine was called first. 
  1287.  
  1288. In almost all cases like this, it's usually a far, far better idea to use the 
  1289. structured control flow mechanisms of next, last, or redo instead of resorting 
  1290. to a goto.  For certain applications, the catch and throw pair of eval{} and 
  1291. die() for exception processing can also be a prudent approach. 
  1292.  
  1293. PODs: Embedded Documentation 
  1294.  
  1295. Perl has a mechanism for intermixing documentation with source code. While it's 
  1296. expecting the beginning of a new statement, if the compiler encounters a line 
  1297. that begins with an equal sign and a word, like this 
  1298.  
  1299.     =head1 Here There Be Pods!
  1300.  
  1301. Then that text and all remaining text up through and including a line beginning 
  1302. with =cut will be ignored.  The format of the intervening text is described in 
  1303. perlpod. 
  1304.  
  1305. This allows you to intermix your source code and your documentation text 
  1306. freely, as in 
  1307.  
  1308.     =item snazzle($)
  1309.  
  1310.     The snazzle() function will behave in the most spectacular
  1311.     form that you can possibly imagine, not even excepting
  1312.     cybernetic pyrotechnics.
  1313.  
  1314.     =cut back to the compiler, nuff of this pod stuff!
  1315.  
  1316.     sub snazzle($) {
  1317.         my $thingie = shift;
  1318.         .........
  1319.     }
  1320.  
  1321. Note that pod translators should only look at paragraphs beginning with a pod 
  1322. diretive (it makes parsing easier), whereas the compiler actually knows to look 
  1323. for pod escapes even in the middle of a paragraph.  This means that the 
  1324. following secret stuff will be ignored by both the compiler and the 
  1325. translators. 
  1326.  
  1327.     $a=3;
  1328.     =secret stuff
  1329.      warn "Neither POD nor CODE!?"
  1330.     =cut back
  1331.     print "got $a\n";
  1332.  
  1333. You probably shouldn't rely upon the warn() being podded out forever. Not all 
  1334. pod translators are well-behaved in this regard, and perhaps the compiler will 
  1335. become pickier. 
  1336.  
  1337.  
  1338. ΓòÉΓòÉΓòÉ 6. Section - perlop ΓòÉΓòÉΓòÉ
  1339.  
  1340. NAME 
  1341.  
  1342. perlop - Perl operators and precedence 
  1343.  
  1344. SYNOPSIS 
  1345.  
  1346. Perl operators have the following associativity and precedence, listed from 
  1347. highest precedence to lowest.  Note that all operators borrowed from C keep the 
  1348. same precedence relationship with each other, even where C's precedence is 
  1349. slightly screwy.  (This makes learning Perl easier for C folks.)  With very few 
  1350. exceptions, these all operate on scalar values only, not array values. 
  1351.  
  1352.     left        terms and list operators (leftward)
  1353.     left        ->
  1354.     nonassoc    ++ --
  1355.     right       **
  1356.     right       ! ~ \ and unary + and -
  1357.     left        =~ !~
  1358.     left        * / % x
  1359.     left        + - .
  1360.     left        << >>
  1361.     nonassoc    named unary operators
  1362.     nonassoc    < > <= >= lt gt le ge
  1363.     nonassoc    == != <=> eq ne cmp
  1364.     left        &
  1365.     left        | ^
  1366.     left        &&
  1367.     left        ||
  1368.     nonassoc    ..
  1369.     right       ?:
  1370.     right       = += -= *= etc.
  1371.     left        , =>
  1372.     nonassoc    list operators (rightward)
  1373.     left        not
  1374.     left        and
  1375.     left        or xor
  1376.  
  1377. In the following sections, these operators are covered in precedence order. 
  1378.  
  1379. DESCRIPTION 
  1380.  
  1381. Terms and List Operators (Leftward) 
  1382.  
  1383. Any TERM is of highest precedence of Perl.  These includes variables, quote and 
  1384. quotelike operators, any expression in parentheses, and any function whose 
  1385. arguments are parenthesized.  Actually, there aren't really functions in this 
  1386. sense, just list operators and unary operators behaving as functions because 
  1387. you put parentheses around the arguments.  These are all documented in 
  1388. perlfunc. 
  1389.  
  1390. If any list operator (print(), etc.) or any unary operator (chdir(), etc.) is 
  1391. followed by a left parenthesis as the next token, the operator and arguments 
  1392. within parentheses are taken to be of highest precedence, just like a normal 
  1393. function call. 
  1394.  
  1395. In the absence of parentheses, the precedence of list operators such as print, 
  1396. sort, or chmod is either very high or very low depending on whether you look at 
  1397. the left side of operator or the right side of it. For example, in 
  1398.  
  1399.     @ary = (1, 3, sort 4, 2);
  1400.     print @ary;         # prints 1324
  1401.  
  1402. the commas on the right of the sort are evaluated before the sort, but the 
  1403. commas on the left are evaluated after.  In other words, list operators tend to 
  1404. gobble up all the arguments that follow them, and then act like a simple TERM 
  1405. with regard to the preceding expression. Note that you have to be careful with 
  1406. parens: 
  1407.  
  1408.     # These evaluate exit before doing the print:
  1409.     print($foo, exit);  # Obviously not what you want.
  1410.     print $foo, exit;   # Nor is this.
  1411.  
  1412.     # These do the print before evaluating exit:
  1413.     (print $foo), exit; # This is what you want.
  1414.     print($foo), exit;  # Or this.
  1415.     print ($foo), exit; # Or even this.
  1416.  
  1417. Also note that 
  1418.  
  1419.     print ($foo & 255) + 1, "\n";
  1420.  
  1421. probably doesn't do what you expect at first glance.  See L<Named Unary 
  1422. Operators> for more discussion of this. 
  1423.  
  1424. Also parsed as terms are the do {} and eval {} constructs, as well as 
  1425. subroutine and method calls, and the anonymous constructors [] and {}. 
  1426.  
  1427. See also L<Quote and Quotelike Operators> toward the end of this section, as 
  1428. well as L<"I/O Operators">. 
  1429.  
  1430. The Arrow Operator 
  1431.  
  1432. Just as in C and C++, "->" is an infix dereference operator.  If the right side 
  1433. is either a [...] or {...} subscript, then the left side must be either a hard 
  1434. or symbolic reference to an array or hash (or a location capable of holding a 
  1435. hard reference, if it's an lvalue (assignable)). See perlref. 
  1436.  
  1437. Otherwise, the right side is a method name or a simple scalar variable 
  1438. containing the method name, and the left side must either be an object (a 
  1439. blessed reference) or a class name (that is, a package name). See perlobj. 
  1440.  
  1441. Autoincrement and Autodecrement 
  1442.  
  1443. "++" and "--" work as in C.  That is, if placed before a variable, they 
  1444. increment or decrement the variable before returning the value, and if placed 
  1445. after, increment or decrement the variable after returning the value. 
  1446.  
  1447. The autoincrement operator has a little extra built-in magic to it.  If you 
  1448. increment a variable that is numeric, or that has ever been used in a numeric 
  1449. context, you get a normal increment.  If, however, the variable has only been 
  1450. used in string contexts since it was set, and has a value that is not null and 
  1451. matches the pattern /^[a-zA-Z]*[0-9]*$/, the increment is done as a string, 
  1452. preserving each character within its range, with carry: 
  1453.  
  1454.     print ++($foo = '99');      # prints '100'
  1455.     print ++($foo = 'a0');      # prints 'a1'
  1456.     print ++($foo = 'Az');      # prints 'Ba'
  1457.     print ++($foo = 'zz');      # prints 'aaa'
  1458.  
  1459. The autodecrement operator is not magical. 
  1460.  
  1461. Exponentiation 
  1462.  
  1463. Binary "**" is the exponentiation operator.  Note that it binds even more 
  1464. tightly than unary minus, so -2**4 is -(2**4), not (-2)**4. (This is 
  1465. implemented using C's pow(3) function, which actually works on doubles 
  1466. internally.) 
  1467.  
  1468. Symbolic Unary Operators 
  1469.  
  1470. Unary "!" performs logical negation, i.e. "not".  See also not for a lower 
  1471. precedence version of this. 
  1472.  
  1473. Unary "-" performs arithmetic negation if the operand is numeric.  If the 
  1474. operand is an identifier, a string consisting of a minus sign concatenated with 
  1475. the identifier is returned.  Otherwise, if the string starts with a plus or 
  1476. minus, a string starting with the opposite sign is returned.  One effect of 
  1477. these rules is that -bareword is equivalent to "-bareword". 
  1478.  
  1479. Unary "~" performs bitwise negation, i.e. 1's complement. 
  1480.  
  1481. Unary "+" has no effect whatsoever, even on strings.  It is useful 
  1482. syntactically for separating a function name from a parenthesized expression 
  1483. that would otherwise be interpreted as the complete list of function arguments. 
  1484. (See examples above under L<List Operators>.) 
  1485.  
  1486. Unary "\" creates a reference to whatever follows it.  See perlref. Do not 
  1487. confuse this behavior with the behavior of backslash within a string, although 
  1488. both forms do convey the notion of protecting the next thing from 
  1489. interpretation. 
  1490.  
  1491. Binding Operators 
  1492.  
  1493. Binary "=~" binds a scalar expression to a pattern match.  Certain operations 
  1494. search or modify the string $_ by default.  This operator makes that kind of 
  1495. operation work on some other string.  The right argument is a search pattern, 
  1496. substitution, or translation.  The left argument is what is supposed to be 
  1497. searched, substituted, or translated instead of the default $_.  The return 
  1498. value indicates the success of the operation.  (If the right argument is an 
  1499. expression rather than a search pattern, substitution, or translation, it is 
  1500. interpreted as a search pattern at run time.  This is less efficient than an 
  1501. explicit search, since the pattern must be compiled every time the expression 
  1502. is evaluated--unless you've used /o.) 
  1503.  
  1504. Binary "!~" is just like "=~" except the return value is negated in the logical 
  1505. sense. 
  1506.  
  1507. Multiplicative Operators 
  1508.  
  1509. Binary "*" multiplies two numbers. 
  1510.  
  1511. Binary "/" divides two numbers. 
  1512.  
  1513. Binary "%" computes the modulus of the two numbers. 
  1514.  
  1515. Binary "x" is the repetition operator.  In a scalar context, it returns a 
  1516. string consisting of the left operand repeated the number of times specified by 
  1517. the right operand.  In a list context, if the left operand is a list in parens, 
  1518. it repeats the list. 
  1519.  
  1520.     print '-' x 80;             # print row of dashes
  1521.  
  1522.     print "\t" x ($tab/8), ' ' x ($tab%8);      # tab over
  1523.  
  1524.     @ones = (1) x 80;           # a list of 80 1's
  1525.     @ones = (5) x @ones;        # set all elements to 5
  1526.  
  1527. Additive Operators 
  1528.  
  1529. Binary "+" returns the sum of two numbers. 
  1530.  
  1531. Binary "-" returns the difference of two numbers. 
  1532.  
  1533. Binary "." concatenates two strings. 
  1534.  
  1535. Shift Operators 
  1536.  
  1537. Binary "<<" returns the value of its left argument shifted left by the number 
  1538. of bits specified by the right argument.  Arguments should be integers. 
  1539.  
  1540. Binary ">>" returns the value of its left argument shifted right by the number 
  1541. of bits specified by the right argument.  Arguments should be integers. 
  1542.  
  1543. Named Unary Operators 
  1544.  
  1545. The various named unary operators are treated as functions with one argument, 
  1546. with optional parentheses.  These include the filetest operators, like -f, -M, 
  1547. etc.  See perlfunc. 
  1548.  
  1549. If any list operator (print(), etc.) or any unary operator (chdir(), etc.) is 
  1550. followed by a left parenthesis as the next token, the operator and arguments 
  1551. within parentheses are taken to be of highest precedence, just like a normal 
  1552. function call.  Examples: 
  1553.  
  1554.     chdir $foo    || die;       # (chdir $foo) || die
  1555.     chdir($foo)   || die;       # (chdir $foo) || die
  1556.     chdir ($foo)  || die;       # (chdir $foo) || die
  1557.     chdir +($foo) || die;       # (chdir $foo) || die
  1558.  
  1559. but, because * is higher precedence than ||: 
  1560.  
  1561.     chdir $foo * 20;    # chdir ($foo * 20)
  1562.     chdir($foo) * 20;   # (chdir $foo) * 20
  1563.     chdir ($foo) * 20;  # (chdir $foo) * 20
  1564.     chdir +($foo) * 20; # chdir ($foo * 20)
  1565.  
  1566.     rand 10 * 20;       # rand (10 * 20)
  1567.     rand(10) * 20;      # (rand 10) * 20
  1568.     rand (10) * 20;     # (rand 10) * 20
  1569.     rand +(10) * 20;    # rand (10 * 20)
  1570.  
  1571. See also L<"List Operators">. 
  1572.  
  1573. Relational Operators 
  1574.  
  1575. Binary "<" returns true if the left argument is numerically less than the right 
  1576. argument. 
  1577.  
  1578. Binary ">" returns true if the left argument is numerically greater than the 
  1579. right argument. 
  1580.  
  1581. Binary "<=" returns true if the left argument is numerically less than or equal 
  1582. to the right argument. 
  1583.  
  1584. Binary ">=" returns true if the left argument is numerically greater than or 
  1585. equal to the right argument. 
  1586.  
  1587. Binary "lt" returns true if the left argument is stringwise less than the right 
  1588. argument. 
  1589.  
  1590. Binary "gt" returns true if the left argument is stringwise greater than the 
  1591. right argument. 
  1592.  
  1593. Binary "le" returns true if the left argument is stringwise less than or equal 
  1594. to the right argument. 
  1595.  
  1596. Binary "ge" returns true if the left argument is stringwise greater than or 
  1597. equal to the right argument. 
  1598.  
  1599. Equality Operators 
  1600.  
  1601. Binary "==" returns true if the left argument is numerically equal to the right 
  1602. argument. 
  1603.  
  1604. Binary "!=" returns true if the left argument is numerically not equal to the 
  1605. right argument. 
  1606.  
  1607. Binary "<=>" returns -1, 0, or 1 depending on whether the left argument is 
  1608. numerically less than, equal to, or greater than the right argument. 
  1609.  
  1610. Binary "eq" returns true if the left argument is stringwise equal to the right 
  1611. argument. 
  1612.  
  1613. Binary "ne" returns true if the left argument is stringwise not equal to the 
  1614. right argument. 
  1615.  
  1616. Binary "cmp" returns -1, 0, or 1 depending on whether the left argument is 
  1617. stringwise less than, equal to, or greater than the right argument. 
  1618.  
  1619. Bitwise And 
  1620.  
  1621. Binary "&" returns its operators ANDed together bit by bit. 
  1622.  
  1623. Bitwise Or and Exclusive Or 
  1624.  
  1625. Binary "|" returns its operators ORed together bit by bit. 
  1626.  
  1627. Binary "^" returns its operators XORed together bit by bit. 
  1628.  
  1629. C-style Logical And 
  1630.  
  1631. Binary "&&" performs a short-circuit logical AND operation.  That is, if the 
  1632. left operand is false, the right operand is not even evaluated. Scalar or list 
  1633. context propagates down to the right operand if it is evaluated. 
  1634.  
  1635. C-style Logical Or 
  1636.  
  1637. Binary "||" performs a short-circuit logical OR operation.  That is, if the 
  1638. left operand is true, the right operand is not even evaluated. Scalar or list 
  1639. context propagates down to the right operand if it is evaluated. 
  1640.  
  1641. The || and && operators differ from C's in that, rather than returning 0 or 1, 
  1642. they return the last value evaluated.  Thus, a reasonably portable way to find 
  1643. out the home directory (assuming it's not "0") might be: 
  1644.  
  1645.     $home = $ENV{'HOME'} || $ENV{'LOGDIR'} ||
  1646.         (getpwuid($<))[7] || die "You're homeless!\n";
  1647.  
  1648. As more readable alternatives to && and ||, Perl provides "and" and "or" 
  1649. operators (see below).  The short-circuit behavior is identical.  The 
  1650. precedence of "and" and "or" is much lower, however, so that you can safely use 
  1651. them after a list operator without the need for parentheses: 
  1652.  
  1653.     unlink "alpha", "beta", "gamma"
  1654.             or gripe(), next LINE;
  1655.  
  1656. With the C-style operators that would have been written like this: 
  1657.  
  1658.     unlink("alpha", "beta", "gamma")
  1659.             || (gripe(), next LINE);
  1660.  
  1661. Range Operator 
  1662.  
  1663. Binary ".." is the range operator, which is really two different operators 
  1664. depending on the context.  In a list context, it returns an array of values 
  1665. counting (by ones) from the left value to the right value.  This is useful for 
  1666. writing for (1..10) loops and for doing slice operations on arrays.  Be aware 
  1667. that under the current implementation, a temporary array is created, so you'll 
  1668. burn a lot of memory if you write something like this: 
  1669.  
  1670.     for (1 .. 1_000_000) {
  1671.         # code
  1672.     }
  1673.  
  1674. In a scalar context, ".." returns a boolean value.  The operator is bistable, 
  1675. like a flip-flop, and emulates the line-range (comma) operator of sed, awk, and 
  1676. various editors.  Each ".." operator maintains its own boolean state.  It is 
  1677. false as long as its left operand is false. Once the left operand is true, the 
  1678. range operator stays true until the right operand is true, AFTER which the 
  1679. range operator becomes false again.  (It doesn't become false till the next 
  1680. time the range operator is evaluated.  It can test the right operand and become 
  1681. false on the same evaluation it became true (as in awk), but it still returns 
  1682. true once. If you don't want it to test the right operand till the next 
  1683. evaluation (as in sed), use three dots ("...") instead of two.)  The right 
  1684. operand is not evaluated while the operator is in the "false" state, and the 
  1685. left operand is not evaluated while the operator is in the "true" state.  The 
  1686. precedence is a little lower than || and &&.  The value returned is either the 
  1687. null string for false, or a sequence number (beginning with 1) for true.  The 
  1688. sequence number is reset for each range encountered.  The final sequence number 
  1689. in a range has the string "E0" appended to it, which doesn't affect its numeric 
  1690. value, but gives you something to search for if you want to exclude the 
  1691. endpoint.  You can exclude the beginning point by waiting for the sequence 
  1692. number to be greater than 1.  If either operand of scalar ".." is a numeric 
  1693. literal, that operand is implicitly compared to the $. variable, the current 
  1694. line number.  Examples: 
  1695.  
  1696. As a scalar operator: 
  1697.  
  1698.     if (101 .. 200) { print; }  # print 2nd hundred lines
  1699.     next line if (1 .. /^$/);   # skip header lines
  1700.     s/^/> / if (/^$/ .. eof()); # quote body
  1701.  
  1702. As a list operator: 
  1703.  
  1704.     for (101 .. 200) { print; } # print $_ 100 times
  1705.     @foo = @foo[$[ .. $#foo];   # an expensive no-op
  1706.     @foo = @foo[$#foo-4 .. $#foo];      # slice last 5 items
  1707.  
  1708. The range operator (in a list context) makes use of the magical autoincrement 
  1709. algorithm if the operaands are strings.  You can say 
  1710.  
  1711.     @alphabet = ('A' .. 'Z');
  1712.  
  1713. to get all the letters of the alphabet, or 
  1714.  
  1715.     $hexdigit = (0 .. 9, 'a' .. 'f')[$num & 15];
  1716.  
  1717. to get a hexadecimal digit, or 
  1718.  
  1719.     @z2 = ('01' .. '31');  print $z2[$mday];
  1720.  
  1721. to get dates with leading zeros.  If the final value specified is not in the 
  1722. sequence that the magical increment would produce, the sequence goes until the 
  1723. next value would be longer than the final value specified. 
  1724.  
  1725. Conditional Operator 
  1726.  
  1727. Ternary "?:" is the conditional operator, just as in C.  It works much like an 
  1728. if-then-else.  If the argument before the ? is true, the argument before the : 
  1729. is returned, otherwise the argument after the : is returned.  For example: 
  1730.  
  1731.     printf "I have %d dog%s.\n", $n,
  1732.             ($n == 1) ? '' : "s";
  1733.  
  1734. Scalar or list context propagates downward into the 2nd or 3rd argument, 
  1735. whichever is selected. 
  1736.  
  1737.     $a = $ok ? $b : $c;  # get a scalar
  1738.     @a = $ok ? @b : @c;  # get an array
  1739.     $a = $ok ? @b : @c;  # oops, that's just a count!
  1740.  
  1741. The operator may be assigned to if both the 2nd and 3rd arguments are legal 
  1742. lvalues (meaning that you can assign to them): 
  1743.  
  1744.     ($a_or_b ? $a : $b) = $c;
  1745.  
  1746. This is not necessarily guaranteed to contribute to the readability of your 
  1747. program. 
  1748.  
  1749. Assignment Operators 
  1750.  
  1751. "=" is the ordinary assignment operator. 
  1752.  
  1753. Assignment operators work as in C.  That is, 
  1754.  
  1755.     $a += 2;
  1756.  
  1757. is equivalent to 
  1758.  
  1759.     $a = $a + 2;
  1760.  
  1761. although without duplicating any side effects that dereferencing the lvalue 
  1762. might trigger, such as from tie().  Other assignment operators work similarly. 
  1763. The following are recognized: 
  1764.  
  1765.     **=    +=    *=    &=    <<=    &&=
  1766.            -=    /=    |=    >>=    ||=
  1767.            .=    %=    ^=
  1768.                  x=
  1769.  
  1770. Note that while these are grouped by family, they all have the precedence of 
  1771. assignment. 
  1772.  
  1773. Unlike in C, the assignment operator produces a valid lvalue.  Modifying an 
  1774. assignment is equivalent to doing the assignment and then modifying the 
  1775. variable that was assigned to.  This is useful for modifying a copy of 
  1776. something, like this: 
  1777.  
  1778.     ($tmp = $global) =~ tr [A-Z] [a-z];
  1779.  
  1780. Likewise, 
  1781.  
  1782.     ($a += 2) *= 3;
  1783.  
  1784. is equivalent to 
  1785.  
  1786.     $a += 2;
  1787.     $a *= 3;
  1788.  
  1789. Comma Operator 
  1790.  
  1791. Binary "," is the comma operator.  In a scalar context it evaluates its left 
  1792. argument, throws that value away, then evaluates its right argument and returns 
  1793. that value.  This is just like C's comma operator. 
  1794.  
  1795. In a list context, it's just the list argument separator, and inserts both its 
  1796. arguments into the list. 
  1797.  
  1798. The => digraph is mostly just a synonym for the comma operator.  It's useful 
  1799. for documenting arguments that come in pairs.  As of release 5.001, it also 
  1800. forces any word to the left of it to be interpreted as a string. 
  1801.  
  1802. List Operators (Rightward) 
  1803.  
  1804. On the right side of a list operator, it has very low precedence, such that it 
  1805. controls all comma-separated expressions found there. The only operators with 
  1806. lower precedence are the logical operators "and", "or", and "not", which may be 
  1807. used to evaluate calls to list operators without the need for extra 
  1808. parentheses: 
  1809.  
  1810.     open HANDLE, "filename"
  1811.         or die "Can't open: $!\n";
  1812.  
  1813. See also discussion of list operators in L<List Operators (Leftward)>. 
  1814.  
  1815. Logical Not 
  1816.  
  1817. Unary "not" returns the logical negation of the expression to its right. It's 
  1818. the equivalent of "!" except for the very low precedence. 
  1819.  
  1820. Logical And 
  1821.  
  1822. Binary "and" returns the logical conjunction of the two surrounding 
  1823. expressions.  It's equivalent to && except for the very low precedence.  This 
  1824. means that it short-circuits: i.e. the right expression is evaluated only if 
  1825. the left expression is true. 
  1826.  
  1827. Logical or and Exclusive Or 
  1828.  
  1829. Binary "or" returns the logical disjunction of the two surrounding expressions. 
  1830. It's equivalent to || except for the very low precedence.  This means that it 
  1831. short-circuits: i.e. the right expression is evaluated only if the left 
  1832. expression is false. 
  1833.  
  1834. Binary "xor" returns the exclusive-OR of the two surrounding expressions. It 
  1835. cannot short circuit, of course. 
  1836.  
  1837. C Operators Missing From Perl 
  1838.  
  1839. Here is what C has that Perl doesn't: 
  1840.  
  1841. unary & 
  1842.  
  1843. Address-of operator.  (But see the "\" operator for taking a reference.) 
  1844.  
  1845. unary * 
  1846.  
  1847. Dereference-address operator. (Perl's prefix dereferencing operators are typed: 
  1848. $, @, %, and &.) 
  1849.  
  1850. (TYPE) 
  1851.  
  1852. Type casting operator. 
  1853.  
  1854. Quote and Quotelike Operators 
  1855.  
  1856. While we usually think of quotes as literal values, in Perl they function as 
  1857. operators, providing various kinds of interpolating and pattern matching 
  1858. capabilities.  Perl provides customary quote characters for these behaviors, 
  1859. but also provides a way for you to choose your quote character for any of them. 
  1860. In the following table, a {} represents any pair of delimiters you choose. 
  1861. Non-bracketing delimiters use the same character fore and aft, but the 4 sorts 
  1862. of brackets (round, angle, square, curly) will all nest. 
  1863.  
  1864.     Customary  Generic     Meaning    Interpolates
  1865.         ''       q{}       Literal         no
  1866.         ""      qq{}       Literal         yes
  1867.         ``      qx{}       Command         yes
  1868.                 qw{}      Word list        no
  1869.         //       m{}    Pattern match      yes
  1870.                  s{}{}   Substitution      yes
  1871.                 tr{}{}   Translation       no
  1872.  
  1873. For constructs that do interpolation, variables beginning with "$" or "@" are 
  1874. interpolated, as are the following sequences: 
  1875.  
  1876.     \t          tab
  1877.     \n          newline
  1878.     \r          return
  1879.     \f          form feed
  1880.     \v          vertical tab, whatever that is
  1881.     \b          backspace
  1882.     \a          alarm (bell)
  1883.     \e          escape
  1884.     \033        octal char
  1885.     \x1b        hex char
  1886.     \c[         control char
  1887.     \l          lowercase next char
  1888.     \u          uppercase next char
  1889.     \L          lowercase till \E
  1890.     \U          uppercase till \E
  1891.     \E          end case modification
  1892.     \Q          quote regexp metacharacters till \E
  1893.  
  1894. Patterns are subject to an additional level of interpretation as a regular 
  1895. expression.  This is done as a second pass, after variables are interpolated, 
  1896. so that regular expressions may be incorporated into the pattern from the 
  1897. variables.  If this is not what you want, use \Q to interpolate a variable 
  1898. literally. 
  1899.  
  1900. Apart from the above, there are no multiple levels of interpolation.  In 
  1901. particular, contrary to the expectations of shell programmers, backquotes do 
  1902. NOT interpolate within double quotes, nor do single quotes impede evaluation of 
  1903. variables when used within double quotes. 
  1904.  
  1905. Regexp Quotelike Operators 
  1906.  
  1907. Here are the quotelike operators that apply to pattern matching and related 
  1908. activities. 
  1909.  
  1910. ?PATTERN? 
  1911.  
  1912. This is just like the /pattern/ search, except that it matches only once 
  1913. between calls to the reset() operator.  This is a useful optimization when you 
  1914. only want to see the first occurrence of something in each file of a set of 
  1915. files, for instance.  Only ?? patterns local to the current package are reset. 
  1916. This usage is vaguely deprecated, and may be removed in some future version of 
  1917. Perl. 
  1918.  
  1919. m/PATTERN/gimosx 
  1920.  
  1921. /PATTERN/gimosx 
  1922.  
  1923. Searches a string for a pattern match, and in a scalar context returns true (1) 
  1924. or false ('').  If no string is specified via the =~ or !~ operator, the $_ 
  1925. string is searched.  (The string specified with =~ need not be an lvalue--it 
  1926. may be the result of an expression evaluation, but remember the =~ binds rather 
  1927. tightly.)  See also perlre. Options are: 
  1928.  
  1929.     g   Match globally, i.e. find all occurrences.
  1930.     i   Do case-insensitive pattern matching.
  1931.     m   Treat string as multiple lines.
  1932.     o   Only compile pattern once.
  1933.     s   Treat string as single line.
  1934.     x   Use extended regular expressions.
  1935.  
  1936. If "/" is the delimiter then the initial m is optional.  With the m you can use 
  1937. any pair of non-alphanumeric, non-whitespace characters as delimiters.  This is 
  1938. particularly useful for matching Unix path names that contain "/", to avoid LTS 
  1939. (leaning toothpick syndrome). PATTERN may contain variables, which will be 
  1940. interpolated (and the pattern recompiled) every time the pattern search is 
  1941. evaluated.  (Note that $) and $| might not be interpolated because they look 
  1942. like end-of-string tests.)  If you want such a pattern to be compiled only 
  1943. once, add a /o after the trailing delimiter.  This avoids expensive run-time 
  1944. recompilations, and is useful when the value you are interpolating won't change 
  1945. over the life of the script.  However, mentioning /o constitutes a promise that 
  1946. you won't change the variables in the pattern. If you change them, Perl won't 
  1947. even notice. If the PATTERN evaluates to a null string, the last successfully 
  1948. executed regular expression is used instead. If used in a context that requires 
  1949. a list value, a pattern match returns a list consisting of the subexpressions 
  1950. matched by the parentheses in the pattern, i.e. ($1, $2, $3...).  (Note that 
  1951. here $1 etc. are also set, and that this differs from Perl 4's behavior.)  If 
  1952. the match fails, a null array is returned.  If the match succeeds, but there 
  1953. were no parentheses, a list value of (1) is returned. Examples: 
  1954.  
  1955.     open(TTY, '/dev/tty');
  1956.     <TTY> =~ /^y/i && foo();    # do foo if desired
  1957.  
  1958.     if (/Version: *([0-9.]*)/) { $version = $1; }
  1959.  
  1960.     next if m#^/usr/spool/uucp#;
  1961.  
  1962.     # poor man's grep
  1963.     $arg = shift;
  1964.     while (<>) {
  1965.         print if /$arg/o;       # compile only once
  1966.     }
  1967.  
  1968.     if (($F1, $F2, $Etc) = ($foo =~ /^(\S+)\s+(\S+)\s*(.*)/))
  1969.  
  1970. This last example splits $foo into the first two words and the remainder of the 
  1971. line, and assigns those three fields to $F1, $F2 and $Etc.  The conditional is 
  1972. true if any variables were assigned, i.e. if the pattern matched. The /g 
  1973. modifier specifies global pattern matching--that is, matching as many times as 
  1974. possible within the string.  How it behaves depends on the context.  In a list 
  1975. context, it returns a list of all the substrings matched by all the parentheses 
  1976. in the regular expression. If there are no parentheses, it returns a list of 
  1977. all the matched strings, as if there were parentheses around the whole pattern. 
  1978. In a scalar context, m//g iterates through the string, returning TRUE each time 
  1979. it matches, and FALSE when it eventually runs out of matches.  (In other words, 
  1980. it remembers where it left off last time and restarts the search at that point. 
  1981. You can actually find the current match position of a string using the pos() 
  1982. function--see perlfunc.) If you modify the string in any way, the match 
  1983. position is reset to the beginning.  Examples: 
  1984.  
  1985.     # list context
  1986.     ($one,$five,$fifteen) = (`uptime` =~ /(\d+\.\d+)/g);
  1987.  
  1988.     # scalar context
  1989.     $/ = ""; $* = 1;  # $* deprecated in Perl 5
  1990.     while ($paragraph = <>) {
  1991.         while ($paragraph =~ /[a-z]['")]*[.!?]+['")]*\s/g) {
  1992.             $sentences++;
  1993.         }
  1994.     }
  1995.     print "$sentences\n";
  1996.  
  1997. q/STRING/ 
  1998.  
  1999. 'STRING' 
  2000.  
  2001. A single-quoted, literal string.  Backslashes are ignored, unless followed by 
  2002. the delimiter or another backslash, in which case the delimiter or backslash is 
  2003. interpolated. 
  2004.  
  2005.     $foo = q!I said, "You said, 'She said it.'"!;
  2006.     $bar = q('This is it.');
  2007.  
  2008. qq/STRING/ 
  2009.  
  2010. "STRING" 
  2011.  
  2012. A double-quoted, interpolated string. 
  2013.  
  2014.     $_ .= qq
  2015.      (*** The previous line contains the naughty word "$1".\n)
  2016.                 if /(tcl|rexx|python)/;      # :-)
  2017.  
  2018. qx/STRING/ 
  2019.  
  2020. `STRING` 
  2021.  
  2022. A string which is interpolated and then executed as a system command. The 
  2023. collected standard output of the command is returned.  In scalar context, it 
  2024. comes back as a single (potentially multi-line) string. In list context, 
  2025. returns a list of lines (however you've defined lines with $/ or 
  2026. $INPUT_RECORD_SEPARATOR). 
  2027.  
  2028.     $today = qx{ date };
  2029.  
  2030. See L<I/O Operators> for more discussion. 
  2031.  
  2032. qw/STRING/ 
  2033.  
  2034. Returns a list of the words extracted out of STRING, using embedded whitespace 
  2035. as the word delimiters.  It is exactly equivalent to 
  2036.  
  2037.     split(' ', q/STRING/);
  2038.  
  2039. Some frequently seen examples: 
  2040.  
  2041.     use POSIX qw( setlocale localeconv )
  2042.     @EXPORT = qw( foo bar baz );
  2043.  
  2044. s/PATTERN/REPLACEMENT/egimosx 
  2045.  
  2046. Searches a string for a pattern, and if found, replaces that pattern with the 
  2047. replacement text and returns the number of substitutions made.  Otherwise it 
  2048. returns false (0). If no string is specified via the =~ or !~ operator, the $_ 
  2049. variable is searched and modified.  (The string specified with =~ must be a 
  2050. scalar variable, an array element, a hash element, or an assignment to one of 
  2051. those, i.e. an lvalue.) If the delimiter chosen is single quote, no variable 
  2052. interpolation is done on either the PATTERN or the REPLACEMENT.  Otherwise, if 
  2053. the PATTERN contains a $ that looks like a variable rather than an 
  2054. end-of-string test, the variable will be interpolated into the pattern at 
  2055. run-time.  If you only want the pattern compiled once the first time the 
  2056. variable is interpolated, use the /o option.  If the pattern evaluates to a 
  2057. null string, the last successfully executed regular expression is used instead. 
  2058. See perlre for further explanation on these. Options are: 
  2059.  
  2060.     e   Evaluate the right side as an expression.
  2061.     g   Replace globally, i.e. all occurrences.
  2062.     i   Do case-insensitive pattern matching.
  2063.     m   Treat string as multiple lines.
  2064.     o   Only compile pattern once.
  2065.     s   Treat string as single line.
  2066.     x   Use extended regular expressions.
  2067.  
  2068. Any non-alphanumeric, non-whitespace delimiter may replace the slashes.  If 
  2069. single quotes are used, no interpretation is done on the replacement string 
  2070. (the /e modifier overrides this, however).  If backquotes are used, the 
  2071. replacement string is a command to execute whose output will be used as the 
  2072. actual replacement text.  If the PATTERN is delimited by bracketing quotes, the 
  2073. REPLACEMENT has its own pair of quotes, which may or may not be bracketing 
  2074. quotes, e.g. s(foo)(bar) or s<foo/bar/>.  A /e will cause the replacement 
  2075. portion to be interpreter as a full-fledged Perl expression and eval()ed right 
  2076. then and there.  It is, however, syntax checked at compile-time. Examples: 
  2077.  
  2078.     s/\bgreen\b/mauve/g;                # don't change wintergreen
  2079.  
  2080.     $path =~ s|/usr/bin|/usr/local/bin|;
  2081.  
  2082.     s/Login: $foo/Login: $bar/; # run-time pattern
  2083.  
  2084.     ($foo = $bar) =~ s/this/that/;
  2085.  
  2086.     $count = ($paragraph =~ s/Mister\b/Mr./g);
  2087.  
  2088.     $_ = 'abc123xyz';
  2089.     s/\d+/$&*2/e;               # yields 'abc246xyz'
  2090.     s/\d+/sprintf("%5d",$&)/e;  # yields 'abc  246xyz'
  2091.     s/\w/$& x 2/eg;             # yields 'aabbcc  224466xxyyzz'
  2092.  
  2093.     s/%(.)/$percent{$1}/g;      # change percent escapes; no /e
  2094.     s/%(.)/$percent{$1} || $&/ge;       # expr now, so /e
  2095.     s/^=(\w+)/&pod($1)/ge;      # use function call
  2096.  
  2097.     # /e's can even nest;  this will expand
  2098.     # simple embedded variables in $_
  2099.     s/(\$\w+)/$1/eeg;
  2100.  
  2101.     # Delete C comments.
  2102.     $program =~ s {
  2103.         /\*     # Match the opening delimiter.
  2104.         .*?     # Match a minimal number of characters.
  2105.         \*/     # Match the closing delimiter.
  2106.     } []gsx;
  2107.  
  2108.     s/^\s*(.*?)\s*$/$1/;        # trim white space
  2109.  
  2110.     s/([^ ]*) *([^ ]*)/$2 $1/;  # reverse 1st two fields
  2111.  
  2112. Note the use of $ instead of \ in the last example.  Unlike sed, we only use 
  2113. the \<digit> form in the left hand side. Anywhere else it's $<digit>. 
  2114. Occasionally, you can't just use a /g to get all the changes to occur.  Here 
  2115. are two common cases: 
  2116.  
  2117.     # put commas in the right places in an integer
  2118.     1 while s/(.*\d)(\d\d\d)/$1,$2/g;      # perl4
  2119.     1 while s/(\d)(\d\d\d)(?!\d)/$1,$2/g;  # perl5
  2120.  
  2121.     # expand tabs to 8-column spacing
  2122.     1 while s/\t+/' ' x (length($&)*8 - length($`)%8)/e;
  2123.  
  2124. tr/SEARCHLIST/REPLACEMENTLIST/cds 
  2125.  
  2126. y/SEARCHLIST/REPLACEMENTLIST/cds 
  2127.  
  2128. Translates all occurrences of the characters found in the search list with the 
  2129. corresponding character in the replacement list.  It returns the number of 
  2130. characters replaced or deleted.  If no string is specified via the =~ or !~ 
  2131. operator, the $_ string is translated.  (The string specified with =~ must be a 
  2132. scalar variable, an array element, or an assignment to one of those, i.e. an 
  2133. lvalue.)  For sed devotees, y is provided as a synonym for tr.  If the 
  2134. SEARCHLIST is delimited by bracketing quotes, the REPLACEMENTLIST has its own 
  2135. pair of quotes, which may or may not be bracketing quotes, e.g. tr[A-Z][a-z] or 
  2136. tr(+-*/)/ABCD/. Options: 
  2137.  
  2138.     c   Complement the SEARCHLIST.
  2139.     d   Delete found but unreplaced characters.
  2140.     s   Squash duplicate replaced characters.
  2141.  
  2142. If the /c modifier is specified, the SEARCHLIST character set is complemented. 
  2143. If the /d modifier is specified, any characters specified by SEARCHLIST not 
  2144. found in REPLACEMENTLIST are deleted.  (Note that this is slightly more 
  2145. flexible than the behavior of some tr programs, which delete anything they find 
  2146. in the SEARCHLIST, period.) If the /s modifier is specified, sequences of 
  2147. characters that were translated to the same character are squashed down to a 
  2148. single instance of the character. If the /d modifier is used, the 
  2149. REPLACEMENTLIST is always interpreted exactly as specified.  Otherwise, if the 
  2150. REPLACEMENTLIST is shorter than the SEARCHLIST, the final character is 
  2151. replicated till it is long enough.  If the REPLACEMENTLIST is null, the 
  2152. SEARCHLIST is replicated. This latter is useful for counting characters in a 
  2153. class or for squashing character sequences in a class. Examples: 
  2154.  
  2155.     $ARGV[1] =~ tr/A-Z/a-z/;    # canonicalize to lower case
  2156.  
  2157.     $cnt = tr/*/*/;             # count the stars in $_
  2158.  
  2159.     $cnt = $sky =~ tr/*/*/;     # count the stars in $sky
  2160.  
  2161.     $cnt = tr/0-9//;            # count the digits in $_
  2162.  
  2163.     tr/a-zA-Z//s;               # bookkeeper -> bokeper
  2164.  
  2165.     ($HOST = $host) =~ tr/a-z/A-Z/;
  2166.  
  2167.     tr/a-zA-Z/ /cs;             # change non-alphas to single space
  2168.  
  2169.     tr [\200-\377]
  2170.        [\000-\177];             # delete 8th bit
  2171.  
  2172. If multiple translations are given for a character, only the first one is used: 
  2173.  
  2174.     tr/AAA/XYZ/
  2175.  
  2176. will translate any A to X. Note that because the translation table is built at 
  2177. compile time, neither the SEARCHLIST nor the REPLACEMENTLIST are subjected to 
  2178. double quote interpolation.  That means that if you want to use variables, you 
  2179. must use an eval(): 
  2180.  
  2181.     eval "tr/$oldlist/$newlist/";
  2182.     die $@ if $@;
  2183.  
  2184.     eval "tr/$oldlist/$newlist/, 1" or die $@;
  2185.  
  2186. I/O Operators 
  2187.  
  2188. There are several I/O operators you should know about. A string is enclosed by 
  2189. backticks (grave accents) first undergoes variable substitution just like a 
  2190. double quoted string.  It is then interpreted as a command, and the output of 
  2191. that command is the value of the pseudo-literal, like in a shell.  In a scalar 
  2192. context, a single string consisting of all the output is returned.  In a list 
  2193. context, a list of values is returned, one for each line of output.  (You can 
  2194. set $/ to use a different line terminator.)  The command is executed each time 
  2195. the pseudo-literal is evaluated.  The status value of the command is returned 
  2196. in $? (see perlvar for the interpretation of $?).  Unlike in csh, no 
  2197. translation is done on the return data--newlines remain newlines.  Unlike in 
  2198. any of the shells, single quotes do not hide variable names in the command from 
  2199. interpretation. To pass a $ through to the shell you need to hide it with a 
  2200. backslash. The generalized form of backticks is qx//.  (Because backticks 
  2201. always undergo shell expansion as well, see perlsec for security concerns.) 
  2202.  
  2203. Evaluating a filehandle in angle brackets yields the next line from that file 
  2204. (newline included, so it's never false until end of file, at which time an 
  2205. undefined value is returned).  Ordinarily you must assign that value to a 
  2206. variable, but there is one situation where an automatic assignment happens.  If 
  2207. and ONLY if the input symbol is the only thing inside the conditional of a 
  2208. while loop, the value is automatically assigned to the variable $_.  The 
  2209. assigned value is then tested to see if it is defined.  (This may seem like an 
  2210. odd thing to you, but you'll use the construct in almost every Perl script you 
  2211. write.)  Anyway, the following lines are equivalent to each other: 
  2212.  
  2213.     while (defined($_ = <STDIN>)) { print; }
  2214.     while (<STDIN>) { print; }
  2215.     for (;<STDIN>;) { print; }
  2216.     print while defined($_ = <STDIN>);
  2217.     print while <STDIN>;
  2218.  
  2219. The filehandles STDIN, STDOUT and STDERR are predefined.  (The filehandles 
  2220. stdin, stdout and stderr will also work except in packages, where they would be 
  2221. interpreted as local identifiers rather than global.)  Additional filehandles 
  2222. may be created with the open() function.  See perlfunc/open() for details on 
  2223. this. 
  2224.  
  2225. If a <FILEHANDLE> is used in a context that is looking for a list, a list 
  2226. consisting of all the input lines is returned, one line per list element.  It's 
  2227. easy to make a LARGE data space this way, so use with care. 
  2228.  
  2229. The null filehandle <> is special and can be used to emulate the behavior of 
  2230. sed and awk.  Input from <> comes either from standard input, or from each file 
  2231. listed on the command line.  Here's how it works: the first time <> is 
  2232. evaluated, the @ARGV array is checked, and if it is null, $ARGV[0] is set to 
  2233. "-", which when opened gives you standard input.  The @ARGV array is then 
  2234. processed as a list of filenames.  The loop 
  2235.  
  2236.     while (<>) {
  2237.         ...                     # code for each line
  2238.     }
  2239.  
  2240. is equivalent to the following Perl-like pseudo code: 
  2241.  
  2242.     unshift(@ARGV, '-') if $#ARGV < $[;
  2243.     while ($ARGV = shift) {
  2244.         open(ARGV, $ARGV);
  2245.         while (<ARGV>) {
  2246.             ...         # code for each line
  2247.         }
  2248.     }
  2249.  
  2250. except that it isn't so cumbersome to say, and will actually work.  It really 
  2251. does shift array @ARGV and put the current filename into variable $ARGV.  It 
  2252. also uses filehandle ARGV internally--<> is just a synonym for <ARGV>, which is 
  2253. magical.  (The pseudo code above doesn't work because it treats <ARGV> as 
  2254. non-magical.) 
  2255.  
  2256. You can modify @ARGV before the first <> as long as the array ends up 
  2257. containing the list of filenames you really want.  Line numbers ($.) continue 
  2258. as if the input were one big happy file.  (But see example under eof() for how 
  2259. to reset line numbers on each file.) 
  2260.  
  2261. If you want to set @ARGV to your own list of files, go right ahead.  If you 
  2262. want to pass switches into your script, you can use one of the Getopts modules 
  2263. or put a loop on the front like this: 
  2264.  
  2265.     while ($_ = $ARGV[0], /^-/) {
  2266.         shift;
  2267.         last if /^--$/;
  2268.         if (/^-D(.*)/) { $debug = $1 }
  2269.         if (/^-v/)     { $verbose++  }
  2270.         ...             # other switches
  2271.     }
  2272.     while (<>) {
  2273.         ...             # code for each line
  2274.     }
  2275.  
  2276. The <> symbol will return FALSE only once.  If you call it again after this it 
  2277. will assume you are processing another @ARGV list, and if you haven't set 
  2278. @ARGV, will input from STDIN. 
  2279.  
  2280. If the string inside the angle brackets is a reference to a scalar variable 
  2281. (e.g. <$foo>), then that variable contains the name of the filehandle to input 
  2282. from, or a reference to the same.  For example: 
  2283.  
  2284.     $fh = \*STDIN;
  2285.     $line = <$fh>;
  2286.  
  2287. If the string inside angle brackets is not a filehandle or a scalar variable 
  2288. containing a filehandle name or reference, then it is interpreted as a filename 
  2289. pattern to be globbed, and either a list of filenames or the next filename in 
  2290. the list is returned, depending on context.  One level of $ interpretation is 
  2291. done first, but you can't say <$foo> because that's an indirect filehandle as 
  2292. explained in the previous paragraph.  In older version of Perl, programmers 
  2293. would insert curly brackets to force interpretation as a filename glob: 
  2294. <${foo}>. These days, it's consdired cleaner to call the internal function 
  2295. directly as glob($foo), which is probably the right way to have done it in the 
  2296. first place.)  Example: 
  2297.  
  2298.     while (<*.c>) {
  2299.         chmod 0644, $_;
  2300.     }
  2301.  
  2302. is equivalent to 
  2303.  
  2304.     open(FOO, "echo *.c | tr -s ' \t\r\f' '\\012\\012\\012\\012'|");
  2305.     while (<FOO>) {
  2306.         chop;
  2307.         chmod 0644, $_;
  2308.     }
  2309.  
  2310. In fact, it's currently implemented that way.  (Which means it will not work on 
  2311. filenames with spaces in them unless you have csh(1) on your machine.)  Of 
  2312. course, the shortest way to do the above is: 
  2313.  
  2314.     chmod 0644, <*.c>;
  2315.  
  2316. Because globbing invokes a shell, it's often faster to call readdir() yourself 
  2317. and just do your own grep() on the filenames.  Furthermore, due to its current 
  2318. implementation of using a shell, the glob() routine may get "Arg list too long" 
  2319. errors (unless you've installed tcsh(1L) as /bin/csh). 
  2320.  
  2321. A glob only evaluates its (embedded) argument when it is starting a new list. 
  2322. All values must be read before it will start over.  In a list context this 
  2323. isn't important, because you automatically get them all anyway.  In a scalar 
  2324. context, however, the operator returns the next value each time it is called, 
  2325. or a FALSE value if you've just run out.  Again, FALSE is returned only once. 
  2326. So if you're expecting a single value from a glob, it is much better to say 
  2327.  
  2328.     ($file) = <blurch*>;
  2329.  
  2330. than 
  2331.  
  2332.     $file = <blurch*>;
  2333.  
  2334. because the latter will alternate between returning a filename and returning 
  2335. FALSE. 
  2336.  
  2337. It you're trying to do variable interpolation, it's definitely better to use 
  2338. the glob() function, because the older notation can cause people to become 
  2339. confused with the indirect filehandle notatin. 
  2340.  
  2341.     @files = glob("$dir/*.[ch]");
  2342.     @files = glob($files[$i]);
  2343.  
  2344. Constant Folding 
  2345.  
  2346. Like C, Perl does a certain amount of expression evaluation at compile time, 
  2347. whenever it determines that all of the arguments to an operator are static and 
  2348. have no side effects.  In particular, string concatenation happens at compile 
  2349. time between literals that don't do variable substitution.  Backslash 
  2350. interpretation also happens at compile time.  You can say 
  2351.  
  2352.     'Now is the time for all' . "\n" .
  2353.         'good men to come to.'
  2354.  
  2355. and this all reduces to one string internally.  Likewise, if you say 
  2356.  
  2357.     foreach $file (@filenames) {
  2358.         if (-s $file > 5 + 100 * 2**16) { ... }
  2359.     }
  2360.  
  2361. the compiler will pre-compute the number that expression represents so that the 
  2362. interpreter won't have to. 
  2363.  
  2364. Integer arithmetic 
  2365.  
  2366. By default Perl assumes that it must do most of its arithmetic in floating 
  2367. point.  But by saying 
  2368.  
  2369.     use integer;
  2370.  
  2371. you may tell the compiler that it's okay to use integer operations from here to 
  2372. the end of the enclosing BLOCK.  An inner BLOCK may countermand this by saying 
  2373.  
  2374.     no integer;
  2375.  
  2376. which lasts until the end of that BLOCK. 
  2377.  
  2378.  
  2379. ΓòÉΓòÉΓòÉ 7. Section - perlre ΓòÉΓòÉΓòÉ
  2380.  
  2381. NAME 
  2382.  
  2383. perlre - Perl regular expressions 
  2384.  
  2385. DESCRIPTION 
  2386.  
  2387. This page describes the syntax of regular expressions in Perl.  For a 
  2388. description of how to actually use regular expressions in matching operations, 
  2389. plus various examples of the same, see m// and s/// in perlop. 
  2390.  
  2391. The matching operations can have various modifiers, some of which relate to the 
  2392. interpretation of the regular expression inside.  These are: 
  2393.  
  2394.     i   Do case-insensitive pattern matching.
  2395.     m   Treat string as multiple lines.
  2396.     s   Treat string as single line.
  2397.     x   Extend your pattern's legibility with whitespace and comments.
  2398.  
  2399. These are usually written as "the /x modifier", even though the delimiter in 
  2400. question might not actually be a slash.  In fact, any of these modifiers may 
  2401. also be embedded within the regular expression itself using the new (?...) 
  2402. construct.  See below. 
  2403.  
  2404. The /x modifier itself needs a little more explanation.  It tells the regular 
  2405. expression parser to ignore whitespace that is not backslashed or within a 
  2406. character class.  You can use this to break up your regular expression into 
  2407. (slightly) more readable parts.  The # character is also treated as a 
  2408. metacharacter introducing a comment, just as in ordinary Perl code.  Taken 
  2409. together, these features go a long way towards making Perl 5 a readable 
  2410. language.  See the C comment deletion code in perlop. 
  2411.  
  2412. Regular Expressions 
  2413.  
  2414. The patterns used in pattern matching are regular expressions such as those 
  2415. supplied in the Version 8 regexp routines.  (In fact, the routines are derived 
  2416. (distantly) from Henry Spencer's freely redistributable reimplementation of the 
  2417. V8 routines.) See L<Version 8 Regular Expressions> for details. 
  2418.  
  2419. In particular the following metacharacters have their standard egrep-ish 
  2420. meanings: 
  2421.  
  2422.     \   Quote the next metacharacter
  2423.     ^   Match the beginning of the line
  2424.     .   Match any character (except newline)
  2425.     $   Match the end of the line (or before newline at the end)
  2426.     |   Alternation
  2427.     ()  Grouping
  2428.     []  Character class
  2429.  
  2430. By default, the "^" character is guaranteed to match only at the beginning of 
  2431. the string, the "$" character only at the end (or before the newline at the 
  2432. end) and Perl does certain optimizations with the assumption that the string 
  2433. contains only one line.  Embedded newlines will not be matched by "^" or "$". 
  2434. You may, however, wish to treat a string as a multi-line buffer, such that the 
  2435. "^" will match after any newline within the string, and "$" will match before 
  2436. any newline.  At the cost of a little more overhead, you can do this by using 
  2437. the /m modifier on the pattern match operator.  (Older programs did this by 
  2438. setting $*, but this practice is deprecated in Perl 5.) 
  2439.  
  2440. To facilitate multi-line substitutions, the "." character never matches a 
  2441. newline unless you use the /s modifier, which tells Perl to pretend the string 
  2442. is a single line--even if it isn't.  The /s modifier also overrides the setting 
  2443. of $*, in case you have some (badly behaved) older code that sets it in another 
  2444. module. 
  2445.  
  2446. The following standard quantifiers are recognized: 
  2447.  
  2448.     *      Match 0 or more times
  2449.     +      Match 1 or more times
  2450.     ?      Match 1 or 0 times
  2451.     {n}    Match exactly n times
  2452.     {n,}   Match at least n times
  2453.     {n,m}  Match at least n but not more than m times
  2454.  
  2455. (If a curly bracket occurs in any other context, it is treated as a regular 
  2456. character.)  The "*" modifier is equivalent to {0,}, the "+" modifier to {1,}, 
  2457. and the "?" modifier to {0,1}.  n and m are limited to integral values less 
  2458. than 65536. 
  2459.  
  2460. By default, a quantified subpattern is "greedy", that is, it will match as many 
  2461. times as possible without causing the rest pattern not to match.  The standard 
  2462. quantifiers are all "greedy", in that they match as many occurrences as 
  2463. possible (given a particular starting location) without causing the pattern to 
  2464. fail.  If you want it to match the minimum number of times possible, follow the 
  2465. quantifier with a "?" after any of them. Note that the meanings don't change, 
  2466. just the "gravity": 
  2467.  
  2468.     *?     Match 0 or more times
  2469.     +?     Match 1 or more times
  2470.     ??     Match 0 or 1 time
  2471.     {n}?   Match exactly n times
  2472.     {n,}?  Match at least n times
  2473.     {n,m}? Match at least n but not more than m times
  2474.  
  2475. Since patterns are processed as double quoted strings, the following also work: 
  2476.  
  2477.     \t          tab
  2478.     \n          newline
  2479.     \r          return
  2480.     \f          form feed
  2481.     \v          vertical tab, whatever that is
  2482.     \a          alarm (bell)
  2483.     \e          escape (think troff)
  2484.     \033        octal char (think of a PDP-11)
  2485.     \x1B        hex char
  2486.     \c[         control char
  2487.     \l          lowercase next char (think vi)
  2488.     \u          uppercase next char (think vi)
  2489.     \L          lowercase till \E (think vi)
  2490.     \U          uppercase till \E (think vi)
  2491.     \E          end case modification (think vi)
  2492.     \Q          quote regexp metacharacters till \E
  2493.  
  2494. In addition, Perl defines the following: 
  2495.  
  2496.     \w  Match a "word" character (alphanumeric plus "_")
  2497.     \W  Match a non-word character
  2498.     \s  Match a whitespace character
  2499.     \S  Match a non-whitespace character
  2500.     \d  Match a digit character
  2501.     \D  Match a non-digit character
  2502.  
  2503. Note that \w matches a single alphanumeric character, not a whole word.  To 
  2504. match a word you'd need to say \w+.  You may use \w, \W, \s, \S, \d and \D 
  2505. within character classes (though not as either end of a range). 
  2506.  
  2507. Perl defines the following zero-width assertions: 
  2508.  
  2509.     \b  Match a word boundary
  2510.     \B  Match a non-(word boundary)
  2511.     \A  Match only at beginning of string
  2512.     \Z  Match only at end of string (or before newline at the end)
  2513.     \G  Match only where previous m//g left off
  2514.  
  2515. A word boundary (\b) is defined as a spot between two characters that has a \w 
  2516. on one side of it and and a \W on the other side of it (in either order), 
  2517. counting the imaginary characters off the beginning and end of the string as 
  2518. matching a \W.  (Within character classes \b represents backspace rather than a 
  2519. word boundary.)  The \A and \Z are just like "^" and "$" except that they won't 
  2520. match multiple times when the /m modifier is used, while "^" and "$" will match 
  2521. at every internal line boundary.  To match the actual end of the string, not 
  2522. ignoring newline, you can use \Z(?!\n). 
  2523.  
  2524. When the bracketing construct ( ... ) is used, \<digit> matches the digit'th 
  2525. substring.  Outside of the pattern, always use "$" instead of "\" in front of 
  2526. the digit.  (The \<digit> notation can on rare occasion work outside the 
  2527. current pattern, this should not be relied upon.  See the WARNING below.) The 
  2528. scope of $<digit> (and $`, $&, and $') extends to the end of the enclosing 
  2529. BLOCK or eval string, or to the next successful pattern match, whichever comes 
  2530. first.  If you want to use parentheses to delimit subpattern (e.g. a set of 
  2531. alternatives) without saving it as a subpattern, follow the ( with a ?. 
  2532.  
  2533. You may have as many parentheses as you wish.  If you have more than 9 
  2534. substrings, the variables $10, $11, ... refer to the corresponding substring. 
  2535. Within the pattern, \10, \11, etc. refer back to substrings if there have been 
  2536. at least that many left parens before the backreference.  Otherwise (for 
  2537. backward compatibility) \10 is the same as \010, a backspace, and \11 the same 
  2538. as \011, a tab.  And so on.  (\1 through \9 are always backreferences.) 
  2539.  
  2540. $+ returns whatever the last bracket match matched.  $& returns the entire 
  2541. matched string.  ($0 used to return the same thing, but not any more.)  $` 
  2542. returns everything before the matched string.  $' returns everything after the 
  2543. matched string.  Examples: 
  2544.  
  2545.     s/^([^ ]*) *([^ ]*)/$2 $1/;     # swap first two words
  2546.  
  2547.     if (/Time: (..):(..):(..)/) {
  2548.         $hours = $1;
  2549.         $minutes = $2;
  2550.         $seconds = $3;
  2551.     }
  2552.  
  2553. You will note that all backslashed metacharacters in Perl are alphanumeric, 
  2554. such as \b, \w, \n.  Unlike some other regular expression languages, there are 
  2555. no backslashed symbols that aren't alphanumeric. So anything that looks like 
  2556. \\, \(, \), \<, \>, \{, or \} is always interpreted as a literal character, not 
  2557. a metacharacter.  This makes it simple to quote a string that you want to use 
  2558. for a pattern but that you are afraid might contain metacharacters.  Simply 
  2559. quote all the non-alphanumeric characters: 
  2560.  
  2561.     $pattern =~ s/(\W)/\\$1/g;
  2562.  
  2563. You can also use the built-in quotemeta() function to do this. An even easier 
  2564. way to quote metacharacters right in the match operator is to say 
  2565.  
  2566.     /$unquoted\Q$quoted\E$unquoted/
  2567.  
  2568. Perl 5 defines a consistent extension syntax for regular expressions. The 
  2569. syntax is a pair of parens with a question mark as the first thing within the 
  2570. parens (this was a syntax error in Perl 4).  The character after the question 
  2571. mark gives the function of the extension.  Several extensions are already 
  2572. supported: 
  2573.  
  2574. (?#text) 
  2575.  
  2576. A comment.  The text is ignored.  If the /x switch is used to enable whitespace 
  2577. formatting, a simple # will suffice. 
  2578.  
  2579. (?:regexp) 
  2580.  
  2581. This groups things like "()" but doesn't make backrefences like "()" does.  So 
  2582.  
  2583.     split(/\b(?:a|b|c)\b/)
  2584.  
  2585. is like 
  2586.  
  2587.     split(/\b(a|b|c)\b/)
  2588.  
  2589. but doesn't spit out extra fields. 
  2590.  
  2591. (?=regexp) 
  2592.  
  2593. A zero-width positive lookahead assertion.  For example, /\w+(?=\t)/ matches a 
  2594. word followed by a tab, without including the tab in $&. 
  2595.  
  2596. (?!regexp) 
  2597.  
  2598. A zero-width negative lookahead assertion.  For example /foo(?!bar)/ matches 
  2599. any occurrence of "foo" that isn't followed by "bar".  Note however that 
  2600. lookahead and lookbehind are NOT the same thing.  You cannot use this for 
  2601. lookbehind: /(?!foo)bar/ will not find an occurrence of "bar" that is preceded 
  2602. by something which is not "foo".  That's because the (?!foo) is just saying 
  2603. that the next thing cannot be "foo"--and it's not, it's a "bar", so "foobar" 
  2604. will match.  You would have to do something like /(?foo)...bar/ for that.  We 
  2605. say "like" because there's the case of your "bar" not having three characters 
  2606. before it.  You could cover that this way: /(?:(?!foo)...|^..?)bar/.  Sometimes 
  2607. it's still easier just to say: 
  2608.  
  2609.     if (/foo/ && $` =~ /bar$/)
  2610.  
  2611. (?imsx) 
  2612.  
  2613. One or more embedded pattern-match modifiers.  This is particularly useful for 
  2614. patterns that are specified in a table somewhere, some of which want to be case 
  2615. sensitive, and some of which don't.  The case insensitive ones merely need to 
  2616. include (?i) at the front of the pattern.  For example: 
  2617.  
  2618.     $pattern = "foobar";
  2619.     if ( /$pattern/i )
  2620.  
  2621.     # more flexible:
  2622.  
  2623.     $pattern = "(?i)foobar";
  2624.     if ( /$pattern/ )
  2625.  
  2626. The specific choice of question mark for this and the new minimal matching 
  2627. construct was because 1) question mark is pretty rare in older regular 
  2628. expressions, and 2) whenever you see one, you should stop and "question" 
  2629. exactly what is going on.  That's psychology... 
  2630.  
  2631. Backtracking 
  2632.  
  2633. A fundamental feature of regular expression matching involves the notion called 
  2634. backtracking.  which is used (when needed) by all regular expression 
  2635. quantifiers, namely *, *?, +, +?, {n,m}, and {n,m}?. 
  2636.  
  2637. For a regular expression to match, the entire regular expression must match, 
  2638. not just part of it.  So if the beginning of a pattern containing a quantifier 
  2639. succeeds in a way that causes later parts in the pattern to fail, the matching 
  2640. engine backs up and recalculates the beginning part--that's why it's called 
  2641. backtracking. 
  2642.  
  2643. Here is an example of backtracking:  Let's say you want to find the word 
  2644. following "foo" in the string "Food is on the foo table.": 
  2645.  
  2646.     $_ = "Food is on the foo table.";
  2647.     if ( /\b(foo)\s+(\w+)/i ) {
  2648.         print "$2 follows $1.\n";
  2649.     }
  2650.  
  2651. When the match runs, the first part of the regular expression (\b(foo)) finds a 
  2652. possible match right at the beginning of the string, and loads up $1 with 
  2653. "Foo".  However, as soon as the matching engine sees that there's no whitespace 
  2654. following the "Foo" that it had saved in $1, it realizes its mistake and starts 
  2655. over again one character after where it had had the tentative match.  This time 
  2656. it goes all the way until the next occurrence of "foo". The complete regular 
  2657. expression matches this time, and you get the expected output of "table follows 
  2658. foo." 
  2659.  
  2660. Sometimes minimal matching can help a lot.  Imagine you'd like to match 
  2661. everything between "foo" and "bar".  Initially, you write something like this: 
  2662.  
  2663.     $_ =  "The food is under the bar in the barn.";
  2664.     if ( /foo(.*)bar/ ) {
  2665.         print "got <$1>\n";
  2666.     }
  2667.  
  2668. Which perhaps unexpectedly yields: 
  2669.  
  2670.   got <d is under the bar in the >
  2671.  
  2672. That's because .* was greedy, so you get everything between the first "foo" and 
  2673. the last "bar".  In this case, it's more effective to use minimal matching to 
  2674. make sure you get the text between a "foo" and the first "bar" thereafter. 
  2675.  
  2676.     if ( /foo(.*?)bar/ ) { print "got <$1>\n" }
  2677.   got <d is under the >
  2678.  
  2679. Here's another example: let's say you'd like to match a number at the end of a 
  2680. string, and you also want to keep the preceding part the match. So you write 
  2681. this: 
  2682.  
  2683.     $_ = "I have 2 numbers: 53147";
  2684.     if ( /(.*)(\d*)/ ) {                                # Wrong!
  2685.         print "Beginning is <$1>, number is <$2>.\n";
  2686.     }
  2687.  
  2688. That won't work at all, because .* was greedy and gobbled up the whole string. 
  2689. As \d* can match on an empty string the complete regular expression matched 
  2690. successfully. 
  2691.  
  2692.     Beginning is <I have 2: 53147>, number is <>.
  2693.  
  2694. Here are some variants, most of which don't work: 
  2695.  
  2696.     $_ = "I have 2 numbers: 53147";
  2697.     @pats = qw{
  2698.         (.*)(\d*)
  2699.         (.*)(\d+)
  2700.         (.*?)(\d*)
  2701.         (.*?)(\d+)
  2702.         (.*)(\d+)$
  2703.         (.*?)(\d+)$
  2704.         (.*)\b(\d+)$
  2705.         (.*\D)(\d+)$
  2706.     };
  2707.  
  2708.     for $pat (@pats) {
  2709.         printf "%-12s ", $pat;
  2710.         if ( /$pat/ ) {
  2711.             print "<$1> <$2>\n";
  2712.         } else {
  2713.             print "FAIL\n";
  2714.         }
  2715.     }
  2716.  
  2717. That will print out: 
  2718.  
  2719.     (.*)(\d*)    <I have 2 numbers: 53147> <>
  2720.     (.*)(\d+)    <I have 2 numbers: 5314> <7>
  2721.     (.*?)(\d*)   <> <>
  2722.     (.*?)(\d+)   <I have > <2>
  2723.     (.*)(\d+)$   <I have 2 numbers: 5314> <7>
  2724.     (.*?)(\d+)$  <I have 2 numbers: > <53147>
  2725.     (.*)\b(\d+)$ <I have 2 numbers: > <53147>
  2726.     (.*\D)(\d+)$ <I have 2 numbers: > <53147>
  2727.  
  2728. As you see, this can be a bit tricky.  It's important to realize that a regular 
  2729. expression is merely a set of assertions that gives a definition of success. 
  2730. There may be 0, 1, or several different ways that the definition might succeed 
  2731. against a particular string.  And if there are multiple ways it might succeed, 
  2732. you need to understand backtracking in order to know which variety of success 
  2733. you will achieve. 
  2734.  
  2735. When using lookahead assertions and negations, this can all get even tricker. 
  2736. Imagine you'd like to find a sequence of nondigits not followed by "123".  You 
  2737. might try to write that as 
  2738.  
  2739.         $_ = "ABC123";
  2740.         if ( /^\D*(?!123)/ ) {                          # Wrong!
  2741.             print "Yup, no 123 in $_\n";
  2742.         }
  2743.  
  2744. But that isn't going to match; at least, not the way you're hoping.  It claims 
  2745. that there is no 123 in the string.  Here's a clearer picture of why it that 
  2746. pattern matches, contrary to popular expectations: 
  2747.  
  2748.     $x = 'ABC123' ;
  2749.     $y = 'ABC445' ;
  2750.  
  2751.     print "1: got $1\n" if $x =~ /^(ABC)(?!123)/ ;
  2752.     print "2: got $1\n" if $y =~ /^(ABC)(?!123)/ ;
  2753.  
  2754.     print "3: got $1\n" if $x =~ /^(\D*)(?!123)/ ;
  2755.     print "4: got $1\n" if $y =~ /^(\D*)(?!123)/ ;
  2756.  
  2757. This prints 
  2758.  
  2759.     2: got ABC
  2760.     3: got AB
  2761.     4: got ABC
  2762.  
  2763. You might have expected test 3 to fail because it just seems to a more general 
  2764. purpose version of test 1.  The important difference between them is that test 
  2765. 3 contains a quantifier (\D*) and so can use backtracking, whereas test 1 will 
  2766. not.  What's happening is that you've asked "Is it true that at the start of 
  2767. $x, following 0 or more nondigits, you have something that's not 123?"  If the 
  2768. pattern matcher had let \D* expand to "ABC", this would have caused the whole 
  2769. pattern to fail. The search engine will initially match \D* with "ABC".  Then 
  2770. it will try to match (?!123 with "123" which, of course, fails.  But because a 
  2771. quantifier (\D*) has been used in the regular expression, the search engine can 
  2772. backtrack and retry the match differently in the hope of matching the complete 
  2773. regular expression. 
  2774.  
  2775. Well now, the pattern really, really wants to succeed, so it uses the standard 
  2776. regexp backoff-and-retry and lets \D* expand to just "AB" this time.  Now 
  2777. there's indeed something following "AB" that is not "123".  It's in fact 
  2778. "C123", which suffices. 
  2779.  
  2780. We can deal with this by using both an assertion and a negation.  We'll say 
  2781. that the first part in $1 must be followed by a digit, and in fact, it must 
  2782. also be followed by something that's not "123".  Remember that the lookaheads 
  2783. are zero-width expressions--they only look, but don't consume any of the string 
  2784. in their match.  So rewriting this way produces what you'd expect; that is, 
  2785. case 5 will fail, but case 6 succeeds: 
  2786.  
  2787.     print "5: got $1\n" if $x =~ /^(\D*)(?=\d)(?!123)/ ;
  2788.     print "6: got $1\n" if $y =~ /^(\D*)(?=\d)(?!123)/ ;
  2789.  
  2790.     6: got ABC
  2791.  
  2792. In other words, the two zero-width assertions next to each other work like 
  2793. they're ANDed together, just as you'd use any builtin assertions:  /^$/ matches 
  2794. only if you're at the beginning of the line AND the end of the line 
  2795. simultaneously.  The deeper underlying truth is that juxtaposition in regular 
  2796. expressions always means AND, except when you write an explicit OR using the 
  2797. vertical bar.  /ab/ means match "a" AND (then) match "b", although the 
  2798. attempted matches are made at different positions because "a" is not a 
  2799. zero-width assertion, but a one-width assertion. 
  2800.  
  2801. One warning: particularly complicated regular expressions can take exponential 
  2802. time to solve due to the immense number of possible ways they can use 
  2803. backtracking to try match.  For example this will take a very long time to run 
  2804.  
  2805.     /((a{0,5}){0,5}){0,5}/
  2806.  
  2807. And if you used *'s instead of limiting it to 0 through 5 matches, then it 
  2808. would take literally forever--or until you ran out of stack space. 
  2809.  
  2810. Version 8 Regular Expressions 
  2811.  
  2812. In case you're not familiar with the "regular" Version 8 regexp routines, here 
  2813. are the pattern-matching rules not described above. 
  2814.  
  2815. Any single character matches itself, unless it is a metacharacter with a 
  2816. special meaning described here or above.  You can cause characters which 
  2817. normally function as metacharacters to be interpreted literally by prefixing 
  2818. them with a "\" (e.g. "\." matches a ".", not any character; "\\" matches a 
  2819. "\").  A series of characters matches that series of characters in the target 
  2820. string, so the pattern blurfl would match "blurfl" in the target string. 
  2821.  
  2822. You can specify a character class, by enclosing a list of characters in [], 
  2823. which will match any one of the characters in the list.  If the first character 
  2824. after the "[" is "^", the class matches any character not in the list.  Within 
  2825. a list, the "-" character is used to specify a range, so that a-z represents 
  2826. all the characters between "a" and "z", inclusive. 
  2827.  
  2828. Characters may be specified using a metacharacter syntax much like that used in 
  2829. C: "\n" matches a newline, "\t" a tab, "\r" a carriage return, "\f" a form 
  2830. feed, etc.  More generally, \nnn, where nnn is a string of octal digits, 
  2831. matches the character whose ASCII value is nnn. Similarly, \xnn, where nn are 
  2832. hexidecimal digits, matches the character whose ASCII value is nn. The 
  2833. expression \cx matches the ASCII character control-x.  Finally, the "." 
  2834. metacharacter matches any character except "\n" (unless you use /s). 
  2835.  
  2836. You can specify a series of alternatives for a pattern using "|" to separate 
  2837. them, so that fee|fie|foe will match any of "fee", "fie", or "foe" in the 
  2838. target string (as would f(e|i|o)e).  Note that the first alternative includes 
  2839. everything from the last pattern delimiter ("(", "[", or the beginning of the 
  2840. pattern) up to the first "|", and the last alternative contains everything from 
  2841. the last "|" to the next pattern delimiter.  For this reason, it's common 
  2842. practice to include alternatives in parentheses, to minimize confusion about 
  2843. where they start and end.  Note however that "|" is interpreted as a literal 
  2844. with square brackets, so if you write [fee|fie|foe] you're really only matching 
  2845. [feio|]. 
  2846.  
  2847. Within a pattern, you may designate subpatterns for later reference by 
  2848. enclosing them in parentheses, and you may refer back to the nth subpattern 
  2849. later in the pattern using the metacharacter \n. Subpatterns are numbered based 
  2850. on the left to right order of their opening parenthesis.  Note that a 
  2851. backreference matches whatever actually matched the subpattern in the string 
  2852. being examined, not the rules for that subpattern.  Therefore, (0|0x)\d*\s\1\d* 
  2853. will match "0x1234 0x4321",but not "0x1234 01234", since subpattern 1 actually 
  2854. matched "0x", even though the rule 0|0x could potentially match the leading 0 
  2855. in the second number. 
  2856.  
  2857. WARNING on \1 vs $1 
  2858.  
  2859. Some people get too used to writing things like 
  2860.  
  2861.     $pattern =~ s/(\W)/\\\1/g;
  2862.  
  2863. This is grandfathered for the RHS of a substitute to avoid shocking the sed 
  2864. addicts, but it's a dirty habit to get into.  That's because in PerlThink, the 
  2865. right-hand side of a s/// is a double-quoted string.  \1 in the usual 
  2866. double-quoted string means a control-A.  The customary Unix meaning of \1 is 
  2867. kludged in for s///.  However, if you get into the habit of doing that, you get 
  2868. yourself into trouble if you then add an /e modifier. 
  2869.  
  2870.     s/(\d+)/ \1 + 1 /eg;
  2871.  
  2872. Or if you try to do 
  2873.  
  2874.     s/(\d+)/\1000/;
  2875.  
  2876. You can't disambiguate that by saying \{1}000, whereas you can fix it with 
  2877. ${1}000.  Basically, the operation of interpolation should not be confused with 
  2878. the operation of matching a backreference.  Certainly they mean two different 
  2879. things on the left side of the s///. 
  2880.  
  2881.  
  2882. ΓòÉΓòÉΓòÉ 8. Section - perlrun ΓòÉΓòÉΓòÉ
  2883.  
  2884. NAME 
  2885.  
  2886. perlrun - how to execute the Perl interpreter 
  2887.  
  2888. SYNOPSIS 
  2889.  
  2890. perl [-acdhnpPsSTuUvw] [-0[octal]] [-D[number/list]] 
  2891.  
  2892.         [B<-F regexp>] [B<-i[extension>]] [B<-I<lt>dir<gt>>]
  2893.         [B<-l[octal]>] [B<-x[dir]>]
  2894.         [programfile | B<-e command>] [argument ...]
  2895.  
  2896. DESCRIPTION 
  2897.  
  2898. Upon startup, Perl looks for your script in one of the following places: 
  2899.  
  2900.    1. Specified line by line via -e switches on the command line. 
  2901.  
  2902.    2. Contained in the file specified by the first filename on the command 
  2903.       line. (Note that systems supporting the #! notation invoke interpreters 
  2904.       this way.) 
  2905.  
  2906.    3. Passed in implicitly via standard input.  This only works if there are no 
  2907.       filename arguments--to pass arguments to a STDIN script you must 
  2908.       explicitly specify a "-" for the script name. 
  2909.  
  2910.  With methods 2 and 3, Perl starts parsing the input file from the beginning, 
  2911.  unless you've specified a -x switch, in which case it scans for the first line 
  2912.  starting with #! and containing the word "perl", and starts there instead. 
  2913.  This is useful for running a script embedded in a larger message.  (In this 
  2914.  case you would indicate the end of the script using the __END__ token.) 
  2915.  
  2916.  As of Perl 5, the #! line is always examined for switches as the line is being 
  2917.  parsed.  Thus, if you're on a machine that only allows one argument with the 
  2918.  #! line, or worse, doesn't even recognize the #! line, you still can get 
  2919.  consistent switch behavior regardless of how Perl was invoked, even if -x was 
  2920.  used to find the beginning of the script. 
  2921.  
  2922.  Because many operating systems silently chop off kernel interpretation of the 
  2923.  #! line after 32 characters, some switches may be passed in on the command 
  2924.  line, and some may not; you could even get a "-" without its letter, if you're 
  2925.  not careful.  You probably want to make sure that all your switches fall 
  2926.  either before or after that 32 character boundary. Most switches don't 
  2927.  actually care if they're processed redundantly, but getting a - instead of a 
  2928.  complete switch could cause Perl to try to execute standard input instead of 
  2929.  your script.  And a partial -I switch could also cause odd results. 
  2930.  
  2931.  Parsing of the #! switches starts wherever "perl" is mentioned in the line. 
  2932.  The sequences "-*" and "- " are specifically ignored so that you could, if you 
  2933.  were so inclined, say 
  2934.  
  2935.       #!/bin/sh -- # -*- perl -*- -p
  2936.       eval 'exec perl $0 -S ${1+"$@"}'
  2937.           if 0;
  2938.  
  2939.  to let Perl see the -p switch. 
  2940.  
  2941.  If the #! line does not contain the word "perl", the program named after the 
  2942.  #! is executed instead of the Perl interpreter.  This is slightly bizarre, but 
  2943.  it helps people on machines that don't do #!, because they can tell a program 
  2944.  that their SHELL is /usr/bin/perl, and Perl will then dispatch the program to 
  2945.  the correct interpreter for them. 
  2946.  
  2947.  After locating your script, Perl compiles the entire script to an internal 
  2948.  form.  If there are any compilation errors, execution of the script is not 
  2949.  attempted.  (This is unlike the typical shell script, which might run partway 
  2950.  through before finding a syntax error.) 
  2951.  
  2952.  If the script is syntactically correct, it is executed.  If the script runs 
  2953.  off the end without hitting an exit() or die() operator, an implicit exit(0) 
  2954.  is provided to indicate successful completion. 
  2955.  
  2956.  Switches 
  2957.  
  2958.  A single-character switch may be combined with the following switch, if any. 
  2959.  
  2960.       #!/usr/bin/perl -spi.bak    # same as -s -p -i.bak
  2961.  
  2962.  Switches include: 
  2963.  
  2964.  -0digits 
  2965.  
  2966.  specifies the record separator ($/) as an octal number.  If there are no 
  2967.  digits, the null character is the separator.  Other switches may precede or 
  2968.  follow the digits.  For example, if you have a version of find which can print 
  2969.  filenames terminated by the null character, you can say this: 
  2970.  
  2971.       find . -name '*.bak' -print0 | perl -n0e unlink
  2972.  
  2973.  The special value 00 will cause Perl to slurp files in paragraph mode. The 
  2974.  value 0777 will cause Perl to slurp files whole since there is no legal 
  2975.  character with that value. 
  2976.  
  2977.  -a 
  2978.  
  2979.  turns on autosplit mode when used with a -n or -p.  An implicit split command 
  2980.  to the @F array is done as the first thing inside the implicit while loop 
  2981.  produced by the -n or -p. 
  2982.  
  2983.       perl -ane 'print pop(@F), "\n";'
  2984.  
  2985.  is equivalent to 
  2986.  
  2987.       while (<>) {
  2988.           @F = split(' ');
  2989.           print pop(@F), "\n";
  2990.       }
  2991.  
  2992.  An alternate delimiter may be specified using -F. 
  2993.  
  2994.  -c 
  2995.  
  2996.  causes Perl to check the syntax of the script and then exit without executing 
  2997.  it.  Actually, it will execute BEGIN, END, and use blocks, since these are 
  2998.  considered as occurring outside the execution of your program. 
  2999.  
  3000.  -d 
  3001.  
  3002.  runs the script under the Perl debugger.  See perldebug. 
  3003.  
  3004.  -d:foo 
  3005.  
  3006.  runs the script under the control of a debugging or tracing module installed 
  3007.  as Devel::foo. E.g., -d:DProf executes the script using the Devel::DProf 
  3008.  profiler.  See perldebug. 
  3009.  
  3010.  -Dnumber 
  3011.  
  3012.  -Dlist 
  3013.  
  3014.  sets debugging flags.  To watch how it executes your script, use -D14.  (This 
  3015.  only works if debugging is compiled into your Perl.)  Another nice value is 
  3016.  -D1024, which lists your compiled syntax tree.  And -D512 displays compiled 
  3017.  regular expressions. As an alternative specify a list of letters instead of 
  3018.  numbers (e.g. -D14 is equivalent to -Dtls): 
  3019.  
  3020.           1  p  Tokenizing and Parsing
  3021.           2  s  Stack Snapshots
  3022.           4  l  Label Stack Processing
  3023.           8  t  Trace Execution
  3024.          16  o  Operator Node Construction
  3025.          32  c  String/Numeric Conversions
  3026.          64  P  Print Preprocessor Command for -P
  3027.         128  m  Memory Allocation
  3028.         256  f  Format Processing
  3029.         512  r  Regular Expression Parsing
  3030.        1024  x  Syntax Tree Dump
  3031.        2048  u  Tainting Checks
  3032.        4096  L  Memory Leaks (not supported anymore)
  3033.        8192  H  Hash Dump -- usurps values()
  3034.       16384  X  Scratchpad Allocation
  3035.       32768  D  Cleaning Up
  3036.  
  3037.  -e commandline 
  3038.  
  3039.  may be used to enter one line of script. If -e is given, Perl will not look 
  3040.  for a script filename in the argument list. Multiple -e commands may be given 
  3041.  to build up a multi-line script. Make sure to use semicolons where you would 
  3042.  in a normal program. 
  3043.  
  3044.  -Fregexp 
  3045.  
  3046.  specifies a regular expression to split on if -a is also in effect. If regexp 
  3047.  has // around it, the slashes will be ignored. 
  3048.  
  3049.  -iextension 
  3050.  
  3051.  specifies that files processed by the <> construct are to be edited in-place. 
  3052.  It does this by renaming the input file, opening the output file by the 
  3053.  original name, and selecting that output file as the default for print() 
  3054.  statements.  The extension, if supplied, is added to the name of the old file 
  3055.  to make a backup copy.  If no extension is supplied, no backup is made.  From 
  3056.  the shell, saying 
  3057.  
  3058.       $ perl -p -i.bak -e "s/foo/bar/; ... "
  3059.  
  3060.  is the same as using the script: 
  3061.  
  3062.       #!/usr/bin/perl -pi.bak
  3063.       s/foo/bar/;
  3064.  
  3065.  which is equivalent to 
  3066.  
  3067.       #!/usr/bin/perl
  3068.       while (<>) {
  3069.           if ($ARGV ne $oldargv) {
  3070.               rename($ARGV, $ARGV . '.bak');
  3071.               open(ARGVOUT, ">$ARGV");
  3072.               select(ARGVOUT);
  3073.               $oldargv = $ARGV;
  3074.           }
  3075.           s/foo/bar/;
  3076.       }
  3077.       continue {
  3078.           print;  # this prints to original filename
  3079.       }
  3080.       select(STDOUT);
  3081.  
  3082.  except that the -i form doesn't need to compare $ARGV to $oldargv to know when 
  3083.  the filename has changed.  It does, however, use ARGVOUT for the selected 
  3084.  filehandle.  Note that STDOUT is restored as the default output filehandle 
  3085.  after the loop. You can use eof without parenthesis to locate the end of each 
  3086.  input file, in case you want to append to each file, or reset line numbering 
  3087.  (see example in perlfunc/eof). 
  3088.  
  3089.  -Idirectory 
  3090.  
  3091.  may be used in conjunction with -P to tell the C preprocessor where to look 
  3092.  for include files.  By default /usr/include and /usr/lib/perl are searched. 
  3093.  
  3094.  -loctnum 
  3095.  
  3096.  enables automatic line-ending processing.  It has two effects:  first, it 
  3097.  automatically chomps the line terminator when used with -n or -p, and second, 
  3098.  it assigns "$\" to have the value of octnum so that any print statements will 
  3099.  have that line terminator added back on.  If octnum is omitted, sets "$\" to 
  3100.  the current value of "$/".  For instance, to trim lines to 80 columns: 
  3101.  
  3102.       perl -lpe 'substr($_, 80) = ""'
  3103.  
  3104.  Note that the assignment $\ = $/ is done when the switch is processed, so the 
  3105.  input record separator can be different than the output record separator if 
  3106.  the -l switch is followed by a -0 switch: 
  3107.  
  3108.       gnufind / -print0 | perl -ln0e 'print "found $_" if -p'
  3109.  
  3110.  This sets $\ to newline and then sets $/ to the null character. 
  3111.  
  3112.  -mmodule 
  3113.  
  3114.  -Mmodule 
  3115.  
  3116.  -mmodule executes use module (); before executing your script. -Mmodule 
  3117.  executes use module ; before executing your script.  You can use quotes to add 
  3118.  extra code after the module name, e.g., -M'module qw(foo bar)'. A little 
  3119.  built-in syntactic sugar means you can also say -mmodule=foo or -Mmodule=foo 
  3120.  as a shortcut for -M'module qw(foo)'.  Note that using the = form removes the 
  3121.  distinction between -m and -M. 
  3122.  
  3123.  -n 
  3124.  
  3125.  causes Perl to assume the following loop around your script, which makes it 
  3126.  iterate over filename arguments somewhat like sed -n or awk: 
  3127.  
  3128.       while (<>) {
  3129.           ...             # your script goes here
  3130.       }
  3131.  
  3132.  Note that the lines are not printed by default.  See -p to have lines printed. 
  3133.  Here is an efficient way to delete all files older than a week: 
  3134.  
  3135.       find . -mtime +7 -print | perl -nle 'unlink;'
  3136.  
  3137.  This is faster than using the -exec switch of find because you don't have to 
  3138.  start a process on every filename found. BEGIN and END blocks may be used to 
  3139.  capture control before or after the implicit loop, just as in awk. 
  3140.  
  3141.  -p 
  3142.  
  3143.  causes Perl to assume the following loop around your script, which makes it 
  3144.  iterate over filename arguments somewhat like sed: 
  3145.  
  3146.       while (<>) {
  3147.           ...             # your script goes here
  3148.       } continue {
  3149.           print;
  3150.       }
  3151.  
  3152.  Note that the lines are printed automatically.  To suppress printing use the 
  3153.  -n switch.  A -p overrides a -n switch. BEGIN and END blocks may be used to 
  3154.  capture control before or after the implicit loop, just as in awk. 
  3155.  
  3156.  -P 
  3157.  
  3158.  causes your script to be run through the C preprocessor before compilation by 
  3159.  Perl.  (Since both comments and cpp directives begin with the # character, you 
  3160.  should avoid starting comments with any words recognized by the C preprocessor 
  3161.  such as "if", " else" or "define".) 
  3162.  
  3163.  -s 
  3164.  
  3165.  enables some rudimentary switch parsing for switches on the command line after 
  3166.  the script name but before any filename arguments (or before a --).  Any 
  3167.  switch found there is removed from @ARGV and sets the corresponding variable 
  3168.  in the Perl script.  The following script prints "true" if and only if the 
  3169.  script is invoked with a -xyz switch. 
  3170.  
  3171.       #!/usr/bin/perl -s
  3172.       if ($xyz) { print "true\n"; }
  3173.  
  3174.  -S 
  3175.  
  3176.  makes Perl use the PATH environment variable to search for the script (unless 
  3177.  the name of the script starts with a slash).  Typically this is used to 
  3178.  emulate #! startup on machines that don't support #!, in the following manner: 
  3179.  
  3180.       #!/usr/bin/perl
  3181.       eval "exec /usr/bin/perl -S $0 $*"
  3182.               if $running_under_some_shell;
  3183.  
  3184.  The system ignores the first line and feeds the script to /bin/sh, which 
  3185.  proceeds to try to execute the Perl script as a shell script. The shell 
  3186.  executes the second line as a normal shell command, and thus starts up the 
  3187.  Perl interpreter.  On some systems $0 doesn't always contain the full 
  3188.  pathname, so the -S tells Perl to search for the script if necessary.  After 
  3189.  Perl locates the script, it parses the lines and ignores them because the 
  3190.  variable $running_under_some_shell is never true.  A better construct than $* 
  3191.  would be ${1+"$@"}, which handles embedded spaces and such in the filenames, 
  3192.  but doesn't work if the script is being interpreted by csh.  In order to start 
  3193.  up sh rather than csh, some systems may have to replace the #! line with a 
  3194.  line containing just a colon, which will be politely ignored by Perl.  Other 
  3195.  systems can't control that, and need a totally devious construct that will 
  3196.  work under any of csh, sh or Perl, such as the following: 
  3197.  
  3198.           eval '(exit $?0)' && eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
  3199.           & eval 'exec /usr/bin/perl -S $0 $argv:q'
  3200.                   if 0;
  3201.  
  3202.  -T 
  3203.  
  3204.  forces "taint" checks to be turned on so you can test them.  Ordinarily these 
  3205.  checks are done only when running setuid or setgid.  It's a good idea to turn 
  3206.  them on explicitly for programs run on another's behalf, such as CGI programs. 
  3207.  See perlsec. 
  3208.  
  3209.  -u 
  3210.  
  3211.  causes Perl to dump core after compiling your script.  You can then take this 
  3212.  core dump and turn it into an executable file by using the undump program (not 
  3213.  supplied).  This speeds startup at the expense of some disk space (which you 
  3214.  can minimize by stripping the executable). (Still, a "hello world" executable 
  3215.  comes out to about 200K on my machine.)  If you want to execute a portion of 
  3216.  your script before dumping, use the dump() operator instead.  Note: 
  3217.  availability of undump is platform specific and may not be available for a 
  3218.  specific port of Perl. 
  3219.  
  3220.  -U 
  3221.  
  3222.  allows Perl to do unsafe operations.  Currently the only "unsafe" operations 
  3223.  are the unlinking of directories while running as superuser, and running 
  3224.  setuid programs with fatal taint checks turned into warnings. 
  3225.  
  3226.  -v 
  3227.  
  3228.  prints the version and patchlevel of your Perl executable. 
  3229.  
  3230.  -V 
  3231.  
  3232.  prints summary of the major perl configuration values and the current value of 
  3233.  @INC. 
  3234.  
  3235.  -V:name 
  3236.  
  3237.  Prints to STDOUT the value of the named configuration variable. 
  3238.  
  3239.  -w 
  3240.  
  3241.  prints warnings about identifiers that are mentioned only once, and scalar 
  3242.  variables that are used before being set.  Also warns about redefined 
  3243.  subroutines, and references to undefined filehandles or filehandles opened 
  3244.  readonly that you are attempting to write on.  Also warns you if you use 
  3245.  values as a number that doesn't look like numbers, using an array as though it 
  3246.  were a scalar, if your subroutines recurse more than 100 deep, and innumerable 
  3247.  other things. See perldiag and perltrap. 
  3248.  
  3249.  -x directory 
  3250.  
  3251.  tells Perl that the script is embedded in a message.  Leading garbage will be 
  3252.  discarded until the first line that starts with #! and contains the string 
  3253.  "perl".  Any meaningful switches on that line will be applied (but only one 
  3254.  group of switches, as with normal #! processing).  If a directory name is 
  3255.  specified, Perl will switch to that directory before running the script.  The 
  3256.  -x switch only controls the the disposal of leading garbage.  The script must 
  3257.  be terminated with __END__ if there is trailing garbage to be ignored (the 
  3258.  script can process any or all of the trailing garbage via the DATA filehandle 
  3259.  if desired). 
  3260.  
  3261.  
  3262. ΓòÉΓòÉΓòÉ 9. Section - perlfunc ΓòÉΓòÉΓòÉ
  3263.  
  3264. NAME 
  3265.  
  3266. perlfunc - Perl builtin functions 
  3267.  
  3268. DESCRIPTION 
  3269.  
  3270. The functions in this section can serve as terms in an expression. They fall 
  3271. into two major categories: list operators and named unary operators.  These 
  3272. differ in their precedence relationship with a following comma.  (See the 
  3273. precedence table in perlop.)  List operators take more than one argument, while 
  3274. unary operators can never take more than one argument.  Thus, a comma 
  3275. terminates the argument of a unary operator, but merely separates the arguments 
  3276. of a list operator.  A unary operator generally provides a scalar context to 
  3277. its argument, while a list operator may provide either scalar and list contexts 
  3278. for its arguments.  If it does both, the scalar arguments will be first, and 
  3279. the list argument will follow.  (Note that there can only ever be one list 
  3280. argument.)  For instance, splice() has three scalar arguments followed by a 
  3281. list. 
  3282.  
  3283. In the syntax descriptions that follow, list operators that expect a list (and 
  3284. provide list context for the elements of the list) are shown with LIST as an 
  3285. argument.  Such a list may consist of any combination of scalar arguments or 
  3286. list values; the list values will be included in the list as if each individual 
  3287. element were interpolated at that point in the list, forming a longer 
  3288. single-dimensional list value. Elements of the LIST should be separated by 
  3289. commas. 
  3290.  
  3291. Any function in the list below may be used either with or without parentheses 
  3292. around its arguments.  (The syntax descriptions omit the parens.)  If you use 
  3293. the parens, the simple (but occasionally surprising) rule is this: It LOOKS 
  3294. like a function, therefore it IS a function, and precedence doesn't matter. 
  3295. Otherwise it's a list operator or unary operator, and precedence does matter. 
  3296. And whitespace between the function and left parenthesis doesn't count--so you 
  3297. need to be careful sometimes: 
  3298.  
  3299.     print 1+2+3;        # Prints 6.
  3300.     print(1+2) + 3;     # Prints 3.
  3301.     print (1+2)+3;      # Also prints 3!
  3302.     print +(1+2)+3;     # Prints 6.
  3303.     print ((1+2)+3);    # Prints 6.
  3304.  
  3305. If you run Perl with the -w switch it can warn you about this.  For example, 
  3306. the third line above produces: 
  3307.  
  3308.     print (...) interpreted as function at - line 1.
  3309.     Useless use of integer addition in void context at - line 1.
  3310.  
  3311. For functions that can be used in either a scalar or list context, non-abortive 
  3312. failure is generally indicated in a scalar context by returning the undefined 
  3313. value, and in a list context by returning the null list. 
  3314.  
  3315. Remember the following rule: 
  3316.  
  3317. THERE IS NO GENERAL RULE FOR CONVERTING A LIST INTO A SCALAR! 
  3318.  
  3319. Each operator and function decides which sort of value it would be most 
  3320. appropriate to return in a scalar context.  Some operators return the length of 
  3321. the list that would have been returned in a list context.  Some operators 
  3322. return the first value in the list.  Some operators return the last value in 
  3323. the list.  Some operators return a count of successful operations.  In general, 
  3324. they do what you want, unless you want consistency. 
  3325.  
  3326. Categorical Listing of Perl Functions 
  3327.  
  3328. Alphabetical Listing of Perl Functions 
  3329.  
  3330.  
  3331. ΓòÉΓòÉΓòÉ 10. Categorical Listing of Perl Functions ΓòÉΓòÉΓòÉ
  3332.  
  3333. Categorical Listing of Perl Functions 
  3334.  
  3335. Here are Perl's functions (including things that look like functions, like some 
  3336. of the keywords and named operators) arranged by category.  Some functions 
  3337. appear in more than one place. 
  3338.  
  3339. Functions for SCALARs or strings 
  3340.  
  3341. chomp, chop, chr, crypt, hex, index, lc, lcfirst, length, oct, ord, pack, 
  3342. q/STRING/, qq/STRING/, reverse, rindex, sprintf, substr, tr///, uc, ucfirst, 
  3343. y/// 
  3344.  
  3345. Regular expressions and pattern matching 
  3346.  
  3347. m//, pos, quotemeta, s///, split, study 
  3348.  
  3349. Numeric functions 
  3350.  
  3351. abs, atan2, cos, exp, hex, int, log, oct, rand, sin, sqrt, srand 
  3352.  
  3353. Functions for real @ARRAYs 
  3354.  
  3355. pop, push, shift, splice, unshift 
  3356.  
  3357. Functions for list data 
  3358.  
  3359. grep, join, map, qw/STRING/, reverse, sort, unpack 
  3360.  
  3361. Functions for real %HASHes 
  3362.  
  3363. delete, each, exists, keys, values 
  3364.  
  3365. Input and output functions 
  3366.  
  3367. binmode, close, closedir, dbmclose, dbmopen, die, eof, fileno, flock, format, 
  3368. getc, print, printf, read, readdir, rewinddir, seek, seekdir, select, syscall, 
  3369. sysread, syswrite, tell, telldir, truncate, warn, write 
  3370.  
  3371. Functions for fixed length data or records 
  3372.  
  3373. pack, read, syscall, sysread, syswrite, unpack, vec 
  3374.  
  3375. Functions for filehandles, files, or directories 
  3376.  
  3377. -X, chdir, chmod, chown, chroot, fcntl, glob, ioctl, link, lstat, mkdir, open, 
  3378. opendir, readlink, rename, rmdir, stat, symlink, umask, unlink, utime 
  3379.  
  3380. Keywords related to the control flow of your perl program 
  3381.  
  3382. caller, continue, die, do, dump, eval, exit, goto, last, next, redo, return, 
  3383. sub, wantarray 
  3384.  
  3385. Keywords related to scoping 
  3386.  
  3387. caller, import, local, my, package, use 
  3388.  
  3389. Miscellaneous functions 
  3390.  
  3391. defined, dump, eval, formline, local, my, reset, scalar, undef, wantarray 
  3392.  
  3393. Functions for processes and process groups 
  3394.  
  3395. alarm, exec, fork, getpgrp, getppid, getpriority, kill, pipe, qx/STRING/, 
  3396. setpgrp, setpriority, sleep, system, times, wait, waitpid 
  3397.  
  3398. Keywords related to perl modules 
  3399.  
  3400. do, import, no, package, require, use 
  3401.  
  3402. Keywords related to classes and object-orientedness 
  3403.  
  3404. bless, dbmclose, dbmopen, package, ref, tie, untie, use 
  3405.  
  3406. Low-level socket functions 
  3407.  
  3408. accept, bind, connect, getpeername, getsockname, getsockopt, listen, recv, 
  3409. send, setsockopt, shutdown, socket, socketpair 
  3410.  
  3411. System V interprocess communication functions 
  3412.  
  3413. msgctl, msgget, msgrcv, msgsnd, semctl, semget, semop, shmctl, shmget, shmread, 
  3414. shmwrite 
  3415.  
  3416. Fetching user and group info 
  3417.  
  3418. endgrent, endhostent, endnetent, endpwent, getgrent, getgrgid, getgrnam, 
  3419. getlogin, getpwent, getpwnam, getpwuid, setgrent, setpwent 
  3420.  
  3421. Fetching network info 
  3422.  
  3423. endprotoent, endservent, gethostbyaddr, gethostbyname, gethostent, 
  3424. getnetbyaddr, getnetbyname, getnetent, getprotobyname, getprotobynumber, 
  3425. getprotoent, getservbyname, getservbyport, getservent, sethostent, setnetent, 
  3426. setprotoent, setservent 
  3427.  
  3428. Time-related functions 
  3429.  
  3430. gmtime, localtime, time, times 
  3431.  
  3432.  
  3433. ΓòÉΓòÉΓòÉ 11. Alphabetical Listing of Perl Functions ΓòÉΓòÉΓòÉ
  3434.  
  3435. Alphabetical Listing of Perl Functions 
  3436.  
  3437.       -X FILEHANDLE 
  3438.       -X EXPR 
  3439.       -X 
  3440.       abs VALUE 
  3441.       accept NEWSOCKET,GENERICSOCKET 
  3442.       alarm SECONDS 
  3443.       atan2 Y,X 
  3444.       bind SOCKET,NAME 
  3445.       binmode FILEHANDLE 
  3446.       bless REF,CLASSNAME 
  3447.       bless REF 
  3448.       caller EXPR 
  3449.       caller 
  3450.       chdir EXPR 
  3451.       chmod LIST 
  3452.       chomp VARIABLE 
  3453.       chomp LIST 
  3454.       chomp 
  3455.       chop VARIABLE 
  3456.       chop LIST 
  3457.       chop 
  3458.       chown LIST 
  3459.       chr NUMBER 
  3460.       chroot FILENAME 
  3461.       close FILEHANDLE 
  3462.       closedir DIRHANDLE 
  3463.       connect SOCKET,NAME 
  3464.       continue BLOCK 
  3465.       cos EXPR 
  3466.       crypt PLAINTEXT,SALT 
  3467.       dbmclose ASSOC_ARRAY 
  3468.       dbmopen ASSOC,DBNAME,MODE 
  3469.       defined EXPR 
  3470.       delete EXPR 
  3471.       die LIST 
  3472.       do BLOCK 
  3473.       do SUBROUTINE(LIST) 
  3474.       do EXPR 
  3475.       dump LABEL 
  3476.       each ASSOC_ARRAY 
  3477.       eof FILEHANDLE 
  3478.       eof () 
  3479.       eof 
  3480.       eval EXPR 
  3481.       eval BLOCK 
  3482.       exec LIST 
  3483.       exists EXPR 
  3484.       exit EXPR 
  3485.       exp EXPR 
  3486.       fcntl FILEHANDLE,FUNCTION,SCALAR 
  3487.       fileno FILEHANDLE 
  3488.       flock FILEHANDLE,OPERATION 
  3489.       fork 
  3490.       format 
  3491.       formline PICTURE, LIST 
  3492.       getc FILEHANDLE 
  3493.       getc 
  3494.       getlogin 
  3495.       getpeername SOCKET 
  3496.       getpgrp PID 
  3497.       getppid 
  3498.       getpriority WHICH,WHO 
  3499.       getpwnam NAME 
  3500.       getgrnam NAME 
  3501.       gethostbyname NAME 
  3502.       getnetbyname NAME 
  3503.       getprotobyname NAME 
  3504.       getpwuid UID 
  3505.       getgrgid GID 
  3506.       getservbyname NAME,PROTO 
  3507.       gethostbyaddr ADDR,ADDRTYPE 
  3508.       getnetbyaddr ADDR,ADDRTYPE 
  3509.       getprotobynumber NUMBER 
  3510.       getservbyport PORT,PROTO 
  3511.       getpwent 
  3512.       getgrent 
  3513.       gethostent 
  3514.       getnetent 
  3515.       getprotoent 
  3516.       getservent 
  3517.       setpwent 
  3518.       setgrent 
  3519.       sethostent STAYOPEN 
  3520.       setnetent STAYOPEN 
  3521.       setprotoent STAYOPEN 
  3522.       setservent STAYOPEN 
  3523.       endpwent 
  3524.       endgrent 
  3525.       endhostent 
  3526.       endnetent 
  3527.       endprotoent 
  3528.       endservent 
  3529.       getsockname SOCKET 
  3530.       getsockopt SOCKET,LEVEL,OPTNAME 
  3531.       glob EXPR 
  3532.       gmtime EXPR 
  3533.       goto LABEL 
  3534.       goto EXPR 
  3535.       goto &NAME 
  3536.       grep BLOCK LIST 
  3537.       grep EXPR,LIST 
  3538.       hex EXPR 
  3539.       import 
  3540.       index STR,SUBSTR,POSITION 
  3541.       index STR,SUBSTR 
  3542.       int EXPR 
  3543.       ioctl FILEHANDLE,FUNCTION,SCALAR 
  3544.       join EXPR,LIST 
  3545.       keys ASSOC_ARRAY 
  3546.       kill LIST 
  3547.       last LABEL 
  3548.       last 
  3549.       lc EXPR 
  3550.       lcfirst EXPR 
  3551.       length EXPR 
  3552.       link OLDFILE,NEWFILE 
  3553.       listen SOCKET,QUEUESIZE 
  3554.       local EXPR 
  3555.       localtime EXPR 
  3556.       log EXPR 
  3557.       lstat FILEHANDLE 
  3558.       lstat EXPR 
  3559.       m// 
  3560.       map BLOCK LIST 
  3561.       map EXPR,LIST 
  3562.       mkdir FILENAME,MODE 
  3563.       msgctl ID,CMD,ARG 
  3564.       msgget KEY,FLAGS 
  3565.       msgsnd ID,MSG,FLAGS 
  3566.       msgrcv ID,VAR,SIZE,TYPE,FLAGS 
  3567.       my EXPR 
  3568.       next LABEL 
  3569.       next 
  3570.       no Module LIST 
  3571.       oct EXPR 
  3572.       open FILEHANDLE,EXPR 
  3573.       open FILEHANDLE 
  3574.       opendir DIRHANDLE,EXPR 
  3575.       ord EXPR 
  3576.       pack TEMPLATE,LIST 
  3577.       package NAMESPACE 
  3578.       pipe READHANDLE,WRITEHANDLE 
  3579.       pop ARRAY 
  3580.       pos SCALAR 
  3581.       print FILEHANDLE LIST 
  3582.       print LIST 
  3583.       print 
  3584.       printf FILEHANDLE LIST 
  3585.       printf LIST 
  3586.       push ARRAY,LIST 
  3587.       q/STRING/ 
  3588.       qq/STRING/ 
  3589.       qx/STRING/ 
  3590.       qw/STRING/ 
  3591.       quotemeta EXPR 
  3592.       rand EXPR 
  3593.       rand 
  3594.       read FILEHANDLE,SCALAR,LENGTH,OFFSET 
  3595.       read FILEHANDLE,SCALAR,LENGTH 
  3596.       readdir DIRHANDLE 
  3597.       readlink EXPR 
  3598.       recv SOCKET,SCALAR,LEN,FLAGS 
  3599.       redo LABEL 
  3600.       redo 
  3601.       ref EXPR 
  3602.       rename OLDNAME,NEWNAME 
  3603.       require EXPR 
  3604.       require 
  3605.       reset EXPR 
  3606.       reset 
  3607.       return LIST 
  3608.       reverse LIST 
  3609.       rewinddir DIRHANDLE 
  3610.       rindex STR,SUBSTR,POSITION 
  3611.       rindex STR,SUBSTR 
  3612.       rmdir FILENAME 
  3613.       s/// 
  3614.       scalar EXPR 
  3615.       seek FILEHANDLE,POSITION,WHENCE 
  3616.       seekdir DIRHANDLE,POS 
  3617.       select FILEHANDLE 
  3618.       select 
  3619.       select RBITS,WBITS,EBITS,TIMEOUT 
  3620.       semctl ID,SEMNUM,CMD,ARG 
  3621.       semget KEY,NSEMS,FLAGS 
  3622.       semop KEY,OPSTRING 
  3623.       send SOCKET,MSG,FLAGS,TO 
  3624.       send SOCKET,MSG,FLAGS 
  3625.       setpgrp PID,PGRP 
  3626.       setpriority WHICH,WHO,PRIORITY 
  3627.       setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL 
  3628.       shift ARRAY 
  3629.       shift 
  3630.       shmctl ID,CMD,ARG 
  3631.       shmget KEY,SIZE,FLAGS 
  3632.       shmread ID,VAR,POS,SIZE 
  3633.       shmwrite ID,STRING,POS,SIZE 
  3634.       shutdown SOCKET,HOW 
  3635.       sin EXPR 
  3636.       sleep EXPR 
  3637.       sleep 
  3638.       socket SOCKET,DOMAIN,TYPE,PROTOCOL 
  3639.       socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL 
  3640.       sort SUBNAME LIST 
  3641.       sort BLOCK LIST 
  3642.       sort LIST 
  3643.       splice ARRAY,OFFSET,LENGTH,LIST 
  3644.       splice ARRAY,OFFSET,LENGTH 
  3645.       splice ARRAY,OFFSET 
  3646.       split /PATTERN/,EXPR,LIMIT 
  3647.       split /PATTERN/,EXPR 
  3648.       split /PATTERN/ 
  3649.       split 
  3650.       sprintf FORMAT,LIST 
  3651.       sqrt EXPR 
  3652.       srand EXPR 
  3653.       stat FILEHANDLE 
  3654.       stat EXPR 
  3655.       study SCALAR 
  3656.       study 
  3657.       sub BLOCK 
  3658.       sub NAME 
  3659.       sub NAME BLOCK 
  3660.       substr EXPR,OFFSET,LEN 
  3661.       substr EXPR,OFFSET 
  3662.       symlink OLDFILE,NEWFILE 
  3663.       syscall LIST 
  3664.       sysopen FILEHANDLE,FILENAME,MODE 
  3665.       sysopen FILEHANDLE,FILENAME,MODE,PERMS 
  3666.       sysread FILEHANDLE,SCALAR,LENGTH,OFFSET 
  3667.       sysread FILEHANDLE,SCALAR,LENGTH 
  3668.       system LIST 
  3669.       syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET 
  3670.       syswrite FILEHANDLE,SCALAR,LENGTH 
  3671.       tell FILEHANDLE 
  3672.       tell 
  3673.       telldir DIRHANDLE 
  3674.       tie VARIABLE,CLASSNAME,LIST 
  3675.       time 
  3676.       times 
  3677.       tr/// 
  3678.       truncate FILEHANDLE,LENGTH 
  3679.       truncate EXPR,LENGTH 
  3680.       uc EXPR 
  3681.       ucfirst EXPR 
  3682.       umask EXPR 
  3683.       umask 
  3684.       undef EXPR 
  3685.       undef 
  3686.       unlink LIST 
  3687.       unpack TEMPLATE,EXPR 
  3688.       untie VARIABLE 
  3689.       unshift ARRAY,LIST 
  3690.       use Module LIST 
  3691.       use Module 
  3692.       utime LIST 
  3693.       values ASSOC_ARRAY 
  3694.       vec EXPR,OFFSET,BITS 
  3695.       wait 
  3696.       waitpid PID,FLAGS 
  3697.       wantarray 
  3698.       warn LIST 
  3699.       write FILEHANDLE 
  3700.       write EXPR 
  3701.       write 
  3702.       y/// 
  3703.  
  3704.  
  3705. ΓòÉΓòÉΓòÉ 11.1. -X FILEHANDLE ΓòÉΓòÉΓòÉ
  3706.  
  3707. -X FILEHANDLE 
  3708.  
  3709. -X EXPR 
  3710.  
  3711. -X 
  3712.  
  3713. A file test, where X is one of the letters listed below.  This unary operator 
  3714. takes one argument, either a filename or a filehandle, and tests the associated 
  3715. file to see if something is true about it.  If the argument is omitted, tests 
  3716. $_, except for -t, which tests STDIN. Unless otherwise documented, it returns 1 
  3717. for TRUE and '' for FALSE, or the undefined value if the file doesn't exist. 
  3718. Despite the funny names, precedence is the same as any other named unary 
  3719. operator, and the argument may be parenthesized like any other unary operator. 
  3720. The operator may be any of: 
  3721.  
  3722.     -r  File is readable by effective uid/gid.
  3723.     -w  File is writable by effective uid/gid.
  3724.     -x  File is executable by effective uid/gid.
  3725.     -o  File is owned by effective uid.
  3726.     -R  File is readable by real uid/gid.
  3727.     -W  File is writable by real uid/gid.
  3728.     -X  File is executable by real uid/gid.
  3729.     -O  File is owned by real uid.
  3730.     -e  File exists.
  3731.     -z  File has zero size.
  3732.     -s  File has non-zero size (returns size).
  3733.     -f  File is a plain file.
  3734.     -d  File is a directory.
  3735.     -l  File is a symbolic link.
  3736.     -p  File is a named pipe (FIFO).
  3737.     -S  File is a socket.
  3738.     -b  File is a block special file.
  3739.     -c  File is a character special file.
  3740.     -t  Filehandle is opened to a tty.
  3741.     -u  File has setuid bit set.
  3742.     -g  File has setgid bit set.
  3743.     -k  File has sticky bit set.
  3744.     -T  File is a text file.
  3745.     -B  File is a binary file (opposite of -T).
  3746.     -M  Age of file in days when script started.
  3747.     -A  Same for access time.
  3748.     -C  Same for inode change time.
  3749.  
  3750. The interpretation of the file permission operators -r, -R, -w, -W, -x and -X 
  3751. is based solely on the mode of the file and the uids and gids of the user. 
  3752. There may be other reasons you can't actually read, write or execute the file. 
  3753. Also note that, for the superuser, -r, -R, -w and -W always return 1, and -x 
  3754. and -X return 1 if any execute bit is set in the mode.  Scripts run by the 
  3755. superuser may thus need to do a stat() in order to determine the actual mode of 
  3756. the file, or temporarily set the uid to something else. 
  3757.  
  3758. Example: 
  3759.  
  3760.     while (<>) {
  3761.         chop;
  3762.         next unless -f $_;      # ignore specials
  3763.         ...
  3764.     }
  3765.  
  3766. Note that -s/a/b/ does not do a negated substitution.  Saying -exp($foo) still 
  3767. works as expected, however--only single letters following a minus are 
  3768. interpreted as file tests. 
  3769.  
  3770. The -T and -B switches work as follows.  The first block or so of the file is 
  3771. examined for odd characters such as strange control codes or characters with 
  3772. the high bit set.  If too many odd characters (>30%) are found, it's a -B file, 
  3773. otherwise it's a -T file.  Also, any file containing null in the first block is 
  3774. considered a binary file.  If -T or -B is used on a filehandle, the current 
  3775. stdio buffer is examined rather than the first block.  Both -T and -B return 
  3776. TRUE on a null file, or a file at EOF when testing a filehandle.  Because you 
  3777. have to read a file to do the -T test, on most occasions you want to use a -f 
  3778. against the file first, as in next unless -f $file && -T $file. 
  3779.  
  3780. If any of the file tests (or either the stat() or lstat() operators) are given 
  3781. the special filehandle consisting of a solitary underline, then the stat 
  3782. structure of the previous file test (or stat operator) is used, saving a system 
  3783. call.  (This doesn't work with -t, and you need to remember that lstat() and -l 
  3784. will leave values in the stat structure for the symbolic link, not the real 
  3785. file.)  Example: 
  3786.  
  3787.     print "Can do.\n" if -r $a || -w _ || -x _;
  3788.     stat($filename);
  3789.     print "Readable\n" if -r _;
  3790.     print "Writable\n" if -w _;
  3791.     print "Executable\n" if -x _;
  3792.     print "Setuid\n" if -u _;
  3793.     print "Setgid\n" if -g _;
  3794.     print "Sticky\n" if -k _;
  3795.     print "Text\n" if -T _;
  3796.     print "Binary\n" if -B _;
  3797.  
  3798.  
  3799. ΓòÉΓòÉΓòÉ 11.2. abs VALUE ΓòÉΓòÉΓòÉ
  3800.  
  3801. abs VALUE 
  3802.  
  3803. Returns the absolute value of its argument. 
  3804.  
  3805.  
  3806. ΓòÉΓòÉΓòÉ 11.3. accept NEWSOCKET,GENERICSOCKET ΓòÉΓòÉΓòÉ
  3807.  
  3808. accept NEWSOCKET,GENERICSOCKET 
  3809.  
  3810. Accepts an incoming socket connect, just as the accept(2) system call does. 
  3811. Returns the packed address if it succeeded, FALSE otherwise. See example in 
  3812. perlipc/"Sockets: Client/Server Communication". 
  3813.  
  3814.  
  3815. ΓòÉΓòÉΓòÉ 11.4. alarm SECONDS ΓòÉΓòÉΓòÉ
  3816.  
  3817. alarm SECONDS 
  3818.  
  3819. Arranges to have a SIGALRM delivered to this process after the specified number 
  3820. of seconds have elapsed.  (On some machines, unfortunately, the elapsed time 
  3821. may be up to one second less than you specified because of how seconds are 
  3822. counted.)  Only one timer may be counting at once.  Each call disables the 
  3823. previous timer, and an argument of 0 may be supplied to cancel the previous 
  3824. timer without starting a new one.  The returned value is the amount of time 
  3825. remaining on the previous timer. 
  3826.  
  3827. For delays of finer granularity than one second, you may use Perl's syscall() 
  3828. interface to access setitimer(2) if your system supports it, or else see 
  3829. L</select()> below.  It is not advised to intermix alarm() and sleep() calls. 
  3830.  
  3831.  
  3832. ΓòÉΓòÉΓòÉ 11.5. atan2 Y,X ΓòÉΓòÉΓòÉ
  3833.  
  3834. atan2 Y,X 
  3835.  
  3836. Returns the arctangent of Y/X in the range -PI to PI. 
  3837.  
  3838.  
  3839. ΓòÉΓòÉΓòÉ 11.6. bind SOCKET,NAME ΓòÉΓòÉΓòÉ
  3840.  
  3841. bind SOCKET,NAME 
  3842.  
  3843. Binds a network address to a socket, just as the bind system call does. 
  3844. Returns TRUE if it succeeded, FALSE otherwise.  NAME should be a packed address 
  3845. of the appropriate type for the socket.  See the examples in perlipc/"Sockets: 
  3846. Client/Server Communication". 
  3847.  
  3848.  
  3849. ΓòÉΓòÉΓòÉ 11.7. binmode FILEHANDLE ΓòÉΓòÉΓòÉ
  3850.  
  3851. binmode FILEHANDLE 
  3852.  
  3853. Arranges for the file to be read or written in "binary" mode in operating 
  3854. systems that distinguish between binary and text files.  Files that are not in 
  3855. binary mode have CR LF sequences translated to LF on input and LF translated to 
  3856. CR LF on output.  Binmode has no effect under Unix; in DOS and similarly 
  3857. archaic systems, it may be imperative--otherwise your DOS-damaged C library may 
  3858. mangle your file.  The key distinction between systems that need binmode and 
  3859. those that don't is their text file formats.  Systems like Unix and Plan9 that 
  3860. delimit lines with a single character, and that encode that character in C as 
  3861. '\n', do not need binmode.  The rest need it.  If FILEHANDLE is an expression, 
  3862. the value is taken as the name of the filehandle. 
  3863.  
  3864.  
  3865. ΓòÉΓòÉΓòÉ 11.8. bless REF,CLASSNAME ΓòÉΓòÉΓòÉ
  3866.  
  3867. bless REF,CLASSNAME 
  3868.  
  3869. bless REF 
  3870.  
  3871. This function tells the referenced object (passed as REF) that it is now an 
  3872. object in the CLASSNAME package--or the current package if no CLASSNAME is 
  3873. specified, which is often the case.  It returns the reference for convenience, 
  3874. since a bless() is often the last thing in a constructor. Always use the 
  3875. two-argument version if the function doing the blessing might be inherited by a 
  3876. derived class.  See perlobj for more about the blessing (and blessings) of 
  3877. objects. 
  3878.  
  3879.  
  3880. ΓòÉΓòÉΓòÉ 11.9. caller EXPR ΓòÉΓòÉΓòÉ
  3881.  
  3882. caller EXPR 
  3883.  
  3884. caller 
  3885.  
  3886. Returns the context of the current subroutine call.  In a scalar context, 
  3887. returns TRUE if there is a caller, that is, if we're in a subroutine or eval() 
  3888. or require(), and FALSE otherwise.  In a list context, returns 
  3889.  
  3890.     ($package, $filename, $line) = caller;
  3891.  
  3892. With EXPR, it returns some extra information that the debugger uses to print a 
  3893. stack trace.  The value of EXPR indicates how many call frames to go back 
  3894. before the current one. 
  3895.  
  3896.     ($package, $filename, $line,
  3897.      $subroutine, $hasargs, $wantargs) = caller($i);
  3898.  
  3899. Furthermore, when called from within the DB package, caller returns more 
  3900. detailed information: it sets the list variable @DB::args to be the arguments 
  3901. with which that subroutine was invoked. 
  3902.  
  3903.  
  3904. ΓòÉΓòÉΓòÉ 11.10. chdir EXPR ΓòÉΓòÉΓòÉ
  3905.  
  3906. chdir EXPR 
  3907.  
  3908. Changes the working directory to EXPR, if possible.  If EXPR is omitted, 
  3909. changes to home directory.  Returns TRUE upon success, FALSE otherwise.  See 
  3910. example under die(). 
  3911.  
  3912.  
  3913. ΓòÉΓòÉΓòÉ 11.11. chmod LIST ΓòÉΓòÉΓòÉ
  3914.  
  3915. chmod LIST 
  3916.  
  3917. Changes the permissions of a list of files.  The first element of the list must 
  3918. be the numerical mode, which should probably be an octal number.  Returns the 
  3919. number of files successfully changed. 
  3920.  
  3921.     $cnt = chmod 0755, 'foo', 'bar';
  3922.     chmod 0755, @executables;
  3923.  
  3924.  
  3925. ΓòÉΓòÉΓòÉ 11.12. chomp VARIABLE ΓòÉΓòÉΓòÉ
  3926.  
  3927. chomp VARIABLE 
  3928.  
  3929. chomp LIST 
  3930.  
  3931. chomp 
  3932.  
  3933. This is a slightly safer version of chop (see below).  It removes any line 
  3934. ending that corresponds to the current value of $/ (also known as 
  3935. $INPUT_RECORD_SEPARATOR in the English module).  It returns the number of 
  3936. characters removed.  It's often used to remove the newline from the end of an 
  3937. input record when you're worried that the final record may be missing its 
  3938. newline.  When in paragraph mode ($/ = ""), it removes all trailing newlines 
  3939. from the string.  If VARIABLE is omitted, it chomps $_.  Example: 
  3940.  
  3941.     while (<>) {
  3942.         chomp;  # avoid \n on last field
  3943.         @array = split(/:/);
  3944.         ...
  3945.     }
  3946.  
  3947. You can actually chomp anything that's an lvalue, including an assignment: 
  3948.  
  3949.     chomp($cwd = `pwd`);
  3950.     chomp($answer = <STDIN>);
  3951.  
  3952. If you chomp a list, each element is chomped, and the total number of 
  3953. characters removed is returned. 
  3954.  
  3955.  
  3956. ΓòÉΓòÉΓòÉ 11.13. chop VARIABLE ΓòÉΓòÉΓòÉ
  3957.  
  3958. chop VARIABLE 
  3959.  
  3960. chop LIST 
  3961.  
  3962. chop 
  3963.  
  3964. Chops off the last character of a string and returns the character chopped. 
  3965. It's used primarily to remove the newline from the end of an input record, but 
  3966. is much more efficient than s/\n// because it neither scans nor copies the 
  3967. string.  If VARIABLE is omitted, chops $_. Example: 
  3968.  
  3969.     while (<>) {
  3970.         chop;   # avoid \n on last field
  3971.         @array = split(/:/);
  3972.         ...
  3973.     }
  3974.  
  3975. You can actually chop anything that's an lvalue, including an assignment: 
  3976.  
  3977.     chop($cwd = `pwd`);
  3978.     chop($answer = <STDIN>);
  3979.  
  3980. If you chop a list, each element is chopped.  Only the value of the last chop 
  3981. is returned. 
  3982.  
  3983. Note that chop returns the last character.  To return all but the last 
  3984. character, use substr($string, 0, -1). 
  3985.  
  3986.  
  3987. ΓòÉΓòÉΓòÉ 11.14. chown LIST ΓòÉΓòÉΓòÉ
  3988.  
  3989. chown LIST 
  3990.  
  3991. Changes the owner (and group) of a list of files.  The first two elements of 
  3992. the list must be the NUMERICAL uid and gid, in that order. Returns the number 
  3993. of files successfully changed. 
  3994.  
  3995.     $cnt = chown $uid, $gid, 'foo', 'bar';
  3996.     chown $uid, $gid, @filenames;
  3997.  
  3998. Here's an example that looks up non-numeric uids in the passwd file: 
  3999.  
  4000.     print "User: ";
  4001.     chop($user = <STDIN>);
  4002.     print "Files: "
  4003.     chop($pattern = <STDIN>);
  4004.     ($login,$pass,$uid,$gid) = getpwnam($user)
  4005.         or die "$user not in passwd file";
  4006.     @ary = <${pattern}>;        # expand filenames
  4007.     chown $uid, $gid, @ary;
  4008.  
  4009. On most systems, you are not allowed to change the ownership of the file unless 
  4010. you're the superuser, although you should be able to change the group to any of 
  4011. your secondary groups.  On insecure systems, these restrictions may be relaxed, 
  4012. but this is not a portable assumption. 
  4013.  
  4014.  
  4015. ΓòÉΓòÉΓòÉ 11.15. chr NUMBER ΓòÉΓòÉΓòÉ
  4016.  
  4017. chr NUMBER 
  4018.  
  4019. Returns the character represented by that NUMBER in the character set. For 
  4020. example, chr(65) is "A" in ASCII. 
  4021.  
  4022.  
  4023. ΓòÉΓòÉΓòÉ 11.16. chroot FILENAME ΓòÉΓòÉΓòÉ
  4024.  
  4025. chroot FILENAME 
  4026.  
  4027. This function works as the system call by the same name: it makes the named 
  4028. directory the new root directory for all further pathnames that begin with a 
  4029. "/" by your process and all of its children.  (It doesn't change your current 
  4030. working directory is unaffected.)  For security reasons, this call is 
  4031. restricted to the superuser.  If FILENAME is omitted, does chroot to $_. 
  4032.  
  4033.  
  4034. ΓòÉΓòÉΓòÉ 11.17. close FILEHANDLE ΓòÉΓòÉΓòÉ
  4035.  
  4036. close FILEHANDLE 
  4037.  
  4038. Closes the file or pipe associated with the file handle, returning TRUE only if 
  4039. stdio successfully flushes buffers and closes the system file descriptor.  You 
  4040. don't have to close FILEHANDLE if you are immediately going to do another 
  4041. open() on it, since open() will close it for you.  (See open().)  However, an 
  4042. explicit close on an input file resets the line counter ($.), while the 
  4043. implicit close done by open() does not.  Also, closing a pipe will wait for the 
  4044. process executing on the pipe to complete, in case you want to look at the 
  4045. output of the pipe afterwards.  Closing a pipe explicitly also puts the status 
  4046. value of the command into $?.  Example: 
  4047.  
  4048.     open(OUTPUT, '|sort >foo'); # pipe to sort
  4049.     ...                         # print stuff to output
  4050.     close OUTPUT;               # wait for sort to finish
  4051.     open(INPUT, 'foo');         # get sort's results
  4052.  
  4053. FILEHANDLE may be an expression whose value gives the real filehandle name. 
  4054.  
  4055.  
  4056. ΓòÉΓòÉΓòÉ 11.18. closedir DIRHANDLE ΓòÉΓòÉΓòÉ
  4057.  
  4058. closedir DIRHANDLE 
  4059.  
  4060. Closes a directory opened by opendir(). 
  4061.  
  4062.  
  4063. ΓòÉΓòÉΓòÉ 11.19. connect SOCKET,NAME ΓòÉΓòÉΓòÉ
  4064.  
  4065. connect SOCKET,NAME 
  4066.  
  4067. Attempts to connect to a remote socket, just as the connect system call does. 
  4068. Returns TRUE if it succeeded, FALSE otherwise.  NAME should be a packed address 
  4069. of the appropriate type for the socket.  See the examples in perlipc/"Sockets: 
  4070. Client/Server Communication". 
  4071.  
  4072.  
  4073. ΓòÉΓòÉΓòÉ 11.20. continue BLOCK ΓòÉΓòÉΓòÉ
  4074.  
  4075. continue BLOCK 
  4076.  
  4077. Actually a flow control statement rather than a function.  If there is a 
  4078. continue BLOCK attached to a BLOCK (typically in a while or foreach), it is 
  4079. always executed just before the conditional is about to be evaluated again, 
  4080. just like the third part of a for loop in C.  Thus it can be used to increment 
  4081. a loop variable, even when the loop has been continued via the next statement 
  4082. (which is similar to the C continue statement). 
  4083.  
  4084.  
  4085. ΓòÉΓòÉΓòÉ 11.21. cos EXPR ΓòÉΓòÉΓòÉ
  4086.  
  4087. cos EXPR 
  4088.  
  4089. Returns the cosine of EXPR (expressed in radians).  If EXPR is omitted takes 
  4090. cosine of $_. 
  4091.  
  4092.  
  4093. ΓòÉΓòÉΓòÉ 11.22. crypt PLAINTEXT,SALT ΓòÉΓòÉΓòÉ
  4094.  
  4095. crypt PLAINTEXT,SALT 
  4096.  
  4097. Encrypts a string exactly like the crypt(3) function in the C library (assuming 
  4098. that you actually have a version there that has not been extirpated as a 
  4099. potential munition).  This can prove useful for checking the password file for 
  4100. lousy passwords, amongst other things.  Only the guys wearing white hats should 
  4101. do this. 
  4102.  
  4103. Here's an example that makes sure that whoever runs this program knows their 
  4104. own password: 
  4105.  
  4106.     $pwd = (getpwuid($<))[1];
  4107.     $salt = substr($pwd, 0, 2);
  4108.     system "stty -echo";
  4109.     print "Password: ";
  4110.     chop($word = <STDIN>);
  4111.     print "\n";
  4112.     system "stty echo";
  4113.     if (crypt($word, $salt) ne $pwd) {
  4114.         die "Sorry...\n";
  4115.     } else {
  4116.         print "ok\n";
  4117.     }
  4118.  
  4119. Of course, typing in your own password to whoever asks you for it is unwise. 
  4120.  
  4121.  
  4122. ΓòÉΓòÉΓòÉ 11.23. dbmclose ASSOC_ARRAY ΓòÉΓòÉΓòÉ
  4123.  
  4124. dbmclose ASSOC_ARRAY 
  4125.  
  4126. [This function has been superseded by the untie() function.] 
  4127.  
  4128. Breaks the binding between a DBM file and an associative array. 
  4129.  
  4130.  
  4131. ΓòÉΓòÉΓòÉ 11.24. dbmopen ASSOC,DBNAME,MODE ΓòÉΓòÉΓòÉ
  4132.  
  4133. dbmopen ASSOC,DBNAME,MODE 
  4134.  
  4135. [This function has been superseded by the tie() function.] 
  4136.  
  4137. This binds a dbm(3), ndbm(3), sdbm(3), gdbm(), or Berkeley DB file to an 
  4138. associative array.  ASSOC is the name of the associative array.  (Unlike normal 
  4139. open, the first argument is NOT a filehandle, even though it looks like one). 
  4140. DBNAME is the name of the database (without the .dir or .pag extension if any). 
  4141. If the database does not exist, it is created with protection specified by MODE 
  4142. (as modified by the umask()). If your system only supports the older DBM 
  4143. functions, you may perform only one dbmopen() in your program.  In older 
  4144. versions of Perl, if your system had neither DBM nor ndbm, calling dbmopen() 
  4145. produced a fatal error; it now falls back to sdbm(3). 
  4146.  
  4147. If you don't have write access to the DBM file, you can only read associative 
  4148. array variables, not set them.  If you want to test whether you can write, 
  4149. either use file tests or try setting a dummy array entry inside an eval(), 
  4150. which will trap the error. 
  4151.  
  4152. Note that functions such as keys() and values() may return huge array values 
  4153. when used on large DBM files.  You may prefer to use the each() function to 
  4154. iterate over large DBM files.  Example: 
  4155.  
  4156.     # print out history file offsets
  4157.     dbmopen(%HIST,'/usr/lib/news/history',0666);
  4158.     while (($key,$val) = each %HIST) {
  4159.         print $key, ' = ', unpack('L',$val), "\n";
  4160.     }
  4161.     dbmclose(%HIST);
  4162.  
  4163. See also L<AnyDBM_File> for a more general description of the pros and cons of 
  4164. the various dbm apparoches, as well as L<DB_File> for a particularly rich 
  4165. implementation. 
  4166.  
  4167.  
  4168. ΓòÉΓòÉΓòÉ 11.25. defined EXPR ΓòÉΓòÉΓòÉ
  4169.  
  4170. defined EXPR 
  4171.  
  4172. Returns a boolean value saying whether EXPR has a real value or not.  Many 
  4173. operations return the undefined value under exceptional conditions, such as end 
  4174. of file, uninitialized variable, system error and such.  This function allows 
  4175. you to distinguish between an undefined null scalar and a defined null scalar 
  4176. with operations that might return a real null string, such as referencing 
  4177. elements of an array.  You may also check to see if arrays or subroutines 
  4178. exist.  Use of defined on predefined variables is not guaranteed to produce 
  4179. intuitive results. 
  4180.  
  4181. When used on a hash array element, it tells you whether the value is defined, 
  4182. not whether the key exists in the hash.  Use exists() for that. 
  4183.  
  4184. Examples: 
  4185.  
  4186.     print if defined $switch{'D'};
  4187.     print "$val\n" while defined($val = pop(@ary));
  4188.     die "Can't readlink $sym: $!"
  4189.         unless defined($value = readlink $sym);
  4190.     eval '@foo = ()' if defined(@foo);
  4191.     die "No XYZ package defined" unless defined %_XYZ;
  4192.     sub foo { defined &$bar ? &$bar(@_) : die "No bar"; }
  4193.  
  4194. See also undef(). 
  4195.  
  4196.  
  4197. ΓòÉΓòÉΓòÉ 11.26. delete EXPR ΓòÉΓòÉΓòÉ
  4198.  
  4199. delete EXPR 
  4200.  
  4201. Deletes the specified value from its hash array.  Returns the deleted value, or 
  4202. the undefined value if nothing was deleted.  Deleting from $ENV{} modifies the 
  4203. environment.  Deleting from an array tied to a DBM file deletes the entry from 
  4204. the DBM file.  (But deleting from a tie()d hash doesn't necessarily return 
  4205. anything.) 
  4206.  
  4207. The following deletes all the values of an associative array: 
  4208.  
  4209.     foreach $key (keys %ARRAY) {
  4210.         delete $ARRAY{$key};
  4211.     }
  4212.  
  4213. (But it would be faster to use the undef() command.)  Note that the EXPR can be 
  4214. arbitrarily complicated as long as the final operation is a hash key lookup: 
  4215.  
  4216.     delete $ref->[$x][$y]{$key};
  4217.  
  4218.  
  4219. ΓòÉΓòÉΓòÉ 11.27. die LIST ΓòÉΓòÉΓòÉ
  4220.  
  4221. die LIST 
  4222.  
  4223. Outside of an eval(), prints the value of LIST to STDERR and exits with the 
  4224. current value of $! (errno).  If $! is 0, exits with the value of ($? > 8)> 
  4225. (backtick `command` status).  If ($? > 8)> is 0, exits with 255.  Inside an 
  4226. eval(), the error message is stuffed into $@, and the eval() is terminated with 
  4227. the undefined value; this makes die() the way to raise an exception. 
  4228.  
  4229. Equivalent examples: 
  4230.  
  4231.     die "Can't cd to spool: $!\n" unless chdir '/usr/spool/news';
  4232.     chdir '/usr/spool/news' or die "Can't cd to spool: $!\n"
  4233.  
  4234. If the value of EXPR does not end in a newline, the current script line number 
  4235. and input line number (if any) are also printed, and a newline is supplied. 
  4236. Hint: sometimes appending ", stopped" to your message will cause it to make 
  4237. better sense when the string "at foo line 123" is appended.  Suppose you are 
  4238. running script "canasta". 
  4239.  
  4240.     die "/etc/games is no good";
  4241.     die "/etc/games is no good, stopped";
  4242.  
  4243. produce, respectively 
  4244.  
  4245.     /etc/games is no good at canasta line 123.
  4246.     /etc/games is no good, stopped at canasta line 123.
  4247.  
  4248. See also exit() and warn(). 
  4249.  
  4250.  
  4251. ΓòÉΓòÉΓòÉ 11.28. do BLOCK ΓòÉΓòÉΓòÉ
  4252.  
  4253. do BLOCK 
  4254.  
  4255. Not really a function.  Returns the value of the last command in the sequence 
  4256. of commands indicated by BLOCK.  When modified by a loop modifier, executes the 
  4257. BLOCK once before testing the loop condition. (On other statements the loop 
  4258. modifiers test the conditional first.) 
  4259.  
  4260.  
  4261. ΓòÉΓòÉΓòÉ 11.29. do SUBROUTINE(LIST) ΓòÉΓòÉΓòÉ
  4262.  
  4263. do SUBROUTINE(LIST) 
  4264.  
  4265. A deprecated form of subroutine call.  See perlsub. 
  4266.  
  4267.  
  4268. ΓòÉΓòÉΓòÉ 11.30. do EXPR ΓòÉΓòÉΓòÉ
  4269.  
  4270. do EXPR 
  4271.  
  4272. Uses the value of EXPR as a filename and executes the contents of the file as a 
  4273. Perl script.  Its primary use is to include subroutines from a Perl subroutine 
  4274. library. 
  4275.  
  4276.     do 'stat.pl';
  4277.  
  4278. is just like 
  4279.  
  4280.     eval `cat stat.pl`;
  4281.  
  4282. except that it's more efficient, more concise, keeps track of the current 
  4283. filename for error messages, and searches all the -I libraries if the file 
  4284. isn't in the current directory (see also the @INC array in perlvar/Predefined 
  4285. Names).  It's the same, however, in that it does reparse the file every time 
  4286. you call it, so you probably don't want to do this inside a loop. 
  4287.  
  4288. Note that inclusion of library modules is better done with the use() and 
  4289. require() operators, which also do error checking and raise an exception if 
  4290. there's a problem. 
  4291.  
  4292.  
  4293. ΓòÉΓòÉΓòÉ 11.31. dump LABEL ΓòÉΓòÉΓòÉ
  4294.  
  4295. dump LABEL 
  4296.  
  4297. This causes an immediate core dump.  Primarily this is so that you can use the 
  4298. undump program to turn your core dump into an executable binary after having 
  4299. initialized all your variables at the beginning of the program.  When the new 
  4300. binary is executed it will begin by executing a goto LABEL (with all the 
  4301. restrictions that goto suffers).  Think of it as a goto with an intervening 
  4302. core dump and reincarnation.  If LABEL is omitted, restarts the program from 
  4303. the top.  WARNING: any files opened at the time of the dump will NOT be open 
  4304. any more when the program is reincarnated, with possible resulting confusion on 
  4305. the part of Perl.  See also -u option in perlrun. 
  4306.  
  4307. Example: 
  4308.  
  4309.     #!/usr/bin/perl
  4310.     require 'getopt.pl';
  4311.     require 'stat.pl';
  4312.     %days = (
  4313.         'Sun' => 1,
  4314.         'Mon' => 2,
  4315.         'Tue' => 3,
  4316.         'Wed' => 4,
  4317.         'Thu' => 5,
  4318.         'Fri' => 6,
  4319.         'Sat' => 7,
  4320.     );
  4321.     dump QUICKSTART if $ARGV[0] eq '-d';
  4322.     QUICKSTART:
  4323.     Getopt('f');
  4324.  
  4325.  
  4326. ΓòÉΓòÉΓòÉ 11.32. each ASSOC_ARRAY ΓòÉΓòÉΓòÉ
  4327.  
  4328. each ASSOC_ARRAY 
  4329.  
  4330. Returns a 2-element array consisting of the key and value for the next value of 
  4331. an associative array, so that you can iterate over it. Entries are returned in 
  4332. an apparently random order.  When the array is entirely read, a null array is 
  4333. returned (which when assigned produces a FALSE (0) value).  The next call to 
  4334. each() after that will start iterating again.  The iterator can be reset only 
  4335. by reading all the elements from the array.  You should not add elements to an 
  4336. array while you're iterating over it.  There is a single iterator for each 
  4337. associative array, shared by all each(), keys() and values() function calls in 
  4338. the program.  The following prints out your environment like the printenv(1) 
  4339. program, only in a different order: 
  4340.  
  4341.     while (($key,$value) = each %ENV) {
  4342.         print "$key=$value\n";
  4343.     }
  4344.  
  4345. See also keys() and values(). 
  4346.  
  4347.  
  4348. ΓòÉΓòÉΓòÉ 11.33. eof FILEHANDLE ΓòÉΓòÉΓòÉ
  4349.  
  4350. eof FILEHANDLE 
  4351.  
  4352. eof () 
  4353.  
  4354. eof 
  4355.  
  4356. Returns 1 if the next read on FILEHANDLE will return end of file, or if 
  4357. FILEHANDLE is not open.  FILEHANDLE may be an expression whose value gives the 
  4358. real filehandle name.  (Note that this function actually reads a character and 
  4359. then ungetc()s it, so it is not very useful in an interactive context.)  Do not 
  4360. read from a terminal file (or call eof(FILEHANDLE) on it) after end-of-file is 
  4361. reached.  Filetypes such as terminals may lose the end-of-file condition if you 
  4362. do. 
  4363.  
  4364. An eof without an argument uses the last file read as argument. Empty 
  4365. parentheses () may be used to indicate the pseudofile formed of the files 
  4366. listed on the command line, i.e. eof() is reasonable to use inside a while (<>) 
  4367. loop to detect the end of only the last file.  Use eof(ARGV) or eof without the 
  4368. parentheses to test EACH file in a while (<>) loop.  Examples: 
  4369.  
  4370.     # reset line numbering on each input file
  4371.     while (<>) {
  4372.         print "$.\t$_";
  4373.         close(ARGV) if (eof);   # Not eof().
  4374.     }
  4375.     # insert dashes just before last line of last file
  4376.     while (<>) {
  4377.         if (eof()) {
  4378.             print "--------------\n";
  4379.             close(ARGV);        # close or break; is needed if we
  4380.                                 # are reading from the terminal
  4381.         }
  4382.         print;
  4383.     }
  4384.  
  4385. Practical hint: you almost never need to use eof in Perl, because the input 
  4386. operators return undef when they run out of data.  Testing eof 
  4387.  
  4388.  
  4389. ΓòÉΓòÉΓòÉ 11.34. eval EXPR ΓòÉΓòÉΓòÉ
  4390.  
  4391. eval EXPR 
  4392.  
  4393. eval BLOCK 
  4394.  
  4395. EXPR is parsed and executed as if it were a little Perl program.  It is 
  4396. executed in the context of the current Perl program, so that any variable 
  4397. settings, subroutine or format definitions remain afterwards. The value 
  4398. returned is the value of the last expression evaluated, or a return statement 
  4399. may be used, just as with subroutines. 
  4400.  
  4401. If there is a syntax error or runtime error, or a die() statement is executed, 
  4402. an undefined value is returned by eval(), and $@ is set to the error message. 
  4403. If there was no error, $@ is guaranteed to be a null string.  If EXPR is 
  4404. omitted, evaluates $_.  The final semicolon, if any, may be omitted from the 
  4405. expression. 
  4406.  
  4407. Note that, since eval() traps otherwise-fatal errors, it is useful for 
  4408. determining whether a particular feature (such as socket() or symlink()) is 
  4409. implemented.  It is also Perl's exception trapping mechanism, where the die 
  4410. operator is used to raise exceptions. 
  4411.  
  4412. If the code to be executed doesn't vary, you may use the eval-BLOCK form to 
  4413. trap run-time errors without incurring the penalty of recompiling each time. 
  4414. The error, if any, is still returned in $@. Examples: 
  4415.  
  4416.     # make divide-by-zero non-fatal
  4417.     eval { $answer = $a / $b; }; warn $@ if $@;
  4418.     # same thing, but less efficient
  4419.     eval '$answer = $a / $b'; warn $@ if $@;
  4420.     # a compile-time error
  4421.     eval { $answer = };
  4422.     # a run-time error
  4423.     eval '$answer =';   # sets $@
  4424.  
  4425. With an eval(), you should be especially careful to remember what's being 
  4426. looked at when: 
  4427.  
  4428.     eval $x;            # CASE 1
  4429.     eval "$x";          # CASE 2
  4430.     eval '$x';          # CASE 3
  4431.     eval { $x };        # CASE 4
  4432.     eval "\$$x++"       # CASE 5
  4433.     $$x++;              # CASE 6
  4434.  
  4435. Cases 1 and 2 above behave identically: they run the code contained in the 
  4436. variable $x.  (Although case 2 has misleading double quotes making the reader 
  4437. wonder what else might be happening (nothing is).) Cases 3 and 4 likewise 
  4438. behave in the same way: they run the code <$x>, which does nothing at all. 
  4439. (Case 4 is preferred for purely visual reasons.) Case 5 is a place where 
  4440. normally you WOULD like to use double quotes, except that in that particular 
  4441. situation, you can just use symbolic references instead, as in case 6. 
  4442.  
  4443.  
  4444. ΓòÉΓòÉΓòÉ 11.35. exec LIST ΓòÉΓòÉΓòÉ
  4445.  
  4446. exec LIST 
  4447.  
  4448. The exec() function executes a system command AND NEVER RETURNS.  Use the 
  4449. system() function if you want it to return. 
  4450.  
  4451. If there is more than one argument in LIST, or if LIST is an array with more 
  4452. than one value, calls execvp(3) with the arguments in LIST.  If there is only 
  4453. one scalar argument, the argument is checked for shell metacharacters.  If 
  4454. there are any, the entire argument is passed to /bin/sh -c for parsing.  If 
  4455. there are none, the argument is split into words and passed directly to 
  4456. execvp(), which is more efficient. Note: exec() (and system(0) do not flush 
  4457. your output buffer, so you may need to set $| to avoid lost output.  Examples: 
  4458.  
  4459.     exec '/bin/echo', 'Your arguments are: ', @ARGV;
  4460.     exec "sort $outfile | uniq";
  4461.  
  4462. If you don't really want to execute the first argument, but want to lie to the 
  4463. program you are executing about its own name, you can specify the program you 
  4464. actually want to run as an "indirect object" (without a comma) in front of the 
  4465. LIST.  (This always forces interpretation of the LIST as a multi-valued list, 
  4466. even if there is only a single scalar in the list.)  Example: 
  4467.  
  4468.     $shell = '/bin/csh';
  4469.     exec $shell '-sh';          # pretend it's a login shell
  4470.  
  4471. or, more directly, 
  4472.  
  4473.     exec {'/bin/csh'} '-sh';    # pretend it's a login shell
  4474.  
  4475.  
  4476. ΓòÉΓòÉΓòÉ 11.36. exists EXPR ΓòÉΓòÉΓòÉ
  4477.  
  4478. exists EXPR 
  4479.  
  4480. Returns TRUE if the specified hash key exists in its hash array, even if the 
  4481. corresponding value is undefined. 
  4482.  
  4483.     print "Exists\n" if exists $array{$key};
  4484.     print "Defined\n" if defined $array{$key};
  4485.     print "True\n" if $array{$key};
  4486.  
  4487. A hash element can only be TRUE if it's defined, and defined if it exists, but 
  4488. the reverse doesn't necessarily hold true. 
  4489.  
  4490. Note that the EXPR can be arbitrarily complicated as long as the final 
  4491. operation is a hash key lookup: 
  4492.  
  4493.     if (exists $ref->[$x][$y]{$key}) { ... }
  4494.  
  4495.  
  4496. ΓòÉΓòÉΓòÉ 11.37. exit EXPR ΓòÉΓòÉΓòÉ
  4497.  
  4498. exit EXPR 
  4499.  
  4500. Evaluates EXPR and exits immediately with that value.  (Actually, it calls any 
  4501. defined END routines first, but the END routines may not abort the exit. 
  4502. Likewise any object destructors that need to be called are called before exit.) 
  4503. Example: 
  4504.  
  4505.     $ans = <STDIN>;
  4506.     exit 0 if $ans =~ /^[Xx]/;
  4507.  
  4508. See also die().  If EXPR is omitted, exits with 0 status. 
  4509.  
  4510.  
  4511. ΓòÉΓòÉΓòÉ 11.38. exp EXPR ΓòÉΓòÉΓòÉ
  4512.  
  4513. exp EXPR 
  4514.  
  4515. Returns e (the natural logarithm base) to the power of EXPR. If EXPR is 
  4516. omitted, gives exp($_). 
  4517.  
  4518.  
  4519. ΓòÉΓòÉΓòÉ 11.39. fcntl FILEHANDLE,FUNCTION,SCALAR ΓòÉΓòÉΓòÉ
  4520.  
  4521. fcntl FILEHANDLE,FUNCTION,SCALAR 
  4522.  
  4523. Implements the fcntl(2) function.  You'll probably have to say 
  4524.  
  4525.     use Fcntl;
  4526.  
  4527. first to get the correct function definitions.  Argument processing and value 
  4528. return works just like ioctl() below.  Note that fcntl() will produce a fatal 
  4529. error if used on a machine that doesn't implement fcntl(2). For example: 
  4530.  
  4531.     use Fcntl;
  4532.     fcntl($filehandle, F_GETLK, $packed_return_buffer);
  4533.  
  4534.  
  4535. ΓòÉΓòÉΓòÉ 11.40. fileno FILEHANDLE ΓòÉΓòÉΓòÉ
  4536.  
  4537. fileno FILEHANDLE 
  4538.  
  4539. Returns the file descriptor for a filehandle.  This is useful for constructing 
  4540. bitmaps for select().  If FILEHANDLE is an expression, the value is taken as 
  4541. the name of the filehandle. 
  4542.  
  4543.  
  4544. ΓòÉΓòÉΓòÉ 11.41. flock FILEHANDLE,OPERATION ΓòÉΓòÉΓòÉ
  4545.  
  4546. flock FILEHANDLE,OPERATION 
  4547.  
  4548. Calls flock(2) on FILEHANDLE.  See L<flock(2)> for definition of OPERATION. 
  4549. Returns TRUE for success, FALSE on failure.  Will produce a fatal error if used 
  4550. on a machine that doesn't implement either flock(2) or fcntl(2). The fcntl(2) 
  4551. system call will be automatically used if flock(2) is missing from your system. 
  4552. This makes flock() the portable file locking strategy, although it will only 
  4553. lock entire files, not records.  Note also that some versions of flock() cannot 
  4554. lock things over the network; you would need to use the more system-specific 
  4555. fcntl() for that. 
  4556.  
  4557. Here's a mailbox appender for BSD systems. 
  4558.  
  4559.     $LOCK_SH = 1;
  4560.     $LOCK_EX = 2;
  4561.     $LOCK_NB = 4;
  4562.     $LOCK_UN = 8;
  4563.     sub lock {
  4564.         flock(MBOX,$LOCK_EX);
  4565.         # and, in case someone appended
  4566.         # while we were waiting...
  4567.         seek(MBOX, 0, 2);
  4568.     }
  4569.     sub unlock {
  4570.         flock(MBOX,$LOCK_UN);
  4571.     }
  4572.     open(MBOX, ">>/usr/spool/mail/$ENV{'USER'}")
  4573.             or die "Can't open mailbox: $!";
  4574.     lock();
  4575.     print MBOX $msg,"\n\n";
  4576.     unlock();
  4577.  
  4578. See also L<DB_File> for other flock() examples. 
  4579.  
  4580.  
  4581. ΓòÉΓòÉΓòÉ 11.42. fork ΓòÉΓòÉΓòÉ
  4582.  
  4583. fork 
  4584.  
  4585. Does a fork(2) system call.  Returns the child pid to the parent process and 0 
  4586. to the child process, or undef if the fork is unsuccessful. Note: unflushed 
  4587. buffers remain unflushed in both processes, which means you may need to set $| 
  4588. ($AUTOFLUSH in English) or call the autoflush() FileHandle method to avoid 
  4589. duplicate output. 
  4590.  
  4591. If you fork() without ever waiting on your children, you will accumulate 
  4592. zombies: 
  4593.  
  4594.     $SIG{CHLD} = sub { wait };
  4595.  
  4596. There's also the double-fork trick (error checking on fork() returns omitted); 
  4597.  
  4598.     unless ($pid = fork) {
  4599.         unless (fork) {
  4600.             exec "what you really wanna do";
  4601.             die "no exec";
  4602.             # ... or ...
  4603.             ## (some_perl_code_here)
  4604.             exit 0;
  4605.         }
  4606.         exit 0;
  4607.     }
  4608.     waitpid($pid,0);
  4609.  
  4610. See also perlipc for more examples of forking and reaping moribund children. 
  4611.  
  4612.  
  4613. ΓòÉΓòÉΓòÉ 11.43. format ΓòÉΓòÉΓòÉ
  4614.  
  4615. format 
  4616.  
  4617. Declare a picture format with use by the write() function.  For example: 
  4618.  
  4619.     format Something =
  4620.         Test: @<<<<<<<< @||||| @>>>>>
  4621.               $str,     $%,    '$' . int($num)
  4622.     .
  4623.     $str = "widget";
  4624.     $num = $cost/$quantiy;
  4625.     $~ = 'Something';
  4626.     write;
  4627.  
  4628. See perlform for many details and examples. 
  4629.  
  4630.  
  4631. ΓòÉΓòÉΓòÉ 11.44. formline PICTURE, LIST ΓòÉΓòÉΓòÉ
  4632.  
  4633. formline PICTURE, LIST 
  4634.  
  4635. This is an internal function used by formats, though you may call it too.  It 
  4636. formats (see perlform) a list of values according to the contents of PICTURE, 
  4637. placing the output into the format output accumulator, $^A (or $ACCUMULATOR in 
  4638. English). Eventually, when a write() is done, the contents of $^A are written 
  4639. to some filehandle, but you could also read $^A yourself and then set $^A back 
  4640. to "".  Note that a format typically does one formline() per line of form, but 
  4641. the formline() function itself doesn't care how many newlines are embedded in 
  4642. the PICTURE.  This means that the ~ and ~~ tokens will treat the entire PICTURE 
  4643. as a single line. You may therefore need to use multiple formlines to implement 
  4644. a single record format, just like the format compiler. 
  4645.  
  4646. Be careful if you put double quotes around the picture, since an "@" character 
  4647. may be taken to mean the beginning of an array name. formline() always returns 
  4648. TRUE.  See perlform for other examples. 
  4649.  
  4650.  
  4651. ΓòÉΓòÉΓòÉ 11.45. getc FILEHANDLE ΓòÉΓòÉΓòÉ
  4652.  
  4653. getc FILEHANDLE 
  4654.  
  4655. getc 
  4656.  
  4657. Returns the next character from the input file attached to FILEHANDLE, or a 
  4658. null string at end of file.  If FILEHANDLE is omitted, reads from STDIN. This 
  4659. is not particularly efficient.  It cannot be used to get unbuffered 
  4660. single-characters, however.  For that, try something more like: 
  4661.  
  4662.     if ($BSD_STYLE) {
  4663.         system "stty cbreak </dev/tty >/dev/tty 2>&1";
  4664.     }
  4665.     else {
  4666.         system "stty", '-icanon', 'eol', "\001";
  4667.     }
  4668.     $key = getc(STDIN);
  4669.     if ($BSD_STYLE) {
  4670.         system "stty -cbreak </dev/tty >/dev/tty 2>&1";
  4671.     }
  4672.     else {
  4673.         system "stty", 'icanon', 'eol', '^@'; # ascii null
  4674.     }
  4675.     print "\n";
  4676.  
  4677. Determination of whether to whether $BSD_STYLE should be set is left as an 
  4678. exercise to the reader. 
  4679.  
  4680. See also the Term::ReadKey module from your nearest CPAN site; details on CPAN 
  4681. can be found on perlmod/CPAN 
  4682.  
  4683.  
  4684. ΓòÉΓòÉΓòÉ 11.46. getlogin ΓòÉΓòÉΓòÉ
  4685.  
  4686. getlogin 
  4687.  
  4688. Returns the current login from /etc/utmp, if any.  If null, use getpwuid(). 
  4689.  
  4690.     $login = getlogin || (getpwuid($<))[0] || "Kilroy";
  4691.  
  4692. Do not consider getlogin() for authorentication: it is not as secure as 
  4693. getpwuid(). 
  4694.  
  4695.  
  4696. ΓòÉΓòÉΓòÉ 11.47. getpeername SOCKET ΓòÉΓòÉΓòÉ
  4697.  
  4698. getpeername SOCKET 
  4699.  
  4700. Returns the packed sockaddr address of other end of the SOCKET connection. 
  4701.  
  4702.     use Socket;
  4703.     $hersockaddr    = getpeername(SOCK);
  4704.     ($port, $iaddr) = unpack_sockaddr_in($hersockaddr);
  4705.     $herhostname    = gethostbyaddr($iaddr, AF_INET);
  4706.     $herstraddr     = inet_ntoa($iaddr);
  4707.  
  4708.  
  4709. ΓòÉΓòÉΓòÉ 11.48. getpgrp PID ΓòÉΓòÉΓòÉ
  4710.  
  4711. getpgrp PID 
  4712.  
  4713. Returns the current process group for the specified PID, 0 for the current 
  4714. process.  Will raise an exception if used on a machine that doesn't implement 
  4715. getpgrp(2).  If PID is omitted, returns process group of current process. 
  4716.  
  4717.  
  4718. ΓòÉΓòÉΓòÉ 11.49. getppid ΓòÉΓòÉΓòÉ
  4719.  
  4720. getppid 
  4721.  
  4722. Returns the process id of the parent process. 
  4723.  
  4724.  
  4725. ΓòÉΓòÉΓòÉ 11.50. getpriority WHICH,WHO ΓòÉΓòÉΓòÉ
  4726.  
  4727. getpriority WHICH,WHO 
  4728.  
  4729. Returns the current priority for a process, a process group, or a user. (See 
  4730. L<getpriority(2)>.)  Will raise a fatal exception if used on a machine that 
  4731. doesn't implement getpriority(2). 
  4732.  
  4733.  
  4734. ΓòÉΓòÉΓòÉ 11.51. getpwnam NAME ΓòÉΓòÉΓòÉ
  4735.  
  4736. getpwnam NAME 
  4737.  
  4738. getgrnam NAME 
  4739.  
  4740. gethostbyname NAME 
  4741.  
  4742. getnetbyname NAME 
  4743.  
  4744. getprotobyname NAME 
  4745.  
  4746. getpwuid UID 
  4747.  
  4748. getgrgid GID 
  4749.  
  4750. getservbyname NAME,PROTO 
  4751.  
  4752. gethostbyaddr ADDR,ADDRTYPE 
  4753.  
  4754. getnetbyaddr ADDR,ADDRTYPE 
  4755.  
  4756. getprotobynumber NUMBER 
  4757.  
  4758. getservbyport PORT,PROTO 
  4759.  
  4760. getpwent 
  4761.  
  4762. getgrent 
  4763.  
  4764. gethostent 
  4765.  
  4766. getnetent 
  4767.  
  4768. getprotoent 
  4769.  
  4770. getservent 
  4771.  
  4772. setpwent 
  4773.  
  4774. setgrent 
  4775.  
  4776. sethostent STAYOPEN 
  4777.  
  4778. setnetent STAYOPEN 
  4779.  
  4780. setprotoent STAYOPEN 
  4781.  
  4782. setservent STAYOPEN 
  4783.  
  4784. endpwent 
  4785.  
  4786. endgrent 
  4787.  
  4788. endhostent 
  4789.  
  4790. endnetent 
  4791.  
  4792. endprotoent 
  4793.  
  4794. endservent 
  4795.  
  4796. These routines perform the same functions as their counterparts in the system 
  4797. library.  Within a list context, the return values from the various get 
  4798. routines are as follows: 
  4799.  
  4800.     ($name,$passwd,$uid,$gid,
  4801.        $quota,$comment,$gcos,$dir,$shell) = getpw*
  4802.     ($name,$passwd,$gid,$members) = getgr*
  4803.     ($name,$aliases,$addrtype,$length,@addrs) = gethost*
  4804.     ($name,$aliases,$addrtype,$net) = getnet*
  4805.     ($name,$aliases,$proto) = getproto*
  4806.     ($name,$aliases,$port,$proto) = getserv*
  4807.  
  4808. (If the entry doesn't exist you get a null list.) 
  4809.  
  4810. Within a scalar context, you get the name, unless the function was a lookup by 
  4811. name, in which case you get the other thing, whatever it is. (If the entry 
  4812. doesn't exist you get the undefined value.)  For example: 
  4813.  
  4814.     $uid = getpwnam
  4815.     $name = getpwuid
  4816.     $name = getpwent
  4817.     $gid = getgrnam
  4818.     $name = getgrgid
  4819.     $name = getgrent
  4820.     etc.
  4821.  
  4822. The $members value returned by getgr*() is a space separated list of the login 
  4823. names of the members of the group. 
  4824.  
  4825. For the gethost*() functions, if the h_errno variable is supported in C, it 
  4826. will be returned to you via $? if the function call fails.  The @addrs value 
  4827. returned by a successful call is a list of the raw addresses returned by the 
  4828. corresponding system library call.  In the Internet domain, each address is 
  4829. four bytes long and you can unpack it by saying something like: 
  4830.  
  4831.     ($a,$b,$c,$d) = unpack('C4',$addr[0]);
  4832.  
  4833.  
  4834. ΓòÉΓòÉΓòÉ 11.52. getsockname SOCKET ΓòÉΓòÉΓòÉ
  4835.  
  4836. getsockname SOCKET 
  4837.  
  4838. Returns the packed sockaddr address of this end of the SOCKET connection. 
  4839.  
  4840.     use Socket;
  4841.     $mysockaddr = getsockname(SOCK);
  4842.     ($port, $myaddr) = unpack_sockaddr_in($mysockaddr);
  4843.  
  4844.  
  4845. ΓòÉΓòÉΓòÉ 11.53. getsockopt SOCKET,LEVEL,OPTNAME ΓòÉΓòÉΓòÉ
  4846.  
  4847. getsockopt SOCKET,LEVEL,OPTNAME 
  4848.  
  4849. Returns the socket option requested, or undefined if there is an error. 
  4850.  
  4851.  
  4852. ΓòÉΓòÉΓòÉ 11.54. glob EXPR ΓòÉΓòÉΓòÉ
  4853.  
  4854. glob EXPR 
  4855.  
  4856. Returns the value of EXPR with filename expansions such as a shell would do. 
  4857. This is the internal function implementing the <*.*> operator, except it's 
  4858. easier to use. 
  4859.  
  4860.  
  4861. ΓòÉΓòÉΓòÉ 11.55. gmtime EXPR ΓòÉΓòÉΓòÉ
  4862.  
  4863. gmtime EXPR 
  4864.  
  4865. Converts a time as returned by the time function to a 9-element array with the 
  4866. time localized for the standard Greenwich timezone. Typically used as follows: 
  4867.  
  4868.     ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  4869.                                             gmtime(time);
  4870.  
  4871. All array elements are numeric, and come straight out of a struct tm. In 
  4872. particular this means that $mon has the range 0..11 and $wday has the range 
  4873. 0..6.  If EXPR is omitted, does gmtime(time()). 
  4874.  
  4875.  
  4876. ΓòÉΓòÉΓòÉ 11.56. goto LABEL ΓòÉΓòÉΓòÉ
  4877.  
  4878. goto LABEL 
  4879.  
  4880. goto EXPR 
  4881.  
  4882. goto &NAME 
  4883.  
  4884. The goto-LABEL form finds the statement labeled with LABEL and resumes 
  4885. execution there.  It may not be used to go into any construct that requires 
  4886. initialization, such as a subroutine or a foreach loop.  It also can't be used 
  4887. to go into a construct that is optimized away.  It can be used to go almost 
  4888. anywhere else within the dynamic scope, including out of subroutines, but it's 
  4889. usually better to use some other construct such as last or die.  The author of 
  4890. Perl has never felt the need to use this form of goto (in Perl, that is--C is 
  4891. another matter). 
  4892.  
  4893. The goto-EXPR form expects a label name, whose scope will be resolved 
  4894. dynamically.  This allows for computed gotos per FORTRAN, but isn't necessarily 
  4895. recommended if you're optimizing for maintainability: 
  4896.  
  4897.     goto ("FOO", "BAR", "GLARCH")[$i];
  4898.  
  4899. The goto-&NAME form is highly magical, and substitutes a call to the named 
  4900. subroutine for the currently running subroutine.  This is used by AUTOLOAD 
  4901. subroutines that wish to load another subroutine and then pretend that the 
  4902. other subroutine had been called in the first place (except that any 
  4903. modifications to @_ in the current subroutine are propagated to the other 
  4904. subroutine.)  After the goto, not even caller() will be able to tell that this 
  4905. routine was called first. 
  4906.  
  4907.  
  4908. ΓòÉΓòÉΓòÉ 11.57. grep BLOCK LIST ΓòÉΓòÉΓòÉ
  4909.  
  4910. grep BLOCK LIST 
  4911.  
  4912. grep EXPR,LIST 
  4913.  
  4914. Evaluates the BLOCK or EXPR for each element of LIST (locally setting $_ to 
  4915. each element) and returns the list value consisting of those elements for which 
  4916. the expression evaluated to TRUE.  In a scalar context, returns the number of 
  4917. times the expression was TRUE. 
  4918.  
  4919.     @foo = grep(!/^#/, @bar);    # weed out comments
  4920.  
  4921. or equivalently, 
  4922.  
  4923.     @foo = grep {!/^#/} @bar;    # weed out comments
  4924.  
  4925. Note that, since $_ is a reference into the list value, it can be used to 
  4926. modify the elements of the array.  While this is useful and supported, it can 
  4927. cause bizarre results if the LIST is not a named array. 
  4928.  
  4929.  
  4930. ΓòÉΓòÉΓòÉ 11.58. hex EXPR ΓòÉΓòÉΓòÉ
  4931.  
  4932. hex EXPR 
  4933.  
  4934. Interprets EXPR as a hex string and returns the corresponding decimal value. 
  4935. (To convert strings that might start with 0 or 0x see oct().)  If EXPR is 
  4936. omitted, uses $_. 
  4937.  
  4938.  
  4939. ΓòÉΓòÉΓòÉ 11.59. import ΓòÉΓòÉΓòÉ
  4940.  
  4941. import 
  4942.  
  4943. There is no built-in import() function.  It is merely an ordinary method 
  4944. (subroutine) defined (or inherited) by modules that wish to export names to 
  4945. another module.  The use() function calls the import() method for the package 
  4946. used.  See also L</use>, perlmod, and L<Exporter>. 
  4947.  
  4948.  
  4949. ΓòÉΓòÉΓòÉ 11.60. index STR,SUBSTR,POSITION ΓòÉΓòÉΓòÉ
  4950.  
  4951. index STR,SUBSTR,POSITION 
  4952.  
  4953. index STR,SUBSTR 
  4954.  
  4955. Returns the position of the first occurrence of SUBSTR in STR at or after 
  4956. POSITION.  If POSITION is omitted, starts searching from the beginning of the 
  4957. string.  The return value is based at 0 (or whatever you've set the $[ variable 
  4958. to--but don't do that).  If the substring is not found, returns one less than 
  4959. the base, ordinarily -1. 
  4960.  
  4961.  
  4962. ΓòÉΓòÉΓòÉ 11.61. int EXPR ΓòÉΓòÉΓòÉ
  4963.  
  4964. int EXPR 
  4965.  
  4966. Returns the integer portion of EXPR.  If EXPR is omitted, uses $_. 
  4967.  
  4968.  
  4969. ΓòÉΓòÉΓòÉ 11.62. ioctl FILEHANDLE,FUNCTION,SCALAR ΓòÉΓòÉΓòÉ
  4970.  
  4971. ioctl FILEHANDLE,FUNCTION,SCALAR 
  4972.  
  4973. Implements the ioctl(2) function.  You'll probably have to say 
  4974.  
  4975.     require "ioctl.ph"; # probably in /usr/local/lib/perl/ioctl.ph
  4976.  
  4977. first to get the correct function definitions.  If ioctl.ph doesn't exist or 
  4978. doesn't have the correct definitions you'll have to roll your own, based on 
  4979. your C header files such as <sys/ioctl.h>. (There is a Perl script called h2ph 
  4980. that comes with the Perl kit which may help you in this, but it's non-trivial.) 
  4981. SCALAR will be read and/or written depending on the FUNCTION--a pointer to the 
  4982. string value of SCALAR will be passed as the third argument of the actual ioctl 
  4983. call.  (If SCALAR has no string value but does have a numeric value, that value 
  4984. will be passed rather than a pointer to the string value.  To guarantee this to 
  4985. be TRUE, add a 0 to the scalar before using it.)  The pack() and unpack() 
  4986. functions are useful for manipulating the values of structures used by ioctl(). 
  4987. The following example sets the erase character to DEL. 
  4988.  
  4989.     require 'ioctl.ph';
  4990.     $getp = &TIOCGETP;
  4991.     die "NO TIOCGETP" if $@ || !$getp;
  4992.     $sgttyb_t = "ccccs";                # 4 chars and a short
  4993.     if (ioctl(STDIN,$getp,$sgttyb)) {
  4994.         @ary = unpack($sgttyb_t,$sgttyb);
  4995.         $ary[2] = 127;
  4996.         $sgttyb = pack($sgttyb_t,@ary);
  4997.         ioctl(STDIN,&TIOCSETP,$sgttyb)
  4998.             || die "Can't ioctl: $!";
  4999.     }
  5000.  
  5001. The return value of ioctl (and fcntl) is as follows: 
  5002.  
  5003.         if OS returns:          then Perl returns:
  5004.             -1                    undefined value
  5005.              0                  string "0 but true"
  5006.         anything else               that number
  5007.  
  5008. Thus Perl returns TRUE on success and FALSE on failure, yet you can still 
  5009. easily determine the actual value returned by the operating system: 
  5010.  
  5011.     ($retval = ioctl(...)) || ($retval = -1);
  5012.     printf "System returned %d\n", $retval;
  5013.  
  5014.  
  5015. ΓòÉΓòÉΓòÉ 11.63. join EXPR,LIST ΓòÉΓòÉΓòÉ
  5016.  
  5017. join EXPR,LIST 
  5018.  
  5019. Joins the separate strings of LIST or ARRAY into a single string with fields 
  5020. separated by the value of EXPR, and returns the string. Example: 
  5021.  
  5022.     $_ = join(':', $login,$passwd,$uid,$gid,$gcos,$home,$shell);
  5023.  
  5024. See perlfunc/split. 
  5025.  
  5026.  
  5027. ΓòÉΓòÉΓòÉ 11.64. keys ASSOC_ARRAY ΓòÉΓòÉΓòÉ
  5028.  
  5029. keys ASSOC_ARRAY 
  5030.  
  5031. Returns a normal array consisting of all the keys of the named associative 
  5032. array.  (In a scalar context, returns the number of keys.) The keys are 
  5033. returned in an apparently random order, but it is the same order as either the 
  5034. values() or each() function produces (given that the associative array has not 
  5035. been modified).  Here is yet another way to print your environment: 
  5036.  
  5037.     @keys = keys %ENV;
  5038.     @values = values %ENV;
  5039.     while ($#keys >= 0) {
  5040.         print pop(@keys), '=', pop(@values), "\n";
  5041.     }
  5042.  
  5043. or how about sorted by key: 
  5044.  
  5045.     foreach $key (sort(keys %ENV)) {
  5046.         print $key, '=', $ENV{$key}, "\n";
  5047.     }
  5048.  
  5049. To sort an array by value, you'll need to use a sort{} function.  Here's a 
  5050. descending numeric sort of a hash by its values: 
  5051.  
  5052.     foreach $key (sort { $hash{$b} <=> $hash{$a} } keys %hash)) {
  5053.         printf "%4d %s\n", $hash{$key}, $key;
  5054.     }
  5055.  
  5056.  
  5057. ΓòÉΓòÉΓòÉ 11.65. kill LIST ΓòÉΓòÉΓòÉ
  5058.  
  5059. kill LIST 
  5060.  
  5061. Sends a signal to a list of processes.  The first element of the list must be 
  5062. the signal to send.  Returns the number of processes successfully signaled. 
  5063.  
  5064.     $cnt = kill 1, $child1, $child2;
  5065.     kill 9, @goners;
  5066.  
  5067. Unlike in the shell, in Perl if the SIGNAL is negative, it kills process groups 
  5068. instead of processes.  (On System V, a negative PROCESS number will also kill 
  5069. process groups, but that's not portable.)  That means you usually want to use 
  5070. positive not negative signals.  You may also use a signal name in quotes.  See 
  5071. the perlipc/"Signals" man page for details. 
  5072.  
  5073.  
  5074. ΓòÉΓòÉΓòÉ 11.66. last LABEL ΓòÉΓòÉΓòÉ
  5075.  
  5076. last LABEL 
  5077.  
  5078. last 
  5079.  
  5080. The last command is like the break statement in C (as used in loops); it 
  5081. immediately exits the loop in question.  If the LABEL is omitted, the command 
  5082. refers to the innermost enclosing loop.  The continue block, if any, is not 
  5083. executed: 
  5084.  
  5085.     LINE: while (<STDIN>) {
  5086.         last LINE if /^$/;      # exit when done with header
  5087.         ...
  5088.     }
  5089.  
  5090.  
  5091. ΓòÉΓòÉΓòÉ 11.67. lc EXPR ΓòÉΓòÉΓòÉ
  5092.  
  5093. lc EXPR 
  5094.  
  5095. Returns an lowercased version of EXPR.  This is the internal function 
  5096. implementing the \L escape in double-quoted strings. Should respect any POSIX 
  5097. setlocale() settings. 
  5098.  
  5099.  
  5100. ΓòÉΓòÉΓòÉ 11.68. lcfirst EXPR ΓòÉΓòÉΓòÉ
  5101.  
  5102. lcfirst EXPR 
  5103.  
  5104. Returns the value of EXPR with the first character lowercased.  This is the 
  5105. internal function implementing the \l escape in double-quoted strings. Should 
  5106. respect any POSIX setlocale() settings. 
  5107.  
  5108.  
  5109. ΓòÉΓòÉΓòÉ 11.69. length EXPR ΓòÉΓòÉΓòÉ
  5110.  
  5111. length EXPR 
  5112.  
  5113. Returns the length in characters of the value of EXPR.  If EXPR is omitted, 
  5114. returns length of $_. 
  5115.  
  5116.  
  5117. ΓòÉΓòÉΓòÉ 11.70. link OLDFILE,NEWFILE ΓòÉΓòÉΓòÉ
  5118.  
  5119. link OLDFILE,NEWFILE 
  5120.  
  5121. Creates a new filename linked to the old filename.  Returns 1 for success, 0 
  5122. otherwise. 
  5123.  
  5124.  
  5125. ΓòÉΓòÉΓòÉ 11.71. listen SOCKET,QUEUESIZE ΓòÉΓòÉΓòÉ
  5126.  
  5127. listen SOCKET,QUEUESIZE 
  5128.  
  5129. Does the same thing that the listen system call does.  Returns TRUE if it 
  5130. succeeded, FALSE otherwise.  See example in perlipc/"Sockets: Client/Server 
  5131. Communication". 
  5132.  
  5133.  
  5134. ΓòÉΓòÉΓòÉ 11.72. local EXPR ΓòÉΓòÉΓòÉ
  5135.  
  5136. local EXPR 
  5137.  
  5138. A local modifies the listed variables to be local to the enclosing block, 
  5139. subroutine, eval{} or do.  If more than one value is listed, the list must be 
  5140. placed in parens.  See L<perlsub/"Temporary Values via local()"> for details. 
  5141.  
  5142. But you really probably want to be using my() instead, because local() isn't 
  5143. what most people think of as "local").  See L<perlsub/"Private Variables via 
  5144. my()"> for details. 
  5145.  
  5146.  
  5147. ΓòÉΓòÉΓòÉ 11.73. localtime EXPR ΓòÉΓòÉΓòÉ
  5148.  
  5149. localtime EXPR 
  5150.  
  5151. Converts a time as returned by the time function to a 9-element array with the 
  5152. time analyzed for the local timezone.  Typically used as follows: 
  5153.  
  5154.     ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  5155.                                                 localtime(time);
  5156.  
  5157. All array elements are numeric, and come straight out of a struct tm. In 
  5158. particular this means that $mon has the range 0..11 and $wday has the range 
  5159. 0..6.  If EXPR is omitted, does localtime(time). 
  5160.  
  5161. In a scalar context, prints out the ctime(3) value: 
  5162.  
  5163.     $now_string = localtime;  # e.g. "Thu Oct 13 04:54:34 1994"
  5164.  
  5165. See also perlmod/timelocal and the strftime(3) function available via the POSIX 
  5166. modulie. 
  5167.  
  5168.  
  5169. ΓòÉΓòÉΓòÉ 11.74. log EXPR ΓòÉΓòÉΓòÉ
  5170.  
  5171. log EXPR 
  5172.  
  5173. Returns logarithm (base e) of EXPR.  If EXPR is omitted, returns log of $_. 
  5174.  
  5175.  
  5176. ΓòÉΓòÉΓòÉ 11.75. lstat FILEHANDLE ΓòÉΓòÉΓòÉ
  5177.  
  5178. lstat FILEHANDLE 
  5179.  
  5180. lstat EXPR 
  5181.  
  5182. Does the same thing as the stat() function, but stats a symbolic link instead 
  5183. of the file the symbolic link points to.  If symbolic links are unimplemented 
  5184. on your system, a normal stat() is done. 
  5185.  
  5186.  
  5187. ΓòÉΓòÉΓòÉ 11.76. m// ΓòÉΓòÉΓòÉ
  5188.  
  5189. m// 
  5190.  
  5191. The match operator.  See perlop. 
  5192.  
  5193.  
  5194. ΓòÉΓòÉΓòÉ 11.77. map BLOCK LIST ΓòÉΓòÉΓòÉ
  5195.  
  5196. map BLOCK LIST 
  5197.  
  5198. map EXPR,LIST 
  5199.  
  5200. Evaluates the BLOCK or EXPR for each element of LIST (locally setting $_ to 
  5201. each element) and returns the list value composed of the results of each such 
  5202. evaluation.  Evaluates BLOCK or EXPR in a list context, so each element of LIST 
  5203. may produce zero, one, or more elements in the returned value. 
  5204.  
  5205.     @chars = map(chr, @nums);
  5206.  
  5207. translates a list of numbers to the corresponding characters.  And 
  5208.  
  5209.     %hash = map { getkey($_) => $_ } @array;
  5210.  
  5211. is just a funny way to write 
  5212.  
  5213.     %hash = ();
  5214.     foreach $_ (@array) {
  5215.         $hash{getkey($_)} = $_;
  5216.     }
  5217.  
  5218.  
  5219. ΓòÉΓòÉΓòÉ 11.78. mkdir FILENAME,MODE ΓòÉΓòÉΓòÉ
  5220.  
  5221. mkdir FILENAME,MODE 
  5222.  
  5223. Creates the directory specified by FILENAME, with permissions specified by MODE 
  5224. (as modified by umask).  If it succeeds it returns 1, otherwise it returns 0 
  5225. and sets $! (errno). 
  5226.  
  5227.  
  5228. ΓòÉΓòÉΓòÉ 11.79. msgctl ID,CMD,ARG ΓòÉΓòÉΓòÉ
  5229.  
  5230. msgctl ID,CMD,ARG 
  5231.  
  5232. Calls the System V IPC function msgctl(2).  If CMD is &IPC_STAT, then ARG must 
  5233. be a variable which will hold the returned msqid_ds structure. Returns like 
  5234. ioctl: the undefined value for error, "0 but true" for zero, or the actual 
  5235. return value otherwise. 
  5236.  
  5237.  
  5238. ΓòÉΓòÉΓòÉ 11.80. msgget KEY,FLAGS ΓòÉΓòÉΓòÉ
  5239.  
  5240. msgget KEY,FLAGS 
  5241.  
  5242. Calls the System V IPC function msgget(2).  Returns the message queue id, or 
  5243. the undefined value if there is an error. 
  5244.  
  5245.  
  5246. ΓòÉΓòÉΓòÉ 11.81. msgsnd ID,MSG,FLAGS ΓòÉΓòÉΓòÉ
  5247.  
  5248. msgsnd ID,MSG,FLAGS 
  5249.  
  5250. Calls the System V IPC function msgsnd to send the message MSG to the message 
  5251. queue ID.  MSG must begin with the long integer message type, which may be 
  5252. created with pack("l", $type).  Returns TRUE if successful, or FALSE if there 
  5253. is an error. 
  5254.  
  5255.  
  5256. ΓòÉΓòÉΓòÉ 11.82. msgrcv ID,VAR,SIZE,TYPE,FLAGS ΓòÉΓòÉΓòÉ
  5257.  
  5258. msgrcv ID,VAR,SIZE,TYPE,FLAGS 
  5259.  
  5260. Calls the System V IPC function msgrcv to receive a message from message queue 
  5261. ID into variable VAR with a maximum message size of SIZE.  Note that if a 
  5262. message is received, the message type will be the first thing in VAR, and the 
  5263. maximum length of VAR is SIZE plus the size of the message type.  Returns TRUE 
  5264. if successful, or FALSE if there is an error. 
  5265.  
  5266.  
  5267. ΓòÉΓòÉΓòÉ 11.83. my EXPR ΓòÉΓòÉΓòÉ
  5268.  
  5269. my EXPR 
  5270.  
  5271. A "my" declares the listed variables to be local (lexically) to the enclosing 
  5272. block, subroutine, eval, or do/require/use'd file.  If more than one value is 
  5273. listed, the list must be placed in parens.  See perlsub/"Private Variables via 
  5274. my()" for details. 
  5275.  
  5276.  
  5277. ΓòÉΓòÉΓòÉ 11.84. next LABEL ΓòÉΓòÉΓòÉ
  5278.  
  5279. next LABEL 
  5280.  
  5281. next 
  5282.  
  5283. The next command is like the continue statement in C; it starts the next 
  5284. iteration of the loop: 
  5285.  
  5286.     LINE: while (<STDIN>) {
  5287.         next LINE if /^#/;      # discard comments
  5288.         ...
  5289.     }
  5290.  
  5291. Note that if there were a continue block on the above, it would get executed 
  5292. even on discarded lines.  If the LABEL is omitted, the command refers to the 
  5293. innermost enclosing loop. 
  5294.  
  5295.  
  5296. ΓòÉΓòÉΓòÉ 11.85. no Module LIST ΓòÉΓòÉΓòÉ
  5297.  
  5298. no Module LIST 
  5299.  
  5300. See the "use" function, which "no" is the opposite of. 
  5301.  
  5302.  
  5303. ΓòÉΓòÉΓòÉ 11.86. oct EXPR ΓòÉΓòÉΓòÉ
  5304.  
  5305. oct EXPR 
  5306.  
  5307. Interprets EXPR as an octal string and returns the corresponding decimal value. 
  5308. (If EXPR happens to start off with 0x, interprets it as a hex string instead.) 
  5309. The following will handle decimal, octal, and hex in the standard Perl or C 
  5310. notation: 
  5311.  
  5312.     $val = oct($val) if $val =~ /^0/;
  5313.  
  5314. If EXPR is omitted, uses $_. 
  5315.  
  5316.  
  5317. ΓòÉΓòÉΓòÉ 11.87. open FILEHANDLE,EXPR ΓòÉΓòÉΓòÉ
  5318.  
  5319. open FILEHANDLE,EXPR 
  5320.  
  5321. open FILEHANDLE 
  5322.  
  5323. Opens the file whose filename is given by EXPR, and associates it with 
  5324. FILEHANDLE.  If FILEHANDLE is an expression, its value is used as the name of 
  5325. the real filehandle wanted.  If EXPR is omitted, the scalar variable of the 
  5326. same name as the FILEHANDLE contains the filename.  If the filename begins with 
  5327. "<" or nothing, the file is opened for input.  If the filename begins with ">", 
  5328. the file is opened for output.  If the filename begins with ">>", the file is 
  5329. opened for appending.  You can put a '+' in front of the '>' or '<' to indicate 
  5330. that you want both read and write access to the file; thus '+<' is usually 
  5331. preferred for read/write updates--the '+>' mode would clobber the file first. 
  5332. These correspond to the fopen(3) modes of 'r', 'r+', 'w', 'w+', 'a', and 'a+'. 
  5333.  
  5334. If the filename begins with "|", the filename is interpreted as a command to 
  5335. which output is to be piped, and if the filename ends with a "|", the filename 
  5336. is interpreted See perlipc/"Using open() for IPC" for more examples of this. 
  5337. as command which pipes input to us.  (You may not have a raw open() to a 
  5338. command that pipes both in and out, but see See L<open2>, L<open3>, and 
  5339. perlipc/"Bidirectional Communication" for alternatives.) 
  5340.  
  5341. Opening '-' opens STDIN and opening '>-' opens STDOUT.  Open returns non-zero 
  5342. upon success, the undefined value otherwise.  If the open involved a pipe, the 
  5343. return value happens to be the pid of the subprocess. 
  5344.  
  5345. If you're unfortunate enough to be running Perl on a system that distinguishes 
  5346. between text files and binary files (modern operating systems don't care), then 
  5347. you should check out L</binmode> for tips for dealing with this.  The key 
  5348. distinction between systems that need binmode and those that don't is their 
  5349. text file formats.  Systems like Unix and Plan9 that delimit lines with a 
  5350. single character, and that encode that character in C as '\n', do not need 
  5351. binmode.  The rest need it. 
  5352.  
  5353. Examples: 
  5354.  
  5355.     $ARTICLE = 100;
  5356.     open ARTICLE or die "Can't find article $ARTICLE: $!\n";
  5357.     while (<ARTICLE>) {...
  5358.     open(LOG, '>>/usr/spool/news/twitlog'); # (log is reserved)
  5359.     open(DBASE, '+<dbase.mine');            # open for update
  5360.     open(ARTICLE, "caesar <$article |");    # decrypt article
  5361.     open(EXTRACT, "|sort >/tmp/Tmp$$");     # $$ is our process id
  5362.     # process argument list of files along with any includes
  5363.     foreach $file (@ARGV) {
  5364.         process($file, 'fh00');
  5365.     }
  5366.     sub process {
  5367.         local($filename, $input) = @_;
  5368.         $input++;               # this is a string increment
  5369.         unless (open($input, $filename)) {
  5370.             print STDERR "Can't open $filename: $!\n";
  5371.             return;
  5372.         }
  5373.         while (<$input>) {              # note use of indirection
  5374.             if (/^#include "(.*)"/) {
  5375.                 process($1, $input);
  5376.                 next;
  5377.             }
  5378.             ...         # whatever
  5379.         }
  5380.     }
  5381.  
  5382. You may also, in the Bourne shell tradition, specify an EXPR beginning with 
  5383. ">&", in which case the rest of the string is interpreted as the name of a 
  5384. filehandle (or file descriptor, if numeric) which is to be duped and opened. 
  5385. You may use & after >, >>, <, +>, +>> and +<.  The mode you specify should 
  5386. match the mode of the original filehandle. (Duping a filehandle does not take 
  5387. into acount any existing contents of stdio buffers.) Here is a script that 
  5388. saves, redirects, and restores STDOUT and STDERR: 
  5389.  
  5390.     #!/usr/bin/perl
  5391.     open(SAVEOUT, ">&STDOUT");
  5392.     open(SAVEERR, ">&STDERR");
  5393.     open(STDOUT, ">foo.out") || die "Can't redirect stdout";
  5394.     open(STDERR, ">&STDOUT") || die "Can't dup stdout";
  5395.     select(STDERR); $| = 1;     # make unbuffered
  5396.     select(STDOUT); $| = 1;     # make unbuffered
  5397.     print STDOUT "stdout 1\n";  # this works for
  5398.     print STDERR "stderr 1\n";  # subprocesses too
  5399.     close(STDOUT);
  5400.     close(STDERR);
  5401.     open(STDOUT, ">&SAVEOUT");
  5402.     open(STDERR, ">&SAVEERR");
  5403.     print STDOUT "stdout 2\n";
  5404.     print STDERR "stderr 2\n";
  5405.  
  5406. If you specify "<&=N", where N is a number, then Perl will do an equivalent of 
  5407. C's fdopen() of that file descriptor; this is more parsimonious of file 
  5408. descriptors.  For example: 
  5409.  
  5410.     open(FILEHANDLE, "<&=$fd")
  5411.  
  5412. If you open a pipe on the command "-", i.e. either "|-" or "-|", then there is 
  5413. an implicit fork done, and the return value of open is the pid of the child 
  5414. within the parent process, and 0 within the child process.  (Use defined($pid) 
  5415. to determine whether the open was successful.) The filehandle behaves normally 
  5416. for the parent, but i/o to that filehandle is piped from/to the STDOUT/STDIN of 
  5417. the child process. In the child process the filehandle isn't opened--i/o 
  5418. happens from/to the new STDOUT or STDIN.  Typically this is used like the 
  5419. normal piped open when you want to exercise more control over just how the pipe 
  5420. command gets executed, such as when you are running setuid, and don't want to 
  5421. have to scan shell commands for metacharacters. The following pairs are more or 
  5422. less equivalent: 
  5423.  
  5424.     open(FOO, "|tr '[a-z]' '[A-Z]'");
  5425.     open(FOO, "|-") || exec 'tr', '[a-z]', '[A-Z]';
  5426.     open(FOO, "cat -n '$file'|");
  5427.     open(FOO, "-|") || exec 'cat', '-n', $file;
  5428.  
  5429. See perlipc/"Safe Pipe Opens" for more examples of this. 
  5430.  
  5431. Explicitly closing any piped filehandle causes the parent process to wait for 
  5432. the child to finish, and returns the status value in $?. Note: on any operation 
  5433. which may do a fork, unflushed buffers remain unflushed in both processes, 
  5434. which means you may need to set $| to avoid duplicate output. 
  5435.  
  5436. Using the FileHandle constructor from the FileHandle package, you can generate 
  5437. anonymous filehandles which have the scope of whatever variables hold 
  5438. references to them, and automatically close whenever and however you leave that 
  5439. scope: 
  5440.  
  5441.     use FileHandle;
  5442.     ...
  5443.     sub read_myfile_munged {
  5444.         my $ALL = shift;
  5445.         my $handle = new FileHandle;
  5446.         open($handle, "myfile") or die "myfile: $!";
  5447.         $first = <$handle>
  5448.             or return ();     # Automatically closed here.
  5449.         mung $first or die "mung failed";       # Or here.
  5450.         return $first, <$handle> if $ALL;       # Or here.
  5451.         $first;                                 # Or here.
  5452.     }
  5453.  
  5454. The filename that is passed to open will have leading and trailing whitespace 
  5455. deleted.  In order to open a file with arbitrary weird characters in it, it's 
  5456. necessary to protect any leading and trailing whitespace thusly: 
  5457.  
  5458.     $file =~ s#^(\s)#./$1#;
  5459.     open(FOO, "< $file\0");
  5460.  
  5461. If you want a "real" C open() (see L<open(2)> on your system), then you should 
  5462. use the sysopen() function.  This is another way to protect your filenames from 
  5463. interpretation.  For example: 
  5464.  
  5465.     use FileHandle;
  5466.     sysopen(HANDLE, $path, O_RDWR|O_CREAT|O_EXCL, 0700)
  5467.         or die "sysopen $path: $!";
  5468.     HANDLE->autoflush(1);
  5469.     HANDLE->print("stuff $$\n");
  5470.     seek(HANDLE, 0, 0);
  5471.     print "File contains: ", <HANDLE>;
  5472.  
  5473. See L</seek()> for some details about mixing reading and writing. 
  5474.  
  5475.  
  5476. ΓòÉΓòÉΓòÉ 11.88. opendir DIRHANDLE,EXPR ΓòÉΓòÉΓòÉ
  5477.  
  5478. opendir DIRHANDLE,EXPR 
  5479.  
  5480. Opens a directory named EXPR for processing by readdir(), telldir(), seekdir(), 
  5481. rewinddir() and closedir().  Returns TRUE if successful. DIRHANDLEs have their 
  5482. own namespace separate from FILEHANDLEs. 
  5483.  
  5484.  
  5485. ΓòÉΓòÉΓòÉ 11.89. ord EXPR ΓòÉΓòÉΓòÉ
  5486.  
  5487. ord EXPR 
  5488.  
  5489. Returns the numeric ascii value of the first character of EXPR.  If EXPR is 
  5490. omitted, uses $_. 
  5491.  
  5492.  
  5493. ΓòÉΓòÉΓòÉ 11.90. pack TEMPLATE,LIST ΓòÉΓòÉΓòÉ
  5494.  
  5495. pack TEMPLATE,LIST 
  5496.  
  5497. Takes an array or list of values and packs it into a binary structure, 
  5498. returning the string containing the structure.  The TEMPLATE is a sequence of 
  5499. characters that give the order and type of values, as follows: 
  5500.  
  5501.     A   An ascii string, will be space padded.
  5502.     a   An ascii string, will be null padded.
  5503.     b   A bit string (ascending bit order, like vec()).
  5504.     B   A bit string (descending bit order).
  5505.     h   A hex string (low nybble first).
  5506.     H   A hex string (high nybble first).
  5507.     c   A signed char value.
  5508.     C   An unsigned char value.
  5509.     s   A signed short value.
  5510.     S   An unsigned short value.
  5511.     i   A signed integer value.
  5512.     I   An unsigned integer value.
  5513.     l   A signed long value.
  5514.     L   An unsigned long value.
  5515.     n   A short in "network" order.
  5516.     N   A long in "network" order.
  5517.     v   A short in "VAX" (little-endian) order.
  5518.     V   A long in "VAX" (little-endian) order.
  5519.     f   A single-precision float in the native format.
  5520.     d   A double-precision float in the native format.
  5521.     p   A pointer to a null-terminated string.
  5522.     P   A pointer to a structure (fixed-length string).
  5523.     u   A uuencoded string.
  5524.     x   A null byte.
  5525.     X   Back up a byte.
  5526.     @   Null fill to absolute position.
  5527.  
  5528. Each letter may optionally be followed by a number which gives a repeat count. 
  5529. With all types except "a", "A", "b", "B", "h" and "H", and "P" the pack 
  5530. function will gobble up that many values from the LIST.  A * for the repeat 
  5531. count means to use however many items are left.  The "a" and "A" types gobble 
  5532. just one value, but pack it as a string of length count, padding with nulls or 
  5533. spaces as necessary.  (When unpacking, "A" strips trailing spaces and nulls, 
  5534. but "a" does not.)  Likewise, the "b" and "B" fields pack a string that many 
  5535. bits long.  The "h" and "H" fields pack a string that many nybbles long.  The 
  5536. "P" packs a pointer to a structure of the size indicated by the length.  Real 
  5537. numbers (floats and doubles) are in the native machine format only; due to the 
  5538. multiplicity of floating formats around, and the lack of a standard "network" 
  5539. representation, no facility for interchange has been made.  This means that 
  5540. packed floating point data written on one machine may not be readable on 
  5541. another - even if both use IEEE floating point arithmetic (as the endian-ness 
  5542. of the memory representation is not part of the IEEE spec).  Note that Perl 
  5543. uses doubles internally for all numeric calculation, and converting from double 
  5544. into float and thence back to double again will lose precision (i.e. 
  5545. unpack("f", pack("f", $foo)) will not in general equal $foo). 
  5546.  
  5547. Examples: 
  5548.  
  5549.     $foo = pack("cccc",65,66,67,68);
  5550.     # foo eq "ABCD"
  5551.     $foo = pack("c4",65,66,67,68);
  5552.     # same thing
  5553.     $foo = pack("ccxxcc",65,66,67,68);
  5554.     # foo eq "AB\0\0CD"
  5555.     $foo = pack("s2",1,2);
  5556.     # "\1\0\2\0" on little-endian
  5557.     # "\0\1\0\2" on big-endian
  5558.     $foo = pack("a4","abcd","x","y","z");
  5559.     # "abcd"
  5560.     $foo = pack("aaaa","abcd","x","y","z");
  5561.     # "axyz"
  5562.     $foo = pack("a14","abcdefg");
  5563.     # "abcdefg\0\0\0\0\0\0\0"
  5564.     $foo = pack("i9pl", gmtime);
  5565.     # a real struct tm (on my system anyway)
  5566.     sub bintodec {
  5567.         unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
  5568.     }
  5569.  
  5570. The same template may generally also be used in the unpack function. 
  5571.  
  5572.  
  5573. ΓòÉΓòÉΓòÉ 11.91. package NAMESPACE ΓòÉΓòÉΓòÉ
  5574.  
  5575. package NAMESPACE 
  5576.  
  5577. Declares the compilation unit as being in the given namespace.  The scope of 
  5578. the package declaration is from the declaration itself through the end of the 
  5579. enclosing block (the same scope as the local() operator).  All further 
  5580. unqualified dynamic identifiers will be in this namespace.  A package statement 
  5581. only affects dynamic variables--including those you've used local() on--but not 
  5582. lexical variables created with my().  Typically it would be the first 
  5583. declaration in a file to be included by the require or use operator.  You can 
  5584. switch into a package in more than one place; it merely influences which symbol 
  5585. table is used by the compiler for the rest of that block.  You can refer to 
  5586. variables and filehandles in other packages by prefixing the identifier with 
  5587. the package name and a double colon:  $Package::Variable.  If the package name 
  5588. is null, the main package as assumed.  That is, $::sail is equivalent to 
  5589. $main::sail. 
  5590.  
  5591. See perlmod/"Packages" for more information about packages, modules, and 
  5592. classes.  See perlsub for other scoping issues. 
  5593.  
  5594.  
  5595. ΓòÉΓòÉΓòÉ 11.92. pipe READHANDLE,WRITEHANDLE ΓòÉΓòÉΓòÉ
  5596.  
  5597. pipe READHANDLE,WRITEHANDLE 
  5598.  
  5599. Opens a pair of connected pipes like the corresponding system call. Note that 
  5600. if you set up a loop of piped processes, deadlock can occur unless you are very 
  5601. careful.  In addition, note that Perl's pipes use stdio buffering, so you may 
  5602. need to set $| to flush your WRITEHANDLE after each command, depending on the 
  5603. application. 
  5604.  
  5605. See L<open2>, L<open3>, and perlipc/"Bidirectional Communication" for examples 
  5606. of such things. 
  5607.  
  5608.  
  5609. ΓòÉΓòÉΓòÉ 11.93. pop ARRAY ΓòÉΓòÉΓòÉ
  5610.  
  5611. pop ARRAY 
  5612.  
  5613. Pops and returns the last value of the array, shortening the array by 1.  Has a 
  5614. similar effect to 
  5615.  
  5616.     $tmp = $ARRAY[$#ARRAY--];
  5617.  
  5618. If there are no elements in the array, returns the undefined value. If ARRAY is 
  5619. omitted, pops the @ARGV array in the main program, and the @_ array in 
  5620. subroutines, just like shift(). 
  5621.  
  5622.  
  5623. ΓòÉΓòÉΓòÉ 11.94. pos SCALAR ΓòÉΓòÉΓòÉ
  5624.  
  5625. pos SCALAR 
  5626.  
  5627. Returns the offset of where the last m//g search left off for the variable in 
  5628. question.  May be modified to change that offset. 
  5629.  
  5630.  
  5631. ΓòÉΓòÉΓòÉ 11.95. print FILEHANDLE LIST ΓòÉΓòÉΓòÉ
  5632.  
  5633. print FILEHANDLE LIST 
  5634.  
  5635. print LIST 
  5636.  
  5637. print 
  5638.  
  5639. Prints a string or a comma-separated list of strings.  Returns TRUE if 
  5640. successful.  FILEHANDLE may be a scalar variable name, in which case the 
  5641. variable contains the name of or a reference to the filehandle, thus 
  5642. introducing one level of indirection.  (NOTE: If FILEHANDLE is a variable and 
  5643. the next token is a term, it may be misinterpreted as an operator unless you 
  5644. interpose a + or put parens around the arguments.)  If FILEHANDLE is omitted, 
  5645. prints by default to standard output (or to the last selected output 
  5646. channel--see select()).  If LIST is also omitted, prints $_ to STDOUT.  To set 
  5647. the default output channel to something other than STDOUT use the select 
  5648. operation.  Note that, because print takes a LIST, anything in the LIST is 
  5649. evaluated in a list context, and any subroutine that you call will have one or 
  5650. more of its expressions evaluated in a list context.  Also be careful not to 
  5651. follow the print keyword with a left parenthesis unless you want the 
  5652. corresponding right parenthesis to terminate the arguments to the 
  5653. print--interpose a + or put parens around all the arguments. 
  5654.  
  5655. Note that if you're storing FILEHANDLES in an array or other expression, you 
  5656. will have to use a block returning its value instead 
  5657.  
  5658.     print { $files[$i] } "stuff\n";
  5659.     print { $OK ? STDOUT : STDERR } "stuff\n";
  5660.  
  5661.  
  5662. ΓòÉΓòÉΓòÉ 11.96. printf FILEHANDLE LIST ΓòÉΓòÉΓòÉ
  5663.  
  5664. printf FILEHANDLE LIST 
  5665.  
  5666. printf LIST 
  5667.  
  5668. Equivalent to a "print FILEHANDLE sprintf(LIST)".  The first argument of the 
  5669. list will be interpreted as the printf format. 
  5670.  
  5671.  
  5672. ΓòÉΓòÉΓòÉ 11.97. push ARRAY,LIST ΓòÉΓòÉΓòÉ
  5673.  
  5674. push ARRAY,LIST 
  5675.  
  5676. Treats ARRAY as a stack, and pushes the values of LIST onto the end of ARRAY. 
  5677. The length of ARRAY increases by the length of LIST.  Has the same effect as 
  5678.  
  5679.     for $value (LIST) {
  5680.         $ARRAY[++$#ARRAY] = $value;
  5681.     }
  5682.  
  5683. but is more efficient.  Returns the new number of elements in the array. 
  5684.  
  5685.  
  5686. ΓòÉΓòÉΓòÉ 11.98. q/STRING/ ΓòÉΓòÉΓòÉ
  5687.  
  5688. q/STRING/ 
  5689.  
  5690. qq/STRING/ 
  5691.  
  5692. qx/STRING/ 
  5693.  
  5694. qw/STRING/ 
  5695.  
  5696. Generalized quotes.  See perlop. 
  5697.  
  5698.  
  5699. ΓòÉΓòÉΓòÉ 11.99. quotemeta EXPR ΓòÉΓòÉΓòÉ
  5700.  
  5701. quotemeta EXPR 
  5702.  
  5703. Returns the value of EXPR with with all regular expression metacharacters 
  5704. backslashed.  This is the internal function implementing the \Q escape in 
  5705. double-quoted strings. 
  5706.  
  5707.  
  5708. ΓòÉΓòÉΓòÉ 11.100. rand EXPR ΓòÉΓòÉΓòÉ
  5709.  
  5710. rand EXPR 
  5711.  
  5712. rand 
  5713.  
  5714. Returns a random fractional number between 0 and the value of EXPR. (EXPR 
  5715. should be positive.)  If EXPR is omitted, returns a value between 0 and 1. 
  5716. This function produces repeatable sequences unless srand() is invoked.  See 
  5717. also srand(). 
  5718.  
  5719. (Note: if your rand function consistently returns numbers that are too large or 
  5720. too small, then your version of Perl was probably compiled with the wrong 
  5721. number of RANDBITS.  As a workaround, you can usually multiply EXPR by the 
  5722. correct power of 2 to get the range you want. This will make your script 
  5723. unportable, however.  It's better to recompile if you can.) 
  5724.  
  5725.  
  5726. ΓòÉΓòÉΓòÉ 11.101. read FILEHANDLE,SCALAR,LENGTH,OFFSET ΓòÉΓòÉΓòÉ
  5727.  
  5728. read FILEHANDLE,SCALAR,LENGTH,OFFSET 
  5729.  
  5730. read FILEHANDLE,SCALAR,LENGTH 
  5731.  
  5732. Attempts to read LENGTH bytes of data into variable SCALAR from the specified 
  5733. FILEHANDLE.  Returns the number of bytes actually read, or undef if there was 
  5734. an error.  SCALAR will be grown or shrunk to the length actually read.  An 
  5735. OFFSET may be specified to place the read data at some other place than the 
  5736. beginning of the string.  This call is actually implemented in terms of stdio's 
  5737. fread call.  To get a true read system call, see sysread(). 
  5738.  
  5739.  
  5740. ΓòÉΓòÉΓòÉ 11.102. readdir DIRHANDLE ΓòÉΓòÉΓòÉ
  5741.  
  5742. readdir DIRHANDLE 
  5743.  
  5744. Returns the next directory entry for a directory opened by opendir(). If used 
  5745. in a list context, returns all the rest of the entries in the directory.  If 
  5746. there are no more entries, returns an undefined value in a scalar context or a 
  5747. null list in a list context. 
  5748.  
  5749. If you're planning to filetest the return values out of a readdir(), you'd 
  5750. better prepend the directory in question.  Otherwise, since we didn't chdir() 
  5751. there, it would have been testing the wrong file. 
  5752.  
  5753.     opendir(DIR, $some_dir) || die "can't opendir $some_dir: $!";
  5754.     @dots = grep { /^\./ && -f "$some_dir/$_" } readdir(DIR);
  5755.     closedir DIR;
  5756.  
  5757.  
  5758. ΓòÉΓòÉΓòÉ 11.103. readlink EXPR ΓòÉΓòÉΓòÉ
  5759.  
  5760. readlink EXPR 
  5761.  
  5762. Returns the value of a symbolic link, if symbolic links are implemented.  If 
  5763. not, gives a fatal error.  If there is some system error, returns the undefined 
  5764. value and sets $! (errno).  If EXPR is omitted, uses $_. 
  5765.  
  5766.  
  5767. ΓòÉΓòÉΓòÉ 11.104. recv SOCKET,SCALAR,LEN,FLAGS ΓòÉΓòÉΓòÉ
  5768.  
  5769. recv SOCKET,SCALAR,LEN,FLAGS 
  5770.  
  5771. Receives a message on a socket.  Attempts to receive LENGTH bytes of data into 
  5772. variable SCALAR from the specified SOCKET filehandle. Actually does a C 
  5773. recvfrom(), so that it can returns the address of the sender.  Returns the 
  5774. undefined value if there's an error.  SCALAR will be grown or shrunk to the 
  5775. length actually read.  Takes the same flags as the system call of the same 
  5776. name. See perlipc/"UDP: Message Passing" for examples. 
  5777.  
  5778.  
  5779. ΓòÉΓòÉΓòÉ 11.105. redo LABEL ΓòÉΓòÉΓòÉ
  5780.  
  5781. redo LABEL 
  5782.  
  5783. redo 
  5784.  
  5785. The redo command restarts the loop block without evaluating the conditional 
  5786. again.  The continue block, if any, is not executed.  If the LABEL is omitted, 
  5787. the command refers to the innermost enclosing loop.  This command is normally 
  5788. used by programs that want to lie to themselves about what was just input: 
  5789.  
  5790.     # a simpleminded Pascal comment stripper
  5791.     # (warning: assumes no { or } in strings)
  5792.     LINE: while (<STDIN>) {
  5793.         while (s|({.*}.*){.*}|$1 |) {}
  5794.         s|{.*}| |;
  5795.         if (s|{.*| |) {
  5796.             $front = $_;
  5797.             while (<STDIN>) {
  5798.                 if (/}/) {      # end of comment?
  5799.                     s|^|$front{|;
  5800.                     redo LINE;
  5801.                 }
  5802.             }
  5803.         }
  5804.         print;
  5805.     }
  5806.  
  5807.  
  5808. ΓòÉΓòÉΓòÉ 11.106. ref EXPR ΓòÉΓòÉΓòÉ
  5809.  
  5810. ref EXPR 
  5811.  
  5812. Returns a TRUE value if EXPR is a reference, FALSE otherwise.  The value 
  5813. returned depends on the type of thing the reference is a reference to. Builtin 
  5814. types include: 
  5815.  
  5816.     REF
  5817.     SCALAR
  5818.     ARRAY
  5819.     HASH
  5820.     CODE
  5821.     GLOB
  5822.  
  5823. If the referenced object has been blessed into a package, then that package 
  5824. name is returned instead.  You can think of ref() as a typeof() operator. 
  5825.  
  5826.     if (ref($r) eq "HASH") {
  5827.         print "r is a reference to an associative array.\n";
  5828.     }
  5829.     if (!ref ($r) {
  5830.         print "r is not a reference at all.\n";
  5831.     }
  5832.  
  5833. See also perlref. 
  5834.  
  5835.  
  5836. ΓòÉΓòÉΓòÉ 11.107. rename OLDNAME,NEWNAME ΓòÉΓòÉΓòÉ
  5837.  
  5838. rename OLDNAME,NEWNAME 
  5839.  
  5840. Changes the name of a file.  Returns 1 for success, 0 otherwise.  Will not work 
  5841. across filesystem boundaries. 
  5842.  
  5843.  
  5844. ΓòÉΓòÉΓòÉ 11.108. require EXPR ΓòÉΓòÉΓòÉ
  5845.  
  5846. require EXPR 
  5847.  
  5848. require 
  5849.  
  5850. Demands some semantics specified by EXPR, or by $_ if EXPR is not supplied.  If 
  5851. EXPR is numeric, demands that the current version of Perl ($] or $PERL_VERSION) 
  5852. be equal or greater than EXPR. 
  5853.  
  5854. Otherwise, demands that a library file be included if it hasn't already been 
  5855. included.  The file is included via the do-FILE mechanism, which is essentially 
  5856. just a variety of eval().  Has semantics similar to the following subroutine: 
  5857.  
  5858.     sub require {
  5859.         local($filename) = @_;
  5860.         return 1 if $INC{$filename};
  5861.         local($realfilename,$result);
  5862.         ITER: {
  5863.             foreach $prefix (@INC) {
  5864.                 $realfilename = "$prefix/$filename";
  5865.                 if (-f $realfilename) {
  5866.                     $result = do $realfilename;
  5867.                     last ITER;
  5868.                 }
  5869.             }
  5870.             die "Can't find $filename in \@INC";
  5871.         }
  5872.         die $@ if $@;
  5873.         die "$filename did not return true value" unless $result;
  5874.         $INC{$filename} = $realfilename;
  5875.         $result;
  5876.     }
  5877.  
  5878. Note that the file will not be included twice under the same specified name. 
  5879. The file must return TRUE as the last statement to indicate successful 
  5880. execution of any initialization code, so it's customary to end such a file with 
  5881. "1;" unless you're sure it'll return TRUE otherwise.  But it's better just to 
  5882. put the "1;", in case you add more statements. 
  5883.  
  5884. If EXPR is a bare word, the require assumes a ".pm" extension for you, to make 
  5885. it easy to load standard modules.  This form of loading of modules does not 
  5886. risk altering your namespace. 
  5887.  
  5888. For a yet-more-powerful import facility, see the L</use()> and perlmod. 
  5889.  
  5890.  
  5891. ΓòÉΓòÉΓòÉ 11.109. reset EXPR ΓòÉΓòÉΓòÉ
  5892.  
  5893. reset EXPR 
  5894.  
  5895. reset 
  5896.  
  5897. Generally used in a continue block at the end of a loop to clear variables and 
  5898. reset ?? searches so that they work again.  The expression is interpreted as a 
  5899. list of single characters (hyphens allowed for ranges).  All variables and 
  5900. arrays beginning with one of those letters are reset to their pristine state. 
  5901. If the expression is omitted, one-match searches (?pattern?) are reset to match 
  5902. again.  Only resets variables or searches in the current package.  Always 
  5903. returns 1.  Examples: 
  5904.  
  5905.     reset 'X';          # reset all X variables
  5906.     reset 'a-z';        # reset lower case variables
  5907.     reset;              # just reset ?? searches
  5908.  
  5909. Resetting "A-Z" is not recommended since you'll wipe out your ARGV and ENV 
  5910. arrays.  Only resets package variables--lexical variables are unaffected, but 
  5911. they clean themselves up on scope exit anyway, so anymore you probably want to 
  5912. use them instead.  See L</my>. 
  5913.  
  5914.  
  5915. ΓòÉΓòÉΓòÉ 11.110. return LIST ΓòÉΓòÉΓòÉ
  5916.  
  5917. return LIST 
  5918.  
  5919. Returns from a subroutine or eval with the value specified.  (Note that in the 
  5920. absence of a return a subroutine or eval() will automatically return the value 
  5921. of the last expression evaluated.) 
  5922.  
  5923.  
  5924. ΓòÉΓòÉΓòÉ 11.111. reverse LIST ΓòÉΓòÉΓòÉ
  5925.  
  5926. reverse LIST 
  5927.  
  5928. In a list context, returns a list value consisting of the elements of LIST in 
  5929. the opposite order.  In a scalar context, returns a string value consisting of 
  5930. the bytes of the first element of LIST in the opposite order. 
  5931.  
  5932.     print reverse <>;                   # line tac
  5933.     undef $/;
  5934.     print scalar reverse scalar <>;     # byte tac
  5935.  
  5936.  
  5937. ΓòÉΓòÉΓòÉ 11.112. rewinddir DIRHANDLE ΓòÉΓòÉΓòÉ
  5938.  
  5939. rewinddir DIRHANDLE 
  5940.  
  5941. Sets the current position to the beginning of the directory for the readdir() 
  5942. routine on DIRHANDLE. 
  5943.  
  5944.  
  5945. ΓòÉΓòÉΓòÉ 11.113. rindex STR,SUBSTR,POSITION ΓòÉΓòÉΓòÉ
  5946.  
  5947. rindex STR,SUBSTR,POSITION 
  5948.  
  5949. rindex STR,SUBSTR 
  5950.  
  5951. Works just like index except that it returns the position of the LAST 
  5952. occurrence of SUBSTR in STR.  If POSITION is specified, returns the last 
  5953. occurrence at or before that position. 
  5954.  
  5955.  
  5956. ΓòÉΓòÉΓòÉ 11.114. rmdir FILENAME ΓòÉΓòÉΓòÉ
  5957.  
  5958. rmdir FILENAME 
  5959.  
  5960. Deletes the directory specified by FILENAME if it is empty.  If it succeeds it 
  5961. returns 1, otherwise it returns 0 and sets $! (errno).  If FILENAME is omitted, 
  5962. uses $_. 
  5963.  
  5964.  
  5965. ΓòÉΓòÉΓòÉ 11.115. s/// ΓòÉΓòÉΓòÉ
  5966.  
  5967. s/// 
  5968.  
  5969. The substitution operator.  See perlop. 
  5970.  
  5971.  
  5972. ΓòÉΓòÉΓòÉ 11.116. scalar EXPR ΓòÉΓòÉΓòÉ
  5973.  
  5974. scalar EXPR 
  5975.  
  5976. Forces EXPR to be interpreted in a scalar context and returns the value of 
  5977. EXPR. 
  5978.  
  5979.     @counts = ( scalar @a, scalar @b, scalar @c );
  5980.  
  5981. There is no equivalent operator to force an expression to be interpolated in a 
  5982. list context because it's in practice never needed.  If you really wanted to do 
  5983. so, however, you could use the construction @{[ (some expression) ]}, but 
  5984. usually a simple (some expression) suffices. 
  5985.  
  5986.  
  5987. ΓòÉΓòÉΓòÉ 11.117. seek FILEHANDLE,POSITION,WHENCE ΓòÉΓòÉΓòÉ
  5988.  
  5989. seek FILEHANDLE,POSITION,WHENCE 
  5990.  
  5991. Randomly positions the file pointer for FILEHANDLE, just like the fseek() call 
  5992. of stdio.  FILEHANDLE may be an expression whose value gives the name of the 
  5993. filehandle.  The values for WHENCE are 0 to set the file pointer to POSITION, 1 
  5994. to set the it to current plus POSITION, and 2 to set it to EOF plus offset. 
  5995. You may use the values SEEK_SET, SEEK_CUR, and SEEK_END for this from POSIX 
  5996. module.  Returns 1 upon success, 0 otherwise. 
  5997.  
  5998. On some systems you have to do a seek whenever you switch between reading and 
  5999. writing.  Amongst other things, this may have the effect of calling stdio's 
  6000. clearerr(3).  A "whence" of 1 (SEEK_CUR) is useful for not moving the file 
  6001. pointer: 
  6002.  
  6003.     seek(TEST,0,1);
  6004.  
  6005. This is also useful for applications emulating tail -f.  Once you hit EOF on 
  6006. your read, and then sleep for a while, you might have to stick in a seek() to 
  6007. reset things.  First the simple trick listed above to clear the filepointer. 
  6008. The seek() doesn't change the current position, but it does clear the 
  6009. end-of-file condition on the handle, so that the next <FILE<> makes Perl try 
  6010. again to read something.  Hopefully. 
  6011.  
  6012. If that doesn't work (some stdios are particularly cantankerous), then you may 
  6013. need something more like this: 
  6014.  
  6015.     for (;;) {
  6016.         for ($curpos = tell(FILE); $_ = <FILE>; $curpos = tell(FILE)) {
  6017.             # search for some stuff and put it into files
  6018.         }
  6019.         sleep($for_a_while);
  6020.         seek(FILE, $curpos, 0);
  6021.     }
  6022.  
  6023.  
  6024. ΓòÉΓòÉΓòÉ 11.118. seekdir DIRHANDLE,POS ΓòÉΓòÉΓòÉ
  6025.  
  6026. seekdir DIRHANDLE,POS 
  6027.  
  6028. Sets the current position for the readdir() routine on DIRHANDLE.  POS must be 
  6029. a value returned by telldir().  Has the same caveats about possible directory 
  6030. compaction as the corresponding system library routine. 
  6031.  
  6032.  
  6033. ΓòÉΓòÉΓòÉ 11.119. select FILEHANDLE ΓòÉΓòÉΓòÉ
  6034.  
  6035. select FILEHANDLE 
  6036.  
  6037. select 
  6038.  
  6039. Returns the currently selected filehandle.  Sets the current default filehandle 
  6040. for output, if FILEHANDLE is supplied.  This has two effects: first, a write or 
  6041. a print without a filehandle will default to this FILEHANDLE.  Second, 
  6042. references to variables related to output will refer to this output channel. 
  6043. For example, if you have to set the top of form format for more than one output 
  6044. channel, you might do the following: 
  6045.  
  6046.     select(REPORT1);
  6047.     $^ = 'report1_top';
  6048.     select(REPORT2);
  6049.     $^ = 'report2_top';
  6050.  
  6051. FILEHANDLE may be an expression whose value gives the name of the actual 
  6052. filehandle.  Thus: 
  6053.  
  6054.     $oldfh = select(STDERR); $| = 1; select($oldfh);
  6055.  
  6056. Some programmers may prefer to think of filehandles as objects with methods, 
  6057. preferring to write the last example as: 
  6058.  
  6059.     use FileHandle;
  6060.     STDERR->autoflush(1);
  6061.  
  6062.  
  6063. ΓòÉΓòÉΓòÉ 11.120. select RBITS,WBITS,EBITS,TIMEOUT ΓòÉΓòÉΓòÉ
  6064.  
  6065. select RBITS,WBITS,EBITS,TIMEOUT 
  6066.  
  6067. This calls the select(2) system call with the bitmasks specified, which can be 
  6068. constructed using fileno() and vec(), along these lines: 
  6069.  
  6070.     $rin = $win = $ein = '';
  6071.     vec($rin,fileno(STDIN),1) = 1;
  6072.     vec($win,fileno(STDOUT),1) = 1;
  6073.     $ein = $rin | $win;
  6074.  
  6075. If you want to select on many filehandles you might wish to write a subroutine: 
  6076.  
  6077.     sub fhbits {
  6078.         local(@fhlist) = split(' ',$_[0]);
  6079.         local($bits);
  6080.         for (@fhlist) {
  6081.             vec($bits,fileno($_),1) = 1;
  6082.         }
  6083.         $bits;
  6084.     }
  6085.     $rin = fhbits('STDIN TTY SOCK');
  6086.  
  6087. The usual idiom is: 
  6088.  
  6089.     ($nfound,$timeleft) =
  6090.       select($rout=$rin, $wout=$win, $eout=$ein, $timeout);
  6091.  
  6092. or to block until something becomes ready just do this 
  6093.  
  6094.     $nfound = select($rout=$rin, $wout=$win, $eout=$ein, undef);
  6095.  
  6096. Most systems do not both to return anything useful in $timeleft, so calling 
  6097. select() in a scalar context just returns $nfound. 
  6098.  
  6099. Any of the bitmasks can also be undef.  The timeout, if specified, is in 
  6100. seconds, which may be fractional.  Note: not all implementations are capable of 
  6101. returning the $timeleft.  If not, they always return $timeleft equal to the 
  6102. supplied $timeout. 
  6103.  
  6104. You can effect a 250-microsecond sleep this way: 
  6105.  
  6106.     select(undef, undef, undef, 0.25);
  6107.  
  6108. WARNING: Do not attempt to mix buffered I/O (like read() or <FH>) with 
  6109. select().  You have to use sysread() instead. 
  6110.  
  6111.  
  6112. ΓòÉΓòÉΓòÉ 11.121. semctl ID,SEMNUM,CMD,ARG ΓòÉΓòÉΓòÉ
  6113.  
  6114. semctl ID,SEMNUM,CMD,ARG 
  6115.  
  6116. Calls the System V IPC function semctl.  If CMD is &IPC_STAT or &GETALL, then 
  6117. ARG must be a variable which will hold the returned semid_ds structure or 
  6118. semaphore value array.  Returns like ioctl: the undefined value for error, "0 
  6119. but true" for zero, or the actual return value otherwise. 
  6120.  
  6121.  
  6122. ΓòÉΓòÉΓòÉ 11.122. semget KEY,NSEMS,FLAGS ΓòÉΓòÉΓòÉ
  6123.  
  6124. semget KEY,NSEMS,FLAGS 
  6125.  
  6126. Calls the System V IPC function semget.  Returns the semaphore id, or the 
  6127. undefined value if there is an error. 
  6128.  
  6129.  
  6130. ΓòÉΓòÉΓòÉ 11.123. semop KEY,OPSTRING ΓòÉΓòÉΓòÉ
  6131.  
  6132. semop KEY,OPSTRING 
  6133.  
  6134. Calls the System V IPC function semop to perform semaphore operations such as 
  6135. signaling and waiting.  OPSTRING must be a packed array of semop structures. 
  6136. Each semop structure can be generated with pack("sss", $semnum, $semop, 
  6137. $semflag).  The number of semaphore operations is implied by the length of 
  6138. OPSTRING.  Returns TRUE if successful, or FALSE if there is an error.  As an 
  6139. example, the following code waits on semaphore $semnum of semaphore id $semid: 
  6140.  
  6141.     $semop = pack("sss", $semnum, -1, 0);
  6142.     die "Semaphore trouble: $!\n" unless semop($semid, $semop);
  6143.  
  6144. To signal the semaphore, replace "-1" with "1". 
  6145.  
  6146.  
  6147. ΓòÉΓòÉΓòÉ 11.124. send SOCKET,MSG,FLAGS,TO ΓòÉΓòÉΓòÉ
  6148.  
  6149. send SOCKET,MSG,FLAGS,TO 
  6150.  
  6151. send SOCKET,MSG,FLAGS 
  6152.  
  6153. Sends a message on a socket.  Takes the same flags as the system call of the 
  6154. same name.  On unconnected sockets you must specify a destination to send TO, 
  6155. in which case it does a C sendto().  Returns the number of characters sent, or 
  6156. the undefined value if there is an error. See perlipc/"UDP: Message Passing" 
  6157. for examples. 
  6158.  
  6159.  
  6160. ΓòÉΓòÉΓòÉ 11.125. setpgrp PID,PGRP ΓòÉΓòÉΓòÉ
  6161.  
  6162. setpgrp PID,PGRP 
  6163.  
  6164. Sets the current process group for the specified PID, 0 for the current 
  6165. process.  Will produce a fatal error if used on a machine that doesn't 
  6166. implement setpgrp(2). 
  6167.  
  6168.  
  6169. ΓòÉΓòÉΓòÉ 11.126. setpriority WHICH,WHO,PRIORITY ΓòÉΓòÉΓòÉ
  6170.  
  6171. setpriority WHICH,WHO,PRIORITY 
  6172.  
  6173. Sets the current priority for a process, a process group, or a user. (See 
  6174. setpriority(2).)  Will produce a fatal error if used on a machine that doesn't 
  6175. implement setpriority(2). 
  6176.  
  6177.  
  6178. ΓòÉΓòÉΓòÉ 11.127. setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL ΓòÉΓòÉΓòÉ
  6179.  
  6180. setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL 
  6181.  
  6182. Sets the socket option requested.  Returns undefined if there is an error. 
  6183. OPTVAL may be specified as undef if you don't want to pass an argument. 
  6184.  
  6185.  
  6186. ΓòÉΓòÉΓòÉ 11.128. shift ARRAY ΓòÉΓòÉΓòÉ
  6187.  
  6188. shift ARRAY 
  6189.  
  6190. shift 
  6191.  
  6192. Shifts the first value of the array off and returns it, shortening the array by 
  6193. 1 and moving everything down.  If there are no elements in the array, returns 
  6194. the undefined value.  If ARRAY is omitted, shifts the @ARGV array in the main 
  6195. program, and the @_ array in subroutines. (This is determined lexically.)  See 
  6196. also unshift(), push(), and pop(). Shift() and unshift() do the same thing to 
  6197. the left end of an array that push() and pop() do to the right end. 
  6198.  
  6199.  
  6200. ΓòÉΓòÉΓòÉ 11.129. shmctl ID,CMD,ARG ΓòÉΓòÉΓòÉ
  6201.  
  6202. shmctl ID,CMD,ARG 
  6203.  
  6204. Calls the System V IPC function shmctl.  If CMD is &IPC_STAT, then ARG must be 
  6205. a variable which will hold the returned shmid_ds structure. Returns like ioctl: 
  6206. the undefined value for error, "0 but true" for zero, or the actual return 
  6207. value otherwise. 
  6208.  
  6209.  
  6210. ΓòÉΓòÉΓòÉ 11.130. shmget KEY,SIZE,FLAGS ΓòÉΓòÉΓòÉ
  6211.  
  6212. shmget KEY,SIZE,FLAGS 
  6213.  
  6214. Calls the System V IPC function shmget.  Returns the shared memory segment id, 
  6215. or the undefined value if there is an error. 
  6216.  
  6217.  
  6218. ΓòÉΓòÉΓòÉ 11.131. shmread ID,VAR,POS,SIZE ΓòÉΓòÉΓòÉ
  6219.  
  6220. shmread ID,VAR,POS,SIZE 
  6221.  
  6222. shmwrite ID,STRING,POS,SIZE 
  6223.  
  6224. Reads or writes the System V shared memory segment ID starting at position POS 
  6225. for size SIZE by attaching to it, copying in/out, and detaching from it.  When 
  6226. reading, VAR must be a variable which will hold the data read.  When writing, 
  6227. if STRING is too long, only SIZE bytes are used; if STRING is too short, nulls 
  6228. are written to fill out SIZE bytes.  Return TRUE if successful, or FALSE if 
  6229. there is an error. 
  6230.  
  6231.  
  6232. ΓòÉΓòÉΓòÉ 11.132. shutdown SOCKET,HOW ΓòÉΓòÉΓòÉ
  6233.  
  6234. shutdown SOCKET,HOW 
  6235.  
  6236. Shuts down a socket connection in the manner indicated by HOW, which has the 
  6237. same interpretation as in the system call of the same name. 
  6238.  
  6239.  
  6240. ΓòÉΓòÉΓòÉ 11.133. sin EXPR ΓòÉΓòÉΓòÉ
  6241.  
  6242. sin EXPR 
  6243.  
  6244. Returns the sine of EXPR (expressed in radians).  If EXPR is omitted, returns 
  6245. sine of $_. 
  6246.  
  6247.  
  6248. ΓòÉΓòÉΓòÉ 11.134. sleep EXPR ΓòÉΓòÉΓòÉ
  6249.  
  6250. sleep EXPR 
  6251.  
  6252. sleep 
  6253.  
  6254. Causes the script to sleep for EXPR seconds, or forever if no EXPR. May be 
  6255. interrupted by sending the process a SIGALRM.  Returns the number of seconds 
  6256. actually slept.  You probably cannot mix alarm() and sleep() calls, since 
  6257. sleep() is often implemented using alarm(). 
  6258.  
  6259. On some older systems, it may sleep up to a full second less than what you 
  6260. requested, depending on how it counts seconds.  Most modern systems always 
  6261. sleep the full amount. 
  6262.  
  6263. For delays of finer granularity than one second, you may use Perl's syscall() 
  6264. interface to access setitimer(2) if your system supports it, or else see 
  6265. L</select()> below. 
  6266.  
  6267.  
  6268. ΓòÉΓòÉΓòÉ 11.135. socket SOCKET,DOMAIN,TYPE,PROTOCOL ΓòÉΓòÉΓòÉ
  6269.  
  6270. socket SOCKET,DOMAIN,TYPE,PROTOCOL 
  6271.  
  6272. Opens a socket of the specified kind and attaches it to filehandle SOCKET. 
  6273. DOMAIN, TYPE and PROTOCOL are specified the same as for the system call of the 
  6274. same name.  You should "use Socket;" first to get the proper definitions 
  6275. imported.  See the example in perlipc/"Sockets: Client/Server Communication". 
  6276.  
  6277.  
  6278. ΓòÉΓòÉΓòÉ 11.136. socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL ΓòÉΓòÉΓòÉ
  6279.  
  6280. socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL 
  6281.  
  6282. Creates an unnamed pair of sockets in the specified domain, of the specified 
  6283. type.  DOMAIN, TYPE and PROTOCOL are specified the same as for the system call 
  6284. of the same name.  If unimplemented, yields a fatal error.  Returns TRUE if 
  6285. successful. 
  6286.  
  6287.  
  6288. ΓòÉΓòÉΓòÉ 11.137. sort SUBNAME LIST ΓòÉΓòÉΓòÉ
  6289.  
  6290. sort SUBNAME LIST 
  6291.  
  6292. sort BLOCK LIST 
  6293.  
  6294. sort LIST 
  6295.  
  6296. Sorts the LIST and returns the sorted list value.  Nonexistent values of arrays 
  6297. are stripped out.  If SUBNAME or BLOCK is omitted, sorts in standard string 
  6298. comparison order.  If SUBNAME is specified, it gives the name of a subroutine 
  6299. that returns an integer less than, equal to, or greater than 0, depending on 
  6300. how the elements of the array are to be ordered.  (The <=> and cmp operators 
  6301. are extremely useful in such routines.)  SUBNAME may be a scalar variable name, 
  6302. in which case the value provides the name of the subroutine to use.  In place 
  6303. of a SUBNAME, you can provide a BLOCK as an anonymous, in-line sort subroutine. 
  6304.  
  6305. In the interests of efficiency the normal calling code for subroutines is 
  6306. bypassed, with the following effects: the subroutine may not be a recursive 
  6307. subroutine, and the two elements to be compared are passed into the subroutine 
  6308. not via @_ but as the package global variables $a and $b (see example below). 
  6309. They are passed by reference, so don't modify $a and $b.  And don't try to 
  6310. declare them as lexicals either. 
  6311.  
  6312. Examples: 
  6313.  
  6314.     # sort lexically
  6315.     @articles = sort @files;
  6316.     # same thing, but with explicit sort routine
  6317.     @articles = sort {$a cmp $b} @files;
  6318.     # now case-insensitively
  6319.     @articles = sort { uc($a) cmp uc($b)} @files;
  6320.     # same thing in reversed order
  6321.     @articles = sort {$b cmp $a} @files;
  6322.     # sort numerically ascending
  6323.     @articles = sort {$a <=> $b} @files;
  6324.     # sort numerically descending
  6325.     @articles = sort {$b <=> $a} @files;
  6326.     # sort using explicit subroutine name
  6327.     sub byage {
  6328.         $age{$a} <=> $age{$b};  # presuming integers
  6329.     }
  6330.     @sortedclass = sort byage @class;
  6331.     # this sorts the %age associative arrays by value
  6332.     # instead of key using an inline function
  6333.     @eldest = sort { $age{$b} <=> $age{$a} } keys %age;
  6334.     sub backwards { $b cmp $a; }
  6335.     @harry = ('dog','cat','x','Cain','Abel');
  6336.     @george = ('gone','chased','yz','Punished','Axed');
  6337.     print sort @harry;
  6338.             # prints AbelCaincatdogx
  6339.     print sort backwards @harry;
  6340.             # prints xdogcatCainAbel
  6341.     print sort @george, 'to', @harry;
  6342.             # prints AbelAxedCainPunishedcatchaseddoggonetoxyz
  6343.     # inefficiently sort by descending numeric compare using
  6344.     # the first integer after the first = sign, or the
  6345.     # whole record case-insensitively otherwise
  6346.     @new = sort {
  6347.         ($b =~ /=(\d+)/)[0] <=> ($a =~ /=(\d+)/)[0]
  6348.                             ||
  6349.                     uc($a)  cmp  uc($b)
  6350.     } @old;
  6351.     # same thing, but much more efficiently;
  6352.     # we'll build auxiliary indices instead
  6353.     # for speed
  6354.     @nums = @caps = ();
  6355.     for (@old) {
  6356.         push @nums, /=(\d+)/;
  6357.         push @caps, uc($_);
  6358.     }
  6359.     @new = @old[ sort {
  6360.                         $nums[$b] <=> $nums[$a]
  6361.                                  ||
  6362.                         $caps[$a] cmp $caps[$b]
  6363.                        } 0..$#old
  6364.                ];
  6365.     # same thing using a Schwartzian Transform (no temps)
  6366.     @new = map { $_->[0] }
  6367.         sort { $b->[1] <=> $a->[1]
  6368.                         ||
  6369.                $a->[2] cmp $b->[2]
  6370.         } map { [$_, /=(\d+)/, uc($_)] } @old;
  6371.  
  6372. If you're and using strict, you MUST NOT declare $a and $b as lexicals.  They 
  6373. are package globals.  That means if you're in the main package, it's 
  6374.  
  6375.     @articles = sort {$main::b <=> $main::a} @files;
  6376.  
  6377. or just 
  6378.  
  6379.     @articles = sort {$::b <=> $::a} @files;
  6380.  
  6381. but if you're in the FooPack package, it's 
  6382.  
  6383.     @articles = sort {$FooPack::b <=> $FooPack::a} @files;
  6384.  
  6385.  
  6386. ΓòÉΓòÉΓòÉ 11.138. splice ARRAY,OFFSET,LENGTH,LIST ΓòÉΓòÉΓòÉ
  6387.  
  6388. splice ARRAY,OFFSET,LENGTH,LIST 
  6389.  
  6390. splice ARRAY,OFFSET,LENGTH 
  6391.  
  6392. splice ARRAY,OFFSET 
  6393.  
  6394. Removes the elements designated by OFFSET and LENGTH from an array, and 
  6395. replaces them with the elements of LIST, if any.  Returns the elements removed 
  6396. from the array.  The array grows or shrinks as necessary.  If LENGTH is 
  6397. omitted, removes everything from OFFSET onward.  The following equivalencies 
  6398. hold (assuming $[ == 0): 
  6399.  
  6400.     push(@a,$x,$y)      splice(@a,$#a+1,0,$x,$y)
  6401.     pop(@a)             splice(@a,-1)
  6402.     shift(@a)           splice(@a,0,1)
  6403.     unshift(@a,$x,$y)   splice(@a,0,0,$x,$y)
  6404.     $a[$x] = $y         splice(@a,$x,1,$y);
  6405.  
  6406. Example, assuming array lengths are passed before arrays: 
  6407.  
  6408.     sub aeq {   # compare two list values
  6409.         local(@a) = splice(@_,0,shift);
  6410.         local(@b) = splice(@_,0,shift);
  6411.         return 0 unless @a == @b;       # same len?
  6412.         while (@a) {
  6413.             return 0 if pop(@a) ne pop(@b);
  6414.         }
  6415.         return 1;
  6416.     }
  6417.     if (&aeq($len,@foo[1..$len],0+@bar,@bar)) { ... }
  6418.  
  6419.  
  6420. ΓòÉΓòÉΓòÉ 11.139. split /PATTERN/,EXPR,LIMIT ΓòÉΓòÉΓòÉ
  6421.  
  6422. split /PATTERN/,EXPR,LIMIT 
  6423.  
  6424. split /PATTERN/,EXPR 
  6425.  
  6426. split /PATTERN/ 
  6427.  
  6428. split 
  6429.  
  6430. Splits a string into an array of strings, and returns it. 
  6431.  
  6432. If not in a list context, returns the number of fields found and splits into 
  6433. the @_ array.  (In a list context, you can force the split into @_ by using ?? 
  6434. as the pattern delimiters, but it still returns the array value.)  The use of 
  6435. implicit split to @_ is deprecated, however. 
  6436.  
  6437. If EXPR is omitted, splits the $_ string.  If PATTERN is also omitted, splits 
  6438. on whitespace (after skipping any leading whitespace).  Anything matching 
  6439. PATTERN is taken to be a delimiter separating the fields.  (Note that the 
  6440. delimiter may be longer than one character.)  If LIMIT is specified and is not 
  6441. negative, splits into no more than that many fields (though it may split into 
  6442. fewer).  If LIMIT is unspecified, trailing null fields are stripped (which 
  6443. potential users of pop() would do well to remember).  If LIMIT is negative, it 
  6444. is treated as if an arbitrarily large LIMIT had been specified. 
  6445.  
  6446. A pattern matching the null string (not to be confused with a null pattern //, 
  6447. which is just one member of the set of patterns matching a null string) will 
  6448. split the value of EXPR into separate characters at each point it matches that 
  6449. way.  For example: 
  6450.  
  6451.     print join(':', split(/ */, 'hi there'));
  6452.  
  6453. produces the output 'h:i:t:h:e:r:e'. 
  6454.  
  6455. The LIMIT parameter can be used to partially split a line 
  6456.  
  6457.     ($login, $passwd, $remainder) = split(/:/, $_, 3);
  6458.  
  6459. When assigning to a list, if LIMIT is omitted, Perl supplies a LIMIT one larger 
  6460. than the number of variables in the list, to avoid unnecessary work.  For the 
  6461. list above LIMIT would have been 4 by default.  In time critical applications 
  6462. it behooves you not to split into more fields than you really need. 
  6463.  
  6464. If the PATTERN contains parentheses, additional array elements are created from 
  6465. each matching substring in the delimiter. 
  6466.  
  6467.     split(/([,-])/, "1-10,20");
  6468.  
  6469. produces the list value 
  6470.  
  6471.     (1, '-', 10, ',', 20)
  6472.  
  6473. If you had the entire header of a normal Unix email message in $header, you 
  6474. could split it up into fields and their values this way: 
  6475.  
  6476.     $header =~ s/\n\s+/ /g;  # fix continuation lines
  6477.     %hdrs   =  (UNIX_FROM => split /^(.*?):\s*/m, $header);
  6478.  
  6479. The pattern /PATTERN/ may be replaced with an expression to specify patterns 
  6480. that vary at runtime.  (To do runtime compilation only once, use /$variable/o.) 
  6481.  
  6482. As a special case, specifying a PATTERN of space (' ') will split on white 
  6483. space just as split with no arguments does.  Thus, split(' ') can be used to 
  6484. emulate awk's default behavior, whereas split(/ /) will give you as many null 
  6485. initial fields as there are leading spaces. A split on /\s+/ is like a split(' 
  6486. ') except that any leading whitespace produces a null first field.  A split 
  6487. with no arguments really does a split(' ', $_) internally. 
  6488.  
  6489. Example: 
  6490.  
  6491.     open(passwd, '/etc/passwd');
  6492.     while (<passwd>) {
  6493.         ($login, $passwd, $uid, $gid, $gcos,
  6494.             $home, $shell) = split(/:/);
  6495.         ...
  6496.     }
  6497.  
  6498. (Note that $shell above will still have a newline on it.  See L</chop>, 
  6499. L</chomp>, and L</join>.) 
  6500.  
  6501.  
  6502. ΓòÉΓòÉΓòÉ 11.140. sprintf FORMAT,LIST ΓòÉΓòÉΓòÉ
  6503.  
  6504. sprintf FORMAT,LIST 
  6505.  
  6506. Returns a string formatted by the usual printf conventions of the C language. 
  6507. See L<sprintf(3)> or L<printf(3)> on your system for details. (The * character 
  6508. for an indirectly specified length is not supported, but you can get the same 
  6509. effect by interpolating a variable into the pattern.)  Some C libraries' 
  6510. implementations of sprintf() can dump core when fed ludicrous arguments. 
  6511.  
  6512.  
  6513. ΓòÉΓòÉΓòÉ 11.141. sqrt EXPR ΓòÉΓòÉΓòÉ
  6514.  
  6515. sqrt EXPR 
  6516.  
  6517. Return the square root of EXPR.  If EXPR is omitted, returns square root of $_. 
  6518.  
  6519.  
  6520. ΓòÉΓòÉΓòÉ 11.142. srand EXPR ΓòÉΓòÉΓòÉ
  6521.  
  6522. srand EXPR 
  6523.  
  6524. Sets the random number seed for the rand operator.  If EXPR is omitted, does 
  6525. srand(time).  Many folks use an explicit srand(time ^ $$) instead.  Of course, 
  6526. you'd need something much more random than that for cryptographic purposes, 
  6527. since it's easy to guess the current time. Checksumming the compressed output 
  6528. of rapidly changing operating system status programs is the usual method. 
  6529. Examples are posted regularly to the comp.security.unix newsgroup. 
  6530.  
  6531.  
  6532. ΓòÉΓòÉΓòÉ 11.143. stat FILEHANDLE ΓòÉΓòÉΓòÉ
  6533.  
  6534. stat FILEHANDLE 
  6535.  
  6536. stat EXPR 
  6537.  
  6538. Returns a 13-element array giving the status info for a file, either the file 
  6539. opened via FILEHANDLE, or named by EXPR.  Returns a null list if the stat 
  6540. fails.  Typically used as follows: 
  6541.  
  6542.     ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
  6543.        $atime,$mtime,$ctime,$blksize,$blocks)
  6544.            = stat($filename);
  6545.  
  6546. Not all fields are supported on all filesystem types.  Here are the meaning of 
  6547. the fields: 
  6548.  
  6549.   dev       device number of filesystem
  6550.   ino       inode number
  6551.   mode      file mode  (type and permissions)
  6552.   nlink     number of (hard) links to the file
  6553.   uid       numeric user ID of file's owner
  6554.   gid       numer group ID of file's owner
  6555.   rdev      the device identifier (special files only)
  6556.   size      total size of file, in bytes
  6557.   atime     last access time since the epoch
  6558.   mtime     last modify time since the epoch
  6559.   ctime     inode change time (NOT creation type!) since the epoch
  6560.   blksize   preferred blocksize for file system I/O
  6561.   blocks    actual number of blocks allocated
  6562.  
  6563. (The epoch was at 00:00 January 1, 1970 GMT.) 
  6564.  
  6565. If stat is passed the special filehandle consisting of an underline, no stat is 
  6566. done, but the current contents of the stat structure from the last stat or 
  6567. filetest are returned.  Example: 
  6568.  
  6569.     if (-x $file && (($d) = stat(_)) && $d < 0) {
  6570.         print "$file is executable NFS file\n";
  6571.     }
  6572.  
  6573. (This only works on machines for which the device number is negative under 
  6574. NFS.) 
  6575.  
  6576.  
  6577. ΓòÉΓòÉΓòÉ 11.144. study SCALAR ΓòÉΓòÉΓòÉ
  6578.  
  6579. study SCALAR 
  6580.  
  6581. study 
  6582.  
  6583. Takes extra time to study SCALAR ($_ if unspecified) in anticipation of doing 
  6584. many pattern matches on the string before it is next modified. This may or may 
  6585. not save time, depending on the nature and number of patterns you are searching 
  6586. on, and on the distribution of character frequencies in the string to be 
  6587. searched--you probably want to compare runtimes with and without it to see 
  6588. which runs faster.  Those loops which scan for many short constant strings 
  6589. (including the constant parts of more complex patterns) will benefit most.  You 
  6590. may have only one study active at a time--if you study a different scalar the 
  6591. first is "unstudied".  (The way study works is this: a linked list of every 
  6592. character in the string to be searched is made, so we know, for example, where 
  6593. all the 'k' characters are.  From each search string, the rarest character is 
  6594. selected, based on some static frequency tables constructed from some C 
  6595. programs and English text.  Only those places that contain this "rarest" 
  6596. character are examined.) 
  6597.  
  6598. For example, here is a loop which inserts index producing entries before any 
  6599. line containing a certain pattern: 
  6600.  
  6601.     while (<>) {
  6602.         study;
  6603.         print ".IX foo\n" if /\bfoo\b/;
  6604.         print ".IX bar\n" if /\bbar\b/;
  6605.         print ".IX blurfl\n" if /\bblurfl\b/;
  6606.         ...
  6607.         print;
  6608.     }
  6609.  
  6610. In searching for /\bfoo\b/, only those locations in $_ that contain "f" will be 
  6611. looked at, because "f" is rarer than "o".  In general, this is a big win except 
  6612. in pathological cases.  The only question is whether it saves you more time 
  6613. than it took to build the linked list in the first place. 
  6614.  
  6615. Note that if you have to look for strings that you don't know till runtime, you 
  6616. can build an entire loop as a string and eval that to avoid recompiling all 
  6617. your patterns all the time.  Together with undefining $/ to input entire files 
  6618. as one record, this can be very fast, often faster than specialized programs 
  6619. like fgrep(1).  The following scans a list of files (@files) for a list of 
  6620. words (@words), and prints out the names of those files that contain a match: 
  6621.  
  6622.     $search = 'while (<>) { study;';
  6623.     foreach $word (@words) {
  6624.         $search .= "++\$seen{\$ARGV} if /\\b$word\\b/;\n";
  6625.     }
  6626.     $search .= "}";
  6627.     @ARGV = @files;
  6628.     undef $/;
  6629.     eval $search;               # this screams
  6630.     $/ = "\n";          # put back to normal input delim
  6631.     foreach $file (sort keys(%seen)) {
  6632.         print $file, "\n";
  6633.     }
  6634.  
  6635.  
  6636. ΓòÉΓòÉΓòÉ 11.145. sub BLOCK ΓòÉΓòÉΓòÉ
  6637.  
  6638. sub BLOCK 
  6639.  
  6640. sub NAME 
  6641.  
  6642. sub NAME BLOCK 
  6643.  
  6644. This is subroutine definition, not a real function per se.  With just a NAME 
  6645. (and possibly prototypes), it's just a forward declaration.  Without a NAME, 
  6646. it's an anonymous function declaration, and does actually return a value: the 
  6647. CODE ref of the closure you just created. See perlsub and perlref for details. 
  6648.  
  6649.  
  6650. ΓòÉΓòÉΓòÉ 11.146. substr EXPR,OFFSET,LEN ΓòÉΓòÉΓòÉ
  6651.  
  6652. substr EXPR,OFFSET,LEN 
  6653.  
  6654. substr EXPR,OFFSET 
  6655.  
  6656. Extracts a substring out of EXPR and returns it.  First character is at offset 
  6657. 0, or whatever you've set $[ to.  If OFFSET is negative, starts that far from 
  6658. the end of the string.  If LEN is omitted, returns everything to the end of the 
  6659. string.  If LEN is negative, leaves that many characters off the end of the 
  6660. string. 
  6661.  
  6662. You can use the substr() function as an lvalue, in which case EXPR must be an 
  6663. lvalue.  If you assign something shorter than LEN, the string will shrink, and 
  6664. if you assign something longer than LEN, the string will grow to accommodate 
  6665. it.  To keep the string the same length you may need to pad or chop your value 
  6666. using sprintf(). 
  6667.  
  6668.  
  6669. ΓòÉΓòÉΓòÉ 11.147. symlink OLDFILE,NEWFILE ΓòÉΓòÉΓòÉ
  6670.  
  6671. symlink OLDFILE,NEWFILE 
  6672.  
  6673. Creates a new filename symbolically linked to the old filename. Returns 1 for 
  6674. success, 0 otherwise.  On systems that don't support symbolic links, produces a 
  6675. fatal error at run time.  To check for that, use eval: 
  6676.  
  6677.     $symlink_exists = (eval 'symlink("","");', $@ eq '');
  6678.  
  6679.  
  6680. ΓòÉΓòÉΓòÉ 11.148. syscall LIST ΓòÉΓòÉΓòÉ
  6681.  
  6682. syscall LIST 
  6683.  
  6684. Calls the system call specified as the first element of the list, passing the 
  6685. remaining elements as arguments to the system call.  If unimplemented, produces 
  6686. a fatal error.  The arguments are interpreted as follows: if a given argument 
  6687. is numeric, the argument is passed as an int.  If not, the pointer to the 
  6688. string value is passed.  You are responsible to make sure a string is 
  6689. pre-extended long enough to receive any result that might be written into a 
  6690. string.  If your integer arguments are not literals and have never been 
  6691. interpreted in a numeric context, you may need to add 0 to them to force them 
  6692. to look like numbers. 
  6693.  
  6694.     require 'syscall.ph';               # may need to run h2ph
  6695.     syscall(&SYS_write, fileno(STDOUT), "hi there\n", 9);
  6696.  
  6697. Note that Perl only supports passing of up to 14 arguments to your system call, 
  6698. which in practice should usually suffice. 
  6699.  
  6700.  
  6701. ΓòÉΓòÉΓòÉ 11.149. sysopen FILEHANDLE,FILENAME,MODE ΓòÉΓòÉΓòÉ
  6702.  
  6703. sysopen FILEHANDLE,FILENAME,MODE 
  6704.  
  6705. sysopen FILEHANDLE,FILENAME,MODE,PERMS 
  6706.  
  6707. Opens the file whose filename is given by FILENAME, and associates it with 
  6708. FILEHANDLE.  If FILEHANDLE is an expression, its value is used as the name of 
  6709. the real filehandle wanted.  This function calls the underlying operating 
  6710. system's open function with the parameters FILENAME, MODE, PERMS. 
  6711.  
  6712. The possible values and flag bits of the MODE parameter are system-dependent; 
  6713. they are available via the standard module Fcntl. However, for historical 
  6714. reasons, some values are universal: zero means read-only, one means write-only, 
  6715. and two means read/write. 
  6716.  
  6717. If the file named by FILENAME does not exist and the open call creates it 
  6718. (typically because MODE includes the O_CREAT flag), then the value of PERMS 
  6719. specifies the permissions of the newly created file.  If PERMS is omitted, the 
  6720. default value is 0666, which allows read and write for all.  This default is 
  6721. reasonable: see umask. 
  6722.  
  6723.  
  6724. ΓòÉΓòÉΓòÉ 11.150. sysread FILEHANDLE,SCALAR,LENGTH,OFFSET ΓòÉΓòÉΓòÉ
  6725.  
  6726. sysread FILEHANDLE,SCALAR,LENGTH,OFFSET 
  6727.  
  6728. sysread FILEHANDLE,SCALAR,LENGTH 
  6729.  
  6730. Attempts to read LENGTH bytes of data into variable SCALAR from the specified 
  6731. FILEHANDLE, using the system call read(2).  It bypasses stdio, so mixing this 
  6732. with other kinds of reads may cause confusion. Returns the number of bytes 
  6733. actually read, or undef if there was an error.  SCALAR will be grown or shrunk 
  6734. to the length actually read.  An OFFSET may be specified to place the read data 
  6735. at some other place than the beginning of the string. 
  6736.  
  6737.  
  6738. ΓòÉΓòÉΓòÉ 11.151. system LIST ΓòÉΓòÉΓòÉ
  6739.  
  6740. system LIST 
  6741.  
  6742. Does exactly the same thing as "exec LIST" except that a fork is done first, 
  6743. and the parent process waits for the child process to complete. Note that 
  6744. argument processing varies depending on the number of arguments.  The return 
  6745. value is the exit status of the program as returned by the wait() call.  To get 
  6746. the actual exit value divide by 256.  See also L</exec>.  This is NOT what you 
  6747. want to use to capture the output from a command, for that you should merely 
  6748. use backticks, as described in perlop/"`STRING`". 
  6749.  
  6750.  
  6751. ΓòÉΓòÉΓòÉ 11.152. syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET ΓòÉΓòÉΓòÉ
  6752.  
  6753. syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET 
  6754.  
  6755. syswrite FILEHANDLE,SCALAR,LENGTH 
  6756.  
  6757. Attempts to write LENGTH bytes of data from variable SCALAR to the specified 
  6758. FILEHANDLE, using the system call write(2).  It bypasses stdio, so mixing this 
  6759. with prints may cause confusion.  Returns the number of bytes actually written, 
  6760. or undef if there was an error.  An OFFSET may be specified to get the write 
  6761. data from some other place than the beginning of the string. 
  6762.  
  6763.  
  6764. ΓòÉΓòÉΓòÉ 11.153. tell FILEHANDLE ΓòÉΓòÉΓòÉ
  6765.  
  6766. tell FILEHANDLE 
  6767.  
  6768. tell 
  6769.  
  6770. Returns the current file position for FILEHANDLE.  FILEHANDLE may be an 
  6771. expression whose value gives the name of the actual filehandle.  If FILEHANDLE 
  6772. is omitted, assumes the file last read. 
  6773.  
  6774.  
  6775. ΓòÉΓòÉΓòÉ 11.154. telldir DIRHANDLE ΓòÉΓòÉΓòÉ
  6776.  
  6777. telldir DIRHANDLE 
  6778.  
  6779. Returns the current position of the readdir() routines on DIRHANDLE. Value may 
  6780. be given to seekdir() to access a particular location in a directory.  Has the 
  6781. same caveats about possible directory compaction as the corresponding system 
  6782. library routine. 
  6783.  
  6784.  
  6785. ΓòÉΓòÉΓòÉ 11.155. tie VARIABLE,CLASSNAME,LIST ΓòÉΓòÉΓòÉ
  6786.  
  6787. tie VARIABLE,CLASSNAME,LIST 
  6788.  
  6789. This function binds a variable to a package class that will provide the 
  6790. implementation for the variable.  VARIABLE is the name of the variable to be 
  6791. enchanted.  CLASSNAME is the name of a class implementing objects of correct 
  6792. type.  Any additional arguments are passed to the "new" method of the class 
  6793. (meaning TIESCALAR, TIEARRAY, or TIEHASH). Typically these are arguments such 
  6794. as might be passed to the dbm_open() function of C.  The object returned by the 
  6795. "new" method is also returned by the tie() function, which would be useful if 
  6796. you want to access other methods in CLASSNAME. 
  6797.  
  6798. Note that functions such as keys() and values() may return huge array values 
  6799. when used on large objects, like DBM files.  You may prefer to use the each() 
  6800. function to iterate over such.  Example: 
  6801.  
  6802.     # print out history file offsets
  6803.     use NDBM_File;
  6804.     tie(%HIST, NDBM_File, '/usr/lib/news/history', 1, 0);
  6805.     while (($key,$val) = each %HIST) {
  6806.         print $key, ' = ', unpack('L',$val), "\n";
  6807.     }
  6808.     untie(%HIST);
  6809.  
  6810. A class implementing an associative array should have the following methods: 
  6811.  
  6812.     TIEHASH classname, LIST
  6813.     DESTROY this
  6814.     FETCH this, key
  6815.     STORE this, key, value
  6816.     DELETE this, key
  6817.     EXISTS this, key
  6818.     FIRSTKEY this
  6819.     NEXTKEY this, lastkey
  6820.  
  6821. A class implementing an ordinary array should have the following methods: 
  6822.  
  6823.     TIEARRAY classname, LIST
  6824.     DESTROY this
  6825.     FETCH this, key
  6826.     STORE this, key, value
  6827.     [others TBD]
  6828.  
  6829. A class implementing a scalar should have the following methods: 
  6830.  
  6831.     TIESCALAR classname, LIST
  6832.     DESTROY this
  6833.     FETCH this,
  6834.     STORE this, value
  6835.  
  6836. Unlike dbmopen(), the tie() function will not use or require a module for 
  6837. you--you need to do that explicitly yourself.  See L<DB_File> or the Config 
  6838. module for interesting tie() implementations. 
  6839.  
  6840.  
  6841. ΓòÉΓòÉΓòÉ 11.156. time ΓòÉΓòÉΓòÉ
  6842.  
  6843. time 
  6844.  
  6845. Returns the number of non-leap seconds since 00:00:00 UTC, January 1, 1970. 
  6846. Suitable for feeding to gmtime() and localtime(). 
  6847.  
  6848.  
  6849. ΓòÉΓòÉΓòÉ 11.157. times ΓòÉΓòÉΓòÉ
  6850.  
  6851. times 
  6852.  
  6853. Returns a four-element array giving the user and system times, in seconds, for 
  6854. this process and the children of this process. 
  6855.  
  6856.     ($user,$system,$cuser,$csystem) = times;
  6857.  
  6858.  
  6859. ΓòÉΓòÉΓòÉ 11.158. tr/// ΓòÉΓòÉΓòÉ
  6860.  
  6861. tr/// 
  6862.  
  6863. The translation operator.  See perlop. 
  6864.  
  6865.  
  6866. ΓòÉΓòÉΓòÉ 11.159. truncate FILEHANDLE,LENGTH ΓòÉΓòÉΓòÉ
  6867.  
  6868. truncate FILEHANDLE,LENGTH 
  6869.  
  6870. truncate EXPR,LENGTH 
  6871.  
  6872. Truncates the file opened on FILEHANDLE, or named by EXPR, to the specified 
  6873. length.  Produces a fatal error if truncate isn't implemented on your system. 
  6874.  
  6875.  
  6876. ΓòÉΓòÉΓòÉ 11.160. uc EXPR ΓòÉΓòÉΓòÉ
  6877.  
  6878. uc EXPR 
  6879.  
  6880. Returns an uppercased version of EXPR.  This is the internal function 
  6881. implementing the \U escape in double-quoted strings. Should respect any POSIX 
  6882. setlocale() settings. 
  6883.  
  6884.  
  6885. ΓòÉΓòÉΓòÉ 11.161. ucfirst EXPR ΓòÉΓòÉΓòÉ
  6886.  
  6887. ucfirst EXPR 
  6888.  
  6889. Returns the value of EXPR with the first character uppercased.  This is the 
  6890. internal function implementing the \u escape in double-quoted strings. Should 
  6891. respect any POSIX setlocale() settings. 
  6892.  
  6893.  
  6894. ΓòÉΓòÉΓòÉ 11.162. umask EXPR ΓòÉΓòÉΓòÉ
  6895.  
  6896. umask EXPR 
  6897.  
  6898. umask 
  6899.  
  6900. Sets the umask for the process and returns the old one.  If EXPR is omitted, 
  6901. merely returns current umask. 
  6902.  
  6903.  
  6904. ΓòÉΓòÉΓòÉ 11.163. undef EXPR ΓòÉΓòÉΓòÉ
  6905.  
  6906. undef EXPR 
  6907.  
  6908. undef 
  6909.  
  6910. Undefines the value of EXPR, which must be an lvalue.  Use only on a scalar 
  6911. value, an entire array, or a subroutine name (using "&").  (Using undef() will 
  6912. probably not do what you expect on most predefined variables or DBM list 
  6913. values, so don't do that.)  Always returns the undefined value.  You can omit 
  6914. the EXPR, in which case nothing is undefined, but you still get an undefined 
  6915. value that you could, for instance, return from a subroutine.  Examples: 
  6916.  
  6917.     undef $foo;
  6918.     undef $bar{'blurfl'};
  6919.     undef @ary;
  6920.     undef %assoc;
  6921.     undef &mysub;
  6922.     return (wantarray ? () : undef) if $they_blew_it;
  6923.  
  6924.  
  6925. ΓòÉΓòÉΓòÉ 11.164. unlink LIST ΓòÉΓòÉΓòÉ
  6926.  
  6927. unlink LIST 
  6928.  
  6929. Deletes a list of files.  Returns the number of files successfully deleted. 
  6930.  
  6931.     $cnt = unlink 'a', 'b', 'c';
  6932.     unlink @goners;
  6933.     unlink <*.bak>;
  6934.  
  6935. Note: unlink will not delete directories unless you are superuser and the -U 
  6936. flag is supplied to Perl.  Even if these conditions are met, be warned that 
  6937. unlinking a directory can inflict damage on your filesystem.  Use rmdir 
  6938. instead. 
  6939.  
  6940.  
  6941. ΓòÉΓòÉΓòÉ 11.165. unpack TEMPLATE,EXPR ΓòÉΓòÉΓòÉ
  6942.  
  6943. unpack TEMPLATE,EXPR 
  6944.  
  6945. Unpack does the reverse of pack: it takes a string representing a structure and 
  6946. expands it out into a list value, returning the array value.  (In a scalar 
  6947. context, it merely returns the first value produced.)  The TEMPLATE has the 
  6948. same format as in the pack function. Here's a subroutine that does substring: 
  6949.  
  6950.     sub substr {
  6951.         local($what,$where,$howmuch) = @_;
  6952.         unpack("x$where a$howmuch", $what);
  6953.     }
  6954.  
  6955. and then there's 
  6956.  
  6957.     sub ordinal { unpack("c",$_[0]); } # same as ord()
  6958.  
  6959. In addition, you may prefix a field with a %<number> to indicate that you want 
  6960. a <number>-bit checksum of the items instead of the items themselves.  Default 
  6961. is a 16-bit checksum.  For example, the following computes the same number as 
  6962. the System V sum program: 
  6963.  
  6964.     while (<>) {
  6965.         $checksum += unpack("%16C*", $_);
  6966.     }
  6967.     $checksum %= 65536;
  6968.  
  6969. The following efficiently counts the number of set bits in a bit vector: 
  6970.  
  6971.     $setbits = unpack("%32b*", $selectmask);
  6972.  
  6973.  
  6974. ΓòÉΓòÉΓòÉ 11.166. untie VARIABLE ΓòÉΓòÉΓòÉ
  6975.  
  6976. untie VARIABLE 
  6977.  
  6978. Breaks the binding between a variable and a package.  (See tie().) 
  6979.  
  6980.  
  6981. ΓòÉΓòÉΓòÉ 11.167. unshift ARRAY,LIST ΓòÉΓòÉΓòÉ
  6982.  
  6983. unshift ARRAY,LIST 
  6984.  
  6985. Does the opposite of a shift.  Or the opposite of a push, depending on how you 
  6986. look at it.  Prepends list to the front of the array, and returns the new 
  6987. number of elements in the array. 
  6988.  
  6989.     unshift(ARGV, '-e') unless $ARGV[0] =~ /^-/;
  6990.  
  6991. Note the LIST is prepended whole, not one element at a time, so the prepended 
  6992. elements stay in the same order.  Use reverse to do the reverse. 
  6993.  
  6994.  
  6995. ΓòÉΓòÉΓòÉ 11.168. use Module LIST ΓòÉΓòÉΓòÉ
  6996.  
  6997. use Module LIST 
  6998.  
  6999. use Module 
  7000.  
  7001. Imports some semantics into the current package from the named module, 
  7002. generally by aliasing certain subroutine or variable names into your package. 
  7003. It is exactly equivalent to 
  7004.  
  7005.     BEGIN { require Module; import Module LIST; }
  7006.  
  7007. The BEGIN forces the require and import to happen at compile time.  The require 
  7008. makes sure the module is loaded into memory if it hasn't been yet.  The import 
  7009. is not a builtin--it's just an ordinary static method call into the "Module" 
  7010. package to tell the module to import the list of features back into the current 
  7011. package.  The module can implement its import method any way it likes, though 
  7012. most modules just choose to derive their import method via inheritance from the 
  7013. Exporter class that is defined in the Exporter module. See L<Exporter>. 
  7014.  
  7015. If you don't want your namespace altered, explicitly supply an empty list: 
  7016.  
  7017.     use Module ();
  7018.  
  7019. That is exactly equivalent to 
  7020.  
  7021.     BEGIN { require Module; }
  7022.  
  7023. Because this is a wide-open interface, pragmas (compiler directives) are also 
  7024. implemented this way.  Currently implemented pragmas are: 
  7025.  
  7026.     use integer;
  7027.     use diagnostics;
  7028.     use sigtrap qw(SEGV BUS);
  7029.     use strict  qw(subs vars refs);
  7030.     use subs    qw(afunc blurfl);
  7031.  
  7032. These pseudomodules import semantics into the current block scope, unlike 
  7033. ordinary modules, which import symbols into the current package (which are 
  7034. effective through the end of the file). 
  7035.  
  7036. There's a corresponding "no" command that unimports meanings imported by use. 
  7037.  
  7038.     no integer;
  7039.     no strict 'refs';
  7040.  
  7041. See perlmod for a list of standard modules and pragmas. 
  7042.  
  7043.  
  7044. ΓòÉΓòÉΓòÉ 11.169. utime LIST ΓòÉΓòÉΓòÉ
  7045.  
  7046. utime LIST 
  7047.  
  7048. Changes the access and modification times on each file of a list of files.  The 
  7049. first two elements of the list must be the NUMERICAL access and modification 
  7050. times, in that order.  Returns the number of files successfully changed.  The 
  7051. inode modification time of each file is set to the current time.  Example of a 
  7052. "touch" command: 
  7053.  
  7054.     #!/usr/bin/perl
  7055.     $now = time;
  7056.     utime $now, $now, @ARGV;
  7057.  
  7058.  
  7059. ΓòÉΓòÉΓòÉ 11.170. values ASSOC_ARRAY ΓòÉΓòÉΓòÉ
  7060.  
  7061. values ASSOC_ARRAY 
  7062.  
  7063. Returns a normal array consisting of all the values of the named associative 
  7064. array.  (In a scalar context, returns the number of values.)  The values are 
  7065. returned in an apparently random order, but it is the same order as either the 
  7066. keys() or each() function would produce on the same array.  See also keys(), 
  7067. each(), and sort(). 
  7068.  
  7069.  
  7070. ΓòÉΓòÉΓòÉ 11.171. vec EXPR,OFFSET,BITS ΓòÉΓòÉΓòÉ
  7071.  
  7072. vec EXPR,OFFSET,BITS 
  7073.  
  7074. Treats the string in EXPR as a vector of unsigned integers, and returns the 
  7075. value of the bitfield specified by OFFSET.  BITS specifies the number of bits 
  7076. that are reserved for each entry in the bit vector. This must be a power of two 
  7077. from 1 to 32. vec() may also be assigned to, in which case parens are needed to 
  7078. give the expression the correct precedence as in 
  7079.  
  7080.     vec($image, $max_x * $x + $y, 8) = 3;
  7081.  
  7082. Vectors created with vec() can also be manipulated with the logical operators 
  7083. |, & and ^, which will assume a bit vector operation is desired when both 
  7084. operands are strings. 
  7085.  
  7086. To transform a bit vector into a string or array of 0's and 1's, use these: 
  7087.  
  7088.     $bits = unpack("b*", $vector);
  7089.     @bits = split(//, unpack("b*", $vector));
  7090.  
  7091. If you know the exact length in bits, it can be used in place of the *. 
  7092.  
  7093.  
  7094. ΓòÉΓòÉΓòÉ 11.172. wait ΓòÉΓòÉΓòÉ
  7095.  
  7096. wait 
  7097.  
  7098. Waits for a child process to terminate and returns the pid of the deceased 
  7099. process, or -1 if there are no child processes.  The status is returned in $?. 
  7100.  
  7101.  
  7102. ΓòÉΓòÉΓòÉ 11.173. waitpid PID,FLAGS ΓòÉΓòÉΓòÉ
  7103.  
  7104. waitpid PID,FLAGS 
  7105.  
  7106. Waits for a particular child process to terminate and returns the pid of the 
  7107. deceased process, or -1 if there is no such child process.  The status is 
  7108. returned in $?.  If you say 
  7109.  
  7110.     use POSIX "wait_h";
  7111.     ...
  7112.     waitpid(-1,&WNOHANG);
  7113.  
  7114. then you can do a non-blocking wait for any process.  Non-blocking wait is only 
  7115. available on machines supporting either the waitpid(2) or wait4(2) system 
  7116. calls.  However, waiting for a particular pid with FLAGS of 0 is implemented 
  7117. everywhere.  (Perl emulates the system call by remembering the status values of 
  7118. processes that have exited but have not been harvested by the Perl script yet.) 
  7119.  
  7120.  
  7121. ΓòÉΓòÉΓòÉ 11.174. wantarray ΓòÉΓòÉΓòÉ
  7122.  
  7123. wantarray 
  7124.  
  7125. Returns TRUE if the context of the currently executing subroutine is looking 
  7126. for a list value.  Returns FALSE if the context is looking for a scalar. 
  7127.  
  7128.     return wantarray ? () : undef;
  7129.  
  7130.  
  7131. ΓòÉΓòÉΓòÉ 11.175. warn LIST ΓòÉΓòÉΓòÉ
  7132.  
  7133. warn LIST 
  7134.  
  7135. Produces a message on STDERR just like die(), but doesn't exit or on an 
  7136. exception. 
  7137.  
  7138.  
  7139. ΓòÉΓòÉΓòÉ 11.176. write FILEHANDLE ΓòÉΓòÉΓòÉ
  7140.  
  7141. write FILEHANDLE 
  7142.  
  7143. write EXPR 
  7144.  
  7145. write 
  7146.  
  7147. Writes a formatted record (possibly multi-line) to the specified file, using 
  7148. the format associated with that file.  By default the format for a file is the 
  7149. one having the same name is the filehandle, but the format for the current 
  7150. output channel (see the select() function) may be set explicitly by assigning 
  7151. the name of the format to the $~ variable. 
  7152.  
  7153. Top of form processing is handled automatically:  if there is insufficient room 
  7154. on the current page for the formatted record, the page is advanced by writing a 
  7155. form feed, a special top-of-page format is used to format the new page header, 
  7156. and then the record is written. By default the top-of-page format is the name 
  7157. of the filehandle with "_TOP" appended, but it may be dynamically set to the 
  7158. format of your choice by assigning the name to the $^ variable while the 
  7159. filehandle is selected.  The number of lines remaining on the current page is 
  7160. in variable $-, which can be set to 0 to force a new page. 
  7161.  
  7162. If FILEHANDLE is unspecified, output goes to the current default output 
  7163. channel, which starts out as STDOUT but may be changed by the select operator. 
  7164. If the FILEHANDLE is an EXPR, then the expression is evaluated and the 
  7165. resulting string is used to look up the name of the FILEHANDLE at run time. 
  7166. For more on formats, see perlform. 
  7167.  
  7168. Note that write is NOT the opposite of read.  Unfortunately. 
  7169.  
  7170.  
  7171. ΓòÉΓòÉΓòÉ 11.177. y/// ΓòÉΓòÉΓòÉ
  7172.  
  7173. y/// 
  7174.  
  7175. The translation operator.  See perlop/tr///. 
  7176.  
  7177.  
  7178. ΓòÉΓòÉΓòÉ 12. Section - perlvar ΓòÉΓòÉΓòÉ
  7179.  
  7180. NAME 
  7181.  
  7182. perlvar - Perl predefined variables 
  7183.  
  7184. DESCRIPTION 
  7185.  
  7186. Predefined Names 
  7187.  
  7188. The following names have special meaning to Perl.  Most of the punctuational 
  7189. names have reasonable mnemonics, or analogues in one of the shells. 
  7190. Nevertheless, if you wish to use the long variable names, you just need to say 
  7191.  
  7192.     use English;
  7193.  
  7194. at the top of your program.  This will alias all the short names to the long 
  7195. names in the current package.  Some of them even have medium names, generally 
  7196. borrowed from awk. 
  7197.  
  7198. To go a step further, those variables that depend on the currently selected 
  7199. filehandle may instead be set by calling an object method on the FileHandle 
  7200. object.  (Summary lines below for this contain the word HANDLE.)  First you 
  7201. must say 
  7202.  
  7203.     use FileHandle;
  7204.  
  7205. after which you may use either 
  7206.  
  7207.     method HANDLE EXPR
  7208.  
  7209. or 
  7210.  
  7211.     HANDLE->method(EXPR)
  7212.  
  7213. Each of the methods returns the old value of the FileHandle attribute. The 
  7214. methods each take an optional EXPR, which if supplied specifies the new value 
  7215. for the FileHandle attribute in question.  If not supplied, most of the methods 
  7216. do nothing to the current value, except for autoflush(), which will assume a 1 
  7217. for you, just to be different. 
  7218.  
  7219. A few of these variables are considered "read-only".  This means that if you 
  7220. try to assign to this variable, either directly or indirectly through a 
  7221. reference, you'll raise a run-time exception. 
  7222.  
  7223. Listing of Perl Predefined Variables 
  7224.  
  7225.  
  7226. ΓòÉΓòÉΓòÉ 13. Listing of Perl Predefined Variables ΓòÉΓòÉΓòÉ
  7227.  
  7228. Listing of Perl Predefined Variables 
  7229.  
  7230.       $ARG 
  7231.       $_ 
  7232.       $<digit> 
  7233.       $MATCH 
  7234.       $& 
  7235.       $PREMATCH 
  7236.       $` 
  7237.       $POSTMATCH 
  7238.       $' 
  7239.       $LAST_PAREN_MATCH 
  7240.       $+ 
  7241.       $MULTILINE_MATCHING 
  7242.       $* 
  7243.       input_line_number HANDLE EXPR 
  7244.       $INPUT_LINE_NUMBER 
  7245.       $NR 
  7246.       $. 
  7247.       input_record_separator HANDLE EXPR 
  7248.       $INPUT_RECORD_SEPARATOR 
  7249.       $RS 
  7250.       $/ 
  7251.       autoflush HANDLE EXPR 
  7252.       $OUTPUT_AUTOFLUSH 
  7253.       $| 
  7254.       output_field_separator HANDLE EXPR 
  7255.       $OUTPUT_FIELD_SEPARATOR 
  7256.       $OFS 
  7257.       $, 
  7258.       output_record_separator HANDLE EXPR 
  7259.       $OUTPUT_RECORD_SEPARATOR 
  7260.       $ORS 
  7261.       $\ 
  7262.       $LIST_SEPARATOR 
  7263.       $" 
  7264.       $SUBSCRIPT_SEPARATOR 
  7265.       $SUBSEP 
  7266.       $; 
  7267.       $OFMT 
  7268.       $# 
  7269.       format_page_number HANDLE EXPR 
  7270.       $FORMAT_PAGE_NUMBER 
  7271.       $% 
  7272.       format_lines_per_page HANDLE EXPR 
  7273.       $FORMAT_LINES_PER_PAGE 
  7274.       $= 
  7275.       format_lines_left HANDLE EXPR 
  7276.       $FORMAT_LINES_LEFT 
  7277.       $- 
  7278.       format_name HANDLE EXPR 
  7279.       $FORMAT_NAME 
  7280.       $~ 
  7281.       format_top_name HANDLE EXPR 
  7282.       $FORMAT_TOP_NAME 
  7283.       $^ 
  7284.       format_line_break_characters HANDLE EXPR 
  7285.       $FORMAT_LINE_BREAK_CHARACTERS 
  7286.       $: 
  7287.       format_formfeed HANDLE EXPR 
  7288.       $FORMAT_FORMFEED 
  7289.       $^L 
  7290.       $ACCUMULATOR 
  7291.       $^A 
  7292.       $CHILD_ERROR 
  7293.       $? 
  7294.       $OS_ERROR 
  7295.       $ERRNO 
  7296.       $! 
  7297.       $EVAL_ERROR 
  7298.       $@ 
  7299.       $PROCESS_ID 
  7300.       $PID 
  7301.       $$ 
  7302.       $REAL_USER_ID 
  7303.       $UID 
  7304.       $< 
  7305.       $EFFECTIVE_USER_ID 
  7306.       $EUID 
  7307.       $> 
  7308.       $REAL_GROUP_ID 
  7309.       $GID 
  7310.       $( 
  7311.       $EFFECTIVE_GROUP_ID 
  7312.       $EGID 
  7313.       $) 
  7314.       $PROGRAM_NAME 
  7315.       $0 
  7316.       $[ 
  7317.       $PERL_VERSION 
  7318.       $] 
  7319.       $DEBUGGING 
  7320.       $^D 
  7321.       $SYSTEM_FD_MAX 
  7322.       $^F 
  7323.       $INPLACE_EDIT 
  7324.       $^I 
  7325.       $PERLDB 
  7326.       $^P 
  7327.       $BASETIME 
  7328.       $^T 
  7329.       $WARNING 
  7330.       $^W 
  7331.       $EXECUTABLE_NAME 
  7332.       $^X 
  7333.       $ARGV 
  7334.       @ARGV 
  7335.       @INC 
  7336.       %INC 
  7337.       $ENV{expr} 
  7338.       $SIG{expr} 
  7339.  
  7340.  
  7341. ΓòÉΓòÉΓòÉ 13.1. $ARG ΓòÉΓòÉΓòÉ
  7342.  
  7343. $ARG 
  7344.  
  7345. $_ 
  7346.  
  7347. The default input and pattern-searching space.  The following pairs are 
  7348. equivalent: 
  7349.  
  7350.     while (<>) {...}    # only equivalent in while!
  7351.     while ($_ = <>) {...}
  7352.     /^Subject:/
  7353.     $_ =~ /^Subject:/
  7354.     tr/a-z/A-Z/
  7355.     $_ =~ tr/a-z/A-Z/
  7356.     chop
  7357.     chop($_)
  7358.  
  7359. Here are the places where Perl will assume $_ even if you don't use it: 
  7360.  
  7361.      Various unary functions, including functions like ord() and int(), as 
  7362.       well as the all file tests (-f, -d) except for -t, which defaults to 
  7363.       STDIN. 
  7364.  
  7365.      Various list functions like print() and unlink(). 
  7366.  
  7367.      The pattern matching operations m//, s///, and tr/// when used without an 
  7368.       =~ operator. 
  7369.  
  7370.      The default iterator variable in a foreach loop if no other variable is 
  7371.       supplied. 
  7372.  
  7373.      The implicit iterator variable in the grep() and map() functions. 
  7374.  
  7375.      The default place to put an input record when a <FH> operation's result 
  7376.       is tested by itself as the sole criterion of a while test.  Note that 
  7377.       outside of a while test, this will not happen. 
  7378.  
  7379.  (Mnemonic: underline is understood in certain operations.) 
  7380.  
  7381.  
  7382. ΓòÉΓòÉΓòÉ 13.2. $< ΓòÉΓòÉΓòÉ
  7383.  
  7384. digit> 
  7385.  
  7386. $<digit> 
  7387.  
  7388. Contains the subpattern from the corresponding set of parentheses in the last 
  7389. pattern matched, not counting patterns matched in nested blocks that have been 
  7390. exited already.  (Mnemonic: like \digit.) These variables are all read-only. 
  7391.  
  7392.  
  7393. ΓòÉΓòÉΓòÉ 13.3. $MATCH ΓòÉΓòÉΓòÉ
  7394.  
  7395. $MATCH 
  7396.  
  7397. $& 
  7398.  
  7399. The string matched by the last successful pattern match (not counting any 
  7400. matches hidden within a BLOCK or eval() enclosed by the current BLOCK). 
  7401. (Mnemonic: like & in some editors.)  This variable is read-only. 
  7402.  
  7403.  
  7404. ΓòÉΓòÉΓòÉ 13.4. $PREMATCH ΓòÉΓòÉΓòÉ
  7405.  
  7406. $PREMATCH 
  7407.  
  7408. $` 
  7409.  
  7410. The string preceding whatever was matched by the last successful pattern match 
  7411. (not counting any matches hidden within a BLOCK or eval enclosed by the current 
  7412. BLOCK).  (Mnemonic: ` often precedes a quoted string.)  This variable is 
  7413. read-only. 
  7414.  
  7415.  
  7416. ΓòÉΓòÉΓòÉ 13.5. $POSTMATCH ΓòÉΓòÉΓòÉ
  7417.  
  7418. $POSTMATCH 
  7419.  
  7420. $' 
  7421.  
  7422. The string following whatever was matched by the last successful pattern match 
  7423. (not counting any matches hidden within a BLOCK or eval() enclosed by the 
  7424. current BLOCK).  (Mnemonic: ' often follows a quoted string.)  Example: 
  7425.  
  7426.     $_ = 'abcdefghi';
  7427.     /def/;
  7428.     print "$`:$&:$'\n";         # prints abc:def:ghi
  7429.  
  7430. This variable is read-only. 
  7431.  
  7432.  
  7433. ΓòÉΓòÉΓòÉ 13.6. $LAST_PAREN_MATCH ΓòÉΓòÉΓòÉ
  7434.  
  7435. $LAST_PAREN_MATCH 
  7436.  
  7437. $+ 
  7438.  
  7439. The last bracket matched by the last search pattern.  This is useful if you 
  7440. don't know which of a set of alternative patterns matched.  For example: 
  7441.  
  7442.     /Version: (.*)|Revision: (.*)/ && ($rev = $+);
  7443.  
  7444. (Mnemonic: be positive and forward looking.) This variable is read-only. 
  7445.  
  7446.  
  7447. ΓòÉΓòÉΓòÉ 13.7. $MULTILINE_MATCHING ΓòÉΓòÉΓòÉ
  7448.  
  7449. $MULTILINE_MATCHING 
  7450.  
  7451. $* 
  7452.  
  7453. Set to 1 to do multiline matching within a string, 0 to tell Perl that it can 
  7454. assume that strings contain a single line, for the purpose of optimizing 
  7455. pattern matches.  Pattern matches on strings containing multiple newlines can 
  7456. produce confusing results when "$*" is 0.  Default is 0.  (Mnemonic: * matches 
  7457. multiple things.)  Note that this variable only influences the interpretation 
  7458. of "^" and "$".  A literal newline can be searched for even when $* == 0. 
  7459.  
  7460. Use of "$*" is deprecated in Perl 5. 
  7461.  
  7462.  
  7463. ΓòÉΓòÉΓòÉ 13.8. input_line_number HANDLE EXPR ΓòÉΓòÉΓòÉ
  7464.  
  7465. input_line_number HANDLE EXPR 
  7466.  
  7467. $INPUT_LINE_NUMBER 
  7468.  
  7469. $NR 
  7470.  
  7471. $. 
  7472.  
  7473. The current input line number of the last filehandle that was read.  An 
  7474. explicit close on the filehandle resets the line number.  Since "<>" never does 
  7475. an explicit close, line numbers increase across ARGV files (but see examples 
  7476. under eof()).  Localizing $. has the effect of also localizing Perl's notion of 
  7477. "the last read filehandle".  (Mnemonic: many programs use "." to mean the 
  7478. current line number.) 
  7479.  
  7480.  
  7481. ΓòÉΓòÉΓòÉ 13.9. input_record_separator HANDLE EXPR ΓòÉΓòÉΓòÉ
  7482.  
  7483. input_record_separator HANDLE EXPR 
  7484.  
  7485. $INPUT_RECORD_SEPARATOR 
  7486.  
  7487. $RS 
  7488.  
  7489. $/ 
  7490.  
  7491. The input record separator, newline by default.  Works like awk's RS variable, 
  7492. including treating blank lines as delimiters if set to the null string.  You 
  7493. may set it to a multicharacter string to match a multi-character delimiter. 
  7494. Note that setting it to "\n\n" means something slightly different than setting 
  7495. it to "", if the file contains consecutive blank lines.  Setting it to "" will 
  7496. treat two or more consecutive blank lines as a single blank line.  Setting it 
  7497. to "\n\n" will blindly assume that the next input character belongs to the next 
  7498. paragraph, even if it's a newline.  (Mnemonic: / is used to delimit line 
  7499. boundaries when quoting poetry.) 
  7500.  
  7501.     undef $/;
  7502.     $_ = <FH>;          # whole file now here
  7503.     s/\n[ \t]+/ /g;
  7504.  
  7505.  
  7506. ΓòÉΓòÉΓòÉ 13.10. autoflush HANDLE EXPR ΓòÉΓòÉΓòÉ
  7507.  
  7508. autoflush HANDLE EXPR 
  7509.  
  7510. $OUTPUT_AUTOFLUSH 
  7511.  
  7512. $| 
  7513.  
  7514. If set to nonzero, forces a flush after every write or print on the currently 
  7515. selected output channel.  Default is 0.  Note that STDOUT will typically be 
  7516. line buffered if output is to the terminal and block buffered otherwise. 
  7517. Setting this variable is useful primarily when you are outputting to a pipe, 
  7518. such as when you are running a Perl script under rsh and want to see the output 
  7519. as it's happening.  This has no effect on input buffering. (Mnemonic: when you 
  7520. want your pipes to be piping hot.) 
  7521.  
  7522.  
  7523. ΓòÉΓòÉΓòÉ 13.11. output_field_separator HANDLE EXPR ΓòÉΓòÉΓòÉ
  7524.  
  7525. output_field_separator HANDLE EXPR 
  7526.  
  7527. $OUTPUT_FIELD_SEPARATOR 
  7528.  
  7529. $OFS 
  7530.  
  7531. $, 
  7532.  
  7533. The output field separator for the print operator.  Ordinarily the print 
  7534. operator simply prints out the comma separated fields you specify.  In order to 
  7535. get behavior more like awk, set this variable as you would set awk's OFS 
  7536. variable to specify what is printed between fields.  (Mnemonic: what is printed 
  7537. when there is a , in your print statement.) 
  7538.  
  7539.  
  7540. ΓòÉΓòÉΓòÉ 13.12. output_record_separator HANDLE EXPR ΓòÉΓòÉΓòÉ
  7541.  
  7542. output_record_separator HANDLE EXPR 
  7543.  
  7544. $OUTPUT_RECORD_SEPARATOR 
  7545.  
  7546. $ORS 
  7547.  
  7548. $\ 
  7549.  
  7550. The output record separator for the print operator.  Ordinarily the print 
  7551. operator simply prints out the comma separated fields you specify, with no 
  7552. trailing newline or record separator assumed.  In order to get behavior more 
  7553. like awk, set this variable as you would set awk's ORS variable to specify what 
  7554. is printed at the end of the print.  (Mnemonic: you set "$\" instead of adding 
  7555. \n at the end of the print.  Also, it's just like /, but it's what you get 
  7556. "back" from Perl.) 
  7557.  
  7558.  
  7559. ΓòÉΓòÉΓòÉ 13.13. $LIST_SEPARATOR ΓòÉΓòÉΓòÉ
  7560.  
  7561. $LIST_SEPARATOR 
  7562.  
  7563. $" 
  7564.  
  7565. This is like "$," except that it applies to array values interpolated into a 
  7566. double-quoted string (or similar interpreted string).  Default is a space. 
  7567. (Mnemonic: obvious, I think.) 
  7568.  
  7569.  
  7570. ΓòÉΓòÉΓòÉ 13.14. $SUBSCRIPT_SEPARATOR ΓòÉΓòÉΓòÉ
  7571.  
  7572. $SUBSCRIPT_SEPARATOR 
  7573.  
  7574. $SUBSEP 
  7575.  
  7576. $; 
  7577.  
  7578. The subscript separator for multi-dimensional array emulation.  If you refer to 
  7579. a hash element as 
  7580.  
  7581.     $foo{$a,$b,$c}
  7582.  
  7583. it really means 
  7584.  
  7585.     $foo{join($;, $a, $b, $c)}
  7586.  
  7587. But don't put 
  7588.  
  7589.     @foo{$a,$b,$c}      # a slice--note the @
  7590.  
  7591. which means 
  7592.  
  7593.     ($foo{$a},$foo{$b},$foo{$c})
  7594.  
  7595. Default is "\034", the same as SUBSEP in awk.  Note that if your keys contain 
  7596. binary data there might not be any safe value for "$;". (Mnemonic: comma (the 
  7597. syntactic subscript separator) is a semi-semicolon.  Yeah, I know, it's pretty 
  7598. lame, but "$," is already taken for something more important.) 
  7599.  
  7600. Consider using "real" multi-dimensional arrays in Perl 5. 
  7601.  
  7602.  
  7603. ΓòÉΓòÉΓòÉ 13.15. $OFMT ΓòÉΓòÉΓòÉ
  7604.  
  7605. $OFMT 
  7606.  
  7607. $# 
  7608.  
  7609. The output format for printed numbers.  This variable is a half-hearted attempt 
  7610. to emulate awk's OFMT variable.  There are times, however, when awk and Perl 
  7611. have differing notions of what is in fact numeric.  Also, the initial value is 
  7612. %.20g rather than %.6g, so you need to set "$#" explicitly to get awk's value. 
  7613. (Mnemonic: # is the number sign.) 
  7614.  
  7615. Use of "$#" is deprecated in Perl 5. 
  7616.  
  7617.  
  7618. ΓòÉΓòÉΓòÉ 13.16. format_page_number HANDLE EXPR ΓòÉΓòÉΓòÉ
  7619.  
  7620. format_page_number HANDLE EXPR 
  7621.  
  7622. $FORMAT_PAGE_NUMBER 
  7623.  
  7624. $% 
  7625.  
  7626. The current page number of the currently selected output channel. (Mnemonic: % 
  7627. is page number in nroff.) 
  7628.  
  7629.  
  7630. ΓòÉΓòÉΓòÉ 13.17. format_lines_per_page HANDLE EXPR ΓòÉΓòÉΓòÉ
  7631.  
  7632. format_lines_per_page HANDLE EXPR 
  7633.  
  7634. $FORMAT_LINES_PER_PAGE 
  7635.  
  7636. $= 
  7637.  
  7638. The current page length (printable lines) of the currently selected output 
  7639. channel.  Default is 60.  (Mnemonic: = has horizontal lines.) 
  7640.  
  7641.  
  7642. ΓòÉΓòÉΓòÉ 13.18. format_lines_left HANDLE EXPR ΓòÉΓòÉΓòÉ
  7643.  
  7644. format_lines_left HANDLE EXPR 
  7645.  
  7646. $FORMAT_LINES_LEFT 
  7647.  
  7648. $- 
  7649.  
  7650. The number of lines left on the page of the currently selected output channel. 
  7651. (Mnemonic: lines_on_page - lines_printed.) 
  7652.  
  7653.  
  7654. ΓòÉΓòÉΓòÉ 13.19. format_name HANDLE EXPR ΓòÉΓòÉΓòÉ
  7655.  
  7656. format_name HANDLE EXPR 
  7657.  
  7658. $FORMAT_NAME 
  7659.  
  7660. $~ 
  7661.  
  7662. The name of the current report format for the currently selected output 
  7663. channel.  Default is name of the filehandle.  (Mnemonic: brother to "$^".) 
  7664.  
  7665.  
  7666. ΓòÉΓòÉΓòÉ 13.20. format_top_name HANDLE EXPR ΓòÉΓòÉΓòÉ
  7667.  
  7668. format_top_name HANDLE EXPR 
  7669.  
  7670. $FORMAT_TOP_NAME 
  7671.  
  7672. $^ 
  7673.  
  7674. The name of the current top-of-page format for the currently selected output 
  7675. channel.  Default is name of the filehandle with _TOP appended.  (Mnemonic: 
  7676. points to top of page.) 
  7677.  
  7678.  
  7679. ΓòÉΓòÉΓòÉ 13.21. format_line_break_characters HANDLE EXPR ΓòÉΓòÉΓòÉ
  7680.  
  7681. format_line_break_characters HANDLE EXPR 
  7682.  
  7683. $FORMAT_LINE_BREAK_CHARACTERS 
  7684.  
  7685. $: 
  7686.  
  7687. The current set of characters after which a string may be broken to fill 
  7688. continuation fields (starting with ^) in a format.  Default is " \n-", to break 
  7689. on whitespace or hyphens.  (Mnemonic: a "colon" in poetry is a part of a line.) 
  7690.  
  7691.  
  7692. ΓòÉΓòÉΓòÉ 13.22. format_formfeed HANDLE EXPR ΓòÉΓòÉΓòÉ
  7693.  
  7694. format_formfeed HANDLE EXPR 
  7695.  
  7696. $FORMAT_FORMFEED 
  7697.  
  7698. $^L 
  7699.  
  7700. What formats output to perform a formfeed.  Default is \f. 
  7701.  
  7702.  
  7703. ΓòÉΓòÉΓòÉ 13.23. $ACCUMULATOR ΓòÉΓòÉΓòÉ
  7704.  
  7705. $ACCUMULATOR 
  7706.  
  7707. $^A 
  7708.  
  7709. The current value of the write() accumulator for format() lines.  A format 
  7710. contains formline() commands that put their result into $^A.  After calling its 
  7711. format, write() prints out the contents of $^A and empties. So you never 
  7712. actually see the contents of $^A unless you call formline() yourself and then 
  7713. look at it.  See perlform and perlfunc/formline(). 
  7714.  
  7715.  
  7716. ΓòÉΓòÉΓòÉ 13.24. $CHILD_ERROR ΓòÉΓòÉΓòÉ
  7717.  
  7718. $CHILD_ERROR 
  7719.  
  7720. $? 
  7721.  
  7722. The status returned by the last pipe close, backtick (``) command, or system() 
  7723. operator.  Note that this is the status word returned by the wait() system 
  7724. call, so the exit value of the subprocess is actually ($? > 8>).  Thus on many 
  7725. systems, $? & 255 gives which signal, if any, the process died from, and 
  7726. whether there was a core dump. (Mnemonic: similar to sh and ksh.) 
  7727.  
  7728.  
  7729. ΓòÉΓòÉΓòÉ 13.25. $OS_ERROR ΓòÉΓòÉΓòÉ
  7730.  
  7731. $OS_ERROR 
  7732.  
  7733. $ERRNO 
  7734.  
  7735. $! 
  7736.  
  7737. If used in a numeric context, yields the current value of errno, with all the 
  7738. usual caveats.  (This means that you shouldn't depend on the value of "$!" to 
  7739. be anything in particular unless you've gotten a specific error return 
  7740. indicating a system error.)  If used in a string context, yields the 
  7741. corresponding system error string.  You can assign to "$!" in order to set 
  7742. errno if, for instance, you want "$!" to return the string for error n, or you 
  7743. want to set the exit value for the die() operator.  (Mnemonic: What just went 
  7744. bang?) 
  7745.  
  7746.  
  7747. ΓòÉΓòÉΓòÉ 13.26. $EVAL_ERROR ΓòÉΓòÉΓòÉ
  7748.  
  7749. $EVAL_ERROR 
  7750.  
  7751. $@ 
  7752.  
  7753. The Perl syntax error message from the last eval() command.  If null, the last 
  7754. eval() parsed and executed correctly (although the operations you invoked may 
  7755. have failed in the normal fashion).  (Mnemonic: Where was the syntax error 
  7756. "at"?) 
  7757.  
  7758. Note that warning messages are not collected in this variable.  You can, 
  7759. however, set up a routine to process warnings by setting $SIG{__WARN__} below. 
  7760.  
  7761.  
  7762. ΓòÉΓòÉΓòÉ 13.27. $PROCESS_ID ΓòÉΓòÉΓòÉ
  7763.  
  7764. $PROCESS_ID 
  7765.  
  7766. $PID 
  7767.  
  7768. $$ 
  7769.  
  7770. The process number of the Perl running this script.  (Mnemonic: same as 
  7771. shells.) 
  7772.  
  7773.  
  7774. ΓòÉΓòÉΓòÉ 13.28. $REAL_USER_ID ΓòÉΓòÉΓòÉ
  7775.  
  7776. $REAL_USER_ID 
  7777.  
  7778. $UID 
  7779.  
  7780. $< 
  7781.  
  7782. The real uid of this process.  (Mnemonic: it's the uid you came FROM, if you're 
  7783. running setuid.) 
  7784.  
  7785.  
  7786. ΓòÉΓòÉΓòÉ 13.29. $EFFECTIVE_USER_ID ΓòÉΓòÉΓòÉ
  7787.  
  7788. $EFFECTIVE_USER_ID 
  7789.  
  7790. $EUID 
  7791.  
  7792. $> 
  7793.  
  7794. The effective uid of this process.  Example: 
  7795.  
  7796.     $< = $>;            # set real to effective uid
  7797.     ($<,$>) = ($>,$<);  # swap real and effective uid
  7798.  
  7799. (Mnemonic: it's the uid you went TO, if you're running setuid.)  Note: "$<" and 
  7800. "$>" can only be swapped on machines supporting setreuid(). 
  7801.  
  7802.  
  7803. ΓòÉΓòÉΓòÉ 13.30. $REAL_GROUP_ID ΓòÉΓòÉΓòÉ
  7804.  
  7805. $REAL_GROUP_ID 
  7806.  
  7807. $GID 
  7808.  
  7809. $( 
  7810.  
  7811. The real gid of this process.  If you are on a machine that supports membership 
  7812. in multiple groups simultaneously, gives a space separated list of groups you 
  7813. are in.  The first number is the one returned by getgid(), and the subsequent 
  7814. ones by getgroups(), one of which may be the same as the first number. 
  7815. (Mnemonic: parentheses are used to GROUP things.  The real gid is the group you 
  7816. LEFT, if you're running setgid.) 
  7817.  
  7818.  
  7819. ΓòÉΓòÉΓòÉ 13.31. $EFFECTIVE_GROUP_ID ΓòÉΓòÉΓòÉ
  7820.  
  7821. $EFFECTIVE_GROUP_ID 
  7822.  
  7823. $EGID 
  7824.  
  7825. $) 
  7826.  
  7827. The effective gid of this process.  If you are on a machine that supports 
  7828. membership in multiple groups simultaneously, gives a space separated list of 
  7829. groups you are in.  The first number is the one returned by getegid(), and the 
  7830. subsequent ones by getgroups(), one of which may be the same as the first 
  7831. number.  (Mnemonic: parentheses are used to GROUP things.  The effective gid is 
  7832. the group that's RIGHT for you, if you're running setgid.) 
  7833.  
  7834. Note: "$<", "$>", "$(" and "$)" can only be set on machines that support the 
  7835. corresponding set[re][ug]id() routine.  "$(" and "$)" can only be swapped on 
  7836. machines supporting setregid().  Because Perl doesn't currently use 
  7837. initgroups(), you can't set your group vector to multiple groups. 
  7838.  
  7839.  
  7840. ΓòÉΓòÉΓòÉ 13.32. $PROGRAM_NAME ΓòÉΓòÉΓòÉ
  7841.  
  7842. $PROGRAM_NAME 
  7843.  
  7844. $0 
  7845.  
  7846. Contains the name of the file containing the Perl script being executed. 
  7847. Assigning to "$0" modifies the argument area that the ps(1) program sees.  This 
  7848. is more useful as a way of indicating the current program state than it is for 
  7849. hiding the program you're running. (Mnemonic: same as sh and ksh.) 
  7850.  
  7851.  
  7852. ΓòÉΓòÉΓòÉ 13.33. $[ ΓòÉΓòÉΓòÉ
  7853.  
  7854. $[ 
  7855.  
  7856. The index of the first element in an array, and of the first character in a 
  7857. substring.  Default is 0, but you could set it to 1 to make Perl behave more 
  7858. like awk (or Fortran) when subscripting and when evaluating the index() and 
  7859. substr() functions.  (Mnemonic: [ begins subscripts.) 
  7860.  
  7861. As of Perl 5, assignment to "$[" is treated as a compiler directive, and cannot 
  7862. influence the behavior of any other file.  Its use is discouraged. 
  7863.  
  7864.  
  7865. ΓòÉΓòÉΓòÉ 13.34. $PERL_VERSION ΓòÉΓòÉΓòÉ
  7866.  
  7867. $PERL_VERSION 
  7868.  
  7869. $] 
  7870.  
  7871. The string printed out when you say perl -v. (This is currently BROKEN). It can 
  7872. be used to determine at the beginning of a script whether the perl interpreter 
  7873. executing the script is in the right range of versions.  If used in a numeric 
  7874. context, returns the version + patchlevel / 1000.  Example: 
  7875.  
  7876.     # see if getc is available
  7877.     ($version,$patchlevel) =
  7878.              $] =~ /(\d+\.\d+).*\nPatch level: (\d+)/;
  7879.     print STDERR "(No filename completion available.)\n"
  7880.              if $version * 1000 + $patchlevel < 2016;
  7881.  
  7882. or, used numerically, 
  7883.  
  7884.     warn "No checksumming!\n" if $] < 3.019;
  7885.  
  7886. (Mnemonic: Is this version of perl in the right bracket?) 
  7887.  
  7888.  
  7889. ΓòÉΓòÉΓòÉ 13.35. $DEBUGGING ΓòÉΓòÉΓòÉ
  7890.  
  7891. $DEBUGGING 
  7892.  
  7893. $^D 
  7894.  
  7895. The current value of the debugging flags.  (Mnemonic: value of -D switch.) 
  7896.  
  7897.  
  7898. ΓòÉΓòÉΓòÉ 13.36. $SYSTEM_FD_MAX ΓòÉΓòÉΓòÉ
  7899.  
  7900. $SYSTEM_FD_MAX 
  7901.  
  7902. $^F 
  7903.  
  7904. The maximum system file descriptor, ordinarily 2.  System file descriptors are 
  7905. passed to exec()ed processes, while higher file descriptors are not.  Also, 
  7906. during an open(), system file descriptors are preserved even if the open() 
  7907. fails.  (Ordinary file descriptors are closed before the open() is attempted.) 
  7908. Note that the close-on-exec status of a file descriptor will be decided 
  7909. according to the value of $^F at the time of the open, not the time of the 
  7910. exec. 
  7911.  
  7912.  
  7913. ΓòÉΓòÉΓòÉ 13.37. $INPLACE_EDIT ΓòÉΓòÉΓòÉ
  7914.  
  7915. $INPLACE_EDIT 
  7916.  
  7917. $^I 
  7918.  
  7919. The current value of the inplace-edit extension.  Use undef to disable inplace 
  7920. editing.  (Mnemonic: value of -i switch.) 
  7921.  
  7922.  
  7923. ΓòÉΓòÉΓòÉ 13.38. $PERLDB ΓòÉΓòÉΓòÉ
  7924.  
  7925. $PERLDB 
  7926.  
  7927. $^P 
  7928.  
  7929. The internal flag that the debugger clears so that it doesn't debug itself. 
  7930. You could conceivable disable debugging yourself by clearing it. 
  7931.  
  7932.  
  7933. ΓòÉΓòÉΓòÉ 13.39. $BASETIME ΓòÉΓòÉΓòÉ
  7934.  
  7935. $BASETIME 
  7936.  
  7937. $^T 
  7938.  
  7939. The time at which the script began running, in seconds since the epoch 
  7940. (beginning of 1970).  The values returned by the -M, -A and -C filetests are 
  7941. based on this value. 
  7942.  
  7943.  
  7944. ΓòÉΓòÉΓòÉ 13.40. $WARNING ΓòÉΓòÉΓòÉ
  7945.  
  7946. $WARNING 
  7947.  
  7948. $^W 
  7949.  
  7950. The current value of the warning switch, either TRUE or FALSE.  (Mnemonic: 
  7951. related to the -w switch.) 
  7952.  
  7953.  
  7954. ΓòÉΓòÉΓòÉ 13.41. $EXECUTABLE_NAME ΓòÉΓòÉΓòÉ
  7955.  
  7956. $EXECUTABLE_NAME 
  7957.  
  7958. $^X 
  7959.  
  7960. The name that the Perl binary itself was executed as, from C's argv[0]. 
  7961.  
  7962.  
  7963. ΓòÉΓòÉΓòÉ 13.42. $ARGV ΓòÉΓòÉΓòÉ
  7964.  
  7965. $ARGV 
  7966.  
  7967. contains the name of the current file when reading from <>. 
  7968.  
  7969.  
  7970. ΓòÉΓòÉΓòÉ 13.43. @ARGV ΓòÉΓòÉΓòÉ
  7971.  
  7972. @ARGV 
  7973.  
  7974. The array @ARGV contains the command line arguments intended for the script. 
  7975. Note that $#ARGV is the generally number of arguments minus one, since $ARGV[0] 
  7976. is the first argument, NOT the command name.  See "$0" for the command name. 
  7977.  
  7978.  
  7979. ΓòÉΓòÉΓòÉ 13.44. @INC ΓòÉΓòÉΓòÉ
  7980.  
  7981. @INC 
  7982.  
  7983. The array @INC contains the list of places to look for Perl scripts to be 
  7984. evaluated by the do EXPR, require, or use constructs.  It initially consists of 
  7985. the arguments to any -I command line switches, followed by the default Perl 
  7986. library, probably "/usr/local/lib/perl", followed by ".", to represent the 
  7987. current directory.  If you need to modify this at runtime, you should use the 
  7988. use lib pragma in order to also get the machine-dependent library properly 
  7989. loaded: 
  7990.  
  7991.     use lib '/mypath/libdir/';
  7992.     use SomeMod;
  7993.  
  7994.  
  7995. ΓòÉΓòÉΓòÉ 13.45. %INC ΓòÉΓòÉΓòÉ
  7996.  
  7997. %INC 
  7998.  
  7999. The hash %INC contains entries for each filename that has been included via do 
  8000. or require.  The key is the filename you specified, and the value is the 
  8001. location of the file actually found. The require command uses this array to 
  8002. determine whether a given file has already been included. 
  8003.  
  8004.  
  8005. ΓòÉΓòÉΓòÉ 13.46. $ENV{expr} ΓòÉΓòÉΓòÉ
  8006.  
  8007. $ENV{expr} 
  8008.  
  8009. The hash %ENV contains your current environment.  Setting a value in ENV 
  8010. changes the environment for child processes. 
  8011.  
  8012.  
  8013. ΓòÉΓòÉΓòÉ 13.47. $SIG{expr} ΓòÉΓòÉΓòÉ
  8014.  
  8015. $SIG{expr} 
  8016.  
  8017. The hash %SIG is used to set signal handlers for various signals.  Example: 
  8018.  
  8019.     sub handler {       # 1st argument is signal name
  8020.         local($sig) = @_;
  8021.         print "Caught a SIG$sig--shutting down\n";
  8022.         close(LOG);
  8023.         exit(0);
  8024.     }
  8025.     $SIG{'INT'} = 'handler';
  8026.     $SIG{'QUIT'} = 'handler';
  8027.     ...
  8028.     $SIG{'INT'} = 'DEFAULT';    # restore default action
  8029.     $SIG{'QUIT'} = 'IGNORE';    # ignore SIGQUIT
  8030.  
  8031. The %SIG array only contains values for the signals actually set within the 
  8032. Perl script.  Here are some other examples: 
  8033.  
  8034.     $SIG{PIPE} = Plumber;       # SCARY!!
  8035.     $SIG{"PIPE"} = "Plumber";   # just fine, assumes main::Plumber
  8036.     $SIG{"PIPE"} = \&Plumber;   # just fine; assume current Plumber
  8037.     $SIG{"PIPE"} = Plumber();   # oops, what did Plumber() return??
  8038.  
  8039. The one marked scary is problematic because it's a bareword, which means 
  8040. sometimes it's a string representing the function, and sometimes it's going to 
  8041. call the subroutine call right then and there!  Best to be sure and quote it or 
  8042. take a reference to it.  *Plumber works too.  See perlsubs. 
  8043.  
  8044. Certain internal hooks can be also set using the %SIG hash.  The routine 
  8045. indicated by $SIG{__WARN__} is called when a warning message is about to be 
  8046. printed.  The warning message is passed as the first argument.  The presence of 
  8047. a __WARN__ hook causes the ordinary printing of warnings to STDERR to be 
  8048. suppressed.  You can use this to save warnings in a variable, or turn warnings 
  8049. into fatal errors, like this: 
  8050.  
  8051.     local $SIG{__WARN__} = sub { die $_[0] };
  8052.     eval $proggie;
  8053.  
  8054. The routine indicated by $SIG{__DIE__} is called when a fatal exception is 
  8055. about to be thrown.  The error message is passed as the first argument.  When a 
  8056. __DIE__ hook routine returns, the exception processing continues as it would 
  8057. have in the absence of the hook, unless the hook routine itself exits via a 
  8058. goto, a loop exit, or a die(). The __DIE__ handler is explicitly disabled 
  8059. during the call, so that you can die from a __DIE__ handler.  Similarly for 
  8060. __WARN__. 
  8061.  
  8062.  
  8063. ΓòÉΓòÉΓòÉ 14. Section - perlsub ΓòÉΓòÉΓòÉ
  8064.  
  8065. NAME 
  8066.  
  8067. perlsub - Perl subroutines 
  8068.  
  8069. SYNOPSIS 
  8070.  
  8071. To declare subroutines: 
  8072.  
  8073.     sub NAME;             # A "forward" declaration.
  8074.     sub NAME(PROTO);      #  ditto, but with prototypes
  8075.  
  8076.     sub NAME BLOCK        # A declaration and a definition.
  8077.     sub NAME(PROTO) BLOCK #  ditto, but with prototypes
  8078.  
  8079. To define an anonymous subroutine at runtime: 
  8080.  
  8081.     $subref = sub BLOCK;
  8082.  
  8083. To import subroutines: 
  8084.  
  8085.     use PACKAGE qw(NAME1 NAME2 NAME3);
  8086.  
  8087. To call subroutines: 
  8088.  
  8089.     NAME(LIST);    # & is optional with parens.
  8090.     NAME LIST;     # Parens optional if predeclared/imported.
  8091.     &NAME;         # Passes current @_ to subroutine.
  8092.  
  8093. DESCRIPTION 
  8094.  
  8095. Like many languages, Perl provides for user-defined subroutines.  These may be 
  8096. located anywhere in the main program, loaded in from other files via the do, 
  8097. require, or use keywords, or even generated on the fly using eval or anonymous 
  8098. subroutines (closures).  You can even call a function indirectly using a 
  8099. variable containing its name or a CODE reference to it, as in $var = 
  8100. \&function. 
  8101.  
  8102. The Perl model for function call and return values is simple: all functions are 
  8103. passed as parameters one single flat list of scalars, and all functions 
  8104. likewise return to their caller one single flat list of scalars.  Any arrays or 
  8105. hashes in these call and return lists will collapse, losing their 
  8106. identities--but you may always use pass-by-reference instead to avoid this. 
  8107. Both call and return lists may contain as many or as few scalar elements as 
  8108. you'd like.  (Often a function without an explicit return statement is called a 
  8109. subroutine, but there's really no difference from the language's perspective.) 
  8110.  
  8111. Any arguments passed to the routine come in as the array @_.  Thus if you 
  8112. called a function with two arguments, those would be stored in $_[0] and $_[1]. 
  8113. The array @_ is a local array, but its values are implicit references 
  8114. (predating perlref) to the actual scalar parameters.  The return value of the 
  8115. subroutine is the value of the last expression evaluated.  Alternatively, a 
  8116. return statement may be used to specify the returned value and exit the 
  8117. subroutine.  If you return one or more arrays and/or hashes, these will be 
  8118. flattened together into one large indistinguishable list. 
  8119.  
  8120. Perl does not have named formal parameters, but in practice all you do is 
  8121. assign to a my() list of these.  Any variables you use in the function that 
  8122. aren't declared private are global variables.  For the gory details on creating 
  8123. private variables, see the sections below on L<"Private Variables via my()"> 
  8124. and L</"Temporary Values via local()">.  To create protected environments for a 
  8125. set of functions in a separate package (and probably a separate file), see 
  8126. perlmod/"Packages". 
  8127.  
  8128. Example: 
  8129.  
  8130.     sub max {
  8131.         my $max = shift(@_);
  8132.         foreach $foo (@_) {
  8133.             $max = $foo if $max < $foo;
  8134.         }
  8135.         return $max;
  8136.     }
  8137.     $bestday = max($mon,$tue,$wed,$thu,$fri);
  8138.  
  8139. Example: 
  8140.  
  8141.     # get a line, combining continuation lines
  8142.     #  that start with whitespace
  8143.  
  8144.     sub get_line {
  8145.         $thisline = $lookahead;  # GLOBAL VARIABLES!!
  8146.         LINE: while ($lookahead = <STDIN>) {
  8147.             if ($lookahead =~ /^[ \t]/) {
  8148.                 $thisline .= $lookahead;
  8149.             }
  8150.             else {
  8151.                 last LINE;
  8152.             }
  8153.         }
  8154.         $thisline;
  8155.     }
  8156.  
  8157.     $lookahead = <STDIN>;       # get first line
  8158.     while ($_ = get_line()) {
  8159.         ...
  8160.     }
  8161.  
  8162. Use array assignment to a local list to name your formal arguments: 
  8163.  
  8164.     sub maybeset {
  8165.         my($key, $value) = @_;
  8166.         $Foo{$key} = $value unless $Foo{$key};
  8167.     }
  8168.  
  8169. This also has the effect of turning call-by-reference into call-by-value, since 
  8170. the assignment copies the values.  Otherwise a function is free to do in-place 
  8171. modifications of @_ and change its callers values. 
  8172.  
  8173.     upcase_in($v1, $v2);  # this changes $v1 and $v2
  8174.     sub upcase_in {
  8175.         for (@_) { tr/a-z/A-Z/ }
  8176.     }
  8177.  
  8178. You aren't allowed to modify constants in this way, of course.  If an argument 
  8179. were actually literal and you tried to change it, you'd take a (presumably 
  8180. fatal) exception.  For example, this won't work: 
  8181.  
  8182.     upcase_in("frederick");
  8183.  
  8184. It would be much safer if the upcase_in() function were written to return a 
  8185. copy of its parameters instead of changing them in place: 
  8186.  
  8187.     ($v3, $v4) = upcase($v1, $v2);  # this doesn't
  8188.     sub upcase {
  8189.         my @parms = @_;
  8190.         for (@parms) { tr/a-z/A-Z/ }
  8191.         # wantarray checks if we were called in list context
  8192.         return wantarray ? @parms : $parms[0];
  8193.     }
  8194.  
  8195. Notice how this (unprototyped) function doesn't care whether it was passed real 
  8196. scalars or arrays.  Perl will see everything as one big long flat @_ parameter 
  8197. list.  This is one of the ways where Perl's simple argument-passing style 
  8198. shines.  The upcase() function would work perfectly well without changing the 
  8199. upcase() definition even if we fed it things like this: 
  8200.  
  8201.     @newlist   = upcase(@list1, @list2);
  8202.     @newlist   = upcase( split /:/, $var );
  8203.  
  8204. Do not, however, be tempted to do this: 
  8205.  
  8206.     (@a, @b)   = upcase(@list1, @list2);
  8207.  
  8208. Because like its flat incoming parameter list, the return list is also flat. 
  8209. So all you have managed to do here is stored everything in @a and made @b an 
  8210. empty list.  See L</"Pass by Reference"> for alternatives. 
  8211.  
  8212. A subroutine may be called using the "&" prefix.  The "&" is optional in Perl 
  8213. 5, and so are the parens if the subroutine has been predeclared. (Note, 
  8214. however, that the "&" is NOT optional when you're just naming the subroutine, 
  8215. such as when it's used as an argument to defined() or undef().  Nor is it 
  8216. optional when you want to do an indirect subroutine call with a subroutine name 
  8217. or reference using the &$subref() or &{$subref}() constructs.  See perlref for 
  8218. more on that.) 
  8219.  
  8220. Subroutines may be called recursively.  If a subroutine is called using the "&" 
  8221. form, the argument list is optional, and if omitted, no @_ array is set up for 
  8222. the subroutine: the @_ array at the time of the call is visible to subroutine 
  8223. instead.  This is an efficiency mechanism that new users may wish to avoid. 
  8224.  
  8225.     &foo(1,2,3);        # pass three arguments
  8226.     foo(1,2,3);         # the same
  8227.  
  8228.     foo();              # pass a null list
  8229.     &foo();             # the same
  8230.  
  8231.     &foo;               # foo() get current args, like foo(@_) !!
  8232.     foo;                # like foo() IFF sub foo pre-declared, else "foo"
  8233.  
  8234. Not only does the "&" form make the argument list optional, but it also 
  8235. disables any prototype checking on the arguments you do provide.  This is 
  8236. partly for historical reasons, and partly for having a convenient way to cheat 
  8237. if you know what you're doing.  See the section on Prototypes below. 
  8238.  
  8239. Private Variables via my() 
  8240.  
  8241. Synopsis: 
  8242.  
  8243.     my $foo;            # declare $foo lexically local
  8244.     my (@wid, %get);    # declare list of variables local
  8245.     my $foo = "flurp";  # declare $foo lexical, and init it
  8246.     my @oof = @bar;     # declare @oof lexical, and init it
  8247.  
  8248. A "my" declares the listed variables to be confined (lexically) to the 
  8249. enclosing block, subroutine, eval, or do/require/use'd file.  If more than one 
  8250. value is listed, the list must be placed in parens.  All listed elements must 
  8251. be legal lvalues.  Only alphanumeric identifiers may be lexically 
  8252. scoped--magical builtins like $/ must currently be localized with "local" 
  8253. instead. 
  8254.  
  8255. Unlike dynamic variables created by the "local" statement, lexical variables 
  8256. declared with "my" are totally hidden from the outside world, including any 
  8257. called subroutines (even if it's the same subroutine called from itself or 
  8258. elsewhere--every call gets its own copy). 
  8259.  
  8260. (An eval(), however, can see the lexical variables of the scope it is being 
  8261. evaluated in so long as the names aren't hidden by declarations within the 
  8262. eval() itself.  See perlref.) 
  8263.  
  8264. The parameter list to my() may be assigned to if desired, which allows you to 
  8265. initialize your variables.  (If no initializer is given for a particular 
  8266. variable, it is created with the undefined value.)  Commonly this is used to 
  8267. name the parameters to a subroutine.  Examples: 
  8268.  
  8269.     $arg = "fred";        # "global" variable
  8270.     $n = cube_root(27);
  8271.     print "$arg thinks the root is $n\n";
  8272.  fred thinks the root is 3
  8273.  
  8274.     sub cube_root {
  8275.         my $arg = shift;  # name doesn't matter
  8276.         $arg **= 1/3;
  8277.         return $arg;
  8278.     }
  8279.  
  8280. The "my" is simply a modifier on something you might assign to.  So when you do 
  8281. assign to the variables in its argument list, the "my" doesn't change whether 
  8282. those variables is viewed as a scalar or an array.  So 
  8283.  
  8284.     my ($foo) = <STDIN>;
  8285.     my @FOO = <STDIN>;
  8286.  
  8287. both supply a list context to the righthand side, while 
  8288.  
  8289.     my $foo = <STDIN>;
  8290.  
  8291. supplies a scalar context.  But the following only declares one variable: 
  8292.  
  8293.     my $foo, $bar = 1;
  8294.  
  8295. That has the same effect as 
  8296.  
  8297.     my $foo;
  8298.     $bar = 1;
  8299.  
  8300. The declared variable is not introduced (is not visible) until after the 
  8301. current statement.  Thus, 
  8302.  
  8303.     my $x = $x;
  8304.  
  8305. can be used to initialize the new $x with the value of the old $x, and the 
  8306. expression 
  8307.  
  8308.     my $x = 123 and $x == 123
  8309.  
  8310. is false unless the old $x happened to have the value 123. 
  8311.  
  8312. Some users may wish to encourage the use of lexically scoped variables. As an 
  8313. aid to catching implicit references to package variables, if you say 
  8314.  
  8315.     use strict 'vars';
  8316.  
  8317. then any variable reference from there to the end of the enclosing block must 
  8318. either refer to a lexical variable, or must be fully qualified with the package 
  8319. name.  A compilation error results otherwise.  An inner block may countermand 
  8320. this with "no strict 'vars'". 
  8321.  
  8322. A my() has both a compile-time and a run-time effect.  At compile time, the 
  8323. compiler takes notice of it; the principle usefulness of this is to quiet use 
  8324. strict 'vars'.  The actual initialization doesn't happen until run time, so 
  8325. gets executed every time through a loop. 
  8326.  
  8327. Variables declared with "my" are not part of any package and are therefore 
  8328. never fully qualified with the package name.  In particular, you're not allowed 
  8329. to try to make a package variable (or other global) lexical: 
  8330.  
  8331.     my $pack::var;      # ERROR!  Illegal syntax
  8332.     my $_;              # also illegal (currently)
  8333.  
  8334. In fact, a dynamic variable (also known as package or global variables) are 
  8335. still accessible using the fully qualified :: notation even while a lexical of 
  8336. the same name is also visible: 
  8337.  
  8338.     package main;
  8339.     local $x = 10;
  8340.     my    $x = 20;
  8341.     print "$x and $::x\n";
  8342.  
  8343. That will print out 20 and 10. 
  8344.  
  8345. You may declare "my" variables at the outer most scope of a file to totally 
  8346. hide any such identifiers from the outside world.  This is similar to a C's 
  8347. static variables at the file level.  To do this with a subroutine requires the 
  8348. use of a closure (anonymous function).  If a block (such as an eval(), 
  8349. function, or package) wants to create a private subroutine that cannot be 
  8350. called from outside that block, it can declare a lexical variable containing an 
  8351. anonymous sub reference: 
  8352.  
  8353.     my $secret_version = '1.001-beta';
  8354.     my $secret_sub = sub { print $secret_version };
  8355.     &$secret_sub();
  8356.  
  8357. As long as the reference is never returned by any function within the module, 
  8358. no outside module can see the subroutine, since its name is not in any 
  8359. package's symbol table.  Remember that it's not REALLY called 
  8360. $some_pack::secret_version or anything; it's just $secret_version, unqualified 
  8361. and unqualifiable. 
  8362.  
  8363. This does not work with object methods, however; all object methods have to be 
  8364. in the symbol table of some package to be found. 
  8365.  
  8366. Just because the lexical variable is lexically (also called statically) scoped 
  8367. doesn't mean that within a function it works like a C static.  It normally 
  8368. works more like a C auto.  But here's a mechanism for giving a function private 
  8369. variables with both lexical scoping and a static lifetime.  If you do want to 
  8370. create something like C's static variables, just enclose the whole function in 
  8371. an extra block, and put the static variable outside the function but in the 
  8372. block. 
  8373.  
  8374.     {
  8375.         my $secret_val = 0;
  8376.         sub gimme_another {
  8377.             return ++$secret_val;
  8378.         }
  8379.     }
  8380.     # $secret_val now becomes unreachable by the outside
  8381.     # world, but retains its value between calls to gimme_another
  8382.  
  8383. If this function is being sourced in from a separate file via require or use, 
  8384. then this is probably just fine.  If it's all in the main program, you'll need 
  8385. to arrange for the my() to be executed early, either by putting the whole block 
  8386. above your pain program, or more likely, merely placing a BEGIN sub around it 
  8387. to make sure it gets executed before your program starts to run: 
  8388.  
  8389.     sub BEGIN {
  8390.         my $secret_val = 0;
  8391.         sub gimme_another {
  8392.             return ++$secret_val;
  8393.         }
  8394.     }
  8395.  
  8396. See perlrun about the BEGIN function. 
  8397.  
  8398. Temporary Values via local() 
  8399.  
  8400. NOTE: In general, you should be using "my" instead of "local", because it's 
  8401. faster and safer.  Execeptions to this include the global punctuation 
  8402. variables, filehandles and formats, and direct manipulation of the Perl symbol 
  8403. table itself.  Format variables often use "local" though, as do other variables 
  8404. whose current value must be visible to called subroutines. 
  8405.  
  8406. Synopsis: 
  8407.  
  8408.     local $foo;                 # declare $foo dynamically local
  8409.     local (@wid, %get);         # declare list of variables local
  8410.     local $foo = "flurp";       # declare $foo dynamic, and init it
  8411.     local @oof = @bar;          # declare @oof dynamic, and init it
  8412.  
  8413.     local *FH;                  # localize $FH, @FH, %FH, &FH  ...
  8414.     local *merlyn = *randal;    # now $merlyn is really $randal, plus
  8415.                                 #     @merlyn is really @randal, etc
  8416.     local *merlyn = 'randal';   # SAME THING: promote 'randal' to *randal
  8417.     local *merlyn = \$randal;   # just alias $merlyn, not @merlyn etc
  8418.  
  8419. A local() modifies its listed variables to be local to the enclosing block, (or 
  8420. subroutine, eval{} or do) and I<the any called from within that block >.  A 
  8421. local() just gives temporary values to global (meaning package) variables. 
  8422. This is known as dynamic scoping.  Lexical scoping is done with "my", which 
  8423. works more like C's auto declarations. 
  8424.  
  8425. If more than one variable is given to local(), they must be placed in parens. 
  8426. All listed elements must be legal lvalues.  This operator works by saving the 
  8427. current values of those variables in its argument list on a hidden stack and 
  8428. restoring them upon exiting the block, subroutine or eval.  This means that 
  8429. called subroutines can also reference the local variable, but not the global 
  8430. one.  The argument list may be assigned to if desired, which allows you to 
  8431. initialize your local variables.  (If no initializer is given for a particular 
  8432. variable, it is created with an undefined value.)  Commonly this is used to 
  8433. name the parameters to a subroutine.  Examples: 
  8434.  
  8435.     for $i ( 0 .. 9 ) {
  8436.         $digits{$i} = $i;
  8437.     }
  8438.     # assume this function uses global %digits hash
  8439.     parse_num();
  8440.  
  8441.     # now temporarily add to %digits hash
  8442.     if ($base12) {
  8443.         # (NOTE: not claiming this is efficient!)
  8444.         local %digits  = (%digits, 't' => 10, 'e' => 11);
  8445.         parse_num();  # parse_num gets this new %digits!
  8446.     }
  8447.     # old %digits restored here
  8448.  
  8449. Because local() is a run-time command, and so gets executed every time through 
  8450. a loop.  In releases of Perl previous to 5.0, this used more stack storage each 
  8451. time until the loop was exited.  Perl now reclaims the space each time through, 
  8452. but it's still more efficient to declare your variables outside the loop. 
  8453.  
  8454. A local is simply a modifier on an lvalue expression.  When you assign to a 
  8455. localized variable, the local doesn't change whether its list is viewed as a 
  8456. scalar or an array.  So 
  8457.  
  8458.     local($foo) = <STDIN>;
  8459.     local @FOO = <STDIN>;
  8460.  
  8461. both supply a list context to the righthand side, while 
  8462.  
  8463.     local $foo = <STDIN>;
  8464.  
  8465. supplies a scalar context. 
  8466.  
  8467. Passing Symbol Table Entries (typeglobs) 
  8468.  
  8469. [Note:  The mechanism described in this section was originally the only way to 
  8470. simulate pass-by-reference in older versions of Perl.  While it still works 
  8471. fine in modern versions, the new reference mechanism is generally easier to 
  8472. work with.  See below.] 
  8473.  
  8474. Sometimes you don't want to pass the value of an array to a subroutine but 
  8475. rather the name of it, so that the subroutine can modify the global copy of it 
  8476. rather than working with a local copy.  In perl you can refer to all objects of 
  8477. a particular name by prefixing the name with a star: *foo.  This is often known 
  8478. as a "type glob", since the star on the front can be thought of as a wildcard 
  8479. match for all the funny prefix characters on variables and subroutines and 
  8480. such. 
  8481.  
  8482. When evaluated, the type glob produces a scalar value that represents all the 
  8483. objects of that name, including any filehandle, format or subroutine.  When 
  8484. assigned to, it causes the name mentioned to refer to whatever "*" value was 
  8485. assigned to it.  Example: 
  8486.  
  8487.     sub doubleary {
  8488.         local(*someary) = @_;
  8489.         foreach $elem (@someary) {
  8490.             $elem *= 2;
  8491.         }
  8492.     }
  8493.     doubleary(*foo);
  8494.     doubleary(*bar);
  8495.  
  8496. Note that scalars are already passed by reference, so you can modify scalar 
  8497. arguments without using this mechanism by referring explicitly to $_[0] etc. 
  8498. You can modify all the elements of an array by passing all the elements as 
  8499. scalars, but you have to use the * mechanism (or the equivalent reference 
  8500. mechanism) to push, pop or change the size of an array.  It will certainly be 
  8501. faster to pass the typeglob (or reference). 
  8502.  
  8503. Even if you don't want to modify an array, this mechanism is useful for passing 
  8504. multiple arrays in a single LIST, since normally the LIST mechanism will merge 
  8505. all the array values so that you can't extract out the individual arrays.  For 
  8506. more on typeglobs, see perldata/"Typeglobs". 
  8507.  
  8508. Pass by Reference 
  8509.  
  8510. If you want to pass more than one array or hash into a function--or return them 
  8511. from it--and have them maintain their integrity, then you're going to have to 
  8512. use an explicit pass-by-reference. Before you do that, you need to understand 
  8513. references as detailed in perlref. This section may not make much sense to you 
  8514. otherwise. 
  8515.  
  8516. Here are a few simple examples.  First, let's pass in several arrays to a 
  8517. function and have it pop all of then, return a new list of all their former 
  8518. last elements: 
  8519.  
  8520.     @tailings = popmany ( \@a, \@b, \@c, \@d );
  8521.  
  8522.     sub popmany {
  8523.         my $aref;
  8524.         my @retlist = ();
  8525.         foreach $aref ( @_ ) {
  8526.             push @retlist, pop @$aref;
  8527.         }
  8528.         return @retlist;
  8529.     }
  8530.  
  8531. Here's how you might write a function that returns a list of keys occurring in 
  8532. all the hashes passed to it: 
  8533.  
  8534.     @common = inter( \%foo, \%bar, \%joe );
  8535.     sub inter {
  8536.         my ($k, $href, %seen); # locals
  8537.         foreach $href (@_) {
  8538.             while ( $k = each %$href ) {
  8539.                 $seen{$k}++;
  8540.             }
  8541.         }
  8542.         return grep { $seen{$_} == @_ } keys %seen;
  8543.     }
  8544.  
  8545. So far, we're just using the normal list return mechanism. What happens if you 
  8546. want to pass or return a hash?  Well, if you're only using one of them, or you 
  8547. don't mind them concatenating, then the normal calling convention is ok, 
  8548. although a little expensive. 
  8549.  
  8550. Where people get into trouble is here: 
  8551.  
  8552.     (@a, @b) = func(@c, @d);
  8553.  
  8554. or 
  8555.  
  8556.     (%a, %b) = func(%c, %d);
  8557.  
  8558. That syntax simply won't work.  It just sets @a or %a and clears the @b or %b. 
  8559. Plus the function didn't get passed into two separate arrays or hashes: it got 
  8560. one long list in @_, as always. 
  8561.  
  8562. If you can arrange for everyone to deal with this through references, it's 
  8563. cleaner code, although not so nice to look at.  Here's a function that takes 
  8564. two array references as arguments, returning the two array elements in order of 
  8565. how many elements they have in them: 
  8566.  
  8567.     ($aref, $bref) = func(\@c, \@d);
  8568.     print "@$aref has more than @$bref\n";
  8569.     sub func {
  8570.         my ($cref, $dref) = @_;
  8571.         if (@$cref > @$dref) {
  8572.             return ($cref, $dref);
  8573.         } else {
  8574.             return ($dref, $cref);
  8575.         }
  8576.     }
  8577.  
  8578. It turns out that you can actually do this also: 
  8579.  
  8580.     (*a, *b) = func(\@c, \@d);
  8581.     print "@a has more than @b\n";
  8582.     sub func {
  8583.         local (*c, *d) = @_;
  8584.         if (@c > @d) {
  8585.             return (\@c, \@d);
  8586.         } else {
  8587.             return (\@d, \@c);
  8588.         }
  8589.     }
  8590.  
  8591. Here we're using the typeglobs to do symbol table aliasing.  It's a tad subtle, 
  8592. though, and also won't work if you're using my() variables, since only globals 
  8593. (well, and local()s) are in the symbol table. 
  8594.  
  8595. If you're passing around filehandles, you could usually just use the bare 
  8596. typeglob, like *STDOUT, but typeglobs references would be better because 
  8597. they'll still work properly under use strict 'refs'.  For example: 
  8598.  
  8599.     splutter(\*STDOUT);
  8600.     sub splutter {
  8601.         my $fh = shift;
  8602.         print $fh "her um well a hmmm\n";
  8603.     }
  8604.  
  8605.     $rec = get_rec(\*STDIN);
  8606.     sub get_rec {
  8607.         my $fh = shift;
  8608.         return scalar <$fh>;
  8609.     }
  8610.  
  8611. If you're planning on generating new filehandles, you could do this: 
  8612.  
  8613.     sub openit {
  8614.         my $name = shift;
  8615.         local *FH;
  8616.         return open (FH, $path) ? \*FH : undef;
  8617.     }
  8618.  
  8619. Although that will actually produce a small memory leak.  See the bottom of 
  8620. perlfunc/open() for a somewhat cleaner way using the FileHandle functions 
  8621. supplied with the POSIX package. 
  8622.  
  8623. Prototypes 
  8624.  
  8625. As of the 5.002 release of perl, if you declare 
  8626.  
  8627.     sub mypush (\@@)
  8628.  
  8629. then mypush() takes arguments exactly like push() does.  The declaration of the 
  8630. function to be called must be visible at compile time.  The prototype only 
  8631. affects the interpretation of new-style calls to the function, where new-style 
  8632. is defined as not using the & character.  In other words, if you call it like a 
  8633. builtin function, then it behaves like a builtin function.  If you call it like 
  8634. an old-fashioned subroutine, then it behaves like an old-fashioned subroutine. 
  8635. It naturally falls out from this rule that prototypes have no influence on 
  8636. subroutine references like \&foo or on indirect subroutine calls like 
  8637. &{$subref}. 
  8638.  
  8639. Method calls are not influenced by prototypes either, because the function to 
  8640. be called is indeterminate at compile time, since it depends on inheritance. 
  8641.  
  8642. Since the intent is primarily to let you define subroutines that work like 
  8643. builtin commands, here are the prototypes for some other functions that parse 
  8644. almost exactly like the corresponding builtins. 
  8645.  
  8646.     Declared as                 Called as
  8647.  
  8648.     sub mylink ($$)             mylink $old, $new
  8649.     sub myvec ($$$)             myvec $var, $offset, 1
  8650.     sub myindex ($$;$)          myindex &getstring, "substr"
  8651.     sub mysyswrite ($$$;$)      mysyswrite $buf, 0, length($buf) - $off, $off
  8652.     sub myreverse (@)           myreverse $a,$b,$c
  8653.     sub myjoin ($@)             myjoin ":",$a,$b,$c
  8654.     sub mypop (\@)              mypop @array
  8655.     sub mysplice (\@$$@)        mysplice @array,@array,0,@pushme
  8656.     sub mykeys (\%)             mykeys %{$hashref}
  8657.     sub myopen (*;$)            myopen HANDLE, $name
  8658.     sub mypipe (**)             mypipe READHANDLE, WRITEHANDLE
  8659.     sub mygrep (&@)             mygrep { /foo/ } $a,$b,$c
  8660.     sub myrand ($)              myrand 42
  8661.     sub mytime ()               mytime
  8662.  
  8663. Any backslashed prototype character represents an actual argument that 
  8664. absolutely must start with that character. 
  8665.  
  8666. Unbackslashed prototype characters have special meanings.  Any unbackslashed @ 
  8667. or % eats all the rest of the arguments, and forces list context.  An argument 
  8668. represented by $ forces scalar context.  An & requires an anonymous subroutine, 
  8669. which, if passed as the first argument, does not require the "sub" keyword or a 
  8670. subsequent comma.  A * does whatever it has to do to turn the argument into a 
  8671. reference to a symbol table entry. 
  8672.  
  8673. A semicolon separates mandatory arguments from optional arguments. (It is 
  8674. redundant before @ or %.) 
  8675.  
  8676. Note how the last three examples above are treated specially by the parser. 
  8677. mygrep() is parsed as a true list operator, myrand() is parsed as a true unary 
  8678. operator with unary precedence the same as rand(), and mytime() is truly 
  8679. argumentless, just like time().  That is, if you say 
  8680.  
  8681.     mytime +2;
  8682.  
  8683. you'll get mytime() + 2, not mytime(2), which is how it would be parsed without 
  8684. the prototype. 
  8685.  
  8686. The interesting thing about & is that you can generate new syntax with it: 
  8687.  
  8688.     sub try (&$) {
  8689.         my($try,$catch) = @_;
  8690.         eval { &$try };
  8691.         if ($@) {
  8692.             local $_ = $@;
  8693.             &$catch;
  8694.         }
  8695.     }
  8696.     sub catch (&) { @_ }
  8697.  
  8698.     try {
  8699.         die "phooey";
  8700.     } catch {
  8701.         /phooey/ and print "unphooey\n";
  8702.     };
  8703.  
  8704. That prints "unphooey".  (Yes, there are still unresolved issues having to do 
  8705. with the visibility of @_.  I'm ignoring that question for the moment.  (But 
  8706. note that if we make @_ lexically scoped, those anonymous subroutines can act 
  8707. like closures... (Gee, is this sounding a little Lispish?  (Nevermind.)))) 
  8708.  
  8709. And here's a reimplementation of grep: 
  8710.  
  8711.     sub mygrep (&@) {
  8712.         my $code = shift;
  8713.         my @result;
  8714.         foreach $_ (@_) {
  8715.             push(@result, $_) if &$ref;
  8716.         }
  8717.         @result;
  8718.     }
  8719.  
  8720. Some folks would prefer full alphanumeric prototypes.  Alphanumerics have been 
  8721. intentionally left out of prototypes for the express purpose of someday in the 
  8722. future adding named, formal parameters.  The current mechanism's main goal is 
  8723. to let module writers provide better diagnostics for module users.  Larry feels 
  8724. the notation quite understandable to Perl programmers, and that it will not 
  8725. intrude greatly upon the meat of the module, nor make it harder to read.  The 
  8726. line noise is visually encapsulated into a small pill that's easy to swallow. 
  8727.  
  8728. It's probably best to prototype new functions, not retrofit prototyping into 
  8729. older ones.  That's because you must be especially careful about silent 
  8730. impositions of differing list versus scalar contexts.  For example, if you 
  8731. decide that a function should take just one parameter, like this: 
  8732.  
  8733.     sub func ($) {
  8734.         my $n = shift;
  8735.         print "you gave me $n\n";
  8736.     }
  8737.  
  8738. and someone has been calling it with an array or expression returning a list: 
  8739.  
  8740.     func(@foo);
  8741.     func( split /:/ );
  8742.  
  8743. Then you've just supplied an automatic scalar() in front of their argument, 
  8744. which can be more than a bit surprising.  The old @foo which used to hold one 
  8745. thing doesn't get passed in.  Instead, the func() now gets passed in 1, that 
  8746. is, the number of elments in @foo.  And the split() gets called in a scalar 
  8747. context and starts scribbling on your @_ parameter list. 
  8748.  
  8749. This is all very powerful, of course, and should only be used in moderation to 
  8750. make the world a better place. 
  8751.  
  8752. Overriding Builtin Functions 
  8753.  
  8754. Many builtin functions may be overridden, though this should only be tried 
  8755. occasionally and for good reason.  Typically this might be done by a package 
  8756. attempting to emulate missing builtin functionality on a non-Unix system. 
  8757.  
  8758. Overriding may only be done by importing the name from a module--ordinary 
  8759. predeclaration isn't good enough.  However, the subs pragma (compiler 
  8760. directive) lets you, in effect, predeclare subs via the import syntax, and 
  8761. these names may then override the builtin ones: 
  8762.  
  8763.     use subs 'chdir', 'chroot', 'chmod', 'chown';
  8764.     chdir $somewhere;
  8765.     sub chdir { ... }
  8766.  
  8767. Library modules should not in general export builtin names like " open" or 
  8768. "chdir" as part of their default @EXPORT list, since these may sneak into 
  8769. someone else's namespace and change the semantics unexpectedly. Instead, if the 
  8770. module adds the name to the @EXPORT_OK list, then it's possible for a user to 
  8771. import the name explicitly, but not implicitly. That is, they could say 
  8772.  
  8773.     use Module 'open';
  8774.  
  8775. and it would import the open override, but if they said 
  8776.  
  8777.     use Module;
  8778.  
  8779. they would get the default imports without the overrides. 
  8780.  
  8781. Autoloading 
  8782.  
  8783. If you call a subroutine that is undefined, you would ordinarily get an 
  8784. immediate fatal error complaining that the subroutine doesn't exist. (Likewise 
  8785. for subroutines being used as methods, when the method doesn't exist in any of 
  8786. the base classes of the class package.) If, however, there is an AUTOLOAD 
  8787. subroutine defined in the package or packages that were searched for the 
  8788. original subroutine, then that AUTOLOAD subroutine is called with the arguments 
  8789. that would have been passed to the original subroutine.  The fully qualified 
  8790. name of the original subroutine magically appears in the $AUTOLOAD variable in 
  8791. the same package as the AUTOLOAD routine.  The name is not passed as an 
  8792. ordinary argument because, er, well, just because, that's why... 
  8793.  
  8794. Most AUTOLOAD routines will load in a definition for the subroutine in question 
  8795. using eval, and then execute that subroutine using a special form of "goto" 
  8796. that erases the stack frame of the AUTOLOAD routine without a trace.  (See the 
  8797. standard AutoLoader module, for example.) But an AUTOLOAD routine can also just 
  8798. emulate the routine and never define it.  For example, let's pretend that a 
  8799. function that wasn't defined should just call system() with those arguments. 
  8800. All you'd do is this: 
  8801.  
  8802.     sub AUTOLOAD {
  8803.         my $program = $AUTOLOAD;
  8804.         $program =~ s/.*:://;
  8805.         system($program, @_);
  8806.     }
  8807.     date();
  8808.     who('am', i');
  8809.     ls('-l');
  8810.  
  8811. In fact, if you preclare the functions you want to call that way, you don't 
  8812. even need the parentheses: 
  8813.  
  8814.     use subs qw(date who ls);
  8815.     date;
  8816.     who "am", "i";
  8817.     ls -l;
  8818.  
  8819. A more complete example of this is the standard Shell module, which can treat 
  8820. undefined subroutine calls as calls to Unix programs. 
  8821.  
  8822. Mechanisms are available for modules writers to help split the modules up into 
  8823. autoloadable files.  See the standard AutoLoader module described in 
  8824. L<Autoloader>, the standard SelfLoader modules in L<SelfLoader>, and the 
  8825. document on adding C functions to perl code in perlxs. 
  8826.  
  8827. SEE ALSO 
  8828.  
  8829. See perlref for more on references.  See perlxs if you'd like to learn about 
  8830. calling C subroutines from perl.  See perlmod to learn about bundling up your 
  8831. functions in separate files. 
  8832.  
  8833.  
  8834. ΓòÉΓòÉΓòÉ 15. Section - perlmod ΓòÉΓòÉΓòÉ
  8835.  
  8836. NAME 
  8837.  
  8838. perlmod - Perl modules (packages) 
  8839.  
  8840. DESCRIPTION 
  8841.  
  8842. Packages 
  8843.  
  8844. Perl provides a mechanism for alternative namespaces to protect packages from 
  8845. stomping on each others variables.  In fact, apart from certain magical 
  8846. variables, there's really no such thing as a global variable in Perl.  The 
  8847. package statement declares the compilation unit as being in the given 
  8848. namespace.  The scope of the package declaration is from the declaration itself 
  8849. through the end of the enclosing block (the same scope as the local() 
  8850. operator).  All further unqualified dynamic identifiers will be in this 
  8851. namespace.  A package statement only affects dynamic variables--including those 
  8852. you've used local() on--but not lexical variables created with my().  Typically 
  8853. it would be the first declaration in a file to be included by the require or 
  8854. use operator.  You can switch into a package in more than one place; it merely 
  8855. influences which symbol table is used by the compiler for the rest of that 
  8856. block.  You can refer to variables and filehandles in other packages by 
  8857. prefixing the identifier with the package name and a double colon: 
  8858. $Package::Variable.  If the package name is null, the main package as assumed. 
  8859. That is, $::sail is equivalent to $main::sail. 
  8860.  
  8861. (The old package delimiter was a single quote, but double colon is now the 
  8862. preferred delimiter, in part because it's more readable to humans, and in part 
  8863. because it's more readable to emacs macros. It also makes C++ programmers feel 
  8864. like they know what's going on.) 
  8865.  
  8866. Packages may be nested inside other packages: $OUTER::INNER::var.  This implies 
  8867. nothing about the order of name lookups, however.  All symbols are either local 
  8868. to the current package, or must be fully qualified from the outer package name 
  8869. down.  For instance, there is nowhere within package OUTER that $INNER::var 
  8870. refers to $OUTER::INNER::var. It would treat package INNER as a totally 
  8871. separate global package. 
  8872.  
  8873. Only identifiers starting with letters (or underscore) are stored in a 
  8874. package's symbol table.  All other symbols are kept in package main, including 
  8875. all of the punctuation variables like $_.  In addition, the identifiers STDIN, 
  8876. STDOUT, STDERR, ARGV, ARGVOUT, ENV, INC and SIG are forced to be in package 
  8877. main, even when used for other purposes than their built-in one.  Note also 
  8878. that, if you have a package called m, s or y, then you can't use the qualified 
  8879. form of an identifier because it will be interpreted instead as a pattern 
  8880. match, a substitution, or a translation. 
  8881.  
  8882. (Variables beginning with underscore used to be forced into package main, but 
  8883. we decided it was more useful for package writers to be able to use leading 
  8884. underscore to indicate private variables and method names. $_ is still global 
  8885. though.) 
  8886.  
  8887. Eval()ed strings are compiled in the package in which the eval() was compiled. 
  8888. (Assignments to $SIG{}, however, assume the signal handler specified is in the 
  8889. main package.  Qualify the signal handler name if you wish to have a signal 
  8890. handler in a package.)  For an example, examine perldb.pl in the Perl library. 
  8891. It initially switches to the DB package so that the debugger doesn't interfere 
  8892. with variables in the script you are trying to debug.  At various points, 
  8893. however, it temporarily switches back to the main package to evaluate various 
  8894. expressions in the context of the main package (or wherever you came from). 
  8895. See perldebug. 
  8896.  
  8897. See perlsub for other scoping issues related to my() and local(), or perlref 
  8898. regarding closures. 
  8899.  
  8900. Symbol Tables 
  8901.  
  8902. The symbol table for a package happens to be stored in the associative array of 
  8903. that name appended with two colons.  The main symbol table's name is thus 
  8904. %main::, or %:: for short.  Likewise the nested package mentioned earlier is 
  8905. named %OUTER::INNER::. 
  8906.  
  8907. The value in each entry of the associative array is what you are referring to 
  8908. when you use the *name typeglob notation.  In fact, the following have the same 
  8909. effect, though the first is more efficient because it does the symbol table 
  8910. lookups at compile time: 
  8911.  
  8912.     local(*main::foo) = *main::bar; local($main::{'foo'}) =
  8913.     $main::{'bar'};
  8914.  
  8915. You can use this to print out all the variables in a package, for instance. 
  8916. Here is dumpvar.pl from the Perl library: 
  8917.  
  8918.    package dumpvar;
  8919.    sub main::dumpvar {
  8920.        ($package) = @_;
  8921.        local(*stab) = eval("*${package}::");
  8922.        while (($key,$val) = each(%stab)) {
  8923.            local(*entry) = $val;
  8924.            if (defined $entry) {
  8925.                print "\$$key = '$entry'\n";
  8926.            }
  8927.  
  8928.            if (defined @entry) {
  8929.                print "\@$key = (\n";
  8930.                foreach $num ($[ .. $#entry) {
  8931.                    print "  $num\t'",$entry[$num],"'\n";
  8932.                }
  8933.                print ")\n";
  8934.            }
  8935.  
  8936.            if ($key ne "${package}::" && defined %entry) {
  8937.                print "\%$key = (\n";
  8938.                foreach $key (sort keys(%entry)) {
  8939.                    print "  $key\t'",$entry{$key},"'\n";
  8940.                }
  8941.                print ")\n";
  8942.            }
  8943.        }
  8944.    }
  8945.  
  8946. Note that even though the subroutine is compiled in package dumpvar, the name 
  8947. of the subroutine is qualified so that its name is inserted into package main. 
  8948.  
  8949. Assignment to a typeglob performs an aliasing operation, i.e., 
  8950.  
  8951.     *dick = *richard;
  8952.  
  8953. causes variables, subroutines and file handles accessible via the identifier 
  8954. richard to also be accessible via the symbol dick.  If you only want to alias a 
  8955. particular variable or subroutine, you can assign a reference instead: 
  8956.  
  8957.     *dick = \$richard;
  8958.  
  8959. makes $richard and $dick the same variable, but leaves @richard and @dick as 
  8960. separate arrays.  Tricky, eh? 
  8961.  
  8962. This mechanism may be used to pass and return cheap references into or from 
  8963. subroutines if you won't want to copy the whole thing. 
  8964.  
  8965.     %some_hash = ();
  8966.     *some_hash = fn( \%another_hash );
  8967.     sub fn {
  8968.         local *hashsym = shift;
  8969.         # now use %hashsym normally, and you
  8970.         # will affect the caller's %another_hash
  8971.         my %nhash = (); # do what you want
  8972.         return \%nhash;
  8973.     }
  8974.  
  8975. On return, the reference wil overwrite the hash slot in the symbol table 
  8976. specified by the *some_hash typeglob.  This is a somewhat tricky way of passing 
  8977. around refernces cheaply when you won't want to have to remember to dereference 
  8978. variables explicitly. 
  8979.  
  8980. Another use of symbol tables is for making "constant"  scalars. 
  8981.  
  8982.     *PI = \3.14159265358979;
  8983.  
  8984. Now you cannot alter $PI, which is probably a good thing all in all. 
  8985.  
  8986. Package Constructors and Destructors 
  8987.  
  8988. There are two special subroutine definitions that function as package 
  8989. constructors and destructors.  These are the BEGIN and END routines.  The sub 
  8990. is optional for these routines. 
  8991.  
  8992. A BEGIN subroutine is executed as soon as possible, that is, the moment it is 
  8993. completely defined, even before the rest of the containing file is parsed.  You 
  8994. may have multiple BEGIN blocks within a file--they will execute in order of 
  8995. definition.  Because a BEGIN block executes immediately, it can pull in 
  8996. definitions of subroutines and such from other files in time to be visible to 
  8997. the rest of the file. 
  8998.  
  8999. An END subroutine is executed as late as possible, that is, when the 
  9000. interpreter is being exited, even if it is exiting as a result of a die() 
  9001. function.  (But not if it's is being blown out of the water by a signal--you 
  9002. have to trap that yourself (if you can).)  You may have multiple END blocks 
  9003. within a file--they will execute in reverse order of definition; that is: last 
  9004. in, first out (LIFO). 
  9005.  
  9006. Note that when you use the -n and -p switches to Perl, BEGIN and END work just 
  9007. as they do in awk, as a degenerate case. 
  9008.  
  9009. Perl Classes 
  9010.  
  9011. There is no special class syntax in Perl, but a package may function as a class 
  9012. if it provides subroutines that function as methods.  Such a package may also 
  9013. derive some of its methods from another class package by listing the other 
  9014. package name in its @ISA array. 
  9015.  
  9016. For more on this, see perlobj. 
  9017.  
  9018. Perl Modules 
  9019.  
  9020. A module is just a package that is defined in a library file of the same name, 
  9021. and is designed to be reusable.  It may do this by providing a mechanism for 
  9022. exporting some of its symbols into the symbol table of any package using it. 
  9023. Or it may function as a class definition and make its semantics available 
  9024. implicitly through method calls on the class and its objects, without explicit 
  9025. exportation of any symbols.  Or it can do a little of both. 
  9026.  
  9027. For example, to start a normal module called Fred, create a file called Fred.pm 
  9028. and put this at the start of it: 
  9029.  
  9030.     package      Fred;
  9031.     require      Exporter;
  9032.     @ISA       = qw(Exporter);
  9033.     @EXPORT    = qw(func1 func2);
  9034.     @EXPORT_OK = qw($sally @listabob %harry func3);
  9035.  
  9036. Then go on to declare and use your variables in functions without any 
  9037. qualifications. See L<Exporter> and the Perl Modules File for details on 
  9038. mechanics and style issues in module creation. 
  9039.  
  9040. Perl modules are included into your program by saying 
  9041.  
  9042.     use Module;
  9043.  
  9044. or 
  9045.  
  9046.     use Module LIST;
  9047.  
  9048. This is exactly equivalent to 
  9049.  
  9050.     BEGIN { require "Module.pm"; import Module; }
  9051.  
  9052. or 
  9053.  
  9054.     BEGIN { require "Module.pm"; import Module LIST; }
  9055.  
  9056. As a special case 
  9057.  
  9058.     use Module ();
  9059.  
  9060. is exactly equivalent to 
  9061.  
  9062.     BEGIN { require "Module.pm"; }
  9063.  
  9064. All Perl module files have the extension .pm.  use assumes this so that you 
  9065. don't have to spell out "Module.pm" in quotes.  This also helps to 
  9066. differentiate new modules from old .pl and .ph files. Module names are also 
  9067. capitalized unless they're functioning as pragmas, "Pragmas" are in effect 
  9068. compiler directives, and are sometimes called "pragmatic modules" (or even 
  9069. "pragmata" if you're a classicist). 
  9070.  
  9071. Because the use statement implies a BEGIN block, the importation of semantics 
  9072. happens at the moment the use statement is compiled, before the rest of the 
  9073. file is compiled.  This is how it is able to function as a pragma mechanism, 
  9074. and also how modules are able to declare subroutines that are then visible as 
  9075. list operators for the rest of the current file.  This will not work if you use 
  9076. require instead of use.  With require you can get into this problem: 
  9077.  
  9078.     require Cwd;                # make Cwd:: accessible
  9079.     $here = Cwd::getcwd();
  9080.  
  9081.     use Cwd;                    # import names from Cwd::
  9082.     $here = getcwd();
  9083.  
  9084.     require Cwd;                # make Cwd:: accessible
  9085.     $here = getcwd();           # oops! no main::getcwd()
  9086.  
  9087. In general use Module (); is recommended over require Module;. 
  9088.  
  9089. Perl packages may be nested inside other package names, so we can have package 
  9090. names containing ::.  But if we used that package name directly as a filename 
  9091. it would makes for unwieldy or impossible filenames on some systems. 
  9092. Therefore, if a module's name is, say, Text::Soundex, then its definition is 
  9093. actually found in the library file Text/Soundex.pm. 
  9094.  
  9095. Perl modules always have a .pm file, but there may also be dynamically linked 
  9096. executables or autoloaded subroutine definitions associated with the module. 
  9097. If so, these will be entirely transparent to the user of the module.  It is the 
  9098. responsibility of the .pm file to load (or arrange to autoload) any additional 
  9099. functionality.  The POSIX module happens to do both dynamic loading and 
  9100. autoloading, but the user can just say use POSIX to get it all. 
  9101.  
  9102. For more information on writing extension modules, see perlxs and perlguts. 
  9103.  
  9104. NOTE 
  9105.  
  9106. Perl does not enforce private and public parts of its modules as you may have 
  9107. been used to in other languages like C++, Ada, or Modula-17.  Perl doesn't have 
  9108. an infatuation with enforced privacy.  It would prefer that you stayed out of 
  9109. its living room because you weren't invited, not because it has a shotgun. 
  9110.  
  9111. The module and its user have a contract, part of which is common law, and part 
  9112. of which is "written".  Part of the common law contract is that a module 
  9113. doesn't pollute any namespace it wasn't asked to.  The written contract for the 
  9114. module (AKA documentation) may make other provisions.  But then you know when 
  9115. you use RedefineTheWorld that you're redefining the world and willing to take 
  9116. the consequences. 
  9117.  
  9118. THE PERL MODULE LIBRARY 
  9119.  
  9120. A number of modules are included the the Perl distribution.  These are 
  9121. described below, and all end in .pm.  You may also discover files in the 
  9122. library directory that end in either .pl or .ph.  These are old libraries 
  9123. supplied so that old programs that use them still run.  The .pl files will all 
  9124. eventually be converted into standard modules, and the .ph files made by h2ph 
  9125. will probably end up as extension modules made by h2xs.  (Some .ph values may 
  9126. already be available through the POSIX module.)  The pl2pm file in the 
  9127. distribution may help in your conversion, but it's just a mechanical process, 
  9128. so is far from bullet proof. 
  9129.  
  9130. Pragmatic Modules 
  9131.  
  9132. They work somewhat like pragmas in that they tend to affect the compilation of 
  9133. your program, and thus will usually only work well when used within a use, or 
  9134. no.  These are locally scoped, so an inner BLOCK may countermand any of these 
  9135. by saying 
  9136.  
  9137.     no integer;
  9138.     no strict 'refs';
  9139.  
  9140. which lasts until the end of that BLOCK. 
  9141.  
  9142. The following programs are defined (and have their own documentation). 
  9143.  
  9144. diagnostics 
  9145.  
  9146. Pragma to produce enhanced diagnostics 
  9147.  
  9148. integer 
  9149.  
  9150. Pragma to compute arithmetic in integer instead of double 
  9151.  
  9152. less 
  9153.  
  9154. Pragma to request less of something from the compiler 
  9155.  
  9156. overload 
  9157.  
  9158. Pragma for overloading operators 
  9159.  
  9160. sigtrap 
  9161.  
  9162. Pragma to enable stack backtrace on unexpected signals 
  9163.  
  9164. strict 
  9165.  
  9166. Pragma to restrict unsafe constructs 
  9167.  
  9168. subs 
  9169.  
  9170. Pragma to predeclare sub names 
  9171.  
  9172. Standard Modules 
  9173.  
  9174. Standard, bundled modules are all expected to behave in a well-defined manner 
  9175. with respect to namespace pollution because they use the Exporter module.  See 
  9176. their own documentation for details. 
  9177.  
  9178. AnyDBM_File 
  9179.  
  9180. provide framework for multiple DBMs 
  9181.  
  9182. AutoLoader 
  9183.  
  9184. load functions only on demand 
  9185.  
  9186. AutoSplit 
  9187.  
  9188. split a package for autoloading 
  9189.  
  9190. Benchmark 
  9191.  
  9192. benchmark running times of code 
  9193.  
  9194. Carp 
  9195.  
  9196. warn of errors (from perspective of caller) 
  9197.  
  9198. Config 
  9199.  
  9200. access Perl configuration option 
  9201.  
  9202. Cwd 
  9203.  
  9204. get pathname of current working directory 
  9205.  
  9206. DB_File 
  9207.  
  9208. Perl access to Berkeley DB 
  9209.  
  9210. Devel::SelfStubber 
  9211.  
  9212. generate stubs for a SelfLoading module 
  9213.  
  9214. DynaLoader 
  9215.  
  9216. Dynamically load C libraries into Perl code 
  9217.  
  9218. English 
  9219.  
  9220. use nice English (or awk) names for ugly punctuation variables 
  9221.  
  9222. Env 
  9223.  
  9224. perl module that imports environment variables 
  9225.  
  9226. Exporter 
  9227.  
  9228. provide inport/export controls for Perl modules 
  9229.  
  9230. ExtUtils::Liblist 
  9231.  
  9232. determine libraries to use and how to use them 
  9233.  
  9234. ExtUtils::MakeMaker 
  9235.  
  9236. create an extension Makefile 
  9237.  
  9238. ExtUtils::Manifest 
  9239.  
  9240. utilities to write and check a MANIFEST file 
  9241.  
  9242. ExtUtils::Mkbootstrap 
  9243.  
  9244. make a bootstrap file for use by DynaLoader 
  9245.  
  9246. ExtUtils::Miniperl 
  9247.  
  9248. !!!GOOD QUESTION!!! 
  9249.  
  9250. Fcntl 
  9251.  
  9252. load the C Fcntl.h defines 
  9253.  
  9254. File::Basename 
  9255.  
  9256. parse file specifications 
  9257.  
  9258. File::CheckTree 
  9259.  
  9260. run many filetest checks on a tree 
  9261.  
  9262. File::Find 
  9263.  
  9264. traverse a file tree 
  9265.  
  9266. FileHandle 
  9267.  
  9268. supply object methods for filehandles 
  9269.  
  9270. File::Path 
  9271.  
  9272. create or remove a series of directories 
  9273.  
  9274. Getopt::Long 
  9275.  
  9276. extended getopt processing 
  9277.  
  9278. Getopt::Std 
  9279.  
  9280. Process single-character switches with switch clustering 
  9281.  
  9282. I18N::Collate 
  9283.  
  9284. compare 8-bit scalar data according to the current locale 
  9285.  
  9286. IPC::Open2 
  9287.  
  9288. a process for both reading and writing 
  9289.  
  9290. IPC::Open3 
  9291.  
  9292. open a process for reading, writing, and error handling 
  9293.  
  9294. Net::Ping 
  9295.  
  9296. check a host for upness 
  9297.  
  9298. POSIX 
  9299.  
  9300. Perl interface to IEEE Std 1003.1 
  9301.  
  9302. SelfLoader 
  9303.  
  9304. load functions only on demand 
  9305.  
  9306. Safe 
  9307.  
  9308. Creation controlled compartments in which perl code can be evaluated. 
  9309.  
  9310. Socket 
  9311.  
  9312. load the C socket.h defines and structure manipulators 
  9313.  
  9314. Test::Harness 
  9315.  
  9316. run perl standard test scripts with statistics 
  9317.  
  9318. Text::Abbrev 
  9319.  
  9320. rceate an abbreviation table from a list 
  9321.  
  9322. To find out all the modules installed on your system, including those without 
  9323. documentation or outside the standard release, do this: 
  9324.  
  9325.     find `perl -e 'print "@INC"'` -name '*.pm' -print
  9326.  
  9327. They should all have their own documentation installed and accessible via your 
  9328. system man(1) command.  If that fails, try the perldoc program. 
  9329.  
  9330. Extension Modules 
  9331.  
  9332. Extension modules are written in C (or a mix of Perl and C) and get dynamically 
  9333. loaded into Perl if and when you need them.  Supported extension modules 
  9334. include the Socket, Fcntl, and POSIX modules. 
  9335.  
  9336. Many popular C extension modules do not come bundled (at least, not completely) 
  9337. due to their size, volatility, or simply lack of time for adequate testing and 
  9338. configuration across the multitude of platforms on which Perl was beta-tested. 
  9339. You are encouraged to look for them in archie(1L), the Perl FAQ or Meta-FAQ, 
  9340. the WWW page, and even with their authors before randomly posting asking for 
  9341. their present condition and disposition. 
  9342.  
  9343. CPAN 
  9344.  
  9345. CPAN stands for the Comprehensive Perl Archive Network.  This is a globally 
  9346. replicated collection of all known Perl materials, including hundreds of 
  9347. unbunded modules.  Here are the major categories of modules: 
  9348.  
  9349.      Language Extensions and Documentation Tools 
  9350.  
  9351.      Development Support 
  9352.  
  9353.      Operating System Interfaces 
  9354.  
  9355.      Networking, Device Control (modems) and InterProcess Communication 
  9356.  
  9357.      Data Types and Data Type Utilities 
  9358.  
  9359.      Database Interfaces 
  9360.  
  9361.      User Interfaces 
  9362.  
  9363.      Interfaces to / Emulations of Other Programming Languages 
  9364.  
  9365.      File Names, File Systems and File Locking (see also File Handles) 
  9366.  
  9367.      String Processing, Language Text Processing, Parsing and Searching 
  9368.  
  9369.      Option, Argument, Parameter and Configuration File Processing 
  9370.  
  9371.      Internationalization and Locale 
  9372.  
  9373.      Authentication, Security and Encryption 
  9374.  
  9375.      World Wide Web, HTML, HTTP, CGI, MIME 
  9376.  
  9377.      Server and Daemon Utilities 
  9378.  
  9379.      Archiving and Compression 
  9380.  
  9381.      Images, Pixmap and Bitmap Manipulation, Drawing and Graphing 
  9382.  
  9383.      Mail and Usenet News 
  9384.  
  9385.      Control Flow Utilities (callbacks and exceptions etc) 
  9386.  
  9387.      File Handle and Input/Output Stream Utilities 
  9388.  
  9389.      Miscellaneous Modules 
  9390.  
  9391.  Some of the reguster CPAN sites as of this writing include the following. You 
  9392.  should try to choose one close to you: 
  9393.  
  9394.      ftp://ftp.sterling.com/programming/languages/perl/ 
  9395.  
  9396.      ftp://ftp.sedl.org/pub/mirrors/CPAN/ 
  9397.  
  9398.      ftp://ftp.uoknor.edu/mirrors/CPAN/ 
  9399.  
  9400.      ftp://ftp.delphi.com/pub/mirrors/packages/perl/CPAN/ 
  9401.  
  9402.      ftp://uiarchive.cso.uiuc.edu/pub/lang/perl/CPAN/ 
  9403.  
  9404.      ftp://ftp.cis.ufl.edu/pub/perl/CPAN/ 
  9405.  
  9406.      ftp://ftp.switch.ch/mirror/CPAN/ 
  9407.  
  9408.      ftp://ftp.sunet.se/pub/lang/perl/CPAN/ 
  9409.  
  9410.      ftp://ftp.ci.uminho.pt/pub/lang/perl/ 
  9411.  
  9412.      ftp://ftp.cs.ruu.nl/pub/PERL/CPAN/ 
  9413.  
  9414.      ftp://ftp.demon.co.uk/pub/mirrors/perl/CPAN/ 
  9415.  
  9416.      ftp://ftp.rz.ruhr-uni-bochum.de/pub/programming/languages/perl/CPAN/ 
  9417.  
  9418.      ftp://ftp.leo.org/pub/comp/programming/languages/perl/CPAN/ 
  9419.  
  9420.      ftp://ftp.pasteur.fr/pub/computing/unix/perl/CPAN/ 
  9421.  
  9422.      ftp://ftp.ibp.fr/pub/perl/CPAN/ 
  9423.  
  9424.      ftp://ftp.funet.fi/pub/languages/perl/CPAN/ 
  9425.  
  9426.      ftp://ftp.tekotago.ac.nz/pub/perl/CPAN/ 
  9427.  
  9428.      ftp://ftp.mame.mu.oz.au/pub/perl/CPAN/ 
  9429.  
  9430.      ftp://coombs.anu.edu.au/pub/perl/ 
  9431.  
  9432.      ftp://dongpo.math.ncu.edu.tw/perl/CPAN/ 
  9433.  
  9434.      ftp://ftp.lab.kdd.co.jp/lang/perl/CPAN/ 
  9435.  
  9436.      ftp://ftp.is.co.za/programming/perl/CPAN/ 
  9437.  
  9438.  For an up-to-date listing of CPAN sites, see http://www.perl.com/perl/ or 
  9439.  ftp://ftp.perl.com/perl/ . 
  9440.  
  9441.  Modules: Creation, Use and Abuse 
  9442.  
  9443.  (The following section is borrowed directly from Tim Bunce's modules file, 
  9444.  available at your nearest CPAN site.) 
  9445.  
  9446.  Perl 5 implements a class using a package, but the presence of a package 
  9447.  doesn't imply the presence of a class.  A package is just a namespace.  A 
  9448.  class is a package that provides subroutines that can be used as methods.  A 
  9449.  method is just a subroutine that expects, as its first argument, either the 
  9450.  name of a package (for "static" methods), or a reference to something (for 
  9451.  "virtual" methods). 
  9452.  
  9453.  A module is a file that (by convention) provides a class of the same name 
  9454.  (sans the .pm), plus an import method in that class that can be called to 
  9455.  fetch exported symbols.  This module may implement some of its methods by 
  9456.  loading dynamic C or C++ objects, but that should be totally transparent to 
  9457.  the user of the module.  Likewise, the module might set up an AUTOLOAD 
  9458.  function to slurp in subroutine definitions on demand, but this is also 
  9459.  transparent.  Only the .pm file is required to exist. 
  9460.  
  9461.  Guidelines for Module Creation 
  9462.  
  9463.  Do similar modules already exist in some form? 
  9464.  
  9465.  If so, please try to reuse the existing modules either in whole or by 
  9466.  inheriting useful features into a new class.  If this is not practical try to 
  9467.  get together with the module authors to work on extending or enhancing the 
  9468.  functionality of the existing modules. A perfect example is the plethora of 
  9469.  packages in perl4 for dealing with command line options. If you are writing a 
  9470.  module to expand an already existing set of modules, please coordinate with 
  9471.  the author of the package.  It helps if you follow the same naming scheme and 
  9472.  module interaction scheme as the original author. 
  9473.  
  9474.  Try to design the new module to be easy to extend and reuse. 
  9475.  
  9476.  Use blessed references.  Use the two argument form of bless to bless into the 
  9477.  class name given as the first parameter of the constructor, e.g.: 
  9478.  
  9479.    sub new {
  9480.           my $class = shift;
  9481.           return bless {}, $class;
  9482.    }
  9483.  
  9484.  or even this if you'd like it to be used as either a static or a virtual 
  9485.  method. 
  9486.  
  9487.    sub new {
  9488.           my $self  = shift;
  9489.           my $class = ref($self) || $self;
  9490.           return bless {}, $class;
  9491.    }
  9492.  
  9493.  Pass arrays as references so more parameters can be added later (it's also 
  9494.  faster).  Convert functions into methods where appropriate.  Split large 
  9495.  methods into smaller more flexible ones. Inherit methods from other modules if 
  9496.  appropriate. Avoid class name tests like: die "Invalid" unless ref $ref eq 
  9497.  'FOO'. Generally you can delete the "eq 'FOO'" part with no harm at all. Let 
  9498.  the objects look after themselves! Generally, avoid hardwired class names as 
  9499.  far as possible. Avoid $r->Class::func() where using @ISA=qw(... Class ...) 
  9500.  and $r->func() would work (see perlbot man page for more details). Use 
  9501.  autosplit so little used or newly added functions won't be a burden to 
  9502.  programs which don't use them. Add test functions to the module after __END__ 
  9503.  either using AutoSplit or by saying: 
  9504.  
  9505.    eval join('',<main::DATA>) || die $@ unless caller();
  9506.  
  9507.  Does your module pass the 'empty sub-class' test? If you say "@SUBCLASS::ISA = 
  9508.  qw(YOURCLASS);" your applications should be able to use SUBCLASS in exactly 
  9509.  the same way as YOURCLASS.  For example, does your application still work if 
  9510.  you change:  $obj = new YOURCLASS; into: $obj = new SUBCLASS; ? Avoid keeping 
  9511.  any state information in your packages. It makes it difficult for multiple 
  9512.  other packages to use yours. Keep state information in objects. Always use -w. 
  9513.  Try to use strict; (or use strict qw(...);). Remember that you can add no 
  9514.  strict qw(...); to individual blocks of code which need less strictness. 
  9515.  Always use -w. Always use -w! Follow the guidelines in the perlstyle(1) 
  9516.  manual. 
  9517.  
  9518.  Some simple style guidelines 
  9519.  
  9520.  The perlstyle manual supplied with perl has many helpful points. Coding style 
  9521.  is a matter of personal taste. Many people evolve their style over several 
  9522.  years as they learn what helps them write and maintain good code.  Here's one 
  9523.  set of assorted suggestions that seem to be widely used by experienced 
  9524.  developers: Use underscores to separate words.  It is generally easier to read 
  9525.  $var_names_like_this than $VarNamesLikeThis, especially for non-native 
  9526.  speakers of English. It's also a simple rule that works consistently with 
  9527.  VAR_NAMES_LIKE_THIS. Package/Module names are an exception to this rule. Perl 
  9528.  informally reserves lowercase module names for 'pragma' modules like integer 
  9529.  and strict. Other modules normally begin with a capital letter and use mixed 
  9530.  case with no underscores (need to be short and portable). You may find it 
  9531.  helpful to use letter case to indicate the scope or nature of a variable. For 
  9532.  example: 
  9533.  
  9534.    $ALL_CAPS_HERE   constants only (beware clashes with perl vars)
  9535.    $Some_Caps_Here  package-wide global/static
  9536.    $no_caps_here    function scope my() or local() variables
  9537.  
  9538.  Function and method names seem to work best as all lowercase. E.g., 
  9539.  $obj->as_string(). You can use a leading underscore to indicate that a 
  9540.  variable or function should not be used outside the package that defined it. 
  9541.  
  9542.  Select what to export. 
  9543.  
  9544.  Do NOT export method names! Do NOT export anything else by default without a 
  9545.  good reason! Exports pollute the namespace of the module user.  If you must 
  9546.  export try to use @EXPORT_OK in preference to @EXPORT and avoid short or 
  9547.  common names to reduce the risk of name clashes. Generally anything not 
  9548.  exported is still accessible from outside the module using the 
  9549.  ModuleName::item_name (or $blessed_ref->method) syntax.  By convention you can 
  9550.  use a leading underscore on names to informally indicate that they are 
  9551.  'internal' and not for public use. (It is actually possible to get private 
  9552.  functions by saying: my $subref = sub { ... };  &$subref; But there's no way 
  9553.  to call that directly as a method, since a method must have a name in the 
  9554.  symbol table.) As a general rule, if the module is trying to be object 
  9555.  oriented then export nothing. If it's just a collection of functions then 
  9556.  @EXPORT_OK anything but use @EXPORT with caution. 
  9557.  
  9558.  Select a name for the module. 
  9559.  
  9560.  This name should be as descriptive, accurate and complete as possible.  Avoid 
  9561.  any risk of ambiguity. Always try to use two or more whole words.  Generally 
  9562.  the name should reflect what is special about what the module does rather than 
  9563.  how it does it.  Please use nested module names to informally group or 
  9564.  categorise a module. A module should have a very good reason not to have a 
  9565.  nested name. Module names should begin with a capital letter. Having 57 
  9566.  modules all called Sort will not make life easy for anyone (though having 23 
  9567.  called Sort::Quick is only marginally better :-). Imagine someone trying to 
  9568.  install your module alongside many others. If in any doubt ask for suggestions 
  9569.  in comp.lang.perl.misc. If you are developing a suite of related 
  9570.  modules/classes it's good practice to use nested classes with a common prefix 
  9571.  as this will avoid namespace clashes. For example:  Xyz::Control, Xyz::View, 
  9572.  Xyz::Model etc. Use the modules in this list as a naming guide. If adding a 
  9573.  new module to a set, follow the original author's standards for naming modules 
  9574.  and the interface to methods in those modules. To be portable each component 
  9575.  of a module name should be limited to 11 characters. If it might be used on 
  9576.  DOS then try to ensure each is unique in the first 8 characters. Nested 
  9577.  modules make this easier. 
  9578.  
  9579.  Have you got it right? 
  9580.  
  9581.  How do you know that you've made the right decisions? Have you picked an 
  9582.  interface design that will cause problems later? Have you picked the most 
  9583.  appropriate name? Do you have any questions? The best way to know for sure, 
  9584.  and pick up many helpful suggestions, is to ask someone who knows. 
  9585.  Comp.lang.perl.misc is read by just about all the people who develop modules 
  9586.  and it's the best place to ask. All you need to do is post a short summary of 
  9587.  the module, its purpose and interfaces. A few lines on each of the main 
  9588.  methods is probably enough. (If you post the whole module it might be ignored 
  9589.  by busy people - generally the very people you want to read it!) Don't worry 
  9590.  about posting if you can't say when the module will be ready - just say so in 
  9591.  the message. It might be worth inviting others to help you, they may be able 
  9592.  to complete it for you! 
  9593.  
  9594.  README and other Additional Files. 
  9595.  
  9596.  It's well known that software developers usually fully document the software 
  9597.  they write. If, however, the world is in urgent need of your software and 
  9598.  there is not enough time to write the full documentation please at least 
  9599.  provide a README file containing: 
  9600.  
  9601.      A description of the module/package/extension etc. 
  9602.  
  9603.      A copyright notice - see below. 
  9604.  
  9605.      Prerequisites - what else you may need to have. 
  9606.  
  9607.      How to build it - possible changes to Makefile.PL etc. 
  9608.  
  9609.      How to install it. 
  9610.  
  9611.      Recent changes in this release, especially incompatibilities 
  9612.  
  9613.      Changes / enhancements you plan to make in the future. 
  9614.  
  9615.  If the README file seems to be getting too large you may wish to split out 
  9616.  some of the sections into separate files: INSTALL, Copying, ToDo etc. 
  9617.  
  9618.  Adding a Copyright Notice. 
  9619.  
  9620.  How you choose to licence your work is a personal decision. The general 
  9621.  mechanism is to assert your Copyright and then make a declaration of how 
  9622.  others may copy/use/modify your work. 
  9623.  
  9624.  Perl, for example, is supplied with two types of licence: The GNU GPL and The 
  9625.  Artistic License (see the files README, Copying and Artistic).  Larry has good 
  9626.  reasons for NOT just using the GNU GPL. 
  9627.  
  9628.  My personal recommendation, out of respect for Larry, Perl and the perl 
  9629.  community at large is to simply state something like: 
  9630.  
  9631.    Copyright (c) 1995 Your Name. All rights reserved.
  9632.    This program is free software; you can redistribute it and/or
  9633.    modify it under the same terms as Perl itself.
  9634.  
  9635.  This statement should at least appear in the README file. You may also wish to 
  9636.  include it in a Copying file and your source files. Remember to include the 
  9637.  other words in addition to the Copyright. 
  9638.  
  9639.  Give the module a version/issue/release number. 
  9640.  
  9641.  To be fully compatible with the Exporter and MakeMaker modules you should 
  9642.  store your module's version number in a non-my package variable called 
  9643.  $VERSION.  This should be a valid floating point number with at least two 
  9644.  digits after the decimal (ie hundredths, e.g, $VERSION = "0.01").  Don't use a 
  9645.  "1.3.2" style version. See Exporter.pm in Perl5.001m or later for details. 
  9646.  
  9647.  It may be handy to add a function or method to retrieve the number. Use the 
  9648.  number in announcements and archive file names when releasing the module 
  9649.  (ModuleName-1.02.tar.Z). See perldoc ExtUtils::MakeMaker.pm for details. 
  9650.  
  9651.  How to release and distribute a module. 
  9652.  
  9653.  It's good idea to post an announcement of the availability of your module (or 
  9654.  the module itself if small) to the comp.lang.perl.announce Usenet newsgroup. 
  9655.  This will at least ensure very wide once-off distribution. 
  9656.  
  9657.  If possible you should place the module into a major ftp archive and include 
  9658.  details of it's location in your announcement. 
  9659.  
  9660.  Some notes about ftp archives: Please use a long descriptive file name which 
  9661.  includes the version number. Most incoming directories will not be 
  9662.  readable/listable, i.e., you won't be able to see your file after uploading 
  9663.  it. Remember to send your email notification message as soon as possible after 
  9664.  uploading else your file may get deleted automatically. Allow time for the 
  9665.  file to be processed and/or check the file has been processed before 
  9666.  announcing its location. 
  9667.  
  9668.  FTP Archives for Perl Modules: 
  9669.  
  9670.  Follow the instructions and links on 
  9671.  
  9672.      http://franz.ww.tu-berlin.de/modulelist
  9673.  
  9674.  or upload to one of these sites: 
  9675.  
  9676.      ftp://franz.ww.tu-berlin.de/incoming
  9677.      ftp://ftp.cis.ufl.edu/incoming
  9678.  
  9679.  and notify upload@franz.ww.tu-berlin.de. 
  9680.  
  9681.  By using the WWW interface you can ask the Upload Server to mirror your 
  9682.  modules from your ftp or WWW site into your own directory on CPAN! 
  9683.  
  9684.  Please remember to send me an updated entry for the Module list! 
  9685.  
  9686.  Take care when changing a released module. 
  9687.  
  9688.  Always strive to remain compatible with previous released versions (see 2.2 
  9689.  above) Otherwise try to add a mechanism to revert to the old behaviour if 
  9690.  people rely on it. Document incompatible changes. 
  9691.  
  9692.  Guidelines for Converting Perl 4 Library Scripts into Modules 
  9693.  
  9694.  There is no requirement to convert anything. 
  9695.  
  9696.  If it ain't broke, don't fix it! Perl 4 library scripts should continue to 
  9697.  work with no problems. You may need to make some minor changes (like escaping 
  9698.  non-array @'s in double quoted strings) but there is no need to convert a .pl 
  9699.  file into a Module for just that. 
  9700.  
  9701.  Consider the implications. 
  9702.  
  9703.  All the perl applications which make use of the script will need to be changed 
  9704.  (slightly) if the script is converted into a module.  Is it worth it unless 
  9705.  you plan to make other changes at the same time? 
  9706.  
  9707.  Make the most of the opportunity. 
  9708.  
  9709.  If you are going to convert the script to a module you can use the opportunity 
  9710.  to redesign the interface. The 'Guidelines for Module Creation' above include 
  9711.  many of the issues you should consider. 
  9712.  
  9713.  The pl2pm utility will get you started. 
  9714.  
  9715.  This utility will read *.pl files (given as parameters) and write 
  9716.  corresponding *.pm files. The pl2pm utilities does the following: 
  9717.  
  9718.      Adds the standard Module prologue lines 
  9719.  
  9720.      Converts package specifiers from ' to :: 
  9721.  
  9722.      Converts die(...) to croak(...) 
  9723.  
  9724.      Several other minor changes 
  9725.  
  9726.  Being a mechanical process pl2pm is not bullet proof. The converted code will 
  9727.  need careful checking, especially any package statements. Don't delete the 
  9728.  original .pl file till the new .pm one works! 
  9729.  
  9730.  Guidelines for Reusing Application Code 
  9731.  
  9732.  Complete applications rarely belong in the Perl Module Library. 
  9733.  
  9734.  Many applications contain some perl code which could be reused. 
  9735.  
  9736.  Help save the world! Share your code in a form that makes it easy to reuse. 
  9737.  
  9738.  Break-out the reusable code into one or more separate module files. 
  9739.  
  9740.  Take the opportunity to reconsider and redesign the interfaces. 
  9741.  
  9742.  In some cases the 'application' can then be reduced to a small 
  9743.  
  9744.  fragment of code built on top of the reusable modules. In these cases the 
  9745.  application could invoked as: 
  9746.  
  9747.        perl -e 'use Module::Name; method(@ARGV)' ...
  9748.  
  9749.  or 
  9750.  
  9751.        perl -mModule::Name ...    (in perl5.002?)
  9752.  
  9753.  
  9754. ΓòÉΓòÉΓòÉ 16. Section - perlref ΓòÉΓòÉΓòÉ
  9755.  
  9756. NAME 
  9757.  
  9758. perlref - Perl references and nested data structures 
  9759.  
  9760. DESCRIPTION 
  9761.  
  9762. Before release 5 of Perl it was difficult to represent complex data structures, 
  9763. because all references had to be symbolic, and even that was difficult to do 
  9764. when you wanted to refer to a variable rather than a symbol table entry.  Perl 
  9765. 5 not only makes it easier to use symbolic references to variables, but lets 
  9766. you have "hard" references to any piece of data.  Any scalar may hold a hard 
  9767. reference.  Since arrays and hashes contain scalars, you can now easily build 
  9768. arrays of arrays, arrays of hashes, hashes of arrays, arrays of hashes of 
  9769. functions, and so on. 
  9770.  
  9771. Hard references are smart--they keep track of reference counts for you, 
  9772. automatically freeing the thing referred to when its reference count goes to 
  9773. zero.  If that thing happens to be an object, the object is destructed.  See 
  9774. perlobj for more about objects.  (In a sense, everything in Perl is an object, 
  9775. but we usually reserve the word for references to objects that have been 
  9776. officially "blessed" into a class package.) 
  9777.  
  9778. A symbolic reference contains the name of a variable, just as a symbolic link 
  9779. in the filesystem merely contains the name of a file. The *glob notation is a 
  9780. kind of symbolic reference.  Hard references are more like hard links in the 
  9781. file system: merely another way at getting at the same underlying object, 
  9782. irrespective of its name. 
  9783.  
  9784. "Hard" references are easy to use in Perl.  There is just one overriding 
  9785. principle:  Perl does no implicit referencing or dereferencing.  When a scalar 
  9786. is holding a reference, it always behaves as a scalar.  It doesn't magically 
  9787. start being an array or a hash unless you tell it so explicitly by 
  9788. dereferencing it. 
  9789.  
  9790. References can be constructed several ways. 
  9791.  
  9792.    1. By using the backslash operator on a variable, subroutine, or value. 
  9793.       (This works much like the & (address-of) operator works in C.)  Note that 
  9794.       this typically creates ANOTHER reference to a variable, since there's 
  9795.       already a reference to the variable in the symbol table.  But the symbol 
  9796.       table reference might go away, and you'll still have the reference that 
  9797.       the backslash returned.  Here are some examples: 
  9798.  
  9799.                 $scalarref = \$foo;
  9800.                 $arrayref  = \@ARGV;
  9801.                 $hashref   = \%ENV;
  9802.                 $coderef   = \&handler;
  9803.                 $globref   = \*STDOUT;
  9804.  
  9805.    2. A reference to an anonymous array can be constructed using square 
  9806.       brackets: 
  9807.  
  9808.                 $arrayref = [1, 2, ['a', 'b', 'c']];
  9809.  
  9810.       Here we've constructed a reference to an anonymous array of three 
  9811.       elements whose final element is itself reference to another anonymous 
  9812.       array of three elements.  (The multidimensional syntax described later 
  9813.       can be used to access this.  For example, after the above, 
  9814.       $arrayref->[2][1] would have the value "b".) Note that taking a reference 
  9815.       to an enumerated list is not the same as using square brackets--instead 
  9816.       it's the same as creating a list of references! 
  9817.  
  9818.                 @list = (\$a, \$b, \$c);
  9819.                 @list = \($a, $b, $c);      # same thing!
  9820.  
  9821.    3. A reference to an anonymous hash can be constructed using curly brackets: 
  9822.  
  9823.                 $hashref = {
  9824.                     'Adam'  => 'Eve',
  9825.                     'Clyde' => 'Bonnie',
  9826.                 };
  9827.  
  9828.       Anonymous hash and array constructors can be intermixed freely to produce 
  9829.       as complicated a structure as you want.  The multidimensional syntax 
  9830.       described below works for these too.  The values above are literals, but 
  9831.       variables and expressions would work just as well, because assignment 
  9832.       operators in Perl (even within local() or my()) are executable 
  9833.       statements, not compile-time declarations. Because curly brackets 
  9834.       (braces) are used for several other things including BLOCKs, you may 
  9835.       occasionally have to disambiguate braces at the beginning of a statement 
  9836.       by putting a + or a return in front so that Perl realizes the opening 
  9837.       brace isn't starting a BLOCK.  The economy and mnemonic value of using 
  9838.       curlies is deemed worth this occasional extra hassle. For example, if you 
  9839.       wanted a function to make a new hash and return a reference to it, you 
  9840.       have these options: 
  9841.  
  9842.                 sub hashem {        { @_ } }   # silently wrong
  9843.                 sub hashem {       +{ @_ } }   # ok
  9844.                 sub hashem { return { @_ } }   # ok
  9845.  
  9846.    4. A reference to an anonymous subroutine can be constructed by using sub 
  9847.       without a subname: 
  9848.  
  9849.                 $coderef = sub { print "Boink!\n" };
  9850.  
  9851.       Note the presence of the semicolon.  Except for the fact that the code 
  9852.       inside isn't executed immediately, a sub {} is not so much a declaration 
  9853.       as it is an operator, like do{} or eval{}.  (However, no matter how many 
  9854.       times you execute that line (unless you're in an eval("...")), $coderef 
  9855.       will still have a reference to the SAME anonymous subroutine.) Anonymous 
  9856.       subroutines act as closures with respect to my() variables, that is, 
  9857.       variables visible lexically within the current scope.  Closure is a 
  9858.       notion out of the Lisp world that says if you define an anonymous 
  9859.       function in a particular lexical context, it pretends to run in that 
  9860.       context even when it's called outside of the context. In human terms, 
  9861.       it's a funny way of passing arguments to a subroutine when you define it 
  9862.       as well as when you call it.  It's useful for setting up little bits of 
  9863.       code to run later, such as callbacks.  You can even do object-oriented 
  9864.       stuff with it, though Perl provides a different mechanism to do that 
  9865.       already--see perlobj. You can also think of closure as a way to write a 
  9866.       subroutine template without using eval.  (In fact, in version 5.000, eval 
  9867.       was the only way to get closures.  You may wish to use "require 5.001" if 
  9868.       you use closures.) Here's a small example of how closures works: 
  9869.  
  9870.                 sub newprint {
  9871.                     my $x = shift;
  9872.                     return sub { my $y = shift; print "$x, $y!\n"; };
  9873.                 }
  9874.                 $h = newprint("Howdy");
  9875.                 $g = newprint("Greetings");
  9876.  
  9877.                 # Time passes...
  9878.  
  9879.                 &$h("world");
  9880.                 &$g("earthlings");
  9881.  
  9882.       This prints 
  9883.  
  9884.                 Howdy, world!
  9885.                 Greetings, earthlings!
  9886.  
  9887.       Note particularly that $x continues to refer to the value passed into 
  9888.       newprint() despite the fact that the "my $x" has seemingly gone out of 
  9889.       scope by the time the anonymous subroutine runs.  That's what closure is 
  9890.       all about. This only applies to lexical variables, by the way.  Dynamic 
  9891.       variables continue to work as they have always worked.  Closure is not 
  9892.       something that most Perl programmers need trouble themselves about to 
  9893.       begin with. 
  9894.  
  9895.    5. References are often returned by special subroutines called constructors. 
  9896.       Perl objects are just references to a special kind of object that happens 
  9897.       to know which package it's associated with.  Constructors are just 
  9898.       special subroutines that know how to create that association.  They do so 
  9899.       by starting with an ordinary reference, and it remains an ordinary 
  9900.       reference even while it's also being an object.  Constructors are 
  9901.       customarily named new(), but don't have to be: 
  9902.  
  9903.                 $objref = new Doggie (Tail => 'short', Ears => 'long');
  9904.  
  9905.    6. References of the appropriate type can spring into existence if you 
  9906.       dereference them in a context that assumes they exist.  Since we haven't 
  9907.       talked about dereferencing yet, we can't show you any examples yet. 
  9908.  
  9909.    7. References to filehandles can be created by taking a reference to a 
  9910.       typeglob.  This is currently the best way to pass filehandles into or out 
  9911.       of subroutines, or to store them in larger data structures. 
  9912.  
  9913.                 splutter(\*STDOUT);
  9914.                 sub splutter {
  9915.                     my $fh = shift;
  9916.                     print $fh "her um well a hmmm\n";
  9917.                 }
  9918.  
  9919.                 $rec = get_rec(\*STDIN);
  9920.                 sub get_rec {
  9921.                     my $fh = shift;
  9922.                     return scalar <$fh>;
  9923.                 }
  9924.  
  9925.  
  9926.  That's it for creating references.  By now you're probably dying to know how 
  9927.  to use references to get back to your long-lost data.  There are several basic 
  9928.  methods. 
  9929.  
  9930.    1. Anywhere you'd put an identifier as part of a variable or subroutine 
  9931.       name, you can replace the identifier with a simple scalar variable 
  9932.       containing a reference of the correct type: 
  9933.  
  9934.                 $bar = $$scalarref;
  9935.                 push(@$arrayref, $filename);
  9936.                 $$arrayref[0] = "January";
  9937.                 $$hashref{"KEY"} = "VALUE";
  9938.                 &$coderef(1,2,3);
  9939.                 print $globref "output\n";
  9940.  
  9941.       It's important to understand that we are specifically NOT dereferencing 
  9942.       $arrayref[0] or $hashref{"KEY"} there.  The dereference of the scalar 
  9943.       variable happens BEFORE it does any key lookups.  Anything more 
  9944.       complicated than a simple scalar variable must use methods 2 or 3 below. 
  9945.       However, a "simple scalar" includes an identifier that itself uses method 
  9946.       1 recursively.  Therefore, the following prints "howdy". 
  9947.  
  9948.                 $refrefref = \\\"howdy";
  9949.                 print $$$$refrefref;
  9950.  
  9951.    2. Anywhere you'd put an identifier as part of a variable or subroutine 
  9952.       name, you can replace the identifier with a BLOCK returning a reference 
  9953.       of the correct type.  In other words, the previous examples could be 
  9954.       written like this: 
  9955.  
  9956.                 $bar = ${$scalarref};
  9957.                 push(@{$arrayref}, $filename);
  9958.                 ${$arrayref}[0] = "January";
  9959.                 ${$hashref}{"KEY"} = "VALUE";
  9960.                 &{$coderef}(1,2,3);
  9961.                 $globref->print("output\n");  # iff you use FileHandle
  9962.  
  9963.       Admittedly, it's a little silly to use the curlies in this case, but the 
  9964.       BLOCK can contain any arbitrary expression, in particular, subscripted 
  9965.       expressions: 
  9966.  
  9967.                 &{ $dispatch{$index} }(1,2,3);      # call correct routine
  9968.  
  9969.       Because of being able to omit the curlies for the simple case of $$x, 
  9970.       people often make the mistake of viewing the dereferencing symbols as 
  9971.       proper operators, and wonder about their precedence.  If they were, 
  9972.       though, you could use parens instead of braces.  That's not the case. 
  9973.       Consider the difference below; case 0 is a short-hand version of case 1, 
  9974.       NOT case 2: 
  9975.  
  9976.                 $$hashref{"KEY"}   = "VALUE";       # CASE 0
  9977.                 ${$hashref}{"KEY"} = "VALUE";       # CASE 1
  9978.                 ${$hashref{"KEY"}} = "VALUE";       # CASE 2
  9979.                 ${$hashref->{"KEY"}} = "VALUE";     # CASE 3
  9980.  
  9981.       Case 2 is also deceptive in that you're accessing a variable called 
  9982.       %hashref, not dereferencing through $hashref to the hash it's presumably 
  9983.       referencing.  That would be case 3. 
  9984.  
  9985.    3. The case of individual array elements arises often enough that it gets 
  9986.       cumbersome to use method 2.  As a form of syntactic sugar, the two lines 
  9987.       like that above can be written: 
  9988.  
  9989.                 $arrayref->[0] = "January";
  9990.                 $hashref->{"KEY"} = "VALUE";
  9991.  
  9992.       The left side of the array can be any expression returning a reference, 
  9993.       including a previous dereference.  Note that $array[$x] is NOT the same 
  9994.       thing as $array-[$x]> here: 
  9995.  
  9996.                 $array[$x]->{"foo"}->[0] = "January";
  9997.  
  9998.       This is one of the cases we mentioned earlier in which references could 
  9999.       spring into existence when in an lvalue context.  Before this statement, 
  10000.       $array[$x] may have been undefined.  If so, it's automatically defined 
  10001.       with a hash reference so that we can look up {"foo"} in it.  Likewise 
  10002.       $array[$x]-{"foo"}> will automatically get defined with an array 
  10003.       reference so that we can look up [0] in it. One more thing here.  The 
  10004.       arrow is optional BETWEEN brackets subscripts, so you can shrink the 
  10005.       above down to 
  10006.  
  10007.                 $array[$x]{"foo"}[0] = "January";
  10008.  
  10009.       Which, in the degenerate case of using only ordinary arrays, gives you 
  10010.       multidimensional arrays just like C's: 
  10011.  
  10012.                 $score[$x][$y][$z] += 42;
  10013.  
  10014.       Well, okay, not entirely like C's arrays, actually.  C doesn't know how 
  10015.       to grow its arrays on demand.  Perl does. 
  10016.  
  10017.    4. If a reference happens to be a reference to an object, then there are 
  10018.       probably methods to access the things referred to, and you should 
  10019.       probably stick to those methods unless you're in the class package that 
  10020.       defines the object's methods.  In other words, be nice, and don't violate 
  10021.       the object's encapsulation without a very good reason.  Perl does not 
  10022.       enforce encapsulation.  We are not totalitarians here.  We do expect some 
  10023.       basic civility though. 
  10024.  
  10025.  The ref() operator may be used to determine what type of thing the reference 
  10026.  is pointing to.  See perlfunc. 
  10027.  
  10028.  The bless() operator may be used to associate a reference with a package 
  10029.  functioning as an object class.  See perlobj. 
  10030.  
  10031.  A typeglob may be dereferenced the same way a reference can, since the 
  10032.  dereference syntax always indicates the kind of reference desired. So ${*foo} 
  10033.  and ${\$foo} both indicate the same scalar variable. 
  10034.  
  10035.  Here's a trick for interpolating a subroutine call into a string: 
  10036.  
  10037.       print "My sub returned @{[mysub(1,2,3)]} that time.\n";
  10038.  
  10039.  The way it works is that when the @{...} is seen in the double-quoted string, 
  10040.  it's evaluated as a block.  The block creates a reference to an anonymous 
  10041.  array containing the results of the call to mysub(1,2,3).  So the whole block 
  10042.  returns a reference to an array, which is then dereferenced by @{...} and 
  10043.  stuck into the double-quoted string. This chicanery is also useful for 
  10044.  arbitrary expressions: 
  10045.  
  10046.       print "That yeilds @{[$n + 5]} widgets\n";
  10047.  
  10048.  Symbolic references 
  10049.  
  10050.  We said that references spring into existence as necessary if they are 
  10051.  undefined, but we didn't say what happens if a value used as a reference is 
  10052.  already defined, but ISN'T a hard reference.  If you use it as a reference in 
  10053.  this case, it'll be treated as a symbolic reference.  That is, the value of 
  10054.  the scalar is taken to be the NAME of a variable, rather than a direct link to 
  10055.  a (possibly) anonymous value. 
  10056.  
  10057.  People frequently expect it to work like this.  So it does. 
  10058.  
  10059.       $name = "foo";
  10060.       $$name = 1;                 # Sets $foo
  10061.       ${$name} = 2;               # Sets $foo
  10062.       ${$name x 2} = 3;           # Sets $foofoo
  10063.       $name->[0] = 4;             # Sets $foo[0]
  10064.       @$name = ();                # Clears @foo
  10065.       &$name();                   # Calls &foo() (as in Perl 4)
  10066.       $pack = "THAT";
  10067.       ${"${pack}::$name"} = 5;    # Sets $THAT::foo without eval
  10068.  
  10069.  This is very powerful, and slightly dangerous, in that it's possible to intend 
  10070.  (with the utmost sincerity) to use a hard reference, and accidentally use a 
  10071.  symbolic reference instead.  To protect against that, you can say 
  10072.  
  10073.       use strict 'refs';
  10074.  
  10075.  and then only hard references will be allowed for the rest of the enclosing 
  10076.  block.  An inner block may countermand that with 
  10077.  
  10078.       no strict 'refs';
  10079.  
  10080.  Only package variables are visible to symbolic references.  Lexical variables 
  10081.  (declared with my()) aren't in a symbol table, and thus are invisible to this 
  10082.  mechanism.  For example: 
  10083.  
  10084.       local($value) = 10;
  10085.       $ref = \$value;
  10086.       {
  10087.           my $value = 20;
  10088.           print $$ref;
  10089.       }
  10090.  
  10091.  This will still print 10, not 20.  Remember that local() affects package 
  10092.  variables, which are all "global" to the package. 
  10093.  
  10094.  Not-so-symbolic references 
  10095.  
  10096.  A new feature contributing to readability in 5.001 is that the brackets around 
  10097.  a symbolic reference behave more like quotes, just as they always have within 
  10098.  a string.  That is, 
  10099.  
  10100.       $push = "pop on ";
  10101.       print "${push}over";
  10102.  
  10103.  has always meant to print "pop on over", despite the fact that push is a 
  10104.  reserved word.  This has been generalized to work the same outside of quotes, 
  10105.  so that 
  10106.  
  10107.       print ${push} . "over";
  10108.  
  10109.  and even 
  10110.  
  10111.       print ${ push } . "over";
  10112.  
  10113.  will have the same effect.  (This would have been a syntax error in 5.000, 
  10114.  though Perl 4 allowed it in the spaceless form.)  Note that this construct is 
  10115.  not considered to be a symbolic reference when you're using strict refs: 
  10116.  
  10117.       use strict 'refs';
  10118.       ${ bareword };      # Okay, means $bareword.
  10119.       ${ "bareword" };    # Error, symbolic reference.
  10120.  
  10121.  Similarly, because of all the subscripting that is done using single words, 
  10122.  we've applied the same rule to any bareword that is used for subscripting a 
  10123.  hash.  So now, instead of writing 
  10124.  
  10125.       $array{ "aaa" }{ "bbb" }{ "ccc" }
  10126.  
  10127.  you can just write 
  10128.  
  10129.       $array{ aaa }{ bbb }{ ccc }
  10130.  
  10131.  and not worry about whether the subscripts are reserved words.  In the rare 
  10132.  event that you do wish to do something like 
  10133.  
  10134.       $array{ shift }
  10135.  
  10136.  you can force interpretation as a reserved word by adding anything that makes 
  10137.  it more than a bareword: 
  10138.  
  10139.       $array{ shift() }
  10140.       $array{ +shift }
  10141.       $array{ shift @_ }
  10142.  
  10143.  The -w switch will warn you if it interprets a reserved word as a string. But 
  10144.  it will no longer warn you about using lowercase words, since the string is 
  10145.  effectively quoted. 
  10146.  
  10147.  WARNING 
  10148.  
  10149.  You may not (usefully) use a reference as the key to a hash.  It will be 
  10150.  converted into a string: 
  10151.  
  10152.       $x{ \$a } = $a;
  10153.  
  10154.  If you try to dereference the key, it won't do a hard dereference, and you 
  10155.  won't accomplish what you're attemping.  You might want to do something more 
  10156.  like 
  10157.  
  10158.       $r = \@a;
  10159.       $x{ $r } = $r;
  10160.  
  10161.  And then at least you can use the values(), which will be real refs, instead 
  10162.  of the keys(), which won't. 
  10163.  
  10164.  SEE ALSO 
  10165.  
  10166.  Besides the obvious documents, source code can be instructive. Some rather 
  10167.  pathological examples of the use of references can be found in the t/op/ref.t 
  10168.  regression test in the Perl source directory. 
  10169.  
  10170.  See also perldsc and perllol for how to use references to create complex data 
  10171.  structures, and perlobj for how to use them to create objects. 
  10172.  
  10173.  
  10174. ΓòÉΓòÉΓòÉ 17. Section - perldsc ΓòÉΓòÉΓòÉ
  10175.  
  10176. NAME 
  10177.  
  10178. perldsc - Perl Data Structures Cookbook 
  10179.  
  10180. DESCRIPTION 
  10181.  
  10182. The single feature most sorely lacking in the Perl programming language prior 
  10183. to its 5.0 release was complex data structures.  Even without direct language 
  10184. support, some valiant programmers did manage to emulate them, but it was hard 
  10185. work and not for the faint of heart.  You could occasionally get away with the 
  10186. $m{$LoL,$b} notation borrowed from awk in which the keys are actually more like 
  10187. a single concatenated string "$LoL$b", but traversal and sorting were 
  10188. difficult.  More desperate programmers even hacked Perl's internal symbol table 
  10189. directly, a strategy that proved hard to develop and maintain--to put it 
  10190. mildly. 
  10191.  
  10192. The 5.0 release of Perl let us have complex data structures.  You may now write 
  10193. something like this and all of a sudden, you'd have a array with three 
  10194. dimensions! 
  10195.  
  10196.     for $x (1 .. 10) {
  10197.         for $y (1 .. 10) {
  10198.             for $z (1 .. 10) {
  10199.                 $LoL[$x][$y][$z] =
  10200.                     $x ** $y + $z;
  10201.             }
  10202.         }
  10203.     }
  10204.  
  10205. Alas, however simple this may appear, underneath it's a much more elaborate 
  10206. construct than meets the eye! 
  10207.  
  10208. How do you print it out?  Why can't you just say print @LoL?  How do you sort 
  10209. it?  How can you pass it to a function or get one of these back from a 
  10210. function?  Is is an object?  Can you save it to disk to read back later?  How 
  10211. do you access whole rows or columns of that matrix?  Do all the values have to 
  10212. be numeric? 
  10213.  
  10214. As you see, it's quite easy to become confused.  While some small portion of 
  10215. the blame for this can be attributed to the reference-based implementation, 
  10216. it's really more due to a lack of existing documentation with examples designed 
  10217. for the beginner. 
  10218.  
  10219. This document is meant to be a detailed but understandable treatment of the 
  10220. many different sorts of data structures you might want to develop.  It should 
  10221. also serve as a cookbook of examples.  That way, when you need to create one of 
  10222. these complex data structures, you can just pinch, pilfer, or purloin a drop-in 
  10223. example from here. 
  10224.  
  10225. Let's look at each of these possible constructs in detail.  There are separate 
  10226. documents on each of the following: 
  10227.  
  10228. * arrays of arrays 
  10229.  
  10230. * hashes of arrays 
  10231.  
  10232. * arrays of hashes 
  10233.  
  10234. * hashes of hashes 
  10235.  
  10236. * more elaborate constructs 
  10237.  
  10238. * recursive and self-referential data structures 
  10239.  
  10240. * objects 
  10241.  
  10242. But for now, let's look at some of the general issues common to all of these 
  10243. types of data structures. 
  10244.  
  10245. REFERENCES 
  10246.  
  10247. The most important thing to understand about all data structures in Perl -- 
  10248. including multidimensional arrays--is that even though they might appear 
  10249. otherwise, Perl @ARRAYs and %HASHes are all internally one-dimensional.  They 
  10250. can only hold scalar values (meaning a string, number, or a reference).  They 
  10251. cannot directly contain other arrays or hashes, but instead contain references 
  10252. to other arrays or hashes. 
  10253.  
  10254. You can't use a reference to a array or hash in quite the same way that you 
  10255. would a real array or hash.  For C or C++ programmers unused to distinguishing 
  10256. between arrays and pointers to the same, this can be confusing.  If so, just 
  10257. think of it as the difference between a structure and a pointer to a structure. 
  10258.  
  10259. You can (and should) read more about references in the perlref(1) man page. 
  10260. Briefly, references are rather like pointers that know what they point to. 
  10261. (Objects are also a kind of reference, but we won't be needing them right 
  10262. away--if ever.)  That means that when you have something that looks to you like 
  10263. an access to two-or-more-dimensional array and/or hash, that what's really 
  10264. going on is that in all these cases, the base type is merely a one-dimensional 
  10265. entity that contains references to the next level.  It's just that you can use 
  10266. it as though it were a two-dimensional one.  This is actually the way almost 
  10267. all C multidimensional arrays work as well. 
  10268.  
  10269.     $list[7][12]                        # array of arrays
  10270.     $list[7]{string}                    # array of hashes
  10271.     $hash{string}[7]                    # hash of arrays
  10272.     $hash{string}{'another string'}     # hash of hashes
  10273.  
  10274. Now, because the top level only contains references, if you try to print out 
  10275. your array in with a simple print() function, you'll get something that doesn't 
  10276. look very nice, like this: 
  10277.  
  10278.     @LoL = ( [2, 3], [4, 5, 7], [0] );
  10279.     print $LoL[1][2];
  10280.   7
  10281.     print @LoL;
  10282.   ARRAY(0x83c38)ARRAY(0x8b194)ARRAY(0x8b1d0)
  10283.  
  10284. That's because Perl doesn't (ever) implicitly dereference your variables. If 
  10285. you want to get at the thing a reference is referring to, then you have to do 
  10286. this yourself using either prefix typing indicators, like ${$blah}, @{$blah}, 
  10287. @{$blah[$i]}, or else postfix pointer arrows, like $a-[3]>, $h-{fred}>, or even 
  10288. $ob-method()->[3]>. 
  10289.  
  10290. COMMON MISTAKES 
  10291.  
  10292. The two most common mistakes made in constructing something like an array of 
  10293. arrays is either accidentally counting the number of elements or else taking a 
  10294. reference to the same memory location repeatedly.  Here's the case where you 
  10295. just get the count instead of a nested array: 
  10296.  
  10297.     for $i (1..10) {
  10298.         @list = somefunc($i);
  10299.         $LoL[$i] = @list;       # WRONG!
  10300.     }
  10301.  
  10302. That's just the simple case of assigning a list to a scalar and getting its 
  10303. element count.  If that's what you really and truly want, then you might do 
  10304. well to consider being a tad more explicit about it, like this: 
  10305.  
  10306.     for $i (1..10) {
  10307.         @list = somefunc($i);
  10308.         $counts[$i] = scalar @list;
  10309.     }
  10310.  
  10311. Here's the case of taking a reference to the same memory location again and 
  10312. again: 
  10313.  
  10314.     for $i (1..10) {
  10315.         @list = somefunc($i);
  10316.         $LoL[$i] = \@list;      # WRONG!
  10317.     }
  10318.  
  10319. So, just what's the big problem with that?  It looks right, doesn't it? After 
  10320. all, I just told you that you need an array of references, so by golly, you've 
  10321. made me one! 
  10322.  
  10323. Unfortunately, while this is true, it's still broken.  All the references in 
  10324. @LoL refer to the very same place, and they will therefore all hold whatever 
  10325. was last in @list!  It's similar to the problem demonstrated in the following C 
  10326. program: 
  10327.  
  10328.     #include <pwd.h>
  10329.     main() {
  10330.         struct passwd *getpwnam(), *rp, *dp;
  10331.         rp = getpwnam("root");
  10332.         dp = getpwnam("daemon");
  10333.  
  10334.         printf("daemon name is %s\nroot name is %s\n",
  10335.                 dp->pw_name, rp->pw_name);
  10336.     }
  10337.  
  10338. Which will print 
  10339.  
  10340.     daemon name is daemon
  10341.     root name is daemon
  10342.  
  10343. The problem is that both rp and dp are pointers to the same location in memory! 
  10344. In C, you'd have to remember to malloc() yourself some new memory.  In Perl, 
  10345. you'll want to use the array constructor [] or the hash constructor {} instead. 
  10346. Here's the right way to do the preceding broken code fragments 
  10347.  
  10348.     for $i (1..10) {
  10349.         @list = somefunc($i);
  10350.         $LoL[$i] = [ @list ];
  10351.     }
  10352.  
  10353. The square brackets make a reference to a new array with a copy of what's in 
  10354. @list at the time of the assignment.  This is what you want. 
  10355.  
  10356. Note that this will produce something similar, but it's much harder to read: 
  10357.  
  10358.     for $i (1..10) {
  10359.         @list = 0 .. $i;
  10360.         @{$LoL[$i]} = @list;
  10361.     }
  10362.  
  10363. Is it the same?  Well, maybe so--and maybe not.  The subtle difference is that 
  10364. when you assign something in square brackets, you know for sure it's always a 
  10365. brand new reference with a new copy of the data. Something else could be going 
  10366. on in this new case with the @{$LoL[$i]}} dereference on the left-hand-side of 
  10367. the assignment.  It all depends on whether $LoL[$i] had been undefined to start 
  10368. with, or whether it already contained a reference.  If you had already 
  10369. populated @LoL with references, as in 
  10370.  
  10371.     $LoL[3] = \@another_list;
  10372.  
  10373. Then the assignment with the indirection on the left-hand-side would use the 
  10374. existing reference that was already there: 
  10375.  
  10376.     @{$LoL[3]} = @list;
  10377.  
  10378. Of course, this would have the "interesting" effect of clobbering 
  10379. @another_list.  (Have you ever noticed how when a programmer says something is 
  10380. "interesting", that rather than meaning "intriguing", they're disturbingly more 
  10381. apt to mean that it's "annoying", "difficult", or both?  :-) 
  10382.  
  10383. So just remember to always use the array or hash constructors with [] or {}, 
  10384. and you'll be fine, although it's not always optimally efficient. 
  10385.  
  10386. Surprisingly, the following dangerous-looking construct will actually work out 
  10387. fine: 
  10388.  
  10389.     for $i (1..10) {
  10390.         my @list = somefunc($i);
  10391.         $LoL[$i] = \@list;
  10392.     }
  10393.  
  10394. That's because my() is more of a run-time statement than it is a compile-time 
  10395. declaration per se.  This means that the my() variable is remade afresh each 
  10396. time through the loop.  So even though it looks as though you stored the same 
  10397. variable reference each time, you actually did not!  This is a subtle 
  10398. distinction that can produce more efficient code at the risk of misleading all 
  10399. but the most experienced of programmers.  So I usually advise against teaching 
  10400. it to beginners.  In fact, except for passing arguments to functions, I seldom 
  10401. like to see the gimme-a-reference operator (backslash) used much at all in 
  10402. code.  Instead, I advise beginners that they (and most of the rest of us) 
  10403. should try to use the much more easily understood constructors [] and {} 
  10404. instead of relying upon lexical (or dynamic) scoping and hidden 
  10405. reference-counting to do the right thing behind the scenes. 
  10406.  
  10407. In summary: 
  10408.  
  10409.     $LoL[$i] = [ @list ];       # usually best
  10410.     $LoL[$i] = \@list;          # perilous; just how my() was that list?
  10411.     @{ $LoL[$i] } = @list;      # way too tricky for most programmers
  10412.  
  10413. CAVEAT ON PRECEDENCE 
  10414.  
  10415. Speaking of things like @{$LoL[$i]}, the following are actually the same thing: 
  10416.  
  10417.     $listref->[2][2]    # clear
  10418.     $$listref[2][2]     # confusing
  10419.  
  10420. That's because Perl's precedence rules on its five prefix dereferencers (which 
  10421. look like someone swearing: $ @ * % &) make them bind more tightly than the 
  10422. postfix subscripting brackets or braces!  This will no doubt come as a great 
  10423. shock to the C or C++ programmer, who is quite accustomed to using *a[i] to 
  10424. mean what's pointed to by the i'th element of a.  That is, they first take the 
  10425. subscript, and only then dereference the thing at that subscript.  That's fine 
  10426. in C, but this isn't C. 
  10427.  
  10428. The seemingly equivalent construct in Perl, $$listref[$i] first does the deref 
  10429. of $listref, making it take $listref as a reference to an array, and then 
  10430. dereference that, and finally tell you the i'th value of the array pointed to 
  10431. by $LoL. If you wanted the C notion, you'd have to write ${$LoL[$i]} to force 
  10432. the $LoL[$i] to get evaluated first before the leading $ dereferencer. 
  10433.  
  10434. WHY YOU SHOULD ALWAYS use strict 
  10435.  
  10436. If this is starting to sound scarier than it's worth, relax.  Perl has some 
  10437. features to help you avoid its most common pitfalls.  The best way to avoid 
  10438. getting confused is to start every program like this: 
  10439.  
  10440.     #!/usr/bin/perl -w
  10441.     use strict;
  10442.  
  10443. This way, you'll be forced to declare all your variables with my() and also 
  10444. disallow accidental "symbolic dereferencing".  Therefore if you'd done this: 
  10445.  
  10446.     my $listref = [
  10447.         [ "fred", "barney", "pebbles", "bambam", "dino", ],
  10448.         [ "homer", "bart", "marge", "maggie", ],
  10449.         [ "george", "jane", "alroy", "judy", ],
  10450.     ];
  10451.  
  10452.     print $listref[2][2];
  10453.  
  10454. The compiler would immediately flag that as an error at compile time, because 
  10455. you were accidentally accessing @listref, an undeclared variable, and it would 
  10456. thereby remind you to instead write: 
  10457.  
  10458.     print $listref->[2][2]
  10459.  
  10460. DEBUGGING 
  10461.  
  10462. The standard Perl debugger in 5.001 doesn't do a very nice job of printing out 
  10463. complex data structures.  However, the perl5db that Ilya Zakharevich 
  10464. <ilya@math.ohio-state.edu> wrote, which is accessible at 
  10465.  
  10466.     ftp://ftp.perl.com/pub/perl/ext/perl5db-kit-0.9.tar.gz
  10467.  
  10468. has several new features, including command line editing as well as the x 
  10469. command to dump out complex data structures.  For example, given the assignment 
  10470. to $LoL above, here's the debugger output: 
  10471.  
  10472.     DB<1> X $LoL
  10473.     $LoL = ARRAY(0x13b5a0)
  10474.        0  ARRAY(0x1f0a24)
  10475.           0  'fred'
  10476.           1  'barney'
  10477.           2  'pebbles'
  10478.           3  'bambam'
  10479.           4  'dino'
  10480.        1  ARRAY(0x13b558)
  10481.           0  'homer'
  10482.           1  'bart'
  10483.           2  'marge'
  10484.           3  'maggie'
  10485.        2  ARRAY(0x13b540)
  10486.           0  'george'
  10487.           1  'jane'
  10488.           2  'alroy'
  10489.           3  'judy'
  10490.  
  10491. There's also a lower-case x command which is nearly the same. 
  10492.  
  10493. CODE EXAMPLES 
  10494.  
  10495. Presented with little comment (these will get their own man pages someday) here 
  10496. are short code examples illustrating access of various types of data 
  10497. structures. 
  10498.  
  10499. LISTS OF LISTS 
  10500.  
  10501. Declaration of a LIST OF LISTS 
  10502.  
  10503.  @LoL = (
  10504.         [ "fred", "barney" ],
  10505.         [ "george", "jane", "elroy" ],
  10506.         [ "homer", "marge", "bart" ],
  10507.       );
  10508.  
  10509. Generation of a LIST OF LISTS 
  10510.  
  10511.  # reading from file
  10512.  while ( <> ) {
  10513.      push @LoL, [ split ];
  10514.  
  10515.  # calling a function
  10516.  for $i ( 1 .. 10 ) {
  10517.      $LoL[$i] = [ somefunc($i) ];
  10518.  
  10519.  # using temp vars
  10520.  for $i ( 1 .. 10 ) {
  10521.      @tmp = somefunc($i);
  10522.      $LoL[$i] = [ @tmp ];
  10523.  
  10524.  # add to an existing row
  10525.  push @{ $LoL[0] }, "wilma", "betty";
  10526.  
  10527. Access and Printing of a LIST OF LISTS 
  10528.  
  10529.  # one element
  10530.  $LoL[0][0] = "Fred";
  10531.  
  10532.  # another element
  10533.  $LoL[1][1] =~ s/(\w)/\u$1/;
  10534.  
  10535.  # print the whole thing with refs
  10536.  for $aref ( @LoL ) {
  10537.      print "\t [ @$aref ],\n";
  10538.  
  10539.  # print the whole thing with indices
  10540.  for $i ( 0 .. $#LoL ) {
  10541.      print "\t [ @{$LoL[$i]} ],\n";
  10542.  
  10543.  # print the whole thing one at a time
  10544.  for $i ( 0 .. $#LoL ) {
  10545.      for $j ( 0 .. $#{$LoL[$i]} ) {
  10546.          print "elt $i $j is $LoL[$i][$j]\n";
  10547.      }
  10548.  
  10549. HASHES OF LISTS 
  10550.  
  10551. Declaration of a HASH OF LISTS 
  10552.  
  10553.  %HoL = (
  10554.         "flintstones"        => [ "fred", "barney" ],
  10555.         "jetsons"            => [ "george", "jane", "elroy" ],
  10556.         "simpsons"           => [ "homer", "marge", "bart" ],
  10557.       );
  10558.  
  10559. Generation of a HASH OF LISTS 
  10560.  
  10561.  # reading from file
  10562.  # flintstones: fred barney wilma dino
  10563.  while ( <> ) {
  10564.      next unless s/^(.*?):\s*//;
  10565.      $HoL{$1} = [ split ];
  10566.  
  10567.  # reading from file; more temps
  10568.  # flintstones: fred barney wilma dino
  10569.  while ( $line = <> ) {
  10570.      ($who, $rest) = split /:\s*/, $line, 2;
  10571.      @fields = split ' ', $rest;
  10572.      $HoL{$who} = [ @fields ];
  10573.  
  10574.  # calling a function that returns a list
  10575.  for $group ( "simpsons", "jetsons", "flintstones" ) {
  10576.      $HoL{$group} = [ get_family($group) ];
  10577.  
  10578.  # likewise, but using temps
  10579.  for $group ( "simpsons", "jetsons", "flintstones" ) {
  10580.      @members = get_family($group);
  10581.      $HoL{$group} = [ @members ];
  10582.  
  10583.  # append new members to an existing family
  10584.  push @{ $HoL{"flintstones"} }, "wilma", "betty";
  10585.  
  10586. Access and Printing of a HASH OF LISTS 
  10587.  
  10588.  # one element
  10589.  $HoL{flintstones}[0] = "Fred";
  10590.  
  10591.  # another element
  10592.  $HoL{simpsons}[1] =~ s/(\w)/\u$1/;
  10593.  
  10594.  # print the whole thing
  10595.  foreach $family ( keys %HoL ) {
  10596.      print "$family: @{ $HoL{$family} }\n"
  10597.  
  10598.  # print the whole thing with indices
  10599.  foreach $family ( keys %HoL ) {
  10600.      print "family: ";
  10601.      foreach $i ( 0 .. $#{ $HoL{$family} ) {
  10602.          print " $i = $HoL{$family}[$i]";
  10603.      }
  10604.      print "\n";
  10605.  
  10606.  # print the whole thing sorted by number of members
  10607.  foreach $family ( sort { @{$HoL{$b}} <=> @{$HoL{$b}} } keys %HoL ) {
  10608.      print "$family: @{ $HoL{$family} }\n"
  10609.  
  10610.  # print the whole thing sorted by number of members and name
  10611.  foreach $family ( sort { @{$HoL{$b}} <=> @{$HoL{$a}} } keys %HoL ) {
  10612.      print "$family: ", join(", ", sort @{ $HoL{$family}), "\n";
  10613.  
  10614. LISTS OF HASHES 
  10615.  
  10616. Declaration of a LIST OF HASHES 
  10617.  
  10618.  @LoH = (
  10619.         {
  10620.            Lead      => "fred",
  10621.            Friend    => "barney",
  10622.         },
  10623.         {
  10624.             Lead     => "george",
  10625.             Wife     => "jane",
  10626.             Son      => "elroy",
  10627.         },
  10628.         {
  10629.             Lead     => "homer",
  10630.             Wife     => "marge",
  10631.             Son      => "bart",
  10632.         }
  10633.   );
  10634.  
  10635. Generation of a LIST OF HASHES 
  10636.  
  10637.  # reading from file
  10638.  # format: LEAD=fred FRIEND=barney
  10639.  while ( <> ) {
  10640.      $rec = {};
  10641.      for $field ( split ) {
  10642.          ($key, $value) = split /=/, $field;
  10643.          $rec->{$key} = $value;
  10644.      }
  10645.      push @LoH, $rec;
  10646.  
  10647.  # reading from file
  10648.  # format: LEAD=fred FRIEND=barney
  10649.  # no temp
  10650.  while ( <> ) {
  10651.      push @LoH, { split /[\s+=]/ };
  10652.  
  10653.  # calling a function  that returns a key,value list, like
  10654.  # "lead","fred","daughter","pebbles"
  10655.  while ( %fields = getnextpairset() )
  10656.      push @LoH, { %fields };
  10657.  
  10658.  # likewise, but using no temp vars
  10659.  while (<>) {
  10660.      push @LoH, { parsepairs($_) };
  10661.  
  10662.  # add key/value to an element
  10663.  $LoH[0]{"pet"} = "dino";
  10664.  $LoH[2]{"pet"} = "santa's little helper";
  10665.  
  10666. Access and Printing of a LIST OF HASHES 
  10667.  
  10668.  # one element
  10669.  $LoH[0]{"lead"} = "fred";
  10670.  
  10671.  # another element
  10672.  $LoH[1]{"lead"} =~ s/(\w)/\u$1/;
  10673.  
  10674.  # print the whole thing with refs
  10675.  for $href ( @LoH ) {
  10676.      print "{ ";
  10677.      for $role ( keys %$href ) {
  10678.          print "$role=$href->{$role} ";
  10679.      }
  10680.      print "}\n";
  10681.  
  10682.  # print the whole thing with indices
  10683.  for $i ( 0 .. $#LoH ) {
  10684.      print "$i is { ";
  10685.      for $role ( keys %{ $LoH[$i] } ) {
  10686.          print "$role=$LoH[$i]{$role} ";
  10687.      }
  10688.      print "}\n";
  10689.  
  10690.  # print the whole thing one at a time
  10691.  for $i ( 0 .. $#LoH ) {
  10692.      for $role ( keys %{ $LoH[$i] } ) {
  10693.          print "elt $i $role is $LoH[$i]{$role}\n";
  10694.      }
  10695.  
  10696. HASHES OF HASHES 
  10697.  
  10698. Declaration of a HASH OF HASHES 
  10699.  
  10700.  %HoH = (
  10701.         "flintstones" => {
  10702.             "lead"    => "fred",
  10703.             "pal"     => "barney",
  10704.         },
  10705.         "jetsons"     => {
  10706.              "lead"   => "george",
  10707.              "wife"   => "jane",
  10708.              "his boy"=> "elroy",
  10709.          }
  10710.         "simpsons"    => {
  10711.              "lead"   => "homer",
  10712.              "wife"   => "marge",
  10713.              "kid"    => "bart",
  10714.       );
  10715.  
  10716. Generation of a HASH OF HASHES 
  10717.  
  10718.  # reading from file
  10719.  # flintstones: lead=fred pal=barney wife=wilma pet=dino
  10720.  while ( <> ) {
  10721.      next unless s/^(.*?):\s*//;
  10722.      $who = $1;
  10723.      for $field ( split ) {
  10724.          ($key, $value) = split /=/, $field;
  10725.          $HoH{$who}{$key} = $value;
  10726.      }
  10727.  
  10728.  # reading from file; more temps
  10729.  while ( <> ) {
  10730.      next unless s/^(.*?):\s*//;
  10731.      $who = $1;
  10732.      $rec = {};
  10733.      $HoH{$who} = $rec;
  10734.      for $field ( split ) {
  10735.          ($key, $value) = split /=/, $field;
  10736.          $rec->{$key} = $value;
  10737.      }
  10738.  
  10739.  # calling a function  that returns a key,value list, like
  10740.  # "lead","fred","daughter","pebbles"
  10741.  while ( %fields = getnextpairset() )
  10742.      push @a, { %fields };
  10743.  
  10744.  # calling a function  that returns a key,value hash
  10745.  for $group ( "simpsons", "jetsons", "flintstones" ) {
  10746.      $HoH{$group} = { get_family($group) };
  10747.  
  10748.  # likewise, but using temps
  10749.  for $group ( "simpsons", "jetsons", "flintstones" ) {
  10750.      %members = get_family($group);
  10751.      $HoH{$group} = { %members };
  10752.  
  10753.  # append new members to an existing family
  10754.  %new_folks = (
  10755.      "wife" => "wilma",
  10756.      "pet"  => "dino";
  10757.  );
  10758.  for $what (keys %new_folks) {
  10759.      $HoH{flintstones}{$what} = $new_folks{$what};
  10760.  
  10761. Access and Printing of a HASH OF HASHES 
  10762.  
  10763.  # one element
  10764.  $HoH{"flintstones"}{"wife"} = "wilma";
  10765.  
  10766.  # another element
  10767.  $HoH{simpsons}{lead} =~ s/(\w)/\u$1/;
  10768.  
  10769.  # print the whole thing
  10770.  foreach $family ( keys %HoH ) {
  10771.      print "$family: ";
  10772.      for $role ( keys %{ $HoH{$family} } {
  10773.          print "$role=$HoH{$family}{$role} ";
  10774.      }
  10775.      print "}\n";
  10776.  
  10777.  # print the whole thing  somewhat sorted
  10778.  foreach $family ( sort keys %HoH ) {
  10779.      print "$family: ";
  10780.      for $role ( sort keys %{ $HoH{$family} } {
  10781.          print "$role=$HoH{$family}{$role} ";
  10782.      }
  10783.      print "}\n";
  10784.  
  10785.  # print the whole thing sorted by number of members
  10786.  foreach $family ( sort { keys %{$HoH{$b}} <=> keys %{$HoH{$b}} } keys %HoH ) {
  10787.      print "$family: ";
  10788.      for $role ( sort keys %{ $HoH{$family} } {
  10789.          print "$role=$HoH{$family}{$role} ";
  10790.      }
  10791.      print "}\n";
  10792.  
  10793.  # establish a sort order (rank) for each role
  10794.  $i = 0;
  10795.  for ( qw(lead wife son daughter pal pet) ) { $rank{$_} = ++$i }
  10796.  
  10797.  # now print the whole thing sorted by number of members
  10798.  foreach $family ( sort { keys %{$HoH{$b}} <=> keys %{$HoH{$b}} } keys %HoH ) {
  10799.      print "$family: ";
  10800.      # and print these according to rank order
  10801.      for $role ( sort { $rank{$a} <=> $rank{$b} keys %{ $HoH{$family} } {
  10802.          print "$role=$HoH{$family}{$role} ";
  10803.      }
  10804.      print "}\n";
  10805.  
  10806. MORE ELABORATE RECORDS 
  10807.  
  10808. Declaration of MORE ELABORATE RECORDS 
  10809.  
  10810. Here's a sample showing how to create and use a record whose fields are of many 
  10811. different sorts: 
  10812.  
  10813.      $rec = {
  10814.          STRING  => $string,
  10815.          LIST    => [ @old_values ],
  10816.          LOOKUP  => { %some_table },
  10817.          FUNC    => \&some_function,
  10818.          FANON   => sub { $_[0] ** $_[1] },
  10819.          FH      => \*STDOUT,
  10820.      };
  10821.  
  10822.      print $rec->{STRING};
  10823.  
  10824.      print $rec->{LIST}[0];
  10825.      $last = pop @ { $rec->{LIST} };
  10826.  
  10827.      print $rec->{LOOKUP}{"key"};
  10828.      ($first_k, $first_v) = each %{ $rec->{LOOKUP} };
  10829.  
  10830.      $answer = &{ $rec->{FUNC} }($arg);
  10831.      $answer = &{ $rec->{FANON} }($arg1, $arg2);
  10832.  
  10833.      # careful of extra block braces on fh ref
  10834.      print { $rec->{FH} } "a string\n";
  10835.  
  10836.      use FileHandle;
  10837.      $rec->{FH}->autoflush(1);
  10838.      $rec->{FH}->print(" a string\n");
  10839.  
  10840. Declaration of a HASH OF COMPLEX RECORDS 
  10841.  
  10842.      %TV = (
  10843.         "flintstones" => {
  10844.             series   => "flintstones",
  10845.             nights   => [ qw(monday thursday friday) ];
  10846.             members  => [
  10847.                 { name => "fred",    role => "lead", age  => 36, },
  10848.                 { name => "wilma",   role => "wife", age  => 31, },
  10849.                 { name => "pebbles", role => "kid", age  =>  4, },
  10850.             ],
  10851.         },
  10852.  
  10853.         "jetsons"     => {
  10854.             series   => "jetsons",
  10855.             nights   => [ qw(wednesday saturday) ];
  10856.             members  => [
  10857.                 { name => "george",  role => "lead", age  => 41, },
  10858.                 { name => "jane",    role => "wife", age  => 39, },
  10859.                 { name => "elroy",   role => "kid",  age  =>  9, },
  10860.             ],
  10861.          },
  10862.  
  10863.         "simpsons"    => {
  10864.             series   => "simpsons",
  10865.             nights   => [ qw(monday) ];
  10866.             members  => [
  10867.                 { name => "homer", role => "lead", age  => 34, },
  10868.                 { name => "marge", role => "wife", age => 37, },
  10869.                 { name => "bart",  role => "kid",  age  =>  11, },
  10870.             ],
  10871.          },
  10872.       );
  10873.  
  10874. Generation of a HASH OF COMPLEX RECORDS 
  10875.  
  10876.      # reading from file
  10877.      # this is most easily done by having the file itself be
  10878.      # in the raw data format as shown above.  perl is happy
  10879.      # to parse complex datastructures if declared as data, so
  10880.      # sometimes it's easiest to do that
  10881.  
  10882.      # here's a piece by piece build up
  10883.      $rec = {};
  10884.      $rec->{series} = "flintstones";
  10885.      $rec->{nights} = [ find_days() ];
  10886.  
  10887.      @members = ();
  10888.      # assume this file in field=value syntax
  10889.      while () {
  10890.          %fields = split /[\s=]+/;
  10891.          push @members, { %fields };
  10892.      }
  10893.      $rec->{members} = [ @members ];
  10894.  
  10895.      # now remember the whole thing
  10896.      $TV{ $rec->{series} } = $rec;
  10897.  
  10898.      ###########################################################
  10899.      # now, you might want to make interesting extra fields that
  10900.      # include pointers back into the same data structure so if
  10901.      # change one piece, it changes everywhere, like for examples
  10902.      # if you wanted a {kids} field that was an array reference
  10903.      # to a list of the kids' records without having duplicate
  10904.      # records and thus update problems.
  10905.      ###########################################################
  10906.      foreach $family (keys %TV) {
  10907.          $rec = $TV{$family}; # temp pointer
  10908.          @kids = ();
  10909.          for $person ( @{$rec->{members}} ) {
  10910.              if ($person->{role} =~ /kid|son|daughter/) {
  10911.                  push @kids, $person;
  10912.              }
  10913.          }
  10914.          # REMEMBER: $rec and $TV{$family} point to same data!!
  10915.          $rec->{kids} = [ @kids ];
  10916.      }
  10917.  
  10918.      # you copied the list, but the list itself contains pointers
  10919.      # to uncopied objects. this means that if you make bart get
  10920.      # older via
  10921.  
  10922.      $TV{simpsons}{kids}[0]{age}++;
  10923.  
  10924.      # then this would also change in
  10925.      print $TV{simpsons}{members}[2]{age};
  10926.  
  10927.      # because $TV{simpsons}{kids}[0] and $TV{simpsons}{members}[2]
  10928.      # both point to the same underlying anonymous hash table
  10929.  
  10930.      # print the whole thing
  10931.      foreach $family ( keys %TV ) {
  10932.          print "the $family";
  10933.          print " is on during @{ $TV{$family}{nights} }\n";
  10934.          print "its members are:\n";
  10935.          for $who ( @{ $TV{$family}{members} } ) {
  10936.              print " $who->{name} ($who->{role}), age $who->{age}\n";
  10937.          }
  10938.          print "it turns out that $TV{$family}{'lead'} has ";
  10939.          print scalar ( @{ $TV{$family}{kids} } ), " kids named ";
  10940.          print join (", ", map { $_->{name} } @{ $TV{$family}{kids} } );
  10941.          print "\n";
  10942.      }
  10943.  
  10944. Database Ties 
  10945.  
  10946. You cannot easily tie a multilevel data structure (such as a hash of hashes) to 
  10947. a dbm file.  The first problem is that all but GDBM and Berkeley DB have size 
  10948. limitations, but beyond that, you also have problems with how references are to 
  10949. be represented on disk.  One experimental module that does attempt to partially 
  10950. address this need is the MLDBM module.  Check your nearest CPAN site as 
  10951. described in perlmod for source code to MLDBM. 
  10952.  
  10953. SEE ALSO 
  10954.  
  10955. perlref, perllol, perldata, perlobj 
  10956.  
  10957. AUTHOR 
  10958.  
  10959. Tom Christiansen <tchrist@perl.com> 
  10960.  
  10961. Last update: Tue Dec 12 09:20:26 MST 1995 
  10962.  
  10963.  
  10964. ΓòÉΓòÉΓòÉ 18. Section - perllol ΓòÉΓòÉΓòÉ
  10965.  
  10966. NAME 
  10967.  
  10968. perlLoL - Manipulating Lists of Lists in Perl 
  10969.  
  10970. DESCRIPTION 
  10971.  
  10972. Declaration and Access of Lists of Lists 
  10973.  
  10974. The simplest thing to build is a list of lists (sometimes called an array of 
  10975. arrays).  It's reasonably easy to understand, and almost everything that 
  10976. applies here will also be applicable later on with the fancier data structures. 
  10977.  
  10978. A list of lists, or an array of an array if you would, is just a regular old 
  10979. array @LoL that you can get at with two subscripts, like $LoL[3][2].  Here's a 
  10980. declaration of the array: 
  10981.  
  10982.     # assign to our array a list of list references
  10983.     @LoL = (
  10984.            [ "fred", "barney" ],
  10985.            [ "george", "jane", "elroy" ],
  10986.            [ "homer", "marge", "bart" ],
  10987.     );
  10988.  
  10989.     print $LoL[2][2];
  10990.   bart
  10991.  
  10992. Now you should be very careful that the outer bracket type is a round one, that 
  10993. is, parentheses.  That's because you're assigning to an @list, so you need 
  10994. parens.  If you wanted there not to be an @LoL, but rather just a reference to 
  10995. it, you could do something more like this: 
  10996.  
  10997.     # assign a reference to list of list references
  10998.     $ref_to_LoL = [
  10999.         [ "fred", "barney", "pebbles", "bambam", "dino", ],
  11000.         [ "homer", "bart", "marge", "maggie", ],
  11001.         [ "george", "jane", "alroy", "judy", ],
  11002.     ];
  11003.  
  11004.     print $ref_to_LoL->[2][2];
  11005.  
  11006. Notice that the outer bracket type has changed, and so our access syntax has 
  11007. also changed.  That's because unlike C, in perl you can't freely interchange 
  11008. arrays and references thereto.  $ref_to_LoL is a reference to an array, whereas 
  11009. @LoL is an array proper.  Likewise, $LoL[2] is not an array, but an array ref. 
  11010. So how come you can write these: 
  11011.  
  11012.     $LoL[2][2]
  11013.     $ref_to_LoL->[2][2]
  11014.  
  11015. instead of having to write these: 
  11016.  
  11017.     $LoL[2]->[2]
  11018.     $ref_to_LoL->[2]->[2]
  11019.  
  11020. Well, that's because the rule is that on adjacent brackets only (whether square 
  11021. or curly), you are free to omit the pointer dereferencing array. But you need 
  11022. not do so for the very first one if it's a scalar containing a reference, which 
  11023. means that $ref_to_LoL always needs it. 
  11024.  
  11025. Growing Your Own 
  11026.  
  11027. That's all well and good for declaration of a fixed data structure, but what if 
  11028. you wanted to add new elements on the fly, or build it up entirely from 
  11029. scratch? 
  11030.  
  11031. First, let's look at reading it in from a file.  This is something like adding 
  11032. a row at a time.  We'll assume that there's a flat file in which each line is a 
  11033. row and each word an element.  If you're trying to develop an @LoL list 
  11034. containing all these, here's the right way to do that: 
  11035.  
  11036.     while (<>) {
  11037.         @tmp = split;
  11038.         push @LoL, [ @tmp ];
  11039.     }
  11040.  
  11041. You might also have loaded that from a function: 
  11042.  
  11043.     for $i ( 1 .. 10 ) {
  11044.         $LoL[$i] = [ somefunc($i) ];
  11045.     }
  11046.  
  11047. Or you might have had a temporary variable sitting around with the list in it. 
  11048.  
  11049.     for $i ( 1 .. 10 ) {
  11050.         @tmp = somefunc($i);
  11051.         $LoL[$i] = [ @tmp ];
  11052.     }
  11053.  
  11054. It's very important that you make sure to use the [] list reference 
  11055. constructor.  That's because this will be very wrong: 
  11056.  
  11057.     $LoL[$i] = @tmp;
  11058.  
  11059. You see, assigning a named list like that to a scalar just counts the number of 
  11060. elements in @tmp, which probably isn't what you want. 
  11061.  
  11062. If you are running under use strict, you'll have to add some declarations to 
  11063. make it happy: 
  11064.  
  11065.     use strict;
  11066.     my(@LoL, @tmp);
  11067.     while (<>) {
  11068.         @tmp = split;
  11069.         push @LoL, [ @tmp ];
  11070.     }
  11071.  
  11072. Of course, you don't need the temporary array to have a name at all: 
  11073.  
  11074.     while (<>) {
  11075.         push @LoL, [ split ];
  11076.     }
  11077.  
  11078. You also don't have to use push().  You could just make a direct assignment if 
  11079. you knew where you wanted to put it: 
  11080.  
  11081.     my (@LoL, $i, $line);
  11082.     for $i ( 0 .. 10 )
  11083.         $line = <>;
  11084.         $LoL[$i] = [ split ' ', $line ];
  11085.     }
  11086.  
  11087. or even just 
  11088.  
  11089.     my (@LoL, $i);
  11090.     for $i ( 0 .. 10 )
  11091.         $LoL[$i] = [ split ' ', <> ];
  11092.     }
  11093.  
  11094. You should in general be leary of using potential list functions in a scalar 
  11095. context without explicitly stating such. This would be clearer to the casual 
  11096. reader: 
  11097.  
  11098.     my (@LoL, $i);
  11099.     for $i ( 0 .. 10 )
  11100.         $LoL[$i] = [ split ' ', scalar(<>) ];
  11101.     }
  11102.  
  11103. If you wanted to have a $ref_to_LoL variable as a reference to an array, you'd 
  11104. have to do something like this: 
  11105.  
  11106.     while (<>) {
  11107.         push @$ref_to_LoL, [ split ];
  11108.     }
  11109.  
  11110. Actually, if you were using strict, you'd not only have to declare $ref_to_LoL 
  11111. as you had to declare @LoL, but you'd also having to initialize it to a 
  11112. reference to an empty list.  (This was a bug in 5.001m that's been fixed for 
  11113. the 5.002 release.) 
  11114.  
  11115.     my $ref_to_LoL = [];
  11116.     while (<>) {
  11117.         push @$ref_to_LoL, [ split ];
  11118.     }
  11119.  
  11120. Ok, now you can add new rows.  What about adding new columns?  If you're just 
  11121. dealing with matrices, it's often easiest to use simple assignment: 
  11122.  
  11123.     for $x (1 .. 10) {
  11124.         for $y (1 .. 10) {
  11125.             $LoL[$x][$y] = func($x, $y);
  11126.         }
  11127.     }
  11128.  
  11129.     for $x ( 3, 7, 9 ) {
  11130.         $LoL[$x][20] += func2($x);
  11131.     }
  11132.  
  11133. It doesn't matter whether those elements are already there or not: it'll gladly 
  11134. create them for you, setting intervening elements to undef as need be. 
  11135.  
  11136. If you just wanted to append to a row, you'd have to do something a bit funnier 
  11137. looking: 
  11138.  
  11139.     # add new columns to an existing row
  11140.     push @{ $LoL[0] }, "wilma", "betty";
  11141.  
  11142. Notice that I couldn't just say: 
  11143.  
  11144.     push $LoL[0], "wilma", "betty";  # WRONG!
  11145.  
  11146. In fact, that wouldn't even compile.  How come?  Because the argument to push() 
  11147. must be a real array, not just a reference to such. 
  11148.  
  11149. Access and Printing 
  11150.  
  11151. Now it's time to print your data structure out.  How are you going to do that? 
  11152. Well, if you only want one of the elements, it's trivial: 
  11153.  
  11154.     print $LoL[0][0];
  11155.  
  11156. If you want to print the whole thing, though, you can't just say 
  11157.  
  11158.     print @LoL;         # WRONG
  11159.  
  11160. because you'll just get references listed, and perl will never automatically 
  11161. dereference things for you.  Instead, you have to roll yourself a loop or two. 
  11162. This prints the whole structure, using the shell-style for() construct to loop 
  11163. across the outer set of subscripts. 
  11164.  
  11165.     for $aref ( @LoL ) {
  11166.         print "\t [ @$aref ],\n";
  11167.     }
  11168.  
  11169. If you wanted to keep track of subscripts, you might do this: 
  11170.  
  11171.     for $i ( 0 .. $#LoL ) {
  11172.         print "\t elt $i is [ @{$LoL[$i]} ],\n";
  11173.     }
  11174.  
  11175. or maybe even this.  Notice the inner loop. 
  11176.  
  11177.     for $i ( 0 .. $#LoL ) {
  11178.         for $j ( 0 .. $#{$LoL[$i]} ) {
  11179.             print "elt $i $j is $LoL[$i][$j]\n";
  11180.         }
  11181.     }
  11182.  
  11183. As you can see, it's getting a bit complicated.  That's why sometimes is easier 
  11184. to take a temporary on your way through: 
  11185.  
  11186.     for $i ( 0 .. $#LoL ) {
  11187.         $aref = $LoL[$i];
  11188.         for $j ( 0 .. $#{$aref} ) {
  11189.             print "elt $i $j is $LoL[$i][$j]\n";
  11190.         }
  11191.     }
  11192.  
  11193. Hm... that's still a bit ugly.  How about this: 
  11194.  
  11195.     for $i ( 0 .. $#LoL ) {
  11196.         $aref = $LoL[$i];
  11197.         $n = @$aref - 1;
  11198.         for $j ( 0 .. $n ) {
  11199.             print "elt $i $j is $LoL[$i][$j]\n";
  11200.         }
  11201.     }
  11202.  
  11203. Slices 
  11204.  
  11205. If you want to get at a slide (part of a row) in a multidimensional array, 
  11206. you're going to have to do some fancy subscripting.  That's because while we 
  11207. have a nice synonym for single elements via the pointer arrow for 
  11208. dereferencing, no such convenience exists for slices. (Remember, of course, 
  11209. that you can always write a loop to do a slice operation.) 
  11210.  
  11211. Here's how to do one operation using a loop.  We'll assume an @LoL variable as 
  11212. before. 
  11213.  
  11214.     @part = ();
  11215.     $x = 4;
  11216.     for ($y = 7; $y < 13; $y++) {
  11217.         push @part, $LoL[$x][$y];
  11218.     }
  11219.  
  11220. That same loop could be replaced with a slice operation: 
  11221.  
  11222.     @part = @{ $LoL[4] } [ 7..12 ];
  11223.  
  11224. but as you might well imagine, this is pretty rough on the reader. 
  11225.  
  11226. Ah, but what if you wanted a two-dimensional slice, such as having $x run from 
  11227. 4..8 and $y run from 7 to 12?  Hm... here's the simple way: 
  11228.  
  11229.     @newLoL = ();
  11230.     for ($startx = $x = 4; $x <= 8; $x++) {
  11231.         for ($starty = $y = 7; $x <= 12; $y++) {
  11232.             $newLoL[$x - $startx][$y - $starty] = $LoL[$x][$y];
  11233.         }
  11234.     }
  11235.  
  11236. We can reduce some of the looping through slices 
  11237.  
  11238.     for ($x = 4; $x <= 8; $x++) {
  11239.         push @newLoL, [ @{ $LoL[$x] } [ 7..12 ] ];
  11240.     }
  11241.  
  11242. If you were into Schwartzian Transforms, you would probably have selected map 
  11243. for that 
  11244.  
  11245.     @newLoL = map { [ @{ $LoL[$_] } [ 7..12 ] ] } 4 .. 8;
  11246.  
  11247. Although if your manager accused of seeking job security (or rapid insecurity) 
  11248. through inscrutable code, it would be hard to argue. :-) If I were you, I'd put 
  11249. that in a function: 
  11250.  
  11251.     @newLoL = splice_2D( \@LoL, 4 => 8, 7 => 12 );
  11252.     sub splice_2D {
  11253.         my $lrr = shift;        # ref to list of list refs!
  11254.         my ($x_lo, $x_hi,
  11255.             $y_lo, $y_hi) = @_;
  11256.  
  11257.         return map {
  11258.             [ @{ $lrr->[$_] } [ $y_lo .. $y_hi ] ]
  11259.         } $x_lo .. $x_hi;
  11260.     }
  11261.  
  11262. SEE ALSO 
  11263.  
  11264. perldata(1), perlref(1), perldsc(1) 
  11265.  
  11266. AUTHOR 
  11267.  
  11268. Tom Christiansen <tchrist@perl.com> 
  11269.  
  11270. Last udpate: Sat Oct  7 19:35:26 MDT 1995 
  11271.  
  11272.  
  11273. ΓòÉΓòÉΓòÉ 19. Section - perlobj ΓòÉΓòÉΓòÉ
  11274.  
  11275. NAME 
  11276.  
  11277. perlobj - Perl objects 
  11278.  
  11279. DESCRIPTION 
  11280.  
  11281. First of all, you need to understand what references are in Perl.  See perlref 
  11282. for that. 
  11283.  
  11284. Here are three very simple definitions that you should find reassuring. 
  11285.  
  11286.    1. An object is simply a reference that happens to know which class it 
  11287.       belongs to. 
  11288.  
  11289.    2. A class is simply a package that happens to provide methods to deal with 
  11290.       object references. 
  11291.  
  11292.    3. A method is simply a subroutine that expects an object reference (or a 
  11293.       package name, for static methods) as the first argument. 
  11294.  
  11295.  We'll cover these points now in more depth. 
  11296.  
  11297.  An Object is Simply a Reference 
  11298.  
  11299.  Unlike say C++, Perl doesn't provide any special syntax for constructors.  A 
  11300.  constructor is merely a subroutine that returns a reference to something 
  11301.  "blessed" into a class, generally the class that the subroutine is defined in. 
  11302.  Here is a typical constructor: 
  11303.  
  11304.       package Critter;
  11305.       sub new { bless {} }
  11306.  
  11307.  The {} constructs a reference to an anonymous hash containing no key/value 
  11308.  pairs.  The bless() takes that reference and tells the object it references 
  11309.  that it's now a Critter, and returns the reference. This is for convenience, 
  11310.  since the referenced object itself knows that it has been blessed, and its 
  11311.  reference to it could have been returned directly, like this: 
  11312.  
  11313.       sub new {
  11314.           my $self = {};
  11315.           bless $self;
  11316.           return $self;
  11317.       }
  11318.  
  11319.  In fact, you often see such a thing in more complicated constructors that wish 
  11320.  to call methods in the class as part of the construction: 
  11321.  
  11322.       sub new {
  11323.           my $self = {}
  11324.           bless $self;
  11325.           $self->initialize();
  11326.           return $self;
  11327.       }
  11328.  
  11329.  If you care about inheritance (and you should; see L<perlmod/"Modules: 
  11330.  Creation, Use and Abuse">), then you want to use the two-arg form of bless so 
  11331.  that your constructors may be inherited: 
  11332.  
  11333.       sub new {
  11334.           my $class = shift;
  11335.           my $self = {};
  11336.           bless $self, $class
  11337.           $self->initialize();
  11338.           return $self;
  11339.       }
  11340.  
  11341.  Or if you expect people to call not just CLASS-new()> but also $obj-new()>, 
  11342.  then use something like this.  The initialize() method used will be of 
  11343.  whatever $class we blessed the object into: 
  11344.  
  11345.       sub new {
  11346.           my $this = shift;
  11347.           my $class = ref($this) || $this;
  11348.           my $self = {};
  11349.           bless $self, $class
  11350.           $self->initialize();
  11351.           return $self;
  11352.       }
  11353.  
  11354.  Within the class package, the methods will typically deal with the reference 
  11355.  as an ordinary reference.  Outside the class package, the reference is 
  11356.  generally treated as an opaque value that may only be accessed through the 
  11357.  class's methods. 
  11358.  
  11359.  A constructor may re-bless a referenced object currently belonging to another 
  11360.  class, but then the new class is responsible for all cleanup later.  The 
  11361.  previous blessing is forgotten, as an object may only belong to one class at a 
  11362.  time.  (Although of course it's free to inherit methods from many classes.) 
  11363.  
  11364.  A clarification:  Perl objects are blessed.  References are not.  Objects know 
  11365.  which package they belong to.  References do not.  The bless() function simply 
  11366.  uses the reference in order to find the object.  Consider the following 
  11367.  example: 
  11368.  
  11369.       $a = {};
  11370.       $b = $a;
  11371.       bless $a, BLAH;
  11372.       print "\$b is a ", ref($b), "\n";
  11373.  
  11374.  This reports $b as being a BLAH, so obviously bless() operated on the object 
  11375.  and not on the reference. 
  11376.  
  11377.  A Class is Simply a Package 
  11378.  
  11379.  Unlike say C++, Perl doesn't provide any special syntax for class definitions. 
  11380.  You just use a package as a class by putting method definitions into the 
  11381.  class. 
  11382.  
  11383.  There is a special array within each package called @ISA which says where else 
  11384.  to look for a method if you can't find it in the current package.  This is how 
  11385.  Perl implements inheritance.  Each element of the @ISA array is just the name 
  11386.  of another package that happens to be a class package.  The classes are 
  11387.  searched (depth first) for missing methods in the order that they occur in 
  11388.  @ISA.  The classes accessible through @ISA are known as base classes of the 
  11389.  current class. 
  11390.  
  11391.  If a missing method is found in one of the base classes, it is cached in the 
  11392.  current class for efficiency.  Changing @ISA or defining new subroutines 
  11393.  invalidates the cache and causes Perl to do the lookup again. 
  11394.  
  11395.  If a method isn't found, but an AUTOLOAD routine is found, then that is called 
  11396.  on behalf of the missing method. 
  11397.  
  11398.  If neither a method nor an AUTOLOAD routine is found in @ISA, then one last 
  11399.  try is made for the method (or an AUTOLOAD routine) in a class called 
  11400.  UNIVERSAL.  If that doesn't work, Perl finally gives up and complains. 
  11401.  
  11402.  Perl classes only do method inheritance.  Data inheritance is left up to the 
  11403.  class itself.  By and large, this is not a problem in Perl, because most 
  11404.  classes model the attributes of their object using an anonymous hash, which 
  11405.  serves as its own little namespace to be carved up by the various classes that 
  11406.  might want to do something with the object. 
  11407.  
  11408.  A Method is Simply a Subroutine 
  11409.  
  11410.  Unlike say C++, Perl doesn't provide any special syntax for method definition. 
  11411.  (It does provide a little syntax for method invocation though.  More on that 
  11412.  later.)  A method expects its first argument to be the object or package it is 
  11413.  being invoked on.  There are just two types of methods, which we'll call 
  11414.  static and virtual, in honor of the two C++ method types they most closely 
  11415.  resemble. 
  11416.  
  11417.  A static method expects a class name as the first argument.  It provides 
  11418.  functionality for the class as a whole, not for any individual object 
  11419.  belonging to the class.  Constructors are typically static methods.  Many 
  11420.  static methods simply ignore their first argument, since they already know 
  11421.  what package they're in, and don't care what package they were invoked via. 
  11422.  (These aren't necessarily the same, since static methods follow the 
  11423.  inheritance tree just like ordinary virtual methods.)  Another typical use for 
  11424.  static methods is to look up an object by name: 
  11425.  
  11426.       sub find {
  11427.           my ($class, $name) = @_;
  11428.           $objtable{$name};
  11429.       }
  11430.  
  11431.  A virtual method expects an object reference as its first argument. Typically 
  11432.  it shifts the first argument into a "self" or "this" variable, and then uses 
  11433.  that as an ordinary reference. 
  11434.  
  11435.       sub display {
  11436.           my $self = shift;
  11437.           my @keys = @_ ? @_ : sort keys %$self;
  11438.           foreach $key (@keys) {
  11439.               print "\t$key => $self->{$key}\n";
  11440.           }
  11441.       }
  11442.  
  11443.  Method Invocation 
  11444.  
  11445.  There are two ways to invoke a method, one of which you're already familiar 
  11446.  with, and the other of which will look familiar.  Perl 4 already had an 
  11447.  "indirect object" syntax that you use when you say 
  11448.  
  11449.       print STDERR "help!!!\n";
  11450.  
  11451.  This same syntax can be used to call either static or virtual methods. We'll 
  11452.  use the two methods defined above, the static method to lookup an object 
  11453.  reference and the virtual method to print out its attributes. 
  11454.  
  11455.       $fred = find Critter "Fred";
  11456.       display $fred 'Height', 'Weight';
  11457.  
  11458.  These could be combined into one statement by using a BLOCK in the indirect 
  11459.  object slot: 
  11460.  
  11461.       display {find Critter "Fred"} 'Height', 'Weight';
  11462.  
  11463.  For C++ fans, there's also a syntax using -> notation that does exactly the 
  11464.  same thing.  The parentheses are required if there are any arguments. 
  11465.  
  11466.       $fred = Critter->find("Fred");
  11467.       $fred->display('Height', 'Weight');
  11468.  
  11469.  or in one statement, 
  11470.  
  11471.       Critter->find("Fred")->display('Height', 'Weight');
  11472.  
  11473.  There are times when one syntax is more readable, and times when the other 
  11474.  syntax is more readable.  The indirect object syntax is less cluttered, but it 
  11475.  has the same ambiguity as ordinary list operators. Indirect object method 
  11476.  calls are parsed using the same rule as list operators: "If it looks like a 
  11477.  function, it is a function".  (Presuming for the moment that you think two 
  11478.  words in a row can look like a function name.  C++ programmers seem to think 
  11479.  so with some regularity, especially when the first word is "new".)  Thus, the 
  11480.  parens of 
  11481.  
  11482.       new Critter ('Barney', 1.5, 70)
  11483.  
  11484.  are assumed to surround ALL the arguments of the method call, regardless of 
  11485.  what comes after.  Saying 
  11486.  
  11487.       new Critter ('Bam' x 2), 1.4, 45
  11488.  
  11489.  would be equivalent to 
  11490.  
  11491.       Critter->new('Bam' x 2), 1.4, 45
  11492.  
  11493.  which is unlikely to do what you want. 
  11494.  
  11495.  There are times when you wish to specify which class's method to use. In this 
  11496.  case, you can call your method as an ordinary subroutine call, being sure to 
  11497.  pass the requisite first argument explicitly: 
  11498.  
  11499.       $fred =  MyCritter::find("Critter", "Fred");
  11500.       MyCritter::display($fred, 'Height', 'Weight');
  11501.  
  11502.  Note however, that this does not do any inheritance.  If you merely wish to 
  11503.  specify that Perl should START looking for a method in a particular package, 
  11504.  use an ordinary method call, but qualify the method name with the package like 
  11505.  this: 
  11506.  
  11507.       $fred = Critter->MyCritter::find("Fred");
  11508.       $fred->MyCritter::display('Height', 'Weight');
  11509.  
  11510.  If you're trying to control where the method search begins and you're 
  11511.  executing in the class itself, then you may use the SUPER pseudoclass, which 
  11512.  says to start looking in your base class's @ISA list without having to 
  11513.  explicitly name it: 
  11514.  
  11515.       $self->SUPER::display('Height', 'Weight');
  11516.  
  11517.  Please note that the SUPER:: construct is only meaningful within the class. 
  11518.  
  11519.  Sometimes you want to call a method when you don't know the method name ahead 
  11520.  of time.  You can use the arrow form, replacing the method name with a simple 
  11521.  scalar variable containing the method name: 
  11522.  
  11523.       $method = $fast ? "findfirst" : "findbest";
  11524.       $fred->$method(@args);
  11525.  
  11526.  Destructors 
  11527.  
  11528.  When the last reference to an object goes away, the object is automatically 
  11529.  destroyed.  (This may even be after you exit, if you've stored references in 
  11530.  global variables.)  If you want to capture control just before the object is 
  11531.  freed, you may define a DESTROY method in your class.  It will automatically 
  11532.  be called at the appropriate moment, and you can do any extra cleanup you need 
  11533.  to do. 
  11534.  
  11535.  Perl doesn't do nested destruction for you.  If your constructor reblessed a 
  11536.  reference from one of your base classes, your DESTROY may need to call DESTROY 
  11537.  for any base classes that need it.  But this only applies to reblessed 
  11538.  objects--an object reference that is merely CONTAINED in the current object 
  11539.  will be freed and destroyed automatically when the current object is freed. 
  11540.  
  11541.  WARNING 
  11542.  
  11543.  An indirect object is limited to a name, a scalar variable, or a block, 
  11544.  because it would have to do too much lookahead otherwise, just like any other 
  11545.  postfix dereference in the language.  The left side of -> is not so limited, 
  11546.  because it's an infix operator, not a postfix operator. 
  11547.  
  11548.  That means that below, A and B are equivalent to each other, and C and D are 
  11549.  equivalent, but AB and CD are different: 
  11550.  
  11551.       A: method $obref->{"fieldname"}
  11552.       B: (method $obref)->{"fieldname"}
  11553.       C: $obref->{"fieldname"}->method()
  11554.       D: method {$obref->{"fieldname"}}
  11555.  
  11556.  Summary 
  11557.  
  11558.  That's about all there is to it.  Now you just need to go off and buy a book 
  11559.  about object-oriented design methodology, and bang your forehead with it for 
  11560.  the next six months or so. 
  11561.  
  11562.  Two-Phased Garbage Collection 
  11563.  
  11564.  For most purposes, Perl uses a fast and simple reference-based garbage 
  11565.  collection system.  For this reason, there's an extra dereference going on at 
  11566.  some level, so if you haven't built your Perl executable using your C 
  11567.  compiler's -O flag, performance will suffer.  If you have built Perl with cc 
  11568.  -O, then this probably won't matter. 
  11569.  
  11570.  A more serious concern is that unreachable memory with a non-zero reference 
  11571.  count will not normally get freed.  Therefore, this is a bad idea: 
  11572.  
  11573.       {
  11574.           my $a;
  11575.           $a = \$a;
  11576.       }
  11577.  
  11578.  Even thought $a should go away, it can't.  When building recursive data 
  11579.  structures, you'll have to break the self-reference yourself explicitly if you 
  11580.  don't care to leak.  For example, here's a self-referential node such as one 
  11581.  might use in a sophisticated tree structure: 
  11582.  
  11583.       sub new_node {
  11584.           my $self = shift;
  11585.           my $class = ref($self) || $self;
  11586.           my $node = {};
  11587.           $node->{LEFT} = $node->{RIGHT} = $node;
  11588.           $node->{DATA} = [ @_ ];
  11589.           return bless $node => $class;
  11590.       }
  11591.  
  11592.  If you create nodes like that, they (currently) won't go away unless you break 
  11593.  their self reference yourself.  (In other words, this is not to be construed 
  11594.  as a feature, and you shouldn't depend on it.) 
  11595.  
  11596.  Almost. 
  11597.  
  11598.  When an interpreter thread finally shuts down (usually when your program 
  11599.  exits), then a rather costly but complete mark-and-sweep style of garbage 
  11600.  collection is performed, and everything allocated by that thread gets 
  11601.  destroyed.  This is essential to support Perl as an embedded or a 
  11602.  multithreadable language.  For example, this program demonstrates Perl's 
  11603.  two-phased garbage collection: 
  11604.  
  11605.       #!/usr/bin/perl
  11606.       package Subtle;
  11607.  
  11608.       sub new {
  11609.           my $test;
  11610.           $test = \$test;
  11611.           warn "CREATING " . \$test;
  11612.           return bless \$test;
  11613.       }
  11614.  
  11615.       sub DESTROY {
  11616.           my $self = shift;
  11617.           warn "DESTROYING $self";
  11618.       }
  11619.  
  11620.       package main;
  11621.  
  11622.       warn "starting program";
  11623.       {
  11624.           my $a = Subtle->new;
  11625.           my $b = Subtle->new;
  11626.           $$a = 0;  # break selfref
  11627.           warn "leaving block";
  11628.       }
  11629.  
  11630.       warn "just exited block";
  11631.       warn "time to die...";
  11632.       exit;
  11633.  
  11634.  When run as /tmp/test, the following output is produced: 
  11635.  
  11636.       starting program at /tmp/test line 18.
  11637.       CREATING SCALAR(0x8e5b8) at /tmp/test line 7.
  11638.       CREATING SCALAR(0x8e57c) at /tmp/test line 7.
  11639.       leaving block at /tmp/test line 23.
  11640.       DESTROYING Subtle=SCALAR(0x8e5b8) at /tmp/test line 13.
  11641.       just exited block at /tmp/test line 26.
  11642.       time to die... at /tmp/test line 27.
  11643.       DESTROYING Subtle=SCALAR(0x8e57c) during global destruction.
  11644.  
  11645.  Notice that "global destruction" bit there?  That's the thread garbage 
  11646.  collector reaching the unreachable. 
  11647.  
  11648.  Objects are always destructed, even when regular refs aren't and in fact are 
  11649.  destructed in a separate pass before ordinary refs just to try to prevent 
  11650.  object destructors from using refs that have been themselves destructed. 
  11651.  Plain refs are only garbage collected if the destruct level is greater than 0. 
  11652.  You can test the higher levels of global destruction by setting the 
  11653.  PERL_DESTRUCT_LEVEL environment variable, presuming -DDEBUGGING was enabled 
  11654.  during perl build time. 
  11655.  
  11656.  A more complete garbage collection strategy will be implemented at a future 
  11657.  date. 
  11658.  
  11659.  SEE ALSO 
  11660.  
  11661.  You should also check out perlbot for other object tricks, traps, and tips, as 
  11662.  well as perlmod for some style guides on constructing both modules and 
  11663.  classes. 
  11664.  
  11665.  
  11666. ΓòÉΓòÉΓòÉ 20. Section - perltie ΓòÉΓòÉΓòÉ
  11667.  
  11668. NAME 
  11669.  
  11670. perltie - how to hide an object class in a simple variable 
  11671.  
  11672. SYNOPSIS 
  11673.  
  11674.  tie VARIABLE, CLASSNAME, LIST
  11675.  
  11676.  untie VARIABLE
  11677.  
  11678. DESCRIPTION 
  11679.  
  11680. Prior to release 5.0 of Perl, a programmer could use dbmopen() to magically 
  11681. connect an on-disk database in the standard Unix dbm(3x) format to a %HASH in 
  11682. their program.  However, their Perl was either built with one particular dbm 
  11683. library or another, but not both, and you couldn't extend this mechanism to 
  11684. other packages or types of variables. 
  11685.  
  11686. Now you can. 
  11687.  
  11688. The tie() function binds a variable to a class (package) that will provide the 
  11689. implementation for access methods for that variable.  Once this magic has been 
  11690. performed, accessing a tied variable automatically triggers method calls in the 
  11691. proper class.  All of the complexity of the class is hidden behind magic 
  11692. methods calls.  The method names are in ALL CAPS, which is a convention that 
  11693. Perl uses to indicate that they're called implicitly rather than 
  11694. explicitly--just like the BEGIN() and END() functions. 
  11695.  
  11696. In the tie() call, VARIABLE is the name of the variable to be enchanted. 
  11697. CLASSNAME is the name of a class implementing objects of the correct type.  Any 
  11698. additional arguments in the LIST are passed to the appropriate constructor 
  11699. method for that class--meaning TIESCALAR(), TIEARRAY(), or TIEHASH(). 
  11700. (Typically these are arguments such as might be passed to the dbminit() 
  11701. function of C.) The object returned by the "new" method is also returned by the 
  11702. tie() function, which would be useful if you wanted to access other methods in 
  11703. CLASSNAME. (You don't actually have to return a reference to a right "type" 
  11704. (e.g. HASH or CLASSNAME) so long as it's a properly blessed object.) 
  11705.  
  11706. Unlike dbmopen(), the tie() function will not use or require a module for 
  11707. you--you need to do that explicitly yourself. 
  11708.  
  11709. Tying Scalars 
  11710.  
  11711. A class implementing a tied scalar should define the following methods: 
  11712. TIESCALAR, FETCH, STORE, and possibly DESTROY. 
  11713.  
  11714. Let's look at each in turn, using as an example a tie class for scalars that 
  11715. allows the user to do something like: 
  11716.  
  11717.     tie $his_speed, 'Nice', getppid();
  11718.     tie $my_speed,  'Nice', $$;
  11719.  
  11720. And now whenever either of those variables is accessed, its current system 
  11721. priority is retrieved and returned.  If those variables are set, then the 
  11722. process's priority is changed! 
  11723.  
  11724. We'll use Jarkko Hietaniemi <Jarkko.Hietaniemi@hut.fi>'s BSD::Resource class 
  11725. (not included) to access the PRIO_PROCESS, PRIO_MIN, and PRIO_MAX constants 
  11726. from your system, as well as the getpriority() and setpriority() system calls. 
  11727. Here's the preamble of the class. 
  11728.  
  11729.     package Nice;
  11730.     use Carp;
  11731.     use BSD::Resource;
  11732.     use strict;
  11733.     $Nice::DEBUG = 0 unless defined $Nice::DEBUG;
  11734.  
  11735. TIESCALAR classname, LIST 
  11736.  
  11737. This is the constructor for the class.  That means it is expected to return a 
  11738. blessed reference to a new scalar (probably anonymous) that it's creating.  For 
  11739. example: 
  11740.  
  11741.     sub TIESCALAR {
  11742.         my $class = shift;
  11743.         my $pid = shift || $$; # 0 means me
  11744.  
  11745.         if ($pid !~ /^\d+$/) {
  11746.             carp "Nice::TieScalar got non-numeric pid $pid" if $^W;
  11747.             return undef;
  11748.         }
  11749.  
  11750.         unless (kill 0, $pid) { # EPERM or ERSCH, no doubt
  11751.             carp "Nice::TieScalar got bad pid $pid: $!" if $^W;
  11752.             return undef;
  11753.         }
  11754.  
  11755.         return bless \$pid, $class;
  11756.     }
  11757.  
  11758. This tie class has chosen to return an error rather than raising an exception 
  11759. if its constructor should fail.  While this is how dbmopen() works, other 
  11760. classes may well not wish to be so forgiving.  It checks the global variable 
  11761. $^W to see whether to emit a bit of noise anyway. 
  11762.  
  11763. FETCH this 
  11764.  
  11765. This method will be triggered every time the tied variable is accessed (read). 
  11766. It takes no arguments beyond its self reference, which is the object 
  11767. representing the scalar we're dealing with.  Since in this case we're just 
  11768. using a SCALAR ref for the tied scalar object, a simple $$self allows the 
  11769. method to get at the real value stored there.  In our example below, that real 
  11770. value is the process ID to which we've tied our variable. 
  11771.  
  11772.     sub FETCH {
  11773.         my $self = shift;
  11774.         confess "wrong type" unless ref $self;
  11775.         croak "usage error" if @_;
  11776.         my $nicety;
  11777.         local($!) = 0;
  11778.         $nicety = getpriority(PRIO_PROCESS, $$self);
  11779.         if ($!) { croak "getpriority failed: $!" }
  11780.         return $nicety;
  11781.     }
  11782.  
  11783. This time we've decided to blow up (raise an exception) if the renice 
  11784. fails--there's no place for us to return an error otherwise, and it's probably 
  11785. the right thing to do. 
  11786.  
  11787. STORE this, value 
  11788.  
  11789. This method will be triggered every time the tied variable is set (assigned). 
  11790. Beyond its self reference, it also expects one (and only one) argument--the new 
  11791. value the user is trying to assign. 
  11792.  
  11793.     sub STORE {
  11794.         my $self = shift;
  11795.         confess "wrong type" unless ref $self;
  11796.         my $new_nicety = shift;
  11797.         croak "usage error" if @_;
  11798.  
  11799.         if ($new_nicety < PRIO_MIN) {
  11800.             carp sprintf
  11801.               "WARNING: priority %d less than minimum system priority %d",
  11802.                   $new_nicety, PRIO_MIN if $^W;
  11803.             $new_nicety = PRIO_MIN;
  11804.         }
  11805.  
  11806.         if ($new_nicety > PRIO_MAX) {
  11807.             carp sprintf
  11808.               "WARNING: priority %d greater than maximum system priority %d",
  11809.                   $new_nicety, PRIO_MAX if $^W;
  11810.             $new_nicety = PRIO_MAX;
  11811.         }
  11812.  
  11813.         unless (defined setpriority(PRIO_PROCESS, $$self, $new_nicety)) {
  11814.             confess "setpriority failed: $!";
  11815.         }
  11816.         return $new_nicety;
  11817.     }
  11818.  
  11819. DESTROY this 
  11820.  
  11821. This method will be triggered when the tied variable needs to be destructed. As 
  11822. with other object classes, such a method is seldom ncessary, since Perl 
  11823. deallocates its moribund object's memory for you automatically--this isn't C++, 
  11824. you know.  We'll use a DESTROY method here for debugging purposes only. 
  11825.  
  11826.     sub DESTROY {
  11827.         my $self = shift;
  11828.         confess "wrong type" unless ref $self;
  11829.         carp "[ Nice::DESTROY pid $$self ]" if $Nice::DEBUG;
  11830.     }
  11831.  
  11832. That's about all there is to it.  Actually, it's more than all there is to it, 
  11833. since we've done a few nice things here for the sake of completeness, 
  11834. robustness, and general aesthetics.  Simpler TIESCALAR classes are certainly 
  11835. possible. 
  11836.  
  11837. Tying Arrays 
  11838.  
  11839. A class implementing a tied ordinary array should define the following methods: 
  11840. TIEARRAY, FETCH, STORE, and perhaps DESTROY. 
  11841.  
  11842. WARNING: Tied arrays are incomplete.  They are also distinctly lacking 
  11843. something for the $#ARRAY access (which is hard, as it's an lvalue), as well as 
  11844. the other obvious array functions, like push(), pop(), shift(), unshift(), and 
  11845. splice(). 
  11846.  
  11847. For this discussion, we'll implement an array whose indices are fixed at its 
  11848. creation.  If you try to access anything beyond those bounds, you'll take an 
  11849. exception.  (Well, if you access an individual element; an aggregate assignment 
  11850. would be missed.) For example: 
  11851.  
  11852.     require Bounded_Array;
  11853.     tie @ary, Bounded_Array, 2;
  11854.     $| = 1;
  11855.     for $i (0 .. 10) {
  11856.         print "setting index $i: ";
  11857.         $ary[$i] = 10 * $i;
  11858.         $ary[$i] = 10 * $i;
  11859.         print "value of elt $i now $ary[$i]\n";
  11860.     }
  11861.  
  11862. The preamble code for the class is as follows: 
  11863.  
  11864.     package Bounded_Array;
  11865.     use Carp;
  11866.     use strict;
  11867.  
  11868. TIEARRAY classname, LIST 
  11869.  
  11870. This is the constructor for the class.  That means it is expected to return a 
  11871. blessed reference through which the new array (probably an anonymous ARRAY ref) 
  11872. will be accessed. In our example, just to show you that you don't really have 
  11873. to return an ARRAY reference, we'll choose a HASH reference to represent our 
  11874. object. A HASH works out well as a generic record type: the {BOUND} field will 
  11875. store the maximum bound allowed, and the C<{ARRAY} field will hold the true 
  11876. ARRAY ref.  If someone outside the class tries to dereference the object 
  11877. returned (doubtless thinking it an ARRAY ref), they'll blow up. This just goes 
  11878. to show you that you should respect an object's privacy. 
  11879.  
  11880.     sub TIEARRAY {
  11881.         my $class = shift;
  11882.         my $bound = shift;
  11883.         confess "usage: tie(\@ary, 'Bounded_Array', max_subscript)"
  11884.             if @_ || $bound =~ /\D/;
  11885.         return bless {
  11886.             BOUND => $bound,
  11887.             ARRAY => [],
  11888.         }, $class;
  11889.     }
  11890.  
  11891. FETCH this, index 
  11892.  
  11893. This method will be triggered every time an individual element the tied array 
  11894. is accessed (read).  It takes one argument beyond its self reference: the index 
  11895. whose value we're trying to fetch. 
  11896.  
  11897.     sub FETCH {
  11898.       my($self,$idx) = @_;
  11899.       if ($idx > $self->{BOUND}) {
  11900.         confess "Array OOB: $idx > $self->{BOUND}";
  11901.       }
  11902.       return $self->{ARRAY}[$idx];
  11903.     }
  11904.  
  11905. As you may have noticed, the name of the FETCH method (et al.) is the same for 
  11906. all accesses, even though the constructors differ in names (TIESCALAR vs 
  11907. TIEARRAY).  While in theory you could have the same class servicing several 
  11908. tied types, in practice this becomes cumbersome, and it's easiest to simply 
  11909. keep them at one tie type per class. 
  11910.  
  11911. STORE this, index, value 
  11912.  
  11913. This method will be triggered every time an element in the tied array is set 
  11914. (written).  It takes two arguments beyond its self reference: the index at 
  11915. which we're trying to store something and the value we're trying to put there. 
  11916. For example: 
  11917.  
  11918.     sub STORE {
  11919.       my($self, $idx, $value) = @_;
  11920.       print "[STORE $value at $idx]\n" if _debug;
  11921.       if ($idx > $self->{BOUND} ) {
  11922.         confess "Array OOB: $idx > $self->{BOUND}";
  11923.       }
  11924.       return $self->{ARRAY}[$idx] = $value;
  11925.     }
  11926.  
  11927. DESTROY this 
  11928.  
  11929. This method will be triggered when the tied variable needs to be destructed. As 
  11930. with the sclar tie class, this is almost never needed in a language that does 
  11931. its own garbage collection, so this time we'll just leave it out. 
  11932.  
  11933. The code we presented at the top of the tied array class accesses many elements 
  11934. of the array, far more than we've set the bounds to.  Therefore, it will blow 
  11935. up once they try to access beyond the 2nd element of @ary, as the following 
  11936. output demonstrates: 
  11937.  
  11938.     setting index 0: value of elt 0 now 0
  11939.     setting index 1: value of elt 1 now 10
  11940.     setting index 2: value of elt 2 now 20
  11941.     setting index 3: Array OOB: 3 > 2 at Bounded_Array.pm line 39
  11942.             Bounded_Array::FETCH called at testba line 12
  11943.  
  11944. Tying Hashes 
  11945.  
  11946. As the first Perl data type to be tied (see dbmopen()), associative arrays have 
  11947. the most complete and useful tie() implementation.  A class implementing a tied 
  11948. associative array should define the following methods:  TIEHASH is the 
  11949. constructor.  FETCH and STORE access the key and value pairs.  EXISTS reports 
  11950. whether a key is present in the hash, and DELETE deletes one.  CLEAR empties 
  11951. the hash by deleting all the key and value pairs.  FIRSTKEY and NEXTKEY 
  11952. implement the keys() and each() functions to iterate over all the keys.  And 
  11953. DESTROY is called when the tied variable is garbage collected. 
  11954.  
  11955. If this seems like a lot, then feel free to merely inherit from the standard 
  11956. TieHash module for most of your methods, redefining only the interesting ones. 
  11957. See L<TieHash> for details. 
  11958.  
  11959. Remember that Perl distinguishes between a key not existing in the hash, and 
  11960. the key existing in the hash but having a corresponding value of undef.  The 
  11961. two possibilities can be tested with the exists() and defined() functions. 
  11962.  
  11963. Here's an example of a somewhat interesting tied hash class:  it gives you a 
  11964. hash representing a particular user's dotfiles.  You index into the hash with 
  11965. the name of the file (minus the dot) and you get back that dotfile's contents. 
  11966. For example: 
  11967.  
  11968.     use DotFiles;
  11969.     tie %dot, DotFiles;
  11970.     if ( $dot{profile} =~ /MANPATH/ ||
  11971.          $dot{login}   =~ /MANPATH/ ||
  11972.          $dot{cshrc}   =~ /MANPATH/    )
  11973.     {
  11974.         print "you seem to set your manpath\n";
  11975.     }
  11976.  
  11977. Or here's another sample of using our tied class: 
  11978.  
  11979.     tie %him, DotFiles, 'daemon';
  11980.     foreach $f ( keys %him ) {
  11981.         printf "daemon dot file %s is size %d\n",
  11982.             $f, length $him{$f};
  11983.     }
  11984.  
  11985. In our tied hash DotFiles example, we use a regular hash for the object 
  11986. containing several important fields, of which only the {LIST} field will be 
  11987. what the user thinks of as the real hash. 
  11988.  
  11989. USER 
  11990.  
  11991. whose dot files this object represents 
  11992.  
  11993. HOME 
  11994.  
  11995. where those dotfiles live 
  11996.  
  11997. CLOBBER 
  11998.  
  11999. whether we should try to change or remove those dot files 
  12000.  
  12001. LIST 
  12002.  
  12003. the hash of dotfile names and content mappings 
  12004.  
  12005. Here's the start of Dotfiles.pm: 
  12006.  
  12007.     package DotFiles;
  12008.     use Carp;
  12009.     sub whowasi { (caller(1))[3] . '()' }
  12010.     my $DEBUG = 0;
  12011.     sub debug { $DEBUG = @_ ? shift : 1 }
  12012.  
  12013. For our example, we want to able to emit debugging info to help in tracing 
  12014. during development.  We keep also one convenience function around internally to 
  12015. help print out warnings; whowasi() returns the function name that calls it. 
  12016.  
  12017. Here are the methods for the DotFiles tied hash. 
  12018.  
  12019. TIEHASH classname, LIST 
  12020.  
  12021. This is the constructor for the class.  That means it is expected to return a 
  12022. blessed reference through which the new object (probably but not necessarily an 
  12023. anonymous hash) will be accessed. Here's the constructor: 
  12024.  
  12025.     sub TIEHASH {
  12026.         my $self = shift;
  12027.         my $user = shift || $>;
  12028.         my $dotdir = shift || '';
  12029.         croak "usage: @{[&whowasi]} [USER [DOTDIR]]" if @_;
  12030.         $user = getpwuid($user) if $user =~ /^\d+$/;
  12031.         my $dir = (getpwnam($user))[7]
  12032.                 || croak "@{[&whowasi]}: no user $user";
  12033.         $dir .= "/$dotdir" if $dotdir;
  12034.  
  12035.         my $node = {
  12036.             USER    => $user,
  12037.             HOME    => $dir,
  12038.             LIST    => {},
  12039.             CLOBBER => 0,
  12040.         };
  12041.  
  12042.         opendir(DIR, $dir)
  12043.                 || croak "@{[&whowasi]}: can't opendir $dir: $!";
  12044.         foreach $dot ( grep /^\./ && -f "$dir/$_", readdir(DIR)) {
  12045.             $dot =~ s/^\.//;
  12046.             $node->{LIST}{$dot} = undef;
  12047.         }
  12048.         closedir DIR;
  12049.         return bless $node, $self;
  12050.     }
  12051.  
  12052. It's probably worth mentioning that if you're going to filetest the return 
  12053. values out of a readdir, you'd better prepend the directory in question. 
  12054. Otherwise, since we didn't chdir() there, it would have been testing the wrong 
  12055. file. 
  12056.  
  12057. FETCH this, key 
  12058.  
  12059. This method will be triggered every time an element in the tied hash is 
  12060. accessed (read).  It takes one argument beyond its self reference: the key 
  12061. whose value we're trying to fetch. Here's the fetch for our DotFiles example. 
  12062.  
  12063.     sub FETCH {
  12064.         carp &whowasi if $DEBUG;
  12065.         my $self = shift;
  12066.         my $dot = shift;
  12067.         my $dir = $self->{HOME};
  12068.         my $file = "$dir/.$dot";
  12069.  
  12070.         unless (exists $self->{LIST}->{$dot} || -f $file) {
  12071.             carp "@{[&whowasi]}: no $dot file" if $DEBUG;
  12072.             return undef;
  12073.         }
  12074.  
  12075.         if (defined $self->{LIST}->{$dot}) {
  12076.             return $self->{LIST}->{$dot};
  12077.         } else {
  12078.             return $self->{LIST}->{$dot} = `cat $dir/.$dot`;
  12079.         }
  12080.     }
  12081.  
  12082. It was easy to write by having it call the Unix cat(1) command, but it would 
  12083. probably be more portable to open the file manually (and somewhat more 
  12084. efficient).  Of course, since dot files are a Unixy concept, we're not that 
  12085. concerned. 
  12086.  
  12087. STORE this, key, value 
  12088.  
  12089. This method will be triggered every time an element in the tied hash is set 
  12090. (written).  It takes two arguments beyond its self reference: the index at 
  12091. which we're trying to store something, and the value we're trying to put there. 
  12092. Here in our DotFiles example, we'll be careful not to let them try to overwrite 
  12093. the file unless they've called the clobber() method on the original object 
  12094. reference returned by tie(). 
  12095.  
  12096.     sub STORE {
  12097.         carp &whowasi if $DEBUG;
  12098.         my $self = shift;
  12099.         my $dot = shift;
  12100.         my $value = shift;
  12101.         my $file = $self->{HOME} . "/.$dot";
  12102.         my $user = $self->{USER};
  12103.  
  12104.         croak "@{[&whowasi]}: $file not clobberable"
  12105.             unless $self->{CLOBBER};
  12106.  
  12107.         open(F, "> $file") || croak "can't open $file: $!";
  12108.         print F $value;
  12109.         close(F);
  12110.     }
  12111.  
  12112. If they wanted to clobber something, they might say: 
  12113.  
  12114.     $ob = tie %daemon_dots, 'daemon';
  12115.     $ob->clobber(1);
  12116.     $daemon_dots{signature} = "A true daemon\n";
  12117.  
  12118. Where the clobber method is simply: 
  12119.  
  12120.     sub clobber {
  12121.         my $self = shift;
  12122.         $self->{CLOBBER} = @_ ? shift : 1;
  12123.     }
  12124.  
  12125. DELETE this, key 
  12126.  
  12127. This method is triggered when we remove an element from the hash, typically by 
  12128. using the delete() function.  Again, we'll be careful to check whether they 
  12129. really want to clobber files. 
  12130.  
  12131.     sub DELETE   {
  12132.         carp &whowasi if $DEBUG;
  12133.  
  12134.         my $self = shift;
  12135.         my $dot = shift;
  12136.         my $file = $self->{HOME} . "/.$dot";
  12137.         croak "@{[&whowasi]}: won't remove file $file"
  12138.             unless $self->{CLOBBER};
  12139.         delete $self->{LIST}->{$dot};
  12140.         unlink($file) || carp "@{[&whowasi]}: can't unlink $file: $!";
  12141.     }
  12142.  
  12143. CLEAR this 
  12144.  
  12145. This method is triggered when the whole hash is to be cleared, usually by 
  12146. assigning the empty list to it. In our example, that would remove all the 
  12147. user's dotfiles!  It's such a dangerous thing that they'll have to set CLOBBER 
  12148. to something higher than 1 to make it happen. 
  12149.  
  12150.     sub CLEAR    {
  12151.         carp &whowasi if $DEBUG;
  12152.         my $self = shift;
  12153.         croak "@{[&whowasi]}: won't remove all dotfiles for $self->{USER}"
  12154.             unless $self->{CLOBBER} > 1;
  12155.         my $dot;
  12156.         foreach $dot ( keys %{$self->{LIST}}) {
  12157.             $self->DELETE($dot);
  12158.         }
  12159.     }
  12160.  
  12161. EXISTS this, key 
  12162.  
  12163. This method is triggered when the user uses the exists() function on a 
  12164. particular hash.  In our example, we'll look at the {LIST} hash element for 
  12165. this: 
  12166.  
  12167.     sub EXISTS   {
  12168.         carp &whowasi if $DEBUG;
  12169.         my $self = shift;
  12170.         my $dot = shift;
  12171.         return exists $self->{LIST}->{$dot};
  12172.     }
  12173.  
  12174. FIRSTKEY this 
  12175.  
  12176. This method will be triggered when the user is going to iterate through the 
  12177. hash, such as via a keys() or each() call. 
  12178.  
  12179.     sub FIRSTKEY {
  12180.         carp &whowasi if $DEBUG;
  12181.         my $self = shift;
  12182.         my $a = keys %{$self->{LIST}};
  12183.         each %{$self->{LIST}}
  12184.     }
  12185.  
  12186. NEXTKEY this, lastkey 
  12187.  
  12188. This method gets triggered during a keys() or each() iteration.  It has a 
  12189. second argument which is the last key that had been accessed.  This is useful 
  12190. if you're carrying about ordering or calling the iterator from more than one 
  12191. sequence, or not really storing things in a hash anywhere. For our example, we 
  12192. our using a real hash so we'll just do the simple thing, but we'll have to 
  12193. indirect through the LIST field. 
  12194.  
  12195.     sub NEXTKEY  {
  12196.         carp &whowasi if $DEBUG;
  12197.         my $self = shift;
  12198.         return each %{ $self->{LIST} }
  12199.     }
  12200.  
  12201. DESTROY this 
  12202.  
  12203. This method is triggered when a tied hash is about to go out of scope.  You 
  12204. don't really need it unless you're trying to add debugging or have auxiliary 
  12205. state to clean up.  Here's a very simple function: 
  12206.  
  12207.     sub DESTROY  {
  12208.         carp &whowasi if $DEBUG;
  12209.     }
  12210.  
  12211. Note that functions such as keys() and values() may return huge array values 
  12212. when used on large objects, like DBM files.  You may prefer to use the each() 
  12213. function to iterate over such.  Example: 
  12214.  
  12215.     # print out history file offsets
  12216.     use NDBM_File;
  12217.     tie(%HIST, NDBM_File, '/usr/lib/news/history', 1, 0);
  12218.     while (($key,$val) = each %HIST) {
  12219.         print $key, ' = ', unpack('L',$val), "\n";
  12220.     }
  12221.     untie(%HIST);
  12222.  
  12223. Tying FileHandles 
  12224.  
  12225. This isn't implemented yet.  Sorry; maybe someday. 
  12226.  
  12227. SEE ALSO 
  12228.  
  12229. See L<DB_File> or L<Config> for some interesting tie() implementations. 
  12230.  
  12231. BUGS 
  12232.  
  12233. Tied arrays are incomplete.  They are also distinctly lacking something for the 
  12234. $#ARRAY access (which is hard, as it's an lvalue), as well as the other obvious 
  12235. array functions, like push(), pop(), shift(), unshift(), and splice(). 
  12236.  
  12237. You cannot easily tie a multilevel data structure (such as a hash of hashes) to 
  12238. a dbm file.  The first problem is that all but GDBM and Berkeley DB have size 
  12239. limitations, but beyond that, you also have problems with how references are to 
  12240. be represented on disk.  One experimental module that does attempt to partially 
  12241. address this need is the MLDBM module.  Check your nearest CPAN site as 
  12242. described in perlmod for source code to MLDBM. 
  12243.  
  12244. AUTHOR 
  12245.  
  12246. Tom Christiansen 
  12247.  
  12248.  
  12249. ΓòÉΓòÉΓòÉ 21. Section - perlbot ΓòÉΓòÉΓòÉ
  12250.  
  12251. NAME 
  12252.  
  12253. perlbot - Bag'o Object Tricks (the BOT) 
  12254.  
  12255. DESCRIPTION 
  12256.  
  12257. The following collection of tricks and hints is intended to whet curious 
  12258. appetites about such things as the use of instance variables and the mechanics 
  12259. of object and class relationships.  The reader is encouraged to consult 
  12260. relevant textbooks for discussion of Object Oriented definitions and 
  12261. methodology.  This is not intended as a tutorial for object-oriented 
  12262. programming or as a comprehensive guide to Perl's object oriented features, nor 
  12263. should it be construed as a style guide. 
  12264.  
  12265. The Perl motto still holds:  There's more than one way to do it. 
  12266.  
  12267. OO SCALING TIPS 
  12268.  
  12269.    1. Do not attempt to verify the type of $self.  That'll break if the class 
  12270.       is inherited, when the type of $self is valid but its package isn't what 
  12271.       you expect.  See rule 5. 
  12272.  
  12273.    2. If an object-oriented (OO) or indirect-object (IO) syntax was used, then 
  12274.       the object is probably the correct type and there's no need to become 
  12275.       paranoid about it.  Perl isn't a paranoid language anyway.  If people 
  12276.       subvert the OO or IO syntax then they probably know what they're doing 
  12277.       and you should let them do it.  See rule 1. 
  12278.  
  12279.    3. Use the two-argument form of bless().  Let a subclass use your 
  12280.       constructor. See L<INHERITING A CONSTRUCTOR>. 
  12281.  
  12282.    4. The subclass is allowed to know things about its immediate superclass, 
  12283.       the superclass is allowed to know nothing about a subclass. 
  12284.  
  12285.    5. Don't be trigger happy with inheritance.  A "using", "containing", or 
  12286.       "delegation" relationship (some sort of aggregation, at least) is often 
  12287.       more appropriate.  See L<OBJECT RELATIONSHIPS>, L<USING RELATIONSHIP WITH 
  12288.       SDBM>, and L<"DELEGATION">. 
  12289.  
  12290.    6. The object is the namespace.  Make package globals accessible via the 
  12291.       object.  This will remove the guess work about the symbol's home package. 
  12292.       See L<CLASS CONTEXT AND THE OBJECT>. 
  12293.  
  12294.    7. IO syntax is certainly less noisy, but it is also prone to ambiguities 
  12295.       which can cause difficult-to-find bugs.  Allow people to use the 
  12296.       sure-thing OO syntax, even if you don't like it. 
  12297.  
  12298.    8. Do not use function-call syntax on a method.  You're going to be bitten 
  12299.       someday.  Someone might move that method into a superclass and your code 
  12300.       will be broken.  On top of that you're feeding the paranoia in rule 2. 
  12301.  
  12302.    9. Don't assume you know the home package of a method.  You're making it 
  12303.       difficult for someone to override that method.  See L<THINKING OF CODE 
  12304.       REUSE>. 
  12305.  
  12306.  INSTANCE VARIABLES 
  12307.  
  12308.  An anonymous array or anonymous hash can be used to hold instance variables. 
  12309.  Named parameters are also demonstrated. 
  12310.  
  12311.           package Foo;
  12312.  
  12313.           sub new {
  12314.                   my $type = shift;
  12315.                   my %params = @_;
  12316.                   my $self = {};
  12317.                   $self->{'High'} = $params{'High'};
  12318.                   $self->{'Low'}  = $params{'Low'};
  12319.                   bless $self, $type;
  12320.           }
  12321.  
  12322.           package Bar;
  12323.  
  12324.           sub new {
  12325.                   my $type = shift;
  12326.                   my %params = @_;
  12327.                   my $self = [];
  12328.                   $self->[0] = $params{'Left'};
  12329.                   $self->[1] = $params{'Right'};
  12330.                   bless $self, $type;
  12331.           }
  12332.  
  12333.           package main;
  12334.  
  12335.           $a = Foo->new( 'High' => 42, 'Low' => 11 );
  12336.           print "High=$a->{'High'}\n";
  12337.           print "Low=$a->{'Low'}\n";
  12338.  
  12339.           $b = Bar->new( 'Left' => 78, 'Right' => 40 );
  12340.           print "Left=$b->[0]\n";
  12341.           print "Right=$b->[1]\n";
  12342.  
  12343.  SCALAR INSTANCE VARIABLES 
  12344.  
  12345.  An anonymous scalar can be used when only one instance variable is needed. 
  12346.  
  12347.           package Foo;
  12348.  
  12349.           sub new {
  12350.                   my $type = shift;
  12351.                   my $self;
  12352.                   $self = shift;
  12353.                   bless \$self, $type;
  12354.           }
  12355.  
  12356.           package main;
  12357.  
  12358.           $a = Foo->new( 42 );
  12359.           print "a=$$a\n";
  12360.  
  12361.  INSTANCE VARIABLE INHERITANCE 
  12362.  
  12363.  This example demonstrates how one might inherit instance variables from a 
  12364.  superclass for inclusion in the new class.  This requires calling the 
  12365.  superclass's constructor and adding one's own instance variables to the new 
  12366.  object. 
  12367.  
  12368.           package Bar;
  12369.  
  12370.           sub new {
  12371.                   my $type = shift;
  12372.                   my $self = {};
  12373.                   $self->{'buz'} = 42;
  12374.                   bless $self, $type;
  12375.           }
  12376.  
  12377.           package Foo;
  12378.           @ISA = qw( Bar );
  12379.  
  12380.           sub new {
  12381.                   my $type = shift;
  12382.                   my $self = Bar->new;
  12383.                   $self->{'biz'} = 11;
  12384.                   bless $self, $type;
  12385.           }
  12386.  
  12387.           package main;
  12388.  
  12389.           $a = Foo->new;
  12390.           print "buz = ", $a->{'buz'}, "\n";
  12391.           print "biz = ", $a->{'biz'}, "\n";
  12392.  
  12393.  OBJECT RELATIONSHIPS 
  12394.  
  12395.  The following demonstrates how one might implement "containing" and "using" 
  12396.  relationships between objects. 
  12397.  
  12398.           package Bar;
  12399.  
  12400.           sub new {
  12401.                   my $type = shift;
  12402.                   my $self = {};
  12403.                   $self->{'buz'} = 42;
  12404.                   bless $self, $type;
  12405.           }
  12406.  
  12407.           package Foo;
  12408.  
  12409.           sub new {
  12410.                   my $type = shift;
  12411.                   my $self = {};
  12412.                   $self->{'Bar'} = Bar->new;
  12413.                   $self->{'biz'} = 11;
  12414.                   bless $self, $type;
  12415.           }
  12416.  
  12417.           package main;
  12418.  
  12419.           $a = Foo->new;
  12420.           print "buz = ", $a->{'Bar'}->{'buz'}, "\n";
  12421.           print "biz = ", $a->{'biz'}, "\n";
  12422.  
  12423.  OVERRIDING SUPERCLASS METHODS 
  12424.  
  12425.  The following example demonstrates how to override a superclass method and 
  12426.  then call the overridden method.  The SUPER pseudo-class allows the programmer 
  12427.  to call an overridden superclass method without actually knowing where that 
  12428.  method is defined. 
  12429.  
  12430.           package Buz;
  12431.           sub goo { print "here's the goo\n" }
  12432.  
  12433.           package Bar; @ISA = qw( Buz );
  12434.           sub google { print "google here\n" }
  12435.  
  12436.           package Baz;
  12437.           sub mumble { print "mumbling\n" }
  12438.  
  12439.           package Foo;
  12440.           @ISA = qw( Bar Baz );
  12441.  
  12442.           sub new {
  12443.                   my $type = shift;
  12444.                   bless [], $type;
  12445.           }
  12446.           sub grr { print "grumble\n" }
  12447.           sub goo {
  12448.                   my $self = shift;
  12449.                   $self->SUPER::goo();
  12450.           }
  12451.           sub mumble {
  12452.                   my $self = shift;
  12453.                   $self->SUPER::mumble();
  12454.           }
  12455.           sub google {
  12456.                   my $self = shift;
  12457.                   $self->SUPER::google();
  12458.           }
  12459.  
  12460.           package main;
  12461.  
  12462.           $foo = Foo->new;
  12463.           $foo->mumble;
  12464.           $foo->grr;
  12465.           $foo->goo;
  12466.           $foo->google;
  12467.  
  12468.  USING RELATIONSHIP WITH SDBM 
  12469.  
  12470.  This example demonstrates an interface for the SDBM class.  This creates a 
  12471.  "using" relationship between the SDBM class and the new class Mydbm. 
  12472.  
  12473.           package Mydbm;
  12474.  
  12475.           require SDBM_File;
  12476.           require TieHash;
  12477.           @ISA = qw( TieHash );
  12478.  
  12479.           sub TIEHASH {
  12480.               my $type = shift;
  12481.               my $ref  = SDBM_File->new(@_);
  12482.               bless {'dbm' => $ref}, $type;
  12483.           }
  12484.           sub FETCH {
  12485.               my $self = shift;
  12486.               my $ref  = $self->{'dbm'};
  12487.               $ref->FETCH(@_);
  12488.           }
  12489.           sub STORE {
  12490.               my $self = shift;
  12491.               if (defined $_[0]){
  12492.                   my $ref = $self->{'dbm'};
  12493.                   $ref->STORE(@_);
  12494.               } else {
  12495.                   die "Cannot STORE an undefined key in Mydbm\n";
  12496.               }
  12497.           }
  12498.  
  12499.           package main;
  12500.           use Fcntl qw( O_RDWR O_CREAT );
  12501.  
  12502.           tie %foo, Mydbm, "Sdbm", O_RDWR|O_CREAT, 0640;
  12503.           $foo{'bar'} = 123;
  12504.           print "foo-bar = $foo{'bar'}\n";
  12505.  
  12506.           tie %bar, Mydbm, "Sdbm2", O_RDWR|O_CREAT, 0640;
  12507.           $bar{'Cathy'} = 456;
  12508.           print "bar-Cathy = $bar{'Cathy'}\n";
  12509.  
  12510.  THINKING OF CODE REUSE 
  12511.  
  12512.  One strength of Object-Oriented languages is the ease with which old code can 
  12513.  use new code.  The following examples will demonstrate first how one can 
  12514.  hinder code reuse and then how one can promote code reuse. 
  12515.  
  12516.  This first example illustrates a class which uses a fully-qualified method 
  12517.  call to access the "private" method BAZ().  The second example will show that 
  12518.  it is impossible to override the BAZ() method. 
  12519.  
  12520.           package FOO;
  12521.  
  12522.           sub new {
  12523.                   my $type = shift;
  12524.                   bless {}, $type;
  12525.           }
  12526.           sub bar {
  12527.                   my $self = shift;
  12528.                   $self->FOO::private::BAZ;
  12529.           }
  12530.  
  12531.           package FOO::private;
  12532.  
  12533.           sub BAZ {
  12534.                   print "in BAZ\n";
  12535.           }
  12536.  
  12537.           package main;
  12538.  
  12539.           $a = FOO->new;
  12540.           $a->bar;
  12541.  
  12542.  Now we try to override the BAZ() method.  We would like FOO::bar() to call 
  12543.  GOOP::BAZ(), but this cannot happen because FOO::bar() explicitly calls 
  12544.  FOO::private::BAZ(). 
  12545.  
  12546.           package FOO;
  12547.  
  12548.           sub new {
  12549.                   my $type = shift;
  12550.                   bless {}, $type;
  12551.           }
  12552.           sub bar {
  12553.                   my $self = shift;
  12554.                   $self->FOO::private::BAZ;
  12555.           }
  12556.  
  12557.           package FOO::private;
  12558.  
  12559.           sub BAZ {
  12560.                   print "in BAZ\n";
  12561.           }
  12562.  
  12563.           package GOOP;
  12564.           @ISA = qw( FOO );
  12565.           sub new {
  12566.                   my $type = shift;
  12567.                   bless {}, $type;
  12568.           }
  12569.  
  12570.           sub BAZ {
  12571.                   print "in GOOP::BAZ\n";
  12572.           }
  12573.  
  12574.           package main;
  12575.  
  12576.           $a = GOOP->new;
  12577.           $a->bar;
  12578.  
  12579.  To create reusable code we must modify class FOO, flattening class 
  12580.  FOO::private.  The next example shows a reusable class FOO which allows the 
  12581.  method GOOP::BAZ() to be used in place of FOO::BAZ(). 
  12582.  
  12583.           package FOO;
  12584.  
  12585.           sub new {
  12586.                   my $type = shift;
  12587.                   bless {}, $type;
  12588.           }
  12589.           sub bar {
  12590.                   my $self = shift;
  12591.                   $self->BAZ;
  12592.           }
  12593.  
  12594.           sub BAZ {
  12595.                   print "in BAZ\n";
  12596.           }
  12597.  
  12598.           package GOOP;
  12599.           @ISA = qw( FOO );
  12600.  
  12601.           sub new {
  12602.                   my $type = shift;
  12603.                   bless {}, $type;
  12604.           }
  12605.           sub BAZ {
  12606.                   print "in GOOP::BAZ\n";
  12607.           }
  12608.  
  12609.           package main;
  12610.  
  12611.           $a = GOOP->new;
  12612.           $a->bar;
  12613.  
  12614.  CLASS CONTEXT AND THE OBJECT 
  12615.  
  12616.  Use the object to solve package and class context problems.  Everything a 
  12617.  method needs should be available via the object or should be passed as a 
  12618.  parameter to the method. 
  12619.  
  12620.  A class will sometimes have static or global data to be used by the methods. 
  12621.  A subclass may want to override that data and replace it with new data.  When 
  12622.  this happens the superclass may not know how to find the new copy of the data. 
  12623.  
  12624.  This problem can be solved by using the object to define the context of the 
  12625.  method.  Let the method look in the object for a reference to the data.  The 
  12626.  alternative is to force the method to go hunting for the data ("Is it in my 
  12627.  class, or in a subclass?  Which subclass?"), and this can be inconvenient and 
  12628.  will lead to hackery.  It is better to just let the object tell the method 
  12629.  where that data is located. 
  12630.  
  12631.           package Bar;
  12632.  
  12633.           %fizzle = ( 'Password' => 'XYZZY' );
  12634.  
  12635.           sub new {
  12636.                   my $type = shift;
  12637.                   my $self = {};
  12638.                   $self->{'fizzle'} = \%fizzle;
  12639.                   bless $self, $type;
  12640.           }
  12641.  
  12642.           sub enter {
  12643.                   my $self = shift;
  12644.  
  12645.                   # Don't try to guess if we should use %Bar::fizzle
  12646.                   # or %Foo::fizzle.  The object already knows which
  12647.                   # we should use, so just ask it.
  12648.                   #
  12649.                   my $fizzle = $self->{'fizzle'};
  12650.  
  12651.                   print "The word is ", $fizzle->{'Password'}, "\n";
  12652.           }
  12653.  
  12654.           package Foo;
  12655.           @ISA = qw( Bar );
  12656.  
  12657.           %fizzle = ( 'Password' => 'Rumple' );
  12658.  
  12659.           sub new {
  12660.                   my $type = shift;
  12661.                   my $self = Bar->new;
  12662.                   $self->{'fizzle'} = \%fizzle;
  12663.                   bless $self, $type;
  12664.           }
  12665.  
  12666.           package main;
  12667.  
  12668.           $a = Bar->new;
  12669.           $b = Foo->new;
  12670.           $a->enter;
  12671.           $b->enter;
  12672.  
  12673.  INHERITING A CONSTRUCTOR 
  12674.  
  12675.  An inheritable constructor should use the second form of bless() which allows 
  12676.  blessing directly into a specified class.  Notice in this example that the 
  12677.  object will be a BAR not a FOO, even though the constructor is in class FOO. 
  12678.  
  12679.           package FOO;
  12680.  
  12681.           sub new {
  12682.                   my $type = shift;
  12683.                   my $self = {};
  12684.                   bless $self, $type;
  12685.           }
  12686.  
  12687.           sub baz {
  12688.                   print "in FOO::baz()\n";
  12689.           }
  12690.  
  12691.           package BAR;
  12692.           @ISA = qw(FOO);
  12693.  
  12694.           sub baz {
  12695.                   print "in BAR::baz()\n";
  12696.           }
  12697.  
  12698.           package main;
  12699.  
  12700.           $a = BAR->new;
  12701.           $a->baz;
  12702.  
  12703.  DELEGATION 
  12704.  
  12705.  Some classes, such as SDBM_File, cannot be effectively subclassed because they 
  12706.  create foreign objects.  Such a class can be extended with some sort of 
  12707.  aggregation technique such as the "using" relationship mentioned earlier or by 
  12708.  delegation. 
  12709.  
  12710.  The following example demonstrates delegation using an AUTOLOAD() function to 
  12711.  perform message-forwarding.  This will allow the Mydbm object to behave 
  12712.  exactly like an SDBM_File object.  The Mydbm class could now extend the 
  12713.  behavior by adding custom FETCH() and STORE() methods, if this is desired. 
  12714.  
  12715.           package Mydbm;
  12716.  
  12717.           require SDBM_File;
  12718.           require TieHash;
  12719.           @ISA = qw(TieHash);
  12720.  
  12721.           sub TIEHASH {
  12722.                   my $type = shift;
  12723.                   my $ref = SDBM_File->new(@_);
  12724.                   bless {'delegate' => $ref};
  12725.           }
  12726.  
  12727.           sub AUTOLOAD {
  12728.                   my $self = shift;
  12729.  
  12730.                   # The Perl interpreter places the name of the
  12731.                   # message in a variable called $AUTOLOAD.
  12732.  
  12733.                   # DESTROY messages should never be propagated.
  12734.                   return if $AUTOLOAD =~ /::DESTROY$/;
  12735.  
  12736.                   # Remove the package name.
  12737.                   $AUTOLOAD =~ s/^Mydbm:://;
  12738.  
  12739.                   # Pass the message to the delegate.
  12740.                   $self->{'delegate'}->$AUTOLOAD(@_);
  12741.           }
  12742.  
  12743.           package main;
  12744.           use Fcntl qw( O_RDWR O_CREAT );
  12745.  
  12746.           tie %foo, Mydbm, "adbm", O_RDWR|O_CREAT, 0640;
  12747.           $foo{'bar'} = 123;
  12748.           print "foo-bar = $foo{'bar'}\n";
  12749.  
  12750.  
  12751. ΓòÉΓòÉΓòÉ 22. Section - perldebug ΓòÉΓòÉΓòÉ
  12752.  
  12753. NAME 
  12754.  
  12755. perldebug - Perl debugging 
  12756.  
  12757. DESCRIPTION 
  12758.  
  12759. First of all, have you tried using the -w switch? 
  12760.  
  12761. Debugging 
  12762.  
  12763. If you invoke Perl with a -d switch, your script will be run under the 
  12764. debugger.  However, the Perl debugger is not a separate program as it is in a C 
  12765. environment.  Instead, the -d flag tells the compiler to insert source 
  12766. information into the pseudocode it's about to hand to the interpreter.  (That 
  12767. means your code must compile correctly for the debugger to work on it.)  Then 
  12768. when the interpreter starts up, it pre-loads a Perl library file containing the 
  12769. debugger itself.  The program will halt before the first executable statement 
  12770. (but see below) and ask you for one of the following commands: 
  12771.  
  12772.  
  12773. Prints out a help message. 
  12774.  
  12775.  
  12776. Stack trace. If you do bizarre things to your @_ arguments in a subroutine, the 
  12777. stack backtrace will not always show the original values. 
  12778.  
  12779.  
  12780. Single step.  Executes until it reaches the beginning of another statement. 
  12781.  
  12782.  
  12783. Next.  Executes over subroutine calls, until it reaches the beginning of the 
  12784. next statement. 
  12785.  
  12786.  
  12787. Finish.  Executes statements until it has finished the current subroutine. 
  12788.  
  12789.  
  12790. Continue.  Executes until the next breakpoint is reached. 
  12791.  
  12792. c line 
  12793.  
  12794. Continue to the specified line.  Inserts a one-time-only breakpoint at the 
  12795. specified line. 
  12796.  
  12797. <CR> 
  12798.  
  12799. Repeat last n or s. 
  12800.  
  12801. l min+incr 
  12802.  
  12803. List incr+1 lines starting at min.  If min is omitted, starts where last 
  12804. listing left off.  If incr is omitted, previous value of incr is used. 
  12805.  
  12806. l min-max 
  12807.  
  12808. List lines in the indicated range. 
  12809.  
  12810. l line 
  12811.  
  12812. List just the indicated line. 
  12813.  
  12814.  
  12815. List next window. 
  12816.  
  12817.  
  12818. List previous window. 
  12819.  
  12820. w line 
  12821.  
  12822. List window (a few lines worth of code) around line. 
  12823.  
  12824. l subname 
  12825.  
  12826. List subroutine.  If it's a long subroutine it just lists the beginning.  Use 
  12827. "l" to list more. 
  12828.  
  12829. /pattern/ 
  12830.  
  12831. Regular expression search forward in the source code for pattern; the final / 
  12832. is optional. 
  12833.  
  12834. ?pattern? 
  12835.  
  12836. Regular expression search backward in the source code for pattern; the final ? 
  12837. is optional. 
  12838.  
  12839.  
  12840. List lines that have breakpoints or actions. 
  12841.  
  12842.  
  12843. Lists the names of all subroutines. 
  12844.  
  12845.  
  12846. Toggle trace mode on or off. 
  12847.  
  12848. b line [ condition ] 
  12849.  
  12850. Set a breakpoint.  If line is omitted, sets a breakpoint on the line that is 
  12851. about to be executed.  If a condition is specified, it is evaluated each time 
  12852. the statement is reached and a breakpoint is taken only if the condition is 
  12853. true.  Breakpoints may only be set on lines that begin an executable statement. 
  12854. Conditions don't use if: 
  12855.  
  12856.     b 237 $x > 30
  12857.     b 33 /pattern/i
  12858.  
  12859. b subname [ condition ] 
  12860.  
  12861. Set breakpoint at first executable line of subroutine. 
  12862.  
  12863. d line 
  12864.  
  12865. Delete breakpoint.  If line is omitted, deletes the breakpoint on the line that 
  12866. is about to be executed. 
  12867.  
  12868.  
  12869. Delete all breakpoints. 
  12870.  
  12871. a line command 
  12872.  
  12873. Set an action for line.  A multiline command may be entered by backslashing the 
  12874. newlines.  This command is Perl code, not another debugger command. 
  12875.  
  12876.  
  12877. Delete all line actions. 
  12878.  
  12879. < command 
  12880.  
  12881. Set an action to happen before every debugger prompt.  A multiline command may 
  12882. be entered by backslashing the newlines. 
  12883.  
  12884. > command 
  12885.  
  12886. Set an action to happen after the prompt when you've just given a command to 
  12887. return to executing the script.  A multiline command may be entered by 
  12888. backslashing the newlines. 
  12889.  
  12890. V package [symbols] 
  12891.  
  12892. Display all (or some) variables in package (defaulting to the main package) 
  12893. using a data pretty-printer (hashes show their keys and values so you see 
  12894. what's what, control characters are made printable, etc.).  Make sure you don't 
  12895. put the type specifier (like $) there, just the symbol names, like this: 
  12896.  
  12897.     V DB filename line
  12898.  
  12899. X [symbols] 
  12900.  
  12901. Same as as "V" command, but within the current package. 
  12902.  
  12903. ! number 
  12904.  
  12905. Redo a debugging command.  If number is omitted, redoes the previous command. 
  12906.  
  12907. ! -number 
  12908.  
  12909. Redo the command that was that many commands ago. 
  12910.  
  12911. H -number 
  12912.  
  12913. Display last n commands.  Only commands longer than one character are listed. 
  12914. If number is omitted, lists them all. 
  12915.  
  12916. q or ^D 
  12917.  
  12918. Quit.  ("quit" doesn't work for this.) 
  12919.  
  12920. command 
  12921.  
  12922. Execute command as a Perl statement.  A missing semicolon will be supplied. 
  12923.  
  12924. p expr 
  12925.  
  12926. Same as print DB::OUT expr.  The DB::OUT filehandle is opened to /dev/tty, 
  12927. regardless of where STDOUT may be redirected to. 
  12928.  
  12929. Any command you type in that isn't recognized by the debugger will be directly 
  12930. executed (eval'd) as Perl code.  Leading white space will cause the debugger to 
  12931. think it's NOT a debugger command. 
  12932.  
  12933. If you have any compile-time executable statements (code within a BEGIN block 
  12934. or a use statement), these will NOT be stopped by debugger, although requires 
  12935. will.  From your own code, however, you can transfer control back to the 
  12936. debugger using the following statement, which is harmless if the debugger is 
  12937. not running: 
  12938.  
  12939.     $DB::single = 1;
  12940.  
  12941. Customization 
  12942.  
  12943. If you want to modify the debugger, copy perl5db.pl from the Perl library to 
  12944. another name and modify it as necessary.  You'll also want to set environment 
  12945. variable PERL5DB to say something like this: 
  12946.  
  12947.     BEGIN { require "myperl5db.pl" }
  12948.  
  12949. You can do some customization by setting up a .perldb file which contains 
  12950. initialization code.  For instance, you could make aliases like these (the last 
  12951. one in particular most people seem to expect to be there): 
  12952.  
  12953.     $DB::alias{'len'} = 's/^len(.*)/p length($1)/';
  12954.     $DB::alias{'stop'} = 's/^stop (at|in)/b/';
  12955.     $DB::alias{'.'} = 's/^\./p '
  12956.                     . '"\$DB::sub(\$DB::filename:\$DB::line):\t"'
  12957.                     . ',\$DB::dbline[\$DB::line]/' ;
  12958.  
  12959. Other resources 
  12960.  
  12961. You did try the -w switch, didn't you ? 
  12962.  
  12963. BUGS 
  12964.  
  12965. If your program exit()s or die()s, so does the debugger. 
  12966.  
  12967. There's no builtin way to restart the debugger without exiting and coming back 
  12968. into it.  You could use an alias like this: 
  12969.  
  12970.     $DB::alias{'rerun'} = 'exec "perl -d $DB::filename"';
  12971.  
  12972. But you'd lose any pending breakpoint information, and that might not be the 
  12973. right path, etc. 
  12974.  
  12975.  
  12976. ΓòÉΓòÉΓòÉ 23. Section - perldiag ΓòÉΓòÉΓòÉ
  12977.  
  12978. NAME 
  12979.  
  12980. perldiag - various Perl diagnostics 
  12981.  
  12982. DESCRIPTION 
  12983.  
  12984. These messages are classified as follows (listed in increasing order of 
  12985. desperation): 
  12986.  
  12987.     (W) A warning (optional).
  12988.     (D) A deprecation (optional).
  12989.     (S) A severe warning (mandatory).
  12990.     (F) A fatal error (trappable).
  12991.     (P) An internal error you should never see (trappable).
  12992.     (X) A very fatal error (non-trappable).
  12993.     (A) An alien error message (not generated by Perl).
  12994.  
  12995. Optional warnings are enabled by using the -w switch.  Warnings may be captured 
  12996. by setting $^Q to a reference to a routine that will be called on each warning 
  12997. instead of printing it.  See perlvar. Trappable errors may be trapped using the 
  12998. eval operator.  See perlfunc/eval. 
  12999.  
  13000. Some of these messages are generic.  Spots that vary are denoted with a %s, 
  13001. just as in a printf format.  Note that some message start with a %s! The 
  13002. symbols "%-?@ sort before the letters, while [ and \ sort after. 
  13003.  
  13004. Listing of Perl Diagnostic Messages 
  13005.  
  13006.  
  13007. ΓòÉΓòÉΓòÉ 24. Listing of Perl Diagnostic Messages ΓòÉΓòÉΓòÉ
  13008.  
  13009. Listing of Perl Diagnostic Messages 
  13010.  
  13011.       "my" variable %s can't be in a package 
  13012.       "no" not allowed in expression 
  13013.       "use" not allowed in expression 
  13014.       % may only be used in unpack 
  13015.       %s (...) interpreted as function 
  13016.       %s argument is not a HASH element 
  13017.       %s did not return a true value 
  13018.       %s found where operator expected 
  13019.       %s had compilation errors. 
  13020.       %s has too many errors. 
  13021.       %s matches null string many times 
  13022.       %s never introduced 
  13023.       %s syntax OK 
  13024.       %s: Command not found. 
  13025.       %s: Expression syntax. 
  13026.       %s: Undefined variable. 
  13027.       %s: not found 
  13028.       -P not allowed for setuid/setgid script 
  13029.       -T and -B not implemented on filehandles 
  13030.       ?+* follows nothing in regexp 
  13031.       @ outside of string 
  13032.       accept() on closed fd 
  13033.       Allocation too large: %lx 
  13034.       Arg too short for msgsnd 
  13035.       Ambiguous use of %s resolved as %s 
  13036.       Args must match #! line 
  13037.       Argument "%s" isn't numeric 
  13038.       Array @%s missing the @ in argument %d of %s() 
  13039.       assertion botched: %s 
  13040.       Assertion failed: file "%s" 
  13041.       Assignment to both a list and a scalar 
  13042.       Attempt to free non-arena SV: 0x%lx 
  13043.       Attempt to free temp prematurely 
  13044.       Attempt to free unreferenced glob pointers 
  13045.       Attempt to free unreferenced scalar 
  13046.       Bad arg length for %s, is %d, should be %d 
  13047.       Bad associative array 
  13048.       Bad filehandle: %s 
  13049.       Bad free() ignored 
  13050.       Bad name after %s:: 
  13051.       Bad symbol for array 
  13052.       Bad symbol for filehandle 
  13053.       Bad symbol for hash 
  13054.       Badly places ()'s 
  13055.       BEGIN failed--compilation aborted 
  13056.       bind() on closed fd 
  13057.       Bizarre copy of %s in %s 
  13058.       Callback called exit 
  13059.       Can't "last" outside a block 
  13060.       Can't "next" outside a block 
  13061.       Can't "redo" outside a block 
  13062.       Can't bless non-reference value 
  13063.       Can't break at that line 
  13064.       Can't call method "%s" in empty package "%s" 
  13065.       Can't call method "%s" on unblessed reference 
  13066.       Can't call method "%s" without a package or object reference 
  13067.       Can't chdir to %s 
  13068.       Can't coerce %s to integer in %s 
  13069.       Can't coerce %s to number in %s 
  13070.       Can't coerce %s to string in %s 
  13071.       Can't create pipe mailbox 
  13072.       Can't declare %s in my 
  13073.       Can't do inplace edit on %s: %s 
  13074.       Can't do inplace edit without backup 
  13075.       Can't do inplace edit: %s > 14 characters 
  13076.       Can't do inplace edit: %s is not a regular file 
  13077.       Can't do setegid! 
  13078.       Can't do seteuid! 
  13079.       Can't do setuid 
  13080.       Can't do waitpid with flags 
  13081.       Can't do {n,m} with n > m 
  13082.       Can't emulate -%s on #! line 
  13083.       Can't exec "%s": %s 
  13084.       Can't exec %s 
  13085.       Can't execute %s 
  13086.       Can't find label %s 
  13087.       Can't find string terminator %s anywhere before EOF 
  13088.       Can't fork 
  13089.       Can't get filespec - stale stat buffer? 
  13090.       Can't get pipe mailbox device name 
  13091.       Can't get SYSGEN parameter value for MAXBUF 
  13092.       Can't goto subroutine outside a subroutine 
  13093.       Can't localize a reference 
  13094.       Can't localize lexical variable %s 
  13095.       Can't locate %s in @INC 
  13096.       Can't locate object method "%s" via package "%s" 
  13097.       Can't locate package %s for @%s::ISA 
  13098.       Can't mktemp() 
  13099.       Can't modify %s in %s 
  13100.       Can't modify non-existent substring 
  13101.       Can't msgrcv to readonly var 
  13102.       Can't open %s: %s 
  13103.       Can't open bidirectional pipe 
  13104.       Can't open error file %s as stderr 
  13105.       Can't open input file %s as stdin 
  13106.       Can't open output file %s as stdout 
  13107.       Can't open output pipe (name: %s) 
  13108.       Can't open perl script "%s": %s 
  13109.       Can't rename %s to %s: %s, skipping file 
  13110.       Can't reopen input pipe (name: %s) in binary mode 
  13111.       Can't reswap uid and euid 
  13112.       Can't return outside a subroutine 
  13113.       Can't stat script "%s" 
  13114.       Can't swap uid and euid 
  13115.       Can't take log of %g 
  13116.       Can't take sqrt of %g 
  13117.       Can't undef active subroutine 
  13118.       Can't unshift 
  13119.       Can't upgrade that kind of scalar 
  13120.       Can't upgrade to undef 
  13121.       Can't use "my %s" in sort comparison 
  13122.       Can't use %s for loop variable 
  13123.       Can't use %s ref as %s ref 
  13124.       Can't use \1 to mean $1 in expression 
  13125.       Can't use string ("%s") as %s ref while "strict refs" in use 
  13126.       Can't use an undefined value as %s reference 
  13127.       Can't use delimiter brackets within expression 
  13128.       Can't use global %s in "my" 
  13129.       Can't use subscript on %s 
  13130.       Can't write to temp file for -e: %s 
  13131.       Can't x= to readonly value 
  13132.       Cannot open temporary file 
  13133.       chmod: mode argument is missing initial 0 
  13134.       Close on unopened file <%s> 
  13135.       connect() on closed fd 
  13136.       Corrupt malloc ptr 0x%lx at 0x%lx 
  13137.       corrupted regexp pointers 
  13138.       corrupted regexp program 
  13139.       Deep recursion on subroutine "%s" 
  13140.       Did you mean &%s instead? 
  13141.       Did you mean $ or @ instead of %? 
  13142.       Do you need to predeclare %s? 
  13143.       Don't know how to handle magic of type '%s' 
  13144.       do_study: out of memory 
  13145.       Duplicate free() ignored 
  13146.       elseif should be elsif 
  13147.       END failed--cleanup aborted 
  13148.       Error converting file specification %s 
  13149.       Execution of %s aborted due to compilation errors. 
  13150.       Exiting eval via %s 
  13151.       Exiting subroutine via %s 
  13152.       Exiting substitution via %s 
  13153.       Fatal VMS error at %s, line %d 
  13154.       fcntl is not implemented 
  13155.       Filehandle %s never opened 
  13156.       Filehandle %s opened only for input 
  13157.       Filehandle only opened for input 
  13158.       Final $ should be \$ or $name 
  13159.       Final @ should be \@ or @name 
  13160.       Format %s redefined 
  13161.       Format not terminated 
  13162.       Found = in conditional, should be == 
  13163.       gdbm store returned %d, errno %d, key "%s" 
  13164.       gethostent not implemented 
  13165.       get{sock,peer}name() on closed fd 
  13166.       getpwnam returned invalid UIC %#o for user "%s" 
  13167.       Glob not terminated 
  13168.       Global symbol "%s" requires explicit package name 
  13169.       goto must have label 
  13170.       Had to create %s unexpectedly 
  13171.       Hash %%s missing the % in argument %d of %s() 
  13172.       Identifier "%s::%s" used only once: possible typo 
  13173.       Illegal division by zero 
  13174.       Illegal modulus zero 
  13175.       Illegal octal digit 
  13176.       Illegal octal digit ignored 
  13177.       Insecure dependency in %s 
  13178.       Insecure directory in %s 
  13179.       Insecure PATH 
  13180.       Internal inconsistency in tracking vforks 
  13181.       internal disaster in regexp 
  13182.       internal urp in regexp at /%s/ 
  13183.       invalid [] range in regexp 
  13184.       ioctl is not implemented 
  13185.       junk on end of regexp 
  13186.       Label not found for "last %s" 
  13187.       Label not found for "next %s" 
  13188.       Label not found for "redo %s" 
  13189.       listen() on closed fd 
  13190.       Literal @%s now requires backslash 
  13191.       Method for operation %s not found in package %s during blessing 
  13192.       Might be a runaway multi-line %s string starting on line %d 
  13193.       Misplaced _ in number 
  13194.       Missing $ on loop variable 
  13195.       Missing comma after first argument to %s function 
  13196.       Missing operator before %s? 
  13197.       Missing right bracket 
  13198.       Missing semicolon on previous line? 
  13199.       Modification of a read-only value attempted 
  13200.       Modification of non-creatable array value attempted, subscript %d 
  13201.       Modification of non-creatable hash value attempted, subscript "%s" 
  13202.       Module name must be constant 
  13203.       msg%s not implemented 
  13204.       Multidimensional syntax %s not supported 
  13205.       Negative length 
  13206.       nested *?+ in regexp 
  13207.       No #! line 
  13208.       No %s allowed while running setuid 
  13209.       No -e allowed in setuid scripts 
  13210.       No comma allowed after %s 
  13211.       No command into which to pipe on command line 
  13212.       No DB::DB routine defined 
  13213.       No dbm on this machine 
  13214.       No DBsub routine 
  13215.       No error file after 2> or 2>> on command line 
  13216.       No input file after < on command line 
  13217.       No output file after > on command line 
  13218.       No output file after > or >> on command line 
  13219.       No Perl script found in input 
  13220.       No setregid available 
  13221.       No setreuid available 
  13222.       No space allowed after -I 
  13223.       No such pipe open 
  13224.       No such signal: SIG%s 
  13225.       Not a CODE reference 
  13226.       Not a format reference 
  13227.       Not a GLOB reference 
  13228.       Not a HASH reference 
  13229.       Not a perl script 
  13230.       Not a SCALAR reference 
  13231.       Not a subroutine reference 
  13232.       Not a subroutine reference in %OVERLOAD 
  13233.       Not an ARRAY reference 
  13234.       Not enough arguments for %s 
  13235.       Not enough format arguments 
  13236.       Null filename used 
  13237.       NULL OP IN RUN 
  13238.       Null realloc 
  13239.       NULL regexp argument 
  13240.       NULL regexp parameter 
  13241.       Odd number of elements in hash list 
  13242.       oops: oopsAV 
  13243.       oops: oopsHV 
  13244.       Operation `%s' %s: no method found, 
  13245.       Operator or semicolon missing before %s 
  13246.       Out of memory for yacc stack 
  13247.       Out of memory! 
  13248.       page overflow 
  13249.       panic: ck_grep 
  13250.       panic: ck_split 
  13251.       panic: corrupt saved stack index 
  13252.       panic: die %s 
  13253.       panic: do_match 
  13254.       panic: do_split 
  13255.       panic: do_subst 
  13256.       panic: do_trans 
  13257.       panic: goto 
  13258.       panic: INTERPCASEMOD 
  13259.       panic: INTERPCONCAT 
  13260.       panic: last 
  13261.       panic: leave_scope clearsv 
  13262.       panic: leave_scope inconsistency 
  13263.       panic: malloc 
  13264.       panic: mapstart 
  13265.       panic: null array 
  13266.       panic: pad_alloc 
  13267.       panic: pad_free curpad 
  13268.       panic: pad_free po 
  13269.       panic: pad_reset curpad 
  13270.       panic: pad_sv po 
  13271.       panic: pad_swipe curpad 
  13272.       panic: pad_swipe po 
  13273.       panic: pp_iter 
  13274.       panic: realloc 
  13275.       panic: restartop 
  13276.       panic: return 
  13277.       panic: scan_num 
  13278.       panic: sv_insert 
  13279.       panic: top_env 
  13280.       panic: yylex 
  13281.       Parens missing around "%s" list 
  13282.       Perl %3.3f required--this is only version %s, stopped 
  13283.       Permission denied 
  13284.       pid %d not a child 
  13285.       POSIX getpgrp can't take an argument 
  13286.       Possible memory corruption: %s overflowed 3rd argument 
  13287.       Precedence problem: open %s should be open(%s) 
  13288.       print on closed filehandle %s 
  13289.       printf on closed filehandle %s 
  13290.       Probable precedence problem on %s 
  13291.       Prototype mismatch: (%s) vs (%s) 
  13292.       Read on closed filehandle <%s> 
  13293.       Reallocation too large: %lx 
  13294.       Recompile perl with -DDEBUGGING to use -D switch 
  13295.       Recursive inheritance detected 
  13296.       Reference miscount in sv_replace() 
  13297.       regexp memory corruption 
  13298.       regexp out of space 
  13299.       regexp too big 
  13300.       Reversed %s= operator 
  13301.       Runaway format 
  13302.       Scalar value @%s[%s] better written as $%s[%s] 
  13303.       Script is not setuid/setgid in suidperl 
  13304.       Search pattern not terminated 
  13305.       seek() on unopened file 
  13306.       select not implemented 
  13307.       sem%s not implemented 
  13308.       semi-panic: attempt to dup freed string 
  13309.       Semicolon seems to be missing 
  13310.       Send on closed socket 
  13311.       Sequence (?#... not terminated 
  13312.       Sequence (?%s...) not implemented 
  13313.       Sequence (?%s...) not recognized 
  13314.       setegid() not implemented 
  13315.       seteuid() not implemented 
  13316.       setrgid() not implemented 
  13317.       setruid() not implemented 
  13318.       Setuid/gid script is writable by world 
  13319.       shm%s not implemented 
  13320.       shutdown() on closed fd 
  13321.       SIG%s handler "%s" not defined. 
  13322.       sort is now a reserved word 
  13323.       Sort subroutine didn't return a numeric value 
  13324.       Sort subroutine didn't return single value 
  13325.       Split loop 
  13326.       Stat on unopened file <%s> 
  13327.       Statement unlikely to be reached 
  13328.       Subroutine %s redefined 
  13329.       Substitution loop 
  13330.       Substitution pattern not terminated 
  13331.       Substitution replacement not terminated 
  13332.       substr outside of string 
  13333.       suidperl is no longer needed since... 
  13334.       syntax error 
  13335.       syntax error at line %d: `%s' unexpected 
  13336.       System V IPC is not implemented on this machine 
  13337.       Syswrite on closed filehandle 
  13338.       tell() on unopened file 
  13339.       Test on unopened file <%s> 
  13340.       That use of $[ is unsupported 
  13341.       The %s function is unimplemented 
  13342.       The crypt() function is unimplemented due to excessive paranoia. 
  13343.       The stat preceding -l _ wasn't an lstat 
  13344.       times not implemented 
  13345.       Too few args to syscall 
  13346.       Too many ('s 
  13347.       Too many )'s 
  13348.       Too many args to syscall 
  13349.       Too many arguments for %s 
  13350.       trailing \ in regexp 
  13351.       Translation pattern not terminated 
  13352.       Translation replacement not terminated 
  13353.       truncate not implemented 
  13354.       Type of arg %d to %s must be %s (not %s) 
  13355.       umask: argument is missing initial 0 
  13356.       Unable to create sub named "%s" 
  13357.       Unbalanced context: %d more PUSHes than POPs 
  13358.       Unbalanced saves: %d more saves than restores 
  13359.       Unbalanced scopes: %d more ENTERs than LEAVEs 
  13360.       Unbalanced tmps: %d more allocs than frees 
  13361.       Undefined format "%s" called 
  13362.       Undefined sort subroutine "%s" called 
  13363.       Undefined subroutine &%s called 
  13364.       Undefined subroutine called 
  13365.       Undefined subroutine in sort 
  13366.       Undefined top format "%s" called 
  13367.       unexec of %s into %s failed! 
  13368.       Unknown BYTEORDER 
  13369.       unmatched () in regexp 
  13370.       Unmatched right bracket 
  13371.       unmatched [] in regexp 
  13372.       Unquoted string "%s" may clash with future reserved word 
  13373.       Unrecognized character \%03o ignored 
  13374.       Unrecognized signal name "%s" 
  13375.       Unrecognized switch: -%s 
  13376.       Unsuccessful %s on filename containing newline 
  13377.       Unsupported directory function "%s" called 
  13378.       Unsupported function %s 
  13379.       Unsupported socket function "%s" called 
  13380.       Unterminated <> operator 
  13381.       Use of $# is deprecated 
  13382.       Use of $* is deprecated 
  13383.       Use of %s in printf format not supported 
  13384.       Use of %s is deprecated 
  13385.       Use of bare << to mean <<"" is deprecated 
  13386.       Use of implicit split to @_ is deprecated 
  13387.       Use of uninitialized value 
  13388.       Useless use of %s in void context 
  13389.       Variable "%s" is not exported 
  13390.       Variable syntax. 
  13391.       Warning: unable to close filehandle %s properly. 
  13392.       Warning: Use of "%s" without parens is ambiguous 
  13393.       Write on closed filehandle 
  13394.       X outside of string 
  13395.       x outside of string 
  13396.       Xsub "%s" called in sort 
  13397.       Xsub called in sort 
  13398.       You can't use -l on a filehandle 
  13399.       YOU HAVEN'T DISABLED SET-ID SCRIPTS IN THE KERNEL YET! 
  13400.       You need to quote "%s" 
  13401.       [gs]etsockopt() on closed fd 
  13402.       \1 better written as $1 
  13403.       ' |' and '<' may not both be specified on command line 
  13404.       '|' and '>' may not both be specified on command line 
  13405.  
  13406.  
  13407. ΓòÉΓòÉΓòÉ 24.1. "my" variable %s can't be in a package ΓòÉΓòÉΓòÉ
  13408.  
  13409. "my" variable %s can't be in a package 
  13410.  
  13411. (F) Lexically scoped variables aren't in a package, so it doesn't make sense to 
  13412. try to declare one with a package qualifier on the front.  Use local() if you 
  13413. want to localize a package variable. 
  13414.  
  13415.  
  13416. ΓòÉΓòÉΓòÉ 24.2. "no" not allowed in expression ΓòÉΓòÉΓòÉ
  13417.  
  13418. "no" not allowed in expression 
  13419.  
  13420. (F) The "no" keyword is recognized and executed at compile time, and returns no 
  13421. useful value.  See perlmod. 
  13422.  
  13423.  
  13424. ΓòÉΓòÉΓòÉ 24.3. "use" not allowed in expression ΓòÉΓòÉΓòÉ
  13425.  
  13426. "use" not allowed in expression 
  13427.  
  13428. (F) The "use" keyword is recognized and executed at compile time, and returns 
  13429. no useful value.  See perlmod. 
  13430.  
  13431.  
  13432. ΓòÉΓòÉΓòÉ 24.4. % may only be used in unpack ΓòÉΓòÉΓòÉ
  13433.  
  13434. % may only be used in unpack 
  13435.  
  13436. (F) You can't pack a string by supplying a checksum, since the checksumming 
  13437. process loses information, and you can't go the other way.  See 
  13438. perlfunc/unpack. 
  13439.  
  13440.  
  13441. ΓòÉΓòÉΓòÉ 24.5. %s (...) interpreted as function ΓòÉΓòÉΓòÉ
  13442.  
  13443. %s (...) interpreted as function 
  13444.  
  13445. (W) You've run afoul of the rule that says that any list operator followed by 
  13446. parentheses turns into a function, with all the list operators arguments found 
  13447. inside the parens.  See perlop/Terms and List Operators (Leftward). 
  13448.  
  13449.  
  13450. ΓòÉΓòÉΓòÉ 24.6. %s argument is not a HASH element ΓòÉΓòÉΓòÉ
  13451.  
  13452. %s argument is not a HASH element 
  13453.  
  13454. (F) The argument to delete() or exists() must be a hash element, such as 
  13455.  
  13456.     $foo{$bar}
  13457.     $ref->[12]->{"susie"}
  13458.  
  13459.  
  13460. ΓòÉΓòÉΓòÉ 24.7. %s did not return a true value ΓòÉΓòÉΓòÉ
  13461.  
  13462. %s did not return a true value 
  13463.  
  13464. (F) A required (or used) file must return a true value to indicate that it 
  13465. compiled correctly and ran its initialization code correctly.  It's traditional 
  13466. to end such a file with a "1;", though any true value would do.  See 
  13467. perlfunc/require. 
  13468.  
  13469.  
  13470. ΓòÉΓòÉΓòÉ 24.8. %s found where operator expected ΓòÉΓòÉΓòÉ
  13471.  
  13472. %s found where operator expected 
  13473.  
  13474. (S) The Perl lexer knows whether to expect a term or an operator.  If it sees 
  13475. what it knows to be a term when it was expecting to see an operator, it gives 
  13476. you this warning.  Usually it indicates that an operator or delimiter was 
  13477. omitted, such as a semicolon. 
  13478.  
  13479.  
  13480. ΓòÉΓòÉΓòÉ 24.9. %s had compilation errors. ΓòÉΓòÉΓòÉ
  13481.  
  13482. %s had compilation errors. 
  13483.  
  13484. (F) The final summary message when a perl -c fails. 
  13485.  
  13486.  
  13487. ΓòÉΓòÉΓòÉ 24.10. %s has too many errors. ΓòÉΓòÉΓòÉ
  13488.  
  13489. %s has too many errors. 
  13490.  
  13491. (F) The parser has given up trying to parse the program after 10 errors. 
  13492. Further error messages would likely be uninformative. 
  13493.  
  13494.  
  13495. ΓòÉΓòÉΓòÉ 24.11. %s matches null string many times ΓòÉΓòÉΓòÉ
  13496.  
  13497. %s matches null string many times 
  13498.  
  13499. (W) The pattern you've specified would be an infinite loop if the regular 
  13500. expression engine didn't specifically check for that.  See perlre. 
  13501.  
  13502.  
  13503. ΓòÉΓòÉΓòÉ 24.12. %s never introduced ΓòÉΓòÉΓòÉ
  13504.  
  13505. %s never introduced 
  13506.  
  13507. (S) The symbol in question was declared but somehow went out of scope before it 
  13508. could possibly have been used. 
  13509.  
  13510.  
  13511. ΓòÉΓòÉΓòÉ 24.13. %s syntax OK ΓòÉΓòÉΓòÉ
  13512.  
  13513. %s syntax OK 
  13514.  
  13515. (F) The final summary message when a perl -c succeeds. 
  13516.  
  13517.  
  13518. ΓòÉΓòÉΓòÉ 24.14. %s: Command not found. ΓòÉΓòÉΓòÉ
  13519.  
  13520. %s: Command not found. 
  13521.  
  13522. (A) You've accidentally run your script through csh instead of Perl.  Check the 
  13523. <#!> line, or manually feed your script into Perl yourself. 
  13524.  
  13525.  
  13526. ΓòÉΓòÉΓòÉ 24.15. %s: Expression syntax. ΓòÉΓòÉΓòÉ
  13527.  
  13528. %s: Expression syntax. 
  13529.  
  13530. (A) You've accidentally run your script through csh instead of Perl.  Check the 
  13531. <#!> line, or manually feed your script into Perl yourself. 
  13532.  
  13533.  
  13534. ΓòÉΓòÉΓòÉ 24.16. %s: Undefined variable. ΓòÉΓòÉΓòÉ
  13535.  
  13536. %s: Undefined variable. 
  13537.  
  13538. (A) You've accidentally run your script through csh instead of Perl.  Check the 
  13539. <#!> line, or manually feed your script into Perl yourself. 
  13540.  
  13541.  
  13542. ΓòÉΓòÉΓòÉ 24.17. %s: not found ΓòÉΓòÉΓòÉ
  13543.  
  13544. %s: not found 
  13545.  
  13546. (A) You've accidentally run your script through the Bourne shell instead of 
  13547. Perl.  Check the <#!> line, or manually feed your script into Perl yourself. 
  13548.  
  13549.  
  13550. ΓòÉΓòÉΓòÉ 24.18. -T and -B not implemented on filehandles ΓòÉΓòÉΓòÉ
  13551.  
  13552. -T and -B not implemented on filehandles 
  13553.  
  13554. (F) Perl can't peek at the stdio buffer of filehandles when it doesn't know 
  13555. about your kind of stdio.  You'll have to use a filename instead. 
  13556.  
  13557.  
  13558. ΓòÉΓòÉΓòÉ 24.19. ?+* follows nothing in regexp ΓòÉΓòÉΓòÉ
  13559.  
  13560. ?+* follows nothing in regexp 
  13561.  
  13562. (F) You started a regular expression with a quantifier.  Backslash it if you 
  13563. meant it literally.  See perlre. 
  13564.  
  13565.  
  13566. ΓòÉΓòÉΓòÉ 24.20. @ outside of string ΓòÉΓòÉΓòÉ
  13567.  
  13568. @ outside of string 
  13569.  
  13570. (F) You had a pack template that specified an absolution position outside the 
  13571. string being unpacked.  See perlfunc/pack. 
  13572.  
  13573.  
  13574. ΓòÉΓòÉΓòÉ 24.21. accept() on closed fd ΓòÉΓòÉΓòÉ
  13575.  
  13576. accept() on closed fd 
  13577.  
  13578. (W) You tried to do an accept on a closed socket.  Did you forget to check the 
  13579. return value of your socket() call?  See perlfunc/accept. 
  13580.  
  13581.  
  13582. ΓòÉΓòÉΓòÉ 24.22. Allocation too large: %lx ΓòÉΓòÉΓòÉ
  13583.  
  13584. Allocation too large: %lx 
  13585.  
  13586. (F) You can't allocate more than 64K on an MSDOS machine. 
  13587.  
  13588.  
  13589. ΓòÉΓòÉΓòÉ 24.23. Arg too short for msgsnd ΓòÉΓòÉΓòÉ
  13590.  
  13591. Arg too short for msgsnd 
  13592.  
  13593. (F) msgsnd() requires a string at least as long as sizeof(long). 
  13594.  
  13595.  
  13596. ΓòÉΓòÉΓòÉ 24.24. Ambiguous use of %s resolved as %s ΓòÉΓòÉΓòÉ
  13597.  
  13598. Ambiguous use of %s resolved as %s 
  13599.  
  13600. (W)(S) You said something that may not be interpreted the way you thought. 
  13601. Normally it's pretty easy to disambiguate it by supplying a missing quote, 
  13602. operator, paren pair or declaration. 
  13603.  
  13604.  
  13605. ΓòÉΓòÉΓòÉ 24.25. Args must match #! line ΓòÉΓòÉΓòÉ
  13606.  
  13607. Args must match #! line 
  13608.  
  13609. (F) The setuid emulator requires that the arguments Perl was invoked with match 
  13610. the arguments specified on the #! line. 
  13611.  
  13612.  
  13613. ΓòÉΓòÉΓòÉ 24.26. Argument "%s" isn't numeric ΓòÉΓòÉΓòÉ
  13614.  
  13615. Argument "%s" isn't numeric 
  13616.  
  13617. (W) The indicated string was fed as an argument to an operator that expected a 
  13618. numeric value instead.  If you're fortunate the message will identify which 
  13619. operator was so unfortunate. 
  13620.  
  13621.  
  13622. ΓòÉΓòÉΓòÉ 24.27. Array @%s missing the @ in argument %d of %s() ΓòÉΓòÉΓòÉ
  13623.  
  13624. Array @%s missing the @ in argument %d of %s() 
  13625.  
  13626. (D) Really old Perl let you omit the @ on array names in some spots.  This is 
  13627. now heavily deprecated. 
  13628.  
  13629.  
  13630. ΓòÉΓòÉΓòÉ 24.28. assertion botched: %s ΓòÉΓòÉΓòÉ
  13631.  
  13632. assertion botched: %s 
  13633.  
  13634. (P) The malloc package that comes with Perl had an internal failure. 
  13635.  
  13636.  
  13637. ΓòÉΓòÉΓòÉ 24.29. Assertion failed: file "%s" ΓòÉΓòÉΓòÉ
  13638.  
  13639. Assertion failed: file "%s" 
  13640.  
  13641. (P) A general assertion failed.  The file in question must be examined. 
  13642.  
  13643.  
  13644. ΓòÉΓòÉΓòÉ 24.30. Assignment to both a list and a scalar ΓòÉΓòÉΓòÉ
  13645.  
  13646. Assignment to both a list and a scalar 
  13647.  
  13648. (F) If you assign to a conditional operator, the 2nd and 3rd arguments must 
  13649. either both be scalars or both be lists.  Otherwise Perl won't know which 
  13650. context to supply to the right side. 
  13651.  
  13652.  
  13653. ΓòÉΓòÉΓòÉ 24.31. Attempt to free non-arena SV: 0x%lx ΓòÉΓòÉΓòÉ
  13654.  
  13655. Attempt to free non-arena SV: 0x%lx 
  13656.  
  13657. (P) All SV objects are supposed to be allocated from arenas that will be 
  13658. garbage collected on exit.  An SV was discovered to be outside any of those 
  13659. arenas. 
  13660.  
  13661.  
  13662. ΓòÉΓòÉΓòÉ 24.32. Attempt to free temp prematurely ΓòÉΓòÉΓòÉ
  13663.  
  13664. Attempt to free temp prematurely 
  13665.  
  13666. (W) Mortalized values are supposed to be freed by the free_tmps() routine. 
  13667. This indicates that something else is freeing the SV before the free_tmps() 
  13668. routine gets a chance, which means that the free_tmps() routine will be freeing 
  13669. an unreferenced scalar when it does try to free it. 
  13670.  
  13671.  
  13672. ΓòÉΓòÉΓòÉ 24.33. Attempt to free unreferenced glob pointers ΓòÉΓòÉΓòÉ
  13673.  
  13674. Attempt to free unreferenced glob pointers 
  13675.  
  13676. (P) The reference counts got screwed up on symbol aliases. 
  13677.  
  13678.  
  13679. ΓòÉΓòÉΓòÉ 24.34. Attempt to free unreferenced scalar ΓòÉΓòÉΓòÉ
  13680.  
  13681. Attempt to free unreferenced scalar 
  13682.  
  13683. (W) Perl went to decrement the reference count of a scalar to see if it would 
  13684. go to 0, and discovered that it had already gone to 0 earlier, and should have 
  13685. been freed, and in fact, probably was freed.  This could indicate that 
  13686. SvREFCNT_dec() was called too many times, or that SvREFCNT_inc() was called too 
  13687. few times, or that the SV was mortalized when it shouldn't have been, or that 
  13688. memory has been corrupted. 
  13689.  
  13690.  
  13691. ΓòÉΓòÉΓòÉ 24.35. Bad arg length for %s, is %d, should be %d ΓòÉΓòÉΓòÉ
  13692.  
  13693. Bad arg length for %s, is %d, should be %d 
  13694.  
  13695. (F) You passed a buffer of the wrong size to one of msgctl(), semctl() or 
  13696. shmctl().  In C parlance, the correct sized are, respectively, sizeof(struct 
  13697. msqid_ds *), sizeof(struct semid_ds *) and sizeof(struct shmid_ds *). 
  13698.  
  13699.  
  13700. ΓòÉΓòÉΓòÉ 24.36. Bad associative array ΓòÉΓòÉΓòÉ
  13701.  
  13702. Bad associative array 
  13703.  
  13704. (P) One of the internal hash routines was passed a null HV pointer. 
  13705.  
  13706.  
  13707. ΓòÉΓòÉΓòÉ 24.37. Bad filehandle: %s ΓòÉΓòÉΓòÉ
  13708.  
  13709. Bad filehandle: %s 
  13710.  
  13711. (F) A symbol was passed to something wanting a filehandle, but the symbol has 
  13712. no filehandle associated with it.  Perhaps you didn't do an open(), or did it 
  13713. in another package. 
  13714.  
  13715.  
  13716. ΓòÉΓòÉΓòÉ 24.38. Bad free() ignored ΓòÉΓòÉΓòÉ
  13717.  
  13718. Bad free() ignored 
  13719.  
  13720. (S) An internal routine called free() on something that had never been 
  13721. malloc()ed in the first place. 
  13722.  
  13723.  
  13724. ΓòÉΓòÉΓòÉ 24.39. Bad name after %s:: ΓòÉΓòÉΓòÉ
  13725.  
  13726. Bad name after %s:: 
  13727.  
  13728. (F) You started to name a symbol by using a package prefix, and then didn't 
  13729. finish the symbol.  In particular, you can't interpolate outside of quotes, so 
  13730.  
  13731.     $var = 'myvar';
  13732.     $sym = mypack::$var;
  13733.  
  13734. is not the same as 
  13735.  
  13736.     $var = 'myvar';
  13737.     $sym = "mypack::$var";
  13738.  
  13739.  
  13740. ΓòÉΓòÉΓòÉ 24.40. Bad symbol for array ΓòÉΓòÉΓòÉ
  13741.  
  13742. Bad symbol for array 
  13743.  
  13744. (P) An internal request asked to add an array entry to something that wasn't a 
  13745. symbol table entry. 
  13746.  
  13747.  
  13748. ΓòÉΓòÉΓòÉ 24.41. Bad symbol for filehandle ΓòÉΓòÉΓòÉ
  13749.  
  13750. Bad symbol for filehandle 
  13751.  
  13752. (P) An internal request asked to add a filehandle entry to something that 
  13753. wasn't a symbol table entry. 
  13754.  
  13755.  
  13756. ΓòÉΓòÉΓòÉ 24.42. Bad symbol for hash ΓòÉΓòÉΓòÉ
  13757.  
  13758. Bad symbol for hash 
  13759.  
  13760. (P) An internal request asked to add a hash entry to something that wasn't a 
  13761. symbol table entry. 
  13762.  
  13763.  
  13764. ΓòÉΓòÉΓòÉ 24.43. Badly places ()'s ΓòÉΓòÉΓòÉ
  13765.  
  13766. Badly places ()'s 
  13767.  
  13768. (A) You've accidentally run your script through csh instead of Perl.  Check the 
  13769. <#!> line, or manually feed your script into Perl yourself. 
  13770.  
  13771.  
  13772. ΓòÉΓòÉΓòÉ 24.44. BEGIN failed--compilation aborted ΓòÉΓòÉΓòÉ
  13773.  
  13774. BEGIN failed--compilation aborted 
  13775.  
  13776. (F) An untrapped exception was raised while executing a BEGIN subroutine. 
  13777. Compilation stops immediately and the interpreter is exited. 
  13778.  
  13779.  
  13780. ΓòÉΓòÉΓòÉ 24.45. bind() on closed fd ΓòÉΓòÉΓòÉ
  13781.  
  13782. bind() on closed fd 
  13783.  
  13784. (W) You tried to do a bind on a closed socket.  Did you forget to check the 
  13785. return value of your socket() call?  See perlfunc/bind. 
  13786.  
  13787.  
  13788. ΓòÉΓòÉΓòÉ 24.46. Bizarre copy of %s in %s ΓòÉΓòÉΓòÉ
  13789.  
  13790. Bizarre copy of %s in %s 
  13791.  
  13792. (P) Perl detected an attempt to copy an internal value that is not copiable. 
  13793.  
  13794.  
  13795. ΓòÉΓòÉΓòÉ 24.47. Callback called exit ΓòÉΓòÉΓòÉ
  13796.  
  13797. Callback called exit 
  13798.  
  13799. (F) A subroutine invoked from an external package via perl_call_sv() exited by 
  13800. calling exit. 
  13801.  
  13802.  
  13803. ΓòÉΓòÉΓòÉ 24.48. Can't "last" outside a block ΓòÉΓòÉΓòÉ
  13804.  
  13805. Can't "last" outside a block 
  13806.  
  13807. (F) A "last" statement was executed to break out of the current block, except 
  13808. that there's this itty bitty problem called there isn't a current block.  Note 
  13809. that an "if" or "else" block doesn't count as a "loopish" block.  You can 
  13810. usually double the curlies to get the same effect though, since the inner 
  13811. curlies will be considered a block that loops once.  See perlfunc/last. 
  13812.  
  13813.  
  13814. ΓòÉΓòÉΓòÉ 24.49. Can't "next" outside a block ΓòÉΓòÉΓòÉ
  13815.  
  13816. Can't "next" outside a block 
  13817.  
  13818. (F) A "next" statement was executed to reiterate the current block, but there 
  13819. isn't a current block.  Note that an "if" or "else" block doesn't count as a 
  13820. "loopish" block.  You can usually double the curlies to get the same effect 
  13821. though, since the inner curlies will be considered a block that loops once. 
  13822. See perlfunc/last. 
  13823.  
  13824.  
  13825. ΓòÉΓòÉΓòÉ 24.50. Can't "redo" outside a block ΓòÉΓòÉΓòÉ
  13826.  
  13827. Can't "redo" outside a block 
  13828.  
  13829. (F) A "redo" statement was executed to restart the current block, but there 
  13830. isn't a current block.  Note that an "if" or "else" block doesn't count as a 
  13831. "loopish" block.  You can usually double the curlies to get the same effect 
  13832. though, since the inner curlies will be considered a block that loops once. 
  13833. See perlfunc/last. 
  13834.  
  13835.  
  13836. ΓòÉΓòÉΓòÉ 24.51. Can't bless non-reference value ΓòÉΓòÉΓòÉ
  13837.  
  13838. Can't bless non-reference value 
  13839.  
  13840. (F) Only hard references may be blessed.  This is how Perl "enforces" 
  13841. encapsulation of objects.  See perlobj. 
  13842.  
  13843.  
  13844. ΓòÉΓòÉΓòÉ 24.52. Can't break at that line ΓòÉΓòÉΓòÉ
  13845.  
  13846. Can't break at that line 
  13847.  
  13848. (S) A warning intended for while running within the debugger, indicating the 
  13849. line number specified wasn't the location of a statement that could be stopped 
  13850. at. 
  13851.  
  13852.  
  13853. ΓòÉΓòÉΓòÉ 24.53. Can't call method "%s" in empty package "%s" ΓòÉΓòÉΓòÉ
  13854.  
  13855. Can't call method "%s" in empty package "%s" 
  13856.  
  13857. (F) You called a method correctly, and it correctly indicated a package 
  13858. functioning as a class, but that package doesn't have ANYTHING defined in it, 
  13859. let alone methods.  See perlobj. 
  13860.  
  13861.  
  13862. ΓòÉΓòÉΓòÉ 24.54. Can't call method "%s" on unblessed reference ΓòÉΓòÉΓòÉ
  13863.  
  13864. Can't call method "%s" on unblessed reference 
  13865.  
  13866. (F) A method call must know what package it's supposed to run in.  It 
  13867. ordinarily finds this out from the object reference you supply, but you didn't 
  13868. supply an object reference in this case.  A reference isn't an object reference 
  13869. until it has been blessed.  See perlobj. 
  13870.  
  13871.  
  13872. ΓòÉΓòÉΓòÉ 24.55. Can't call method "%s" without a package or object reference ΓòÉΓòÉΓòÉ
  13873.  
  13874. Can't call method "%s" without a package or object reference 
  13875.  
  13876. (F) You used the syntax of a method call, but the slot filled by the object 
  13877. reference or package name contains an expression that returns neither an object 
  13878. reference nor a package name.  (Perhaps it's null?) Something like this will 
  13879. reproduce the error: 
  13880.  
  13881.     $BADREF = undef;
  13882.     process $BADREF 1,2,3;
  13883.     $BADREF->process(1,2,3);
  13884.  
  13885.  
  13886. ΓòÉΓòÉΓòÉ 24.56. Can't chdir to %s ΓòÉΓòÉΓòÉ
  13887.  
  13888. Can't chdir to %s 
  13889.  
  13890. (F) You called perl -x/foo/bar, but /foo/bar is not a directory that you can 
  13891. chdir to, possibly because it doesn't exist. 
  13892.  
  13893.  
  13894. ΓòÉΓòÉΓòÉ 24.57. Can't coerce %s to integer in %s ΓòÉΓòÉΓòÉ
  13895.  
  13896. Can't coerce %s to integer in %s 
  13897.  
  13898. (F) Certain types of SVs, in particular real symbol table entries (type GLOB), 
  13899. can't be forced to stop being what they are.  So you can't say things like: 
  13900.  
  13901.     *foo += 1;
  13902.  
  13903. You CAN say 
  13904.  
  13905.     $foo = *foo;
  13906.     $foo += 1;
  13907.  
  13908. but then $foo no longer contains a glob. 
  13909.  
  13910.  
  13911. ΓòÉΓòÉΓòÉ 24.58. Can't coerce %s to number in %s ΓòÉΓòÉΓòÉ
  13912.  
  13913. Can't coerce %s to number in %s 
  13914.  
  13915. (F) Certain types of SVs, in particular real symbol table entries (type GLOB), 
  13916. can't be forced to stop being what they are. 
  13917.  
  13918.  
  13919. ΓòÉΓòÉΓòÉ 24.59. Can't coerce %s to string in %s ΓòÉΓòÉΓòÉ
  13920.  
  13921. Can't coerce %s to string in %s 
  13922.  
  13923. (F) Certain types of SVs, in particular real symbol table entries (type GLOB), 
  13924. can't be forced to stop being what they are. 
  13925.  
  13926.  
  13927. ΓòÉΓòÉΓòÉ 24.60. Can't create pipe mailbox ΓòÉΓòÉΓòÉ
  13928.  
  13929. Can't create pipe mailbox 
  13930.  
  13931. (P) An error peculiar to VMS.  The process is suffering from exhausted quotas 
  13932. or other plumbing problems. 
  13933.  
  13934.  
  13935. ΓòÉΓòÉΓòÉ 24.61. Can't declare %s in my ΓòÉΓòÉΓòÉ
  13936.  
  13937. Can't declare %s in my 
  13938.  
  13939. (F) Only scalar, array and hash variables may be declared as lexical variables. 
  13940. They must have ordinary identifiers as names. 
  13941.  
  13942.  
  13943. ΓòÉΓòÉΓòÉ 24.62. Can't do inplace edit on %s: %s ΓòÉΓòÉΓòÉ
  13944.  
  13945. Can't do inplace edit on %s: %s 
  13946.  
  13947. (S) The creation of the new file failed for the indicated reason. 
  13948.  
  13949.  
  13950. ΓòÉΓòÉΓòÉ 24.63. Can't do inplace edit without backup ΓòÉΓòÉΓòÉ
  13951.  
  13952. Can't do inplace edit without backup 
  13953.  
  13954. (F) You're on a system such as MSDOS that gets confused if you try reading from 
  13955. a deleted (but still opened) file.  You have to say -i.bak, or some such. 
  13956.  
  13957.  
  13958. ΓòÉΓòÉΓòÉ 24.64. Can't do inplace edit: %s > 14 characters ΓòÉΓòÉΓòÉ
  13959.  
  13960. Can't do inplace edit: %s > 14 characters 
  13961.  
  13962. (S) There isn't enough room in the filename to make a backup name for the file. 
  13963.  
  13964.  
  13965. ΓòÉΓòÉΓòÉ 24.65. Can't do inplace edit: %s is not a regular file ΓòÉΓòÉΓòÉ
  13966.  
  13967. Can't do inplace edit: %s is not a regular file 
  13968.  
  13969. (S) You tried to use the -i switch on a special file, such as a file in /dev, 
  13970. or a FIFO.  The file was ignored. 
  13971.  
  13972.  
  13973. ΓòÉΓòÉΓòÉ 24.66. Can't do setegid! ΓòÉΓòÉΓòÉ
  13974.  
  13975. Can't do setegid! 
  13976.  
  13977. (P) The setegid() call failed for some reason in the setuid emulator of 
  13978. suidperl. 
  13979.  
  13980.  
  13981. ΓòÉΓòÉΓòÉ 24.67. Can't do seteuid! ΓòÉΓòÉΓòÉ
  13982.  
  13983. Can't do seteuid! 
  13984.  
  13985. (P) The setuid emulator of suidperl failed for some reason. 
  13986.  
  13987.  
  13988. ΓòÉΓòÉΓòÉ 24.68. Can't do setuid ΓòÉΓòÉΓòÉ
  13989.  
  13990. Can't do setuid 
  13991.  
  13992. (F) This typically means that ordinary perl tried to exec suidperl to do setuid 
  13993. emulation, but couldn't exec it.  It looks for a name of the form sperl5.000 in 
  13994. the same directory that the perl executable resides under the name perl5.000, 
  13995. typically /usr/local/bin on Unix machines. If the file is there, check the 
  13996. execute permissions.  If it isn't, ask your sysadmin why he and/or she removed 
  13997. it. 
  13998.  
  13999.  
  14000. ΓòÉΓòÉΓòÉ 24.69. Can't do waitpid with flags ΓòÉΓòÉΓòÉ
  14001.  
  14002. Can't do waitpid with flags 
  14003.  
  14004. (F) This machine doesn't have either waitpid() or wait4(), so only waitpid() 
  14005. without flags is emulated. 
  14006.  
  14007.  
  14008. ΓòÉΓòÉΓòÉ 24.70. Can't do {n,m} with n > m ΓòÉΓòÉΓòÉ
  14009.  
  14010. Can't do {n,m} with n > m 
  14011.  
  14012. (F) Minima must be less than or equal to maxima.  If you really want your 
  14013. regexp to match something 0 times, just put {0}.  See perlre. 
  14014.  
  14015.  
  14016. ΓòÉΓòÉΓòÉ 24.71. Can't emulate -%s on #! line ΓòÉΓòÉΓòÉ
  14017.  
  14018. Can't emulate -%s on #! line 
  14019.  
  14020. (F) The #! line specifies a switch that doesn't make sense at this point. For 
  14021. example, it'd be kind of silly to put a -x on the #! line. 
  14022.  
  14023.  
  14024. ΓòÉΓòÉΓòÉ 24.72. Can't exec "%s": %s ΓòÉΓòÉΓòÉ
  14025.  
  14026. Can't exec "%s": %s 
  14027.  
  14028. (W) An system(), exec() or piped open call could not execute the named program 
  14029. for the indicated reason.  Typical reasons include: the permissions were wrong 
  14030. on the file, the file wasn't found in $ENV{PATH}, the executable in question 
  14031. was compiled for another architecture, or the #! line in a script points to an 
  14032. interpreter that can't be run for similar reasons.  (Or maybe your system 
  14033. doesn't support #! at all.) 
  14034.  
  14035.  
  14036. ΓòÉΓòÉΓòÉ 24.73. Can't exec %s ΓòÉΓòÉΓòÉ
  14037.  
  14038. Can't exec %s 
  14039.  
  14040. (F) Perl was trying to execute the indicated program for you because that's 
  14041. what the #! line said.  If that's not what you wanted, you may need to mention 
  14042. "perl" on the #! line somewhere. 
  14043.  
  14044.  
  14045. ΓòÉΓòÉΓòÉ 24.74. Can't execute %s ΓòÉΓòÉΓòÉ
  14046.  
  14047. Can't execute %s 
  14048.  
  14049. (F) You used the -S switch, but the script to execute could not be found in the 
  14050. PATH, or at least not with the correct permissions. 
  14051.  
  14052.  
  14053. ΓòÉΓòÉΓòÉ 24.75. Can't find label %s ΓòÉΓòÉΓòÉ
  14054.  
  14055. Can't find label %s 
  14056.  
  14057. (F) You said to goto a label that isn't mentioned anywhere that it's possible 
  14058. for us to go to.  See perlfunc/goto. 
  14059.  
  14060.  
  14061. ΓòÉΓòÉΓòÉ 24.76. Can't find string terminator %s anywhere before EOF ΓòÉΓòÉΓòÉ
  14062.  
  14063. Can't find string terminator %s anywhere before EOF 
  14064.  
  14065. (F) Perl strings can stretch over multiple lines.  This message means that the 
  14066. closing delimiter was omitted.  Since bracketed quotes count nesting levels, 
  14067. the following is missing its final parenthesis: 
  14068.  
  14069.     print q(The character '(' starts a side comment.)
  14070.  
  14071.  
  14072. ΓòÉΓòÉΓòÉ 24.77. Can't fork ΓòÉΓòÉΓòÉ
  14073.  
  14074. Can't fork 
  14075.  
  14076. (F) A fatal error occurred while trying to fork while opening a pipeline. 
  14077.  
  14078.  
  14079. ΓòÉΓòÉΓòÉ 24.78. Can't get filespec - stale stat buffer? ΓòÉΓòÉΓòÉ
  14080.  
  14081. Can't get filespec - stale stat buffer? 
  14082.  
  14083. (S) A warning peculiar to VMS.  This arises because of the difference between 
  14084. access checks under VMS and under the Unix model Perl assumes.  Under VMS, 
  14085. access checks are done by filename, rather than by bits in the stat buffer, so 
  14086. that ACLs and other protections can be taken into account.  Unfortunately, Perl 
  14087. assumes that the stat buffer contains all the necessary information, and passes 
  14088. it, instead of the filespec, to the access checking routine.  It will try to 
  14089. retrieve the filespec using the device name and FID present in the stat buffer, 
  14090. but this works only if you haven't made a subsequent call to the CRTL stat() 
  14091. routine, since the device name is overwritten with each call.  If this warning 
  14092. appears, the name lookup failed, and the access checking routine gave up and 
  14093. returned FALSE, just to be conservative.  (Note: The access checking routine 
  14094. knows about the Perl stat operator and file tests, so you shouldn't ever see 
  14095. this warning in response to a Perl command; it arises only if some internal 
  14096. code takes stat buffers lightly.) 
  14097.  
  14098.  
  14099. ΓòÉΓòÉΓòÉ 24.79. Can't get pipe mailbox device name ΓòÉΓòÉΓòÉ
  14100.  
  14101. Can't get pipe mailbox device name 
  14102.  
  14103. (P) An error peculiar to VMS.  After creating a mailbox to act as a pipe, Perl 
  14104. can't retrieve its name for later use. 
  14105.  
  14106.  
  14107. ΓòÉΓòÉΓòÉ 24.80. Can't get SYSGEN parameter value for MAXBUF ΓòÉΓòÉΓòÉ
  14108.  
  14109. Can't get SYSGEN parameter value for MAXBUF 
  14110.  
  14111. (P) An error peculiar to VMS.  Perl asked $GETSYI how big you want your mailbox 
  14112. buffers to be, and didn't get an answer. 
  14113.  
  14114.  
  14115. ΓòÉΓòÉΓòÉ 24.81. Can't goto subroutine outside a subroutine ΓòÉΓòÉΓòÉ
  14116.  
  14117. Can't goto subroutine outside a subroutine 
  14118.  
  14119. (F) The deeply magical "goto subroutine" call can only replace one subroutine 
  14120. call for another.  It can't manufacture one out of whole cloth.  In general you 
  14121. should only be calling it out of an AUTOLOAD routine anyway.  See 
  14122. perlfunc/goto. 
  14123.  
  14124.  
  14125. ΓòÉΓòÉΓòÉ 24.82. Can't localize a reference ΓòÉΓòÉΓòÉ
  14126.  
  14127. Can't localize a reference 
  14128.  
  14129. (F) You said something like local $$ref, which is not allowed because the 
  14130. compiler can't determine whether $ref will end up pointing to anything with a 
  14131. symbol table entry, and a symbol table entry is necessary to do a local. 
  14132.  
  14133.  
  14134. ΓòÉΓòÉΓòÉ 24.83. Can't localize lexical variable %s ΓòÉΓòÉΓòÉ
  14135.  
  14136. Can't localize lexical variable %s 
  14137.  
  14138. (F) You used local on a variable name that was previous declared as a lexical 
  14139. variable using "my".  This is not allowed.  If you want to localize a package 
  14140. variable of the same name, qualify it with the package name. 
  14141.  
  14142.  
  14143. ΓòÉΓòÉΓòÉ 24.84. Can't locate %s in @INC ΓòÉΓòÉΓòÉ
  14144.  
  14145. Can't locate %s in @INC 
  14146.  
  14147. (F) You said to do (or require, or use) a file that couldn't be found in any of 
  14148. the libraries mentioned in @INC.  Perhaps you need to set the PERL5LIB 
  14149. environment variable to say where the extra library is, or maybe the script 
  14150. needs to add the library name to @INC.  Or maybe you just misspelled the name 
  14151. of the file.  See perlfunc/require. 
  14152.  
  14153.  
  14154. ΓòÉΓòÉΓòÉ 24.85. Can't locate object method "%s" via package "%s" ΓòÉΓòÉΓòÉ
  14155.  
  14156. Can't locate object method "%s" via package "%s" 
  14157.  
  14158. (F) You called a method correctly, and it correctly indicated a package 
  14159. functioning as a class, but that package doesn't define that particular method, 
  14160. nor does any of it's base classes.  See perlobj. 
  14161.  
  14162.  
  14163. ΓòÉΓòÉΓòÉ 24.86. Can't locate package %s for @%s::ISA ΓòÉΓòÉΓòÉ
  14164.  
  14165. Can't locate package %s for @%s::ISA 
  14166.  
  14167. (W) The @ISA array contained the name of another package that doesn't seem to 
  14168. exist. 
  14169.  
  14170.  
  14171. ΓòÉΓòÉΓòÉ 24.87. Can't mktemp() ΓòÉΓòÉΓòÉ
  14172.  
  14173. Can't mktemp() 
  14174.  
  14175. (F) The mktemp() routine failed for some reason while trying to process a -e 
  14176. switch.  Maybe your /tmp partition is full, or clobbered. 
  14177.  
  14178.  
  14179. ΓòÉΓòÉΓòÉ 24.88. Can't modify %s in %s ΓòÉΓòÉΓòÉ
  14180.  
  14181. Can't modify %s in %s 
  14182.  
  14183. (F) You aren't allowed to assign to the item indicated, or otherwise try to 
  14184. change it, such as with an autoincrement. 
  14185.  
  14186.  
  14187. ΓòÉΓòÉΓòÉ 24.89. Can't modify non-existent substring ΓòÉΓòÉΓòÉ
  14188.  
  14189. Can't modify non-existent substring 
  14190.  
  14191. (P) The internal routine that does assignment to a substr() was handed a NULL. 
  14192.  
  14193.  
  14194. ΓòÉΓòÉΓòÉ 24.90. Can't msgrcv to readonly var ΓòÉΓòÉΓòÉ
  14195.  
  14196. Can't msgrcv to readonly var 
  14197.  
  14198. (F) The target of a msgrcv must be modifiable in order to be used as a receive 
  14199. buffer. 
  14200.  
  14201.  
  14202. ΓòÉΓòÉΓòÉ 24.91. Can't open %s: %s ΓòÉΓòÉΓòÉ
  14203.  
  14204. Can't open %s: %s 
  14205.  
  14206. (S) An inplace edit couldn't open the original file for the indicated reason. 
  14207. Usually this is because you don't have read permission for the file. 
  14208.  
  14209.  
  14210. ΓòÉΓòÉΓòÉ 24.92. Can't open bidirectional pipe ΓòÉΓòÉΓòÉ
  14211.  
  14212. Can't open bidirectional pipe 
  14213.  
  14214. (W) You tried to say open(CMD, "|cmd|"), which is not supported.  You can try 
  14215. any of several modules in the Perl library to do this, such as "open2.pl". 
  14216. Alternately, direct the pipe's output to a file using ">", and then read it in 
  14217. under a different file handle. 
  14218.  
  14219.  
  14220. ΓòÉΓòÉΓòÉ 24.93. Can't open error file %s as stderr ΓòÉΓòÉΓòÉ
  14221.  
  14222. Can't open error file %s as stderr 
  14223.  
  14224. (F) An error peculiar to VMS.  Perl does its own command line redirection, and 
  14225. couldn't open the file specified after '2>' or '2>>' on the command line for 
  14226. writing. 
  14227.  
  14228.  
  14229. ΓòÉΓòÉΓòÉ 24.94. Can't open input file %s as stdin ΓòÉΓòÉΓòÉ
  14230.  
  14231. Can't open input file %s as stdin 
  14232.  
  14233. (F) An error peculiar to VMS.  Perl does its own command line redirection, and 
  14234. couldn't open the file specified after '<' on the command line for reading. 
  14235.  
  14236.  
  14237. ΓòÉΓòÉΓòÉ 24.95. Can't open output file %s as stdout ΓòÉΓòÉΓòÉ
  14238.  
  14239. Can't open output file %s as stdout 
  14240.  
  14241. (F) An error peculiar to VMS.  Perl does its own command line redirection, and 
  14242. couldn't open the file specified after '>' or '>>' on the command line for 
  14243. writing. 
  14244.  
  14245.  
  14246. ΓòÉΓòÉΓòÉ 24.96. Can't open output pipe (name: %s) ΓòÉΓòÉΓòÉ
  14247.  
  14248. Can't open output pipe (name: %s) 
  14249.  
  14250. (P) An error peculiar to VMS.  Perl does its own command line redirection, and 
  14251. couldn't open the pipe into which to send data destined for stdout. 
  14252.  
  14253.  
  14254. ΓòÉΓòÉΓòÉ 24.97. Can't open perl script "%s": %s ΓòÉΓòÉΓòÉ
  14255.  
  14256. Can't open perl script "%s": %s 
  14257.  
  14258. (F) The script you specified can't be opened for the indicated reason. 
  14259.  
  14260.  
  14261. ΓòÉΓòÉΓòÉ 24.98. Can't rename %s to %s: %s, skipping file ΓòÉΓòÉΓòÉ
  14262.  
  14263. Can't rename %s to %s: %s, skipping file 
  14264.  
  14265. (S) The rename done by the -i switch failed for some reason, probably because 
  14266. you don't have write permission to the directory. 
  14267.  
  14268.  
  14269. ΓòÉΓòÉΓòÉ 24.99. Can't reopen input pipe (name: %s) in binary mode ΓòÉΓòÉΓòÉ
  14270.  
  14271. Can't reopen input pipe (name: %s) in binary mode 
  14272.  
  14273. (P) An error peculiar to VMS.  Perl thought stdin was a pipe, and tried to 
  14274. reopen it to accept binary data.  Alas, it failed. 
  14275.  
  14276.  
  14277. ΓòÉΓòÉΓòÉ 24.100. Can't reswap uid and euid ΓòÉΓòÉΓòÉ
  14278.  
  14279. Can't reswap uid and euid 
  14280.  
  14281. (P) The setreuid() call failed for some reason in the setuid emulator of 
  14282. suidperl. 
  14283.  
  14284.  
  14285. ΓòÉΓòÉΓòÉ 24.101. Can't return outside a subroutine ΓòÉΓòÉΓòÉ
  14286.  
  14287. Can't return outside a subroutine 
  14288.  
  14289. (F) The return statement was executed in mainline code, that is, where there 
  14290. was no subroutine call to return out of.  See perlsub. 
  14291.  
  14292.  
  14293. ΓòÉΓòÉΓòÉ 24.102. Can't stat script "%s" ΓòÉΓòÉΓòÉ
  14294.  
  14295. Can't stat script "%s" 
  14296.  
  14297. (P) For some reason you can't fstat() the script even though you have it open 
  14298. already.  Bizarre. 
  14299.  
  14300.  
  14301. ΓòÉΓòÉΓòÉ 24.103. Can't swap uid and euid ΓòÉΓòÉΓòÉ
  14302.  
  14303. Can't swap uid and euid 
  14304.  
  14305. (P) The setreuid() call failed for some reason in the setuid emulator of 
  14306. suidperl. 
  14307.  
  14308.  
  14309. ΓòÉΓòÉΓòÉ 24.104. Can't take log of %g ΓòÉΓòÉΓòÉ
  14310.  
  14311. Can't take log of %g 
  14312.  
  14313. (F) Logarithms are only defined on positive real numbers. 
  14314.  
  14315.  
  14316. ΓòÉΓòÉΓòÉ 24.105. Can't take sqrt of %g ΓòÉΓòÉΓòÉ
  14317.  
  14318. Can't take sqrt of %g 
  14319.  
  14320. (F) For ordinary real numbers, you can't take the square root of a negative 
  14321. number.  There's a Complex package available for Perl, though, if you really 
  14322. want to do that. 
  14323.  
  14324.  
  14325. ΓòÉΓòÉΓòÉ 24.106. Can't undef active subroutine ΓòÉΓòÉΓòÉ
  14326.  
  14327. Can't undef active subroutine 
  14328.  
  14329. (F) You can't undefine a routine that's currently running.  You can, however, 
  14330. redefine it while it's running, and you can even undef the redefined subroutine 
  14331. while the old routine is running.  Go figure. 
  14332.  
  14333.  
  14334. ΓòÉΓòÉΓòÉ 24.107. Can't unshift ΓòÉΓòÉΓòÉ
  14335.  
  14336. Can't unshift 
  14337.  
  14338. (F) You tried to unshift an "unreal" array that can't be unshifted, such as the 
  14339. main Perl stack. 
  14340.  
  14341.  
  14342. ΓòÉΓòÉΓòÉ 24.108. Can't upgrade that kind of scalar ΓòÉΓòÉΓòÉ
  14343.  
  14344. Can't upgrade that kind of scalar 
  14345.  
  14346. (P) The internal sv_upgrade routine adds "members" to an SV, making it into a 
  14347. more specialized kind of SV.  The top several SV types are so specialized, 
  14348. however, that they cannot be interconverted.  This message indicates that such 
  14349. a conversion was attempted. 
  14350.  
  14351.  
  14352. ΓòÉΓòÉΓòÉ 24.109. Can't upgrade to undef ΓòÉΓòÉΓòÉ
  14353.  
  14354. Can't upgrade to undef 
  14355.  
  14356. (P) The undefined SV is the bottom of the totem pole, in the scheme of 
  14357. upgradability.  Upgrading to undef indicates an error in the code calling 
  14358. sv_upgrade. 
  14359.  
  14360.  
  14361. ΓòÉΓòÉΓòÉ 24.110. Can't use "my %s" in sort comparison ΓòÉΓòÉΓòÉ
  14362.  
  14363. Can't use "my %s" in sort comparison 
  14364.  
  14365. (F) The global variables $a and $b are reserved for sort comparisons. You 
  14366. mentioned $a or $b in the same line as the <=> or cmp operator, and the 
  14367. variable had earlier been declared as a lexical variable. Either qualify the 
  14368. sort variable with the package name, or rename the lexical variable. 
  14369.  
  14370.  
  14371. ΓòÉΓòÉΓòÉ 24.111. Can't use %s for loop variable ΓòÉΓòÉΓòÉ
  14372.  
  14373. Can't use %s for loop variable 
  14374.  
  14375. (F) Only a simple scalar variable may be used as a loop variable on a foreach. 
  14376.  
  14377.  
  14378. ΓòÉΓòÉΓòÉ 24.112. Can't use %s ref as %s ref ΓòÉΓòÉΓòÉ
  14379.  
  14380. Can't use %s ref as %s ref 
  14381.  
  14382. (F) You've mixed up your reference types.  You have to dereference a reference 
  14383. of the type needed.  You can use the ref() function to test the type of the 
  14384. reference, if need be. 
  14385.  
  14386.  
  14387. ΓòÉΓòÉΓòÉ 24.113. Can't use \1 to mean $1 in expression ΓòÉΓòÉΓòÉ
  14388.  
  14389. Can't use \1 to mean $1 in expression 
  14390.  
  14391. (W) In an ordinary expression, backslash is a unary operator that creates a 
  14392. reference to its argument.  The use of backslash to indicate a backreference to 
  14393. a matched substring is only valid as part of a regular expression pattern. 
  14394. Trying to do this in ordinary Perl code produces a value that prints out 
  14395. looking like SCALAR(0xdecaf).  Use the $1 form instead. 
  14396.  
  14397.  
  14398. ΓòÉΓòÉΓòÉ 24.114. Can't use string ("%s") as %s ref while "strict refs" in use ΓòÉΓòÉΓòÉ
  14399.  
  14400. Can't use string ("%s") as %s ref while "strict refs" in use 
  14401.  
  14402. (F) Only hard references are allowed by "strict refs".  Symbolic references are 
  14403. disallowed.  See perlref. 
  14404.  
  14405.  
  14406. ΓòÉΓòÉΓòÉ 24.115. Can't use an undefined value as %s reference ΓòÉΓòÉΓòÉ
  14407.  
  14408. Can't use an undefined value as %s reference 
  14409.  
  14410. (F) A value used as either a hard reference or a symbolic reference must be a 
  14411. defined value.  This helps to de-lurk some insidious errors. 
  14412.  
  14413.  
  14414. ΓòÉΓòÉΓòÉ 24.116. Can't use delimiter brackets within expression ΓòÉΓòÉΓòÉ
  14415.  
  14416. Can't use delimiter brackets within expression 
  14417.  
  14418. (F) The ${name} construct is for disambiguating identifiers in strings, not in 
  14419. ordinary code. 
  14420.  
  14421.  
  14422. ΓòÉΓòÉΓòÉ 24.117. Can't use global %s in "my" ΓòÉΓòÉΓòÉ
  14423.  
  14424. Can't use global %s in "my" 
  14425.  
  14426. (F) You tried to declare a magical variable as a lexical variable.  This is not 
  14427. allowed, because the magic can only be tied to one location (namely the global 
  14428. variable) and it would be incredibly confusing to have variables in your 
  14429. program that looked like magical variables but weren't. 
  14430.  
  14431.  
  14432. ΓòÉΓòÉΓòÉ 24.118. Can't use subscript on %s ΓòÉΓòÉΓòÉ
  14433.  
  14434. Can't use subscript on %s 
  14435.  
  14436. (F) The compiler tried to interpret a bracketed expression as a subscript.  But 
  14437. to the left of the brackets was an expression that didn't look like an array 
  14438. reference, or anything else subscriptable. 
  14439.  
  14440.  
  14441. ΓòÉΓòÉΓòÉ 24.119. Can't write to temp file for  ΓòÉΓòÉΓòÉ
  14442.  
  14443. -e: %s 
  14444.  
  14445. Can't write to temp file for -e: %s 
  14446.  
  14447. (F) The write routine failed for some reason while trying to process a -e 
  14448. switch.  Maybe your /tmp partition is full, or clobbered. 
  14449.  
  14450.  
  14451. ΓòÉΓòÉΓòÉ 24.120. Can't x= to readonly value ΓòÉΓòÉΓòÉ
  14452.  
  14453. Can't x= to readonly value 
  14454.  
  14455. (F) You tried to repeat a constant value (often the undefined value) with an 
  14456. assignment operator, which implies modifying the value itself. Perhaps you need 
  14457. to copy the value to a temporary, and repeat that. 
  14458.  
  14459.  
  14460. ΓòÉΓòÉΓòÉ 24.121. Cannot open temporary file ΓòÉΓòÉΓòÉ
  14461.  
  14462. Cannot open temporary file 
  14463.  
  14464. (F) The create routine failed for some reaon while trying to process a -e 
  14465. switch.  Maybe your /tmp partition is full, or clobbered. 
  14466.  
  14467.  
  14468. ΓòÉΓòÉΓòÉ 24.122. chmod: mode argument is missing initial 0 ΓòÉΓòÉΓòÉ
  14469.  
  14470. chmod: mode argument is missing initial 0 
  14471.  
  14472. (W) A novice will sometimes say 
  14473.  
  14474.     chmod 777, $filename
  14475.  
  14476. not realizing that 777 will be interpreted as a decimal number, equivalent to 
  14477. 01411.  Octal constants are introduced with a leading 0 in Perl, as in C. 
  14478.  
  14479.  
  14480. ΓòÉΓòÉΓòÉ 24.123. Close on unopened file <%s> ΓòÉΓòÉΓòÉ
  14481.  
  14482. Close on unopened file <%s> 
  14483.  
  14484. (W) You tried to close a filehandle that was never opened. 
  14485.  
  14486.  
  14487. ΓòÉΓòÉΓòÉ 24.124. connect() on closed fd ΓòÉΓòÉΓòÉ
  14488.  
  14489. connect() on closed fd 
  14490.  
  14491. (W) You tried to do a connect on a closed socket.  Did you forget to check the 
  14492. return value of your socket() call?  See perlfunc/connect. 
  14493.  
  14494.  
  14495. ΓòÉΓòÉΓòÉ 24.125. Corrupt malloc ptr 0x%lx at 0x%lx ΓòÉΓòÉΓòÉ
  14496.  
  14497. Corrupt malloc ptr 0x%lx at 0x%lx 
  14498.  
  14499. (P) The malloc package that comes with Perl had an internal failure. 
  14500.  
  14501.  
  14502. ΓòÉΓòÉΓòÉ 24.126. corrupted regexp pointers ΓòÉΓòÉΓòÉ
  14503.  
  14504. corrupted regexp pointers 
  14505.  
  14506. (P) The regular expression engine got confused by what the regular expression 
  14507. compiler gave it. 
  14508.  
  14509.  
  14510. ΓòÉΓòÉΓòÉ 24.127. corrupted regexp program ΓòÉΓòÉΓòÉ
  14511.  
  14512. corrupted regexp program 
  14513.  
  14514. (P) The regular expression engine got passed a regexp program without a valid 
  14515. magic number. 
  14516.  
  14517.  
  14518. ΓòÉΓòÉΓòÉ 24.128. Deep recursion on subroutine "%s" ΓòÉΓòÉΓòÉ
  14519.  
  14520. Deep recursion on subroutine "%s" 
  14521.  
  14522. (W) This subroutine has called itself (directly or indirectly) 100 times than 
  14523. it has returned.  This probably indicates an infinite recursion, unless you're 
  14524. writing strange benchmark programs, in which case it indicates something else. 
  14525.  
  14526.  
  14527. ΓòÉΓòÉΓòÉ 24.129. Did you mean &%s instead? ΓòÉΓòÉΓòÉ
  14528.  
  14529. Did you mean &%s instead? 
  14530.  
  14531. (W) You probably referred to an imported subroutine &FOO as $FOO or some such. 
  14532.  
  14533.  
  14534. ΓòÉΓòÉΓòÉ 24.130. Did you mean $ or @ instead of %? ΓòÉΓòÉΓòÉ
  14535.  
  14536. Did you mean $ or @ instead of %? 
  14537.  
  14538. (W) You probably said %hash{$key} when you meant $hash{$key} or @hash{@keys}. 
  14539. On the other hand, maybe you just meant %hash and got carried away. 
  14540.  
  14541.  
  14542. ΓòÉΓòÉΓòÉ 24.131. Do you need to predeclare %s? ΓòÉΓòÉΓòÉ
  14543.  
  14544. Do you need to predeclare %s? 
  14545.  
  14546. (S) This is an educated guess made in conjunction with the message "%s found 
  14547. where operator expected".  It often means a subroutine or module name is being 
  14548. referenced that hasn't been declared yet.  This may be because of ordering 
  14549. problems in your file, or because of a missing "sub", "package", "require", or 
  14550. "use" statement.  If you're referencing something that isn't defined yet, you 
  14551. don't actually have to define the subroutine or package before the current 
  14552. location.  You can use an empty "sub foo;" or "package FOO;" to enter a 
  14553. "forward" declaration. 
  14554.  
  14555.  
  14556. ΓòÉΓòÉΓòÉ 24.132. Don't know how to handle magic of type '%s' ΓòÉΓòÉΓòÉ
  14557.  
  14558. Don't know how to handle magic of type '%s' 
  14559.  
  14560. (P) The internal handling of magical variables has been cursed. 
  14561.  
  14562.  
  14563. ΓòÉΓòÉΓòÉ 24.133. do_study: out of memory ΓòÉΓòÉΓòÉ
  14564.  
  14565. do_study: out of memory 
  14566.  
  14567. (P) This should have been caught by safemalloc() instead. 
  14568.  
  14569.  
  14570. ΓòÉΓòÉΓòÉ 24.134. Duplicate free() ignored ΓòÉΓòÉΓòÉ
  14571.  
  14572. Duplicate free() ignored 
  14573.  
  14574. (S) An internal routine called free() on something that had already been freed. 
  14575.  
  14576.  
  14577. ΓòÉΓòÉΓòÉ 24.135. elseif should be elsif ΓòÉΓòÉΓòÉ
  14578.  
  14579. elseif should be elsif 
  14580.  
  14581. (S) There is no keyword "elseif" in Perl because Larry thinks it's ugly.  Your 
  14582. code will be interpreted as an attempt to call a method named "elseif" for the 
  14583. class returned by the following block.  This is unlikely to be what you want. 
  14584.  
  14585.  
  14586. ΓòÉΓòÉΓòÉ 24.136. END failed--cleanup aborted ΓòÉΓòÉΓòÉ
  14587.  
  14588. END failed--cleanup aborted 
  14589.  
  14590. (F) An untrapped exception was raised while executing an END subroutine. The 
  14591. interpreter is immediately exited. 
  14592.  
  14593.  
  14594. ΓòÉΓòÉΓòÉ 24.137. Error converting file specification %s ΓòÉΓòÉΓòÉ
  14595.  
  14596. Error converting file specification %s 
  14597.  
  14598. (F) An error peculiar to VMS.  Since Perl may have to deal with file 
  14599. specifications in either VMS or Unix syntax, it converts them to a single form 
  14600. when it must operate on them directly.  Either you've passed an invalid file 
  14601. specification to Perl, or you've found a case the conversion routines don't 
  14602. handle.  Drat. 
  14603.  
  14604.  
  14605. ΓòÉΓòÉΓòÉ 24.138. Execution of %s aborted due to compilation errors. ΓòÉΓòÉΓòÉ
  14606.  
  14607. Execution of %s aborted due to compilation errors. 
  14608.  
  14609. (F) The final summary message when a Perl compilation fails. 
  14610.  
  14611.  
  14612. ΓòÉΓòÉΓòÉ 24.139. Exiting eval via %s ΓòÉΓòÉΓòÉ
  14613.  
  14614. Exiting eval via %s 
  14615.  
  14616. (W) You are exiting an eval by unconventional means, such as a a goto, or a 
  14617. loop control statement. 
  14618.  
  14619.  
  14620. ΓòÉΓòÉΓòÉ 24.140. Exiting subroutine via %s ΓòÉΓòÉΓòÉ
  14621.  
  14622. Exiting subroutine via %s 
  14623.  
  14624. (W) You are exiting a subroutine by unconventional means, such as a a goto, or 
  14625. a loop control statement. 
  14626.  
  14627.  
  14628. ΓòÉΓòÉΓòÉ 24.141. Exiting substitution via %s ΓòÉΓòÉΓòÉ
  14629.  
  14630. Exiting substitution via %s 
  14631.  
  14632. (W) You are exiting a substitution by unconventional means, such as a a return, 
  14633. a goto, or a loop control statement. 
  14634.  
  14635.  
  14636. ΓòÉΓòÉΓòÉ 24.142. Fatal VMS error at %s, line %d ΓòÉΓòÉΓòÉ
  14637.  
  14638. Fatal VMS error at %s, line %d 
  14639.  
  14640. (P) An error peculiar to VMS.  Something untoward happened in a VMS system 
  14641. service or RTL routine; Perl's exit status should provide more details.  The 
  14642. filename in "at %s" and the line number in "line %d" tell you which section of 
  14643. the Perl source code is distressed. 
  14644.  
  14645.  
  14646. ΓòÉΓòÉΓòÉ 24.143. fcntl is not implemented ΓòÉΓòÉΓòÉ
  14647.  
  14648. fcntl is not implemented 
  14649.  
  14650. (F) Your machine apparently doesn't implement fcntl().  What is this, a PDP-11 
  14651. or something? 
  14652.  
  14653.  
  14654. ΓòÉΓòÉΓòÉ 24.144. Filehandle %s never opened ΓòÉΓòÉΓòÉ
  14655.  
  14656. Filehandle %s never opened 
  14657.  
  14658. (W) An I/O operation was attempted on a filehandle that was never initialized. 
  14659. You need to do an open() or a socket() call, or call a constructor from the 
  14660. FileHandle package. 
  14661.  
  14662.  
  14663. ΓòÉΓòÉΓòÉ 24.145. Filehandle %s opened only for input ΓòÉΓòÉΓòÉ
  14664.  
  14665. Filehandle %s opened only for input 
  14666.  
  14667. (W) You tried to write on a read-only filehandle.  If you intended it to be a 
  14668. read-write filehandle, you needed to open it with "+<" or "+>" or "+>>" instead 
  14669. of with "<" or nothing.  If you only intended to write the file, use ">" or 
  14670. ">>".  See perlfunc/open. 
  14671.  
  14672.  
  14673. ΓòÉΓòÉΓòÉ 24.146. Filehandle only opened for input ΓòÉΓòÉΓòÉ
  14674.  
  14675. Filehandle only opened for input 
  14676.  
  14677. (W) You tried to write on a read-only filehandle.  If you intended it to be a 
  14678. read-write filehandle, you needed to open it with "+<" or "+>" or "+>>" instead 
  14679. of with "<" or nothing.  If you only intended to write the file, use ">" or 
  14680. ">>".  See perlfunc/open. 
  14681.  
  14682.  
  14683. ΓòÉΓòÉΓòÉ 24.147. Final $ should be \$ or $name ΓòÉΓòÉΓòÉ
  14684.  
  14685. Final $ should be \$ or $name 
  14686.  
  14687. (F) You must now decide whether the final $ in a string was meant to be a 
  14688. literal dollar sign, or was meant to introduce a variable name that happens to 
  14689. be missing.  So you have to put either the backslash or the name. 
  14690.  
  14691.  
  14692. ΓòÉΓòÉΓòÉ 24.148. Final @ should be \@ or @name ΓòÉΓòÉΓòÉ
  14693.  
  14694. Final @ should be \@ or @name 
  14695.  
  14696. (F) You must now decide whether the final @ in a string was meant to be a 
  14697. literal "at" sign, or was meant to introduce a variable name that happens to be 
  14698. missing.  So you have to put either the backslash or the name. 
  14699.  
  14700.  
  14701. ΓòÉΓòÉΓòÉ 24.149. Format %s redefined ΓòÉΓòÉΓòÉ
  14702.  
  14703. Format %s redefined 
  14704.  
  14705. (W) You redefined a format.  To suppress this warning, say 
  14706.  
  14707.     {
  14708.         local $^W = 0;
  14709.         eval "format NAME =...";
  14710.     }
  14711.  
  14712.  
  14713. ΓòÉΓòÉΓòÉ 24.150. Format not terminated ΓòÉΓòÉΓòÉ
  14714.  
  14715. Format not terminated 
  14716.  
  14717. (F) A format must be terminated by a line with a solitary dot.  Perl got to the 
  14718. end of your file without finding such a line. 
  14719.  
  14720.  
  14721. ΓòÉΓòÉΓòÉ 24.151. Found = in conditional, should be == ΓòÉΓòÉΓòÉ
  14722.  
  14723. Found = in conditional, should be == 
  14724.  
  14725. (W) You said 
  14726.  
  14727.     if ($foo = 123)
  14728.  
  14729. when you meant 
  14730.  
  14731.     if ($foo == 123)
  14732.  
  14733. (or something like that). 
  14734.  
  14735.  
  14736. ΓòÉΓòÉΓòÉ 24.152. gdbm store returned %d, errno %d, key "%s" ΓòÉΓòÉΓòÉ
  14737.  
  14738. gdbm store returned %d, errno %d, key "%s" 
  14739.  
  14740. (S) A warning from the GDBM_File extension that a store failed. 
  14741.  
  14742.  
  14743. ΓòÉΓòÉΓòÉ 24.153. gethostent not implemented ΓòÉΓòÉΓòÉ
  14744.  
  14745. gethostent not implemented 
  14746.  
  14747. (F) Your C library apparently doesn't implement gethostent(), probably because 
  14748. if it did, it'd feel morally obligated to return every hostname on the 
  14749. Internet. 
  14750.  
  14751.  
  14752. ΓòÉΓòÉΓòÉ 24.154. get{sock,peer}name() on closed fd ΓòÉΓòÉΓòÉ
  14753.  
  14754. get{sock,peer}name() on closed fd 
  14755.  
  14756. (W) You tried to get a socket or peer socket name on a closed socket. Did you 
  14757. forget to check the return value of your socket() call? 
  14758.  
  14759.  
  14760. ΓòÉΓòÉΓòÉ 24.155. getpwnam returned invalid UIC %#o for user "%s" ΓòÉΓòÉΓòÉ
  14761.  
  14762. getpwnam returned invalid UIC %#o for user "%s" 
  14763.  
  14764. (S) A warning peculiar to VMS.  The call to sys$getuai underlying the getpwnam 
  14765. operator returned an invalid UIC. 
  14766.  
  14767.  
  14768. ΓòÉΓòÉΓòÉ 24.156. Glob not terminated ΓòÉΓòÉΓòÉ
  14769.  
  14770. Glob not terminated 
  14771.  
  14772. (F) The lexer saw a left angle bracket in a place where it was expecting a 
  14773. term, so it's looking for the corresponding right angle bracket, and not 
  14774. finding it.  Chances are you left some needed parentheses out earlier in the 
  14775. line, and you really meant a "less than". 
  14776.  
  14777.  
  14778. ΓòÉΓòÉΓòÉ 24.157. Global symbol "%s" requires explicit package name ΓòÉΓòÉΓòÉ
  14779.  
  14780. Global symbol "%s" requires explicit package name 
  14781.  
  14782. (F) You've said "use strict vars", which indicates that all variables must 
  14783. either be lexically scoped (using "my"), or explicitly qualified to say which 
  14784. package the global variable is in (using "::"). 
  14785.  
  14786.  
  14787. ΓòÉΓòÉΓòÉ 24.158. goto must have label ΓòÉΓòÉΓòÉ
  14788.  
  14789. goto must have label 
  14790.  
  14791. (F) Unlike with "next" or "last", you're not allowed to goto an unspecified 
  14792. destination.  See perlfunc/goto. 
  14793.  
  14794.  
  14795. ΓòÉΓòÉΓòÉ 24.159. Had to create %s unexpectedly ΓòÉΓòÉΓòÉ
  14796.  
  14797. Had to create %s unexpectedly 
  14798.  
  14799. (S) A routine asked for a symbol from a symbol table that ought to have existed 
  14800. already, but for some reason it didn't, and had to be created on an emergency 
  14801. basis to prevent a core dump. 
  14802.  
  14803.  
  14804. ΓòÉΓòÉΓòÉ 24.160. Hash %%s missing the % in argument %d of %s() ΓòÉΓòÉΓòÉ
  14805.  
  14806. Hash %%s missing the % in argument %d of %s() 
  14807.  
  14808. (D) Really old Perl let you omit the % on hash names in some spots.  This is 
  14809. now heavily deprecated. 
  14810.  
  14811.  
  14812. ΓòÉΓòÉΓòÉ 24.161. Identifier "%s::%s" used only once: possible typo ΓòÉΓòÉΓòÉ
  14813.  
  14814. Identifier "%s::%s" used only once: possible typo 
  14815.  
  14816. (W) Typographical errors often show up as unique identifiers.  If you had a 
  14817. good reason for having a unique identifier, then just mention it again somehow 
  14818. to suppress the message. 
  14819.  
  14820.  
  14821. ΓòÉΓòÉΓòÉ 24.162. Illegal division by zero ΓòÉΓòÉΓòÉ
  14822.  
  14823. Illegal division by zero 
  14824.  
  14825. (F) You tried to divide a number by 0.  Either something was wrong in your 
  14826. logic, or you need to put a conditional in to guard against meaningless input. 
  14827.  
  14828.  
  14829. ΓòÉΓòÉΓòÉ 24.163. Illegal modulus zero ΓòÉΓòÉΓòÉ
  14830.  
  14831. Illegal modulus zero 
  14832.  
  14833. (F) You tried to divide a number by 0 to get the remainder.  Most numbers don't 
  14834. take to this kindly. 
  14835.  
  14836.  
  14837. ΓòÉΓòÉΓòÉ 24.164. Illegal octal digit ΓòÉΓòÉΓòÉ
  14838.  
  14839. Illegal octal digit 
  14840.  
  14841. (F) You used an 8 or 9 in a octal number. 
  14842.  
  14843.  
  14844. ΓòÉΓòÉΓòÉ 24.165. Illegal octal digit ignored ΓòÉΓòÉΓòÉ
  14845.  
  14846. Illegal octal digit ignored 
  14847.  
  14848. (W) You may have tried to use an 8 or 9 in a octal number.  Interpretation of 
  14849. the octal number stopped before the 8 or 9. 
  14850.  
  14851.  
  14852. ΓòÉΓòÉΓòÉ 24.166. Insecure dependency in %s ΓòÉΓòÉΓòÉ
  14853.  
  14854. Insecure dependency in %s 
  14855.  
  14856. (F) You tried to do something that the tainting mechanism didn't like. The 
  14857. tainting mechanism is turned on when you're running setuid or setgid, or when 
  14858. you specify -T to turn it on explicitly.  The tainting mechanism labels all 
  14859. data that's derived directly or indirectly from the user, who is considered to 
  14860. be unworthy of your trust.  If any such data is used in a "dangerous" 
  14861. operation, you get this error.  See perlsec for more information. 
  14862.  
  14863.  
  14864. ΓòÉΓòÉΓòÉ 24.167. Insecure directory in %s ΓòÉΓòÉΓòÉ
  14865.  
  14866. Insecure directory in %s 
  14867.  
  14868. (F) You can't use system(), exec(), or a piped open in a setuid or setgid 
  14869. script if $ENV{PATH} contains a directory that is writable by the world. See 
  14870. perlsec. 
  14871.  
  14872.  
  14873. ΓòÉΓòÉΓòÉ 24.168. Insecure PATH ΓòÉΓòÉΓòÉ
  14874.  
  14875. Insecure PATH 
  14876.  
  14877. (F) You can't use system(), exec(), or a piped open in a setuid or setgid 
  14878. script if $ENV{PATH} is derived from data supplied (or potentially supplied) by 
  14879. the user.  The script must set the path to a known value, using trustworthy 
  14880. data.  See perlsec. 
  14881.  
  14882.  
  14883. ΓòÉΓòÉΓòÉ 24.169. Internal inconsistency in tracking vforks ΓòÉΓòÉΓòÉ
  14884.  
  14885. Internal inconsistency in tracking vforks 
  14886.  
  14887. (S) A warning peculiar to VMS.  Perl keeps track of the number of times you've 
  14888. called fork and exec, in order to determine whether the current call to exec 
  14889. should be affect the current script or a subprocess (see perlvms/exec). 
  14890. Somehow, this count has become scrambled, so Perl is making a guess and 
  14891. treating this exec as a request to terminate the Perl script and execute the 
  14892. specified command. 
  14893.  
  14894.  
  14895. ΓòÉΓòÉΓòÉ 24.170. internal disaster in regexp ΓòÉΓòÉΓòÉ
  14896.  
  14897. internal disaster in regexp 
  14898.  
  14899. (P) Something went badly wrong in the regular expression parser. 
  14900.  
  14901.  
  14902. ΓòÉΓòÉΓòÉ 24.171. internal urp in regexp at /%s/ ΓòÉΓòÉΓòÉ
  14903.  
  14904. internal urp in regexp at /%s/ 
  14905.  
  14906. (P) Something went badly awry in the regular expression parser. 
  14907.  
  14908.  
  14909. ΓòÉΓòÉΓòÉ 24.172. invalid [] range in regexp ΓòÉΓòÉΓòÉ
  14910.  
  14911. invalid [] range in regexp 
  14912.  
  14913. (F) The range specified in a character class had a minimum character greater 
  14914. than the maximum character.  See perlre. 
  14915.  
  14916.  
  14917. ΓòÉΓòÉΓòÉ 24.173. ioctl is not implemented ΓòÉΓòÉΓòÉ
  14918.  
  14919. ioctl is not implemented 
  14920.  
  14921. (F) Your machine apparently doesn't implement ioctl(), which is pretty strange 
  14922. for a machine that supports C. 
  14923.  
  14924.  
  14925. ΓòÉΓòÉΓòÉ 24.174. junk on end of regexp ΓòÉΓòÉΓòÉ
  14926.  
  14927. junk on end of regexp 
  14928.  
  14929. (P) The regular expression parser is confused. 
  14930.  
  14931.  
  14932. ΓòÉΓòÉΓòÉ 24.175. Label not found for "last %s" ΓòÉΓòÉΓòÉ
  14933.  
  14934. Label not found for "last %s" 
  14935.  
  14936. (F) You named a loop to break out of, but you're not currently in a loop of 
  14937. that name, not even if you count where you were called from. See perlfunc/last. 
  14938.  
  14939.  
  14940. ΓòÉΓòÉΓòÉ 24.176. Label not found for "next %s" ΓòÉΓòÉΓòÉ
  14941.  
  14942. Label not found for "next %s" 
  14943.  
  14944. (F) You named a loop to continue, but you're not currently in a loop of that 
  14945. name, not even if you count where you were called from.  See perlfunc/last. 
  14946.  
  14947.  
  14948. ΓòÉΓòÉΓòÉ 24.177. Label not found for "redo %s" ΓòÉΓòÉΓòÉ
  14949.  
  14950. Label not found for "redo %s" 
  14951.  
  14952. (F) You named a loop to restart, but you're not currently in a loop of that 
  14953. name, not even if you count where you were called from.  See perlfunc/last. 
  14954.  
  14955.  
  14956. ΓòÉΓòÉΓòÉ 24.178. listen() on closed fd ΓòÉΓòÉΓòÉ
  14957.  
  14958. listen() on closed fd 
  14959.  
  14960. (W) You tried to do a listen on a closed socket.  Did you forget to check the 
  14961. return value of your socket() call?  See perlfunc/listen. 
  14962.  
  14963.  
  14964. ΓòÉΓòÉΓòÉ 24.179. Literal @%s now requires backslash ΓòÉΓòÉΓòÉ
  14965.  
  14966. Literal @%s now requires backslash 
  14967.  
  14968. (F) It used to be that Perl would try to guess whether you wanted an array 
  14969. interpolated or a literal @.  It did this when the string was first used at 
  14970. runtime.  Now strings are parsed at compile time, and ambiguous instances of @ 
  14971. must be disambiguated, either by putting a backslash to indicate a literal, or 
  14972. by declaring (or using) the array within the program before the string 
  14973. (lexically).  (Someday it will simply assume that an unbackslashed @ 
  14974. interpolates an array.) 
  14975.  
  14976.  
  14977. ΓòÉΓòÉΓòÉ 24.180. Method for operation %s not found in package %s during blessing ΓòÉΓòÉΓòÉ
  14978.  
  14979. Method for operation %s not found in package %s during blessing 
  14980.  
  14981. (F) An attempt was made to specify an entry in an overloading table that 
  14982. doesn't somehow point to a valid method.  See perlovl. 
  14983.  
  14984.  
  14985. ΓòÉΓòÉΓòÉ 24.181. Might be a runaway multi-line %s string starting on line %d ΓòÉΓòÉΓòÉ
  14986.  
  14987. Might be a runaway multi-line %s string starting on line %d 
  14988.  
  14989. (S) An advisory indicating that the previous error may have been caused by a 
  14990. missing delimiter on a string or pattern, because it eventually ended earlier 
  14991. on the current line. 
  14992.  
  14993.  
  14994. ΓòÉΓòÉΓòÉ 24.182. Misplaced _ in number ΓòÉΓòÉΓòÉ
  14995.  
  14996. Misplaced _ in number 
  14997.  
  14998. (W) An underline in a decimal constant wasn't on a 3-digit boundary. 
  14999.  
  15000.  
  15001. ΓòÉΓòÉΓòÉ 24.183. Missing $ on loop variable ΓòÉΓòÉΓòÉ
  15002.  
  15003. Missing $ on loop variable 
  15004.  
  15005. (F) Apparently you've been programming in csh too much.  Variables are always 
  15006. mentioned with the $ in Perl, unlike in the shells, where it can vary from one 
  15007. line to the next. 
  15008.  
  15009.  
  15010. ΓòÉΓòÉΓòÉ 24.184. Missing comma after first argument to %s function ΓòÉΓòÉΓòÉ
  15011.  
  15012. Missing comma after first argument to %s function 
  15013.  
  15014. (F) While certain functions allow you to specify a filehandle or an "indirect 
  15015. object" before the argument list, this ain't one of them. 
  15016.  
  15017.  
  15018. ΓòÉΓòÉΓòÉ 24.185. Missing operator before %s? ΓòÉΓòÉΓòÉ
  15019.  
  15020. Missing operator before %s? 
  15021.  
  15022. (S) This is an educated guess made in conjunction with the message "%s found 
  15023. where operator expected".  Often the missing operator is a comma. 
  15024.  
  15025.  
  15026. ΓòÉΓòÉΓòÉ 24.186. Missing right bracket ΓòÉΓòÉΓòÉ
  15027.  
  15028. Missing right bracket 
  15029.  
  15030. (F) The lexer counted more opening curly brackets (braces) than closing ones. 
  15031. As a general rule, you'll find it's missing near the place you were last 
  15032. editing. 
  15033.  
  15034.  
  15035. ΓòÉΓòÉΓòÉ 24.187. Missing semicolon on previous line? ΓòÉΓòÉΓòÉ
  15036.  
  15037. Missing semicolon on previous line? 
  15038.  
  15039. (S) This is an educated guess made in conjunction with the message "%s found 
  15040. where operator expected".  Don't automatically put a semicolon on the previous 
  15041. line just because you saw this message. 
  15042.  
  15043.  
  15044. ΓòÉΓòÉΓòÉ 24.188. Modification of a read-only value attempted ΓòÉΓòÉΓòÉ
  15045.  
  15046. Modification of a read-only value attempted 
  15047.  
  15048. (F) You tried, directly or indirectly, to change the value of a constant.  You 
  15049. didn't, of course, try "2 = 1", since the compiler catches that.  But an easy 
  15050. way to do the same thing is: 
  15051.  
  15052.     sub mod { $_[0] = 1 }
  15053.     mod(2);
  15054.  
  15055. Another way is to assign to a substr() that's off the end of the string. 
  15056.  
  15057.  
  15058. ΓòÉΓòÉΓòÉ 24.189. Modification of non-creatable array value attempted, subscript %d ΓòÉΓòÉΓòÉ
  15059.  
  15060. Modification of non-creatable array value attempted, subscript %d 
  15061.  
  15062. (F) You tried to make an array value spring into existence, and the subscript 
  15063. was probably negative, even counting from end of the array backwards. 
  15064.  
  15065.  
  15066. ΓòÉΓòÉΓòÉ 24.190. Modification of non-creatable hash value attempted, subscript "%s" ΓòÉΓòÉΓòÉ
  15067.  
  15068. Modification of non-creatable hash value attempted, subscript "%s" 
  15069.  
  15070. (F) You tried to make a hash value spring into existence, and it couldn't be 
  15071. created for some peculiar reason. 
  15072.  
  15073.  
  15074. ΓòÉΓòÉΓòÉ 24.191. Module name must be constant ΓòÉΓòÉΓòÉ
  15075.  
  15076. Module name must be constant 
  15077.  
  15078. (F) Only a bare module name is allowed as the first argument to a "use". 
  15079.  
  15080.  
  15081. ΓòÉΓòÉΓòÉ 24.192. msg%s not implemented ΓòÉΓòÉΓòÉ
  15082.  
  15083. msg%s not implemented 
  15084.  
  15085. (F) You don't have System V message IPC on your system. 
  15086.  
  15087.  
  15088. ΓòÉΓòÉΓòÉ 24.193. Multidimensional syntax %s not supported ΓòÉΓòÉΓòÉ
  15089.  
  15090. Multidimensional syntax %s not supported 
  15091.  
  15092. (W) Multidimensional arrays aren't written like $foo[1,2,3].  They're written 
  15093. like $foo[1][2][3], as in C. 
  15094.  
  15095.  
  15096. ΓòÉΓòÉΓòÉ 24.194. Negative length ΓòÉΓòÉΓòÉ
  15097.  
  15098. Negative length 
  15099.  
  15100. (F) You tried to do a read/write/send/recv operation with a buffer length that 
  15101. is less than 0.  This is difficult to imagine. 
  15102.  
  15103.  
  15104. ΓòÉΓòÉΓòÉ 24.195. nested *?+ in regexp ΓòÉΓòÉΓòÉ
  15105.  
  15106. nested *?+ in regexp 
  15107.  
  15108. (F) You can't quantify a quantifier without intervening parens.  So things like 
  15109. ** or +* or ?* are illegal. 
  15110.  
  15111. Note, however, that the minimal matching quantifiers, *?, +? and ?? appear to 
  15112. be nested quantifiers, but aren't.  See perlre. 
  15113.  
  15114.  
  15115. ΓòÉΓòÉΓòÉ 24.196. No #! line ΓòÉΓòÉΓòÉ
  15116.  
  15117. No #! line 
  15118.  
  15119. (F) The setuid emulator requires that scripts have a well-formed #! line even 
  15120. on machines that don't support the #! construct. 
  15121.  
  15122.  
  15123. ΓòÉΓòÉΓòÉ 24.197. No %s allowed while running setuid ΓòÉΓòÉΓòÉ
  15124.  
  15125. No %s allowed while running setuid 
  15126.  
  15127. (F) Certain operations are deemed to be too insecure for a setuid or setgid 
  15128. script to even be allowed to attempt.  Generally speaking there will be another 
  15129. way to do what you want that is, if not secure, at least securable. See 
  15130. perlsec. 
  15131.  
  15132.  
  15133. ΓòÉΓòÉΓòÉ 24.198. No  ΓòÉΓòÉΓòÉ
  15134.  
  15135. -e allowed in setuid scripts 
  15136.  
  15137. No -e allowed in setuid scripts 
  15138.  
  15139. (F) A setuid script can't be specified by the user. 
  15140.  
  15141.  
  15142. ΓòÉΓòÉΓòÉ 24.199. No comma allowed after %s ΓòÉΓòÉΓòÉ
  15143.  
  15144. No comma allowed after %s 
  15145.  
  15146. (F) A list operator that has a filehandle or "indirect object" is not allowed 
  15147. to have a comma between that and the following arguments. Otherwise it'd be 
  15148. just another one of the arguments. 
  15149.  
  15150.  
  15151. ΓòÉΓòÉΓòÉ 24.200. No command into which to pipe on command line ΓòÉΓòÉΓòÉ
  15152.  
  15153. No command into which to pipe on command line 
  15154.  
  15155. (F) An error peculiar to VMS.  Perl handles its own command line redirection, 
  15156. and found a '|' at the end of the command line, so it doesn't know whither you 
  15157. want to pipe the output from this command. 
  15158.  
  15159.  
  15160. ΓòÉΓòÉΓòÉ 24.201. No DB::DB routine defined ΓòÉΓòÉΓòÉ
  15161.  
  15162. No DB::DB routine defined 
  15163.  
  15164. (F) The currently executing code was compiled with the -d switch, but for some 
  15165. reason the perl5db.pl file (or some facsimile thereof) didn't define a routine 
  15166. to be called at the beginning of each statement.  Which is odd, because the 
  15167. file should have been required automatically, and should have blown up the 
  15168. require if it didn't parse right. 
  15169.  
  15170.  
  15171. ΓòÉΓòÉΓòÉ 24.202. No dbm on this machine ΓòÉΓòÉΓòÉ
  15172.  
  15173. No dbm on this machine 
  15174.  
  15175. (P) This is counted as an internal error, because every machine should supply 
  15176. dbm nowadays, since Perl comes with SDBM.  See L<SDBM_File>. 
  15177.  
  15178.  
  15179. ΓòÉΓòÉΓòÉ 24.203. No DBsub routine ΓòÉΓòÉΓòÉ
  15180.  
  15181. No DBsub routine 
  15182.  
  15183. (F) The currently executing code was compiled with the -d switch, but for some 
  15184. reason the perl5db.pl file (or some facsimile thereof) didn't define a DB::sub 
  15185. routine to be called at the beginning of each ordinary subroutine call. 
  15186.  
  15187.  
  15188. ΓòÉΓòÉΓòÉ 24.204. No error file after 2> or 2>> on command line ΓòÉΓòÉΓòÉ
  15189.  
  15190. No error file after 2> or 2>> on command line 
  15191.  
  15192. (F) An error peculiar to VMS.  Perl handles its own command line redirection, 
  15193. and found a '2>' or a '2>>' on the command line, but can't find the name of the 
  15194. file to which to write data destined for stderr. 
  15195.  
  15196.  
  15197. ΓòÉΓòÉΓòÉ 24.205. No input file after < on command line ΓòÉΓòÉΓòÉ
  15198.  
  15199. No input file after < on command line 
  15200.  
  15201. (F) An error peculiar to VMS.  Perl handles its own command line redirection, 
  15202. and found a '<' on the command line, but can't find the name of the file from 
  15203. which to read data for stdin. 
  15204.  
  15205.  
  15206. ΓòÉΓòÉΓòÉ 24.206. No output file after > on command line ΓòÉΓòÉΓòÉ
  15207.  
  15208. No output file after > on command line 
  15209.  
  15210. (F) An error peculiar to VMS.  Perl handles its own command line redirection, 
  15211. and found a lone '>' at the end of the command line, so it doesn't know whither 
  15212. you wanted to redirect stdout. 
  15213.  
  15214.  
  15215. ΓòÉΓòÉΓòÉ 24.207. No output file after > or >> on command line ΓòÉΓòÉΓòÉ
  15216.  
  15217. No output file after > or >> on command line 
  15218.  
  15219. (F) An error peculiar to VMS.  Perl handles its own command line redirection, 
  15220. and found a '>' or a '>>' on the command line, but can't find the name of the 
  15221. file to which to write data destined for stdout. 
  15222.  
  15223.  
  15224. ΓòÉΓòÉΓòÉ 24.208. No Perl script found in input ΓòÉΓòÉΓòÉ
  15225.  
  15226. No Perl script found in input 
  15227.  
  15228. (F) You called perl -x, but no line was found in the file beginning with #! and 
  15229. containing the word "perl". 
  15230.  
  15231.  
  15232. ΓòÉΓòÉΓòÉ 24.209. No setregid available ΓòÉΓòÉΓòÉ
  15233.  
  15234. No setregid available 
  15235.  
  15236. (F) Configure didn't find anything resembling the setregid() call for your 
  15237. system. 
  15238.  
  15239.  
  15240. ΓòÉΓòÉΓòÉ 24.210. No setreuid available ΓòÉΓòÉΓòÉ
  15241.  
  15242. No setreuid available 
  15243.  
  15244. (F) Configure didn't find anything resembling the setreuid() call for your 
  15245. system. 
  15246.  
  15247.  
  15248. ΓòÉΓòÉΓòÉ 24.211. No space allowed after  ΓòÉΓòÉΓòÉ
  15249.  
  15250. -I 
  15251.  
  15252. No space allowed after -I 
  15253.  
  15254. (F) The argument to -I must follow the -I immediately with no intervening 
  15255. space. 
  15256.  
  15257.  
  15258. ΓòÉΓòÉΓòÉ 24.212. No such pipe open ΓòÉΓòÉΓòÉ
  15259.  
  15260. No such pipe open 
  15261.  
  15262. (P) An error peculiar to VMS.  The internal routine my_pclose() tried to close 
  15263. a pipe which hadn't been opened.  This should have been caught earlier as an 
  15264. attempt to close an unopened filehandle. 
  15265.  
  15266.  
  15267. ΓòÉΓòÉΓòÉ 24.213. No such signal: SIG%s ΓòÉΓòÉΓòÉ
  15268.  
  15269. No such signal: SIG%s 
  15270.  
  15271. (W) You specified a signal name as a subscript to %SIG that was not recognized. 
  15272. Say kill -l in your shell to see the valid signal names on your system. 
  15273.  
  15274.  
  15275. ΓòÉΓòÉΓòÉ 24.214. Not a CODE reference ΓòÉΓòÉΓòÉ
  15276.  
  15277. Not a CODE reference 
  15278.  
  15279. (F) Perl was trying to evaluate a reference to a code value (that is, a 
  15280. subroutine), but found a reference to something else instead.  You can use the 
  15281. ref() function to find out what kind of ref it really was. See also perlref. 
  15282.  
  15283.  
  15284. ΓòÉΓòÉΓòÉ 24.215. Not a format reference ΓòÉΓòÉΓòÉ
  15285.  
  15286. Not a format reference 
  15287.  
  15288. (F) I'm not sure how you managed to generate a reference to an anonymous 
  15289. format, but this indicates you did, and that it didn't exist. 
  15290.  
  15291.  
  15292. ΓòÉΓòÉΓòÉ 24.216. Not a GLOB reference ΓòÉΓòÉΓòÉ
  15293.  
  15294. Not a GLOB reference 
  15295.  
  15296. (F) Perl was trying to evaluate a reference to a "type glob" (that is, a symbol 
  15297. table entry that looks like *foo), but found a reference to something else 
  15298. instead.  You can use the ref() function to find out what kind of ref it really 
  15299. was.  See perlref. 
  15300.  
  15301.  
  15302. ΓòÉΓòÉΓòÉ 24.217. Not a HASH reference ΓòÉΓòÉΓòÉ
  15303.  
  15304. Not a HASH reference 
  15305.  
  15306. (F) Perl was trying to evaluate a reference to a hash value, but found a 
  15307. reference to something else instead.  You can use the ref() function to find 
  15308. out what kind of ref it really was.  See perlref. 
  15309.  
  15310.  
  15311. ΓòÉΓòÉΓòÉ 24.218. Not a perl script ΓòÉΓòÉΓòÉ
  15312.  
  15313. Not a perl script 
  15314.  
  15315. (F) The setuid emulator requires that scripts have a well-formed #! line even 
  15316. on machines that don't support the #! construct.  The line must mention perl. 
  15317.  
  15318.  
  15319. ΓòÉΓòÉΓòÉ 24.219. Not a SCALAR reference ΓòÉΓòÉΓòÉ
  15320.  
  15321. Not a SCALAR reference 
  15322.  
  15323. (F) Perl was trying to evaluate a reference to a scalar value, but found a 
  15324. reference to something else instead.  You can use the ref() function to find 
  15325. out what kind of ref it really was.  See perlref. 
  15326.  
  15327.  
  15328. ΓòÉΓòÉΓòÉ 24.220. Not a subroutine reference ΓòÉΓòÉΓòÉ
  15329.  
  15330. Not a subroutine reference 
  15331.  
  15332. (F) Perl was trying to evaluate a reference to a code value (that is, a 
  15333. subroutine), but found a reference to something else instead.  You can use the 
  15334. ref() function to find out what kind of ref it really was. See also perlref. 
  15335.  
  15336.  
  15337. ΓòÉΓòÉΓòÉ 24.221. Not a subroutine reference in %OVERLOAD ΓòÉΓòÉΓòÉ
  15338.  
  15339. Not a subroutine reference in %OVERLOAD 
  15340.  
  15341. (F) An attempt was made to specify an entry in an overloading table that 
  15342. doesn't somehow point to a valid subroutine.  See perlovl. 
  15343.  
  15344.  
  15345. ΓòÉΓòÉΓòÉ 24.222. Not an ARRAY reference ΓòÉΓòÉΓòÉ
  15346.  
  15347. Not an ARRAY reference 
  15348.  
  15349. (F) Perl was trying to evaluate a reference to an array value, but found a 
  15350. reference to something else instead.  You can use the ref() function to find 
  15351. out what kind of ref it really was.  See perlref. 
  15352.  
  15353.  
  15354. ΓòÉΓòÉΓòÉ 24.223. Not enough arguments for %s ΓòÉΓòÉΓòÉ
  15355.  
  15356. Not enough arguments for %s 
  15357.  
  15358. (F) The function requires more arguments than you specified. 
  15359.  
  15360.  
  15361. ΓòÉΓòÉΓòÉ 24.224. Not enough format arguments ΓòÉΓòÉΓòÉ
  15362.  
  15363. Not enough format arguments 
  15364.  
  15365. (W) A format specified more picture fields than the next line supplied. See 
  15366. perlform. 
  15367.  
  15368.  
  15369. ΓòÉΓòÉΓòÉ 24.225. Null filename used ΓòÉΓòÉΓòÉ
  15370.  
  15371. Null filename used 
  15372.  
  15373. (F) You can't require the null filename, especially since on many machines that 
  15374. means the current directory!  See perlfunc/require. 
  15375.  
  15376.  
  15377. ΓòÉΓòÉΓòÉ 24.226. NULL OP IN RUN ΓòÉΓòÉΓòÉ
  15378.  
  15379. NULL OP IN RUN 
  15380.  
  15381. (P) Some internal routine called run() with a null opcode pointer. 
  15382.  
  15383.  
  15384. ΓòÉΓòÉΓòÉ 24.227. Null realloc ΓòÉΓòÉΓòÉ
  15385.  
  15386. Null realloc 
  15387.  
  15388. (P) An attempt was made to realloc NULL. 
  15389.  
  15390.  
  15391. ΓòÉΓòÉΓòÉ 24.228. NULL regexp argument ΓòÉΓòÉΓòÉ
  15392.  
  15393. NULL regexp argument 
  15394.  
  15395. (P) The internal pattern matching routines blew it bigtime. 
  15396.  
  15397.  
  15398. ΓòÉΓòÉΓòÉ 24.229. NULL regexp parameter ΓòÉΓòÉΓòÉ
  15399.  
  15400. NULL regexp parameter 
  15401.  
  15402. (P) The internal pattern matching routines are out of their gourd. 
  15403.  
  15404.  
  15405. ΓòÉΓòÉΓòÉ 24.230. Odd number of elements in hash list ΓòÉΓòÉΓòÉ
  15406.  
  15407. Odd number of elements in hash list 
  15408.  
  15409. (S) You specified an odd number of elements to a hash list, which is odd, since 
  15410. hash lists come in key/value pairs. 
  15411.  
  15412.  
  15413. ΓòÉΓòÉΓòÉ 24.231. oops: oopsAV ΓòÉΓòÉΓòÉ
  15414.  
  15415. oops: oopsAV 
  15416.  
  15417. (S) An internal warning that the grammar is screwed up. 
  15418.  
  15419.  
  15420. ΓòÉΓòÉΓòÉ 24.232. oops: oopsHV ΓòÉΓòÉΓòÉ
  15421.  
  15422. oops: oopsHV 
  15423.  
  15424. (S) An internal warning that the grammar is screwed up. 
  15425.  
  15426.  
  15427. ΓòÉΓòÉΓòÉ 24.233. Operation `%s' %s: no method found, ΓòÉΓòÉΓòÉ
  15428.  
  15429. Operation `%s' %s: no method found, 
  15430.  
  15431. (F) An attempt was made to use an entry in an overloading table that somehow no 
  15432. longer points to a valid method.  See perlovl. 
  15433.  
  15434.  
  15435. ΓòÉΓòÉΓòÉ 24.234. Operator or semicolon missing before %s ΓòÉΓòÉΓòÉ
  15436.  
  15437. Operator or semicolon missing before %s 
  15438.  
  15439. (S) You used a variable or subroutine call where the parser was expecting an 
  15440. operator.  The parser has assumed you really meant to use an operator, but this 
  15441. is highly likely to be incorrect. For example, if you say "*foo *foo" it will 
  15442. be interpreted as if you said "*foo * 'foo'". 
  15443.  
  15444.  
  15445. ΓòÉΓòÉΓòÉ 24.235. Out of memory for yacc stack ΓòÉΓòÉΓòÉ
  15446.  
  15447. Out of memory for yacc stack 
  15448.  
  15449. (F) The yacc parser wanted to grow its stack so it could continue parsing, but 
  15450. realloc() wouldn't give it more memory, virtual or otherwise. 
  15451.  
  15452.  
  15453. ΓòÉΓòÉΓòÉ 24.236. Out of memory! ΓòÉΓòÉΓòÉ
  15454.  
  15455. Out of memory! 
  15456.  
  15457. (X) The malloc() function returned 0, indicating there was insufficient 
  15458. remaining memory (or virtual memory) to satisfy the request. 
  15459.  
  15460.  
  15461. ΓòÉΓòÉΓòÉ 24.237. page overflow ΓòÉΓòÉΓòÉ
  15462.  
  15463. page overflow 
  15464.  
  15465. (W) A single call to write() produced more lines than can fit on a page. See 
  15466. perlform. 
  15467.  
  15468.  
  15469. ΓòÉΓòÉΓòÉ 24.238. panic: ck_grep ΓòÉΓòÉΓòÉ
  15470.  
  15471. panic: ck_grep 
  15472.  
  15473. (P) Failed an internal consistency check trying to compile a grep. 
  15474.  
  15475.  
  15476. ΓòÉΓòÉΓòÉ 24.239. panic: ck_split ΓòÉΓòÉΓòÉ
  15477.  
  15478. panic: ck_split 
  15479.  
  15480. (P) Failed an internal consistency check trying to compile a split. 
  15481.  
  15482.  
  15483. ΓòÉΓòÉΓòÉ 24.240. panic: corrupt saved stack index ΓòÉΓòÉΓòÉ
  15484.  
  15485. panic: corrupt saved stack index 
  15486.  
  15487. (P) The savestack was requested to restore more localized values than there are 
  15488. in the savestack. 
  15489.  
  15490.  
  15491. ΓòÉΓòÉΓòÉ 24.241. panic: die %s ΓòÉΓòÉΓòÉ
  15492.  
  15493. panic: die %s 
  15494.  
  15495. (P) We popped the context stack to an eval context, and then discovered it 
  15496. wasn't an eval context. 
  15497.  
  15498.  
  15499. ΓòÉΓòÉΓòÉ 24.242. panic: do_match ΓòÉΓòÉΓòÉ
  15500.  
  15501. panic: do_match 
  15502.  
  15503. (P) The internal pp_match() routine was called with invalid operational data. 
  15504.  
  15505.  
  15506. ΓòÉΓòÉΓòÉ 24.243. panic: do_split ΓòÉΓòÉΓòÉ
  15507.  
  15508. panic: do_split 
  15509.  
  15510. (P) Something terrible went wrong in setting up for the split. 
  15511.  
  15512.  
  15513. ΓòÉΓòÉΓòÉ 24.244. panic: do_subst ΓòÉΓòÉΓòÉ
  15514.  
  15515. panic: do_subst 
  15516.  
  15517. (P) The internal pp_subst() routine was called with invalid operational data. 
  15518.  
  15519.  
  15520. ΓòÉΓòÉΓòÉ 24.245. panic: do_trans ΓòÉΓòÉΓòÉ
  15521.  
  15522. panic: do_trans 
  15523.  
  15524. (P) The internal do_trans() routine was called with invalid operational data. 
  15525.  
  15526.  
  15527. ΓòÉΓòÉΓòÉ 24.246. panic: goto ΓòÉΓòÉΓòÉ
  15528.  
  15529. panic: goto 
  15530.  
  15531. (P) We popped the context stack to a context with the specified label, and then 
  15532. discovered it wasn't a context we know how to do a goto in. 
  15533.  
  15534.  
  15535. ΓòÉΓòÉΓòÉ 24.247. panic: INTERPCASEMOD ΓòÉΓòÉΓòÉ
  15536.  
  15537. panic: INTERPCASEMOD 
  15538.  
  15539. (P) The lexer got into a bad state at a case modifier. 
  15540.  
  15541.  
  15542. ΓòÉΓòÉΓòÉ 24.248. panic: INTERPCONCAT ΓòÉΓòÉΓòÉ
  15543.  
  15544. panic: INTERPCONCAT 
  15545.  
  15546. (P) The lexer got into a bad state parsing a string with brackets. 
  15547.  
  15548.  
  15549. ΓòÉΓòÉΓòÉ 24.249. panic: last ΓòÉΓòÉΓòÉ
  15550.  
  15551. panic: last 
  15552.  
  15553. (P) We popped the context stack to a block context, and then discovered it 
  15554. wasn't a block context. 
  15555.  
  15556.  
  15557. ΓòÉΓòÉΓòÉ 24.250. panic: leave_scope clearsv ΓòÉΓòÉΓòÉ
  15558.  
  15559. panic: leave_scope clearsv 
  15560.  
  15561. (P) A writable lexical variable became readonly somehow within the scope. 
  15562.  
  15563.  
  15564. ΓòÉΓòÉΓòÉ 24.251. panic: leave_scope inconsistency ΓòÉΓòÉΓòÉ
  15565.  
  15566. panic: leave_scope inconsistency 
  15567.  
  15568. (P) The savestack probably got out of sync.  At least, there was an invalid 
  15569. enum on the top of it. 
  15570.  
  15571.  
  15572. ΓòÉΓòÉΓòÉ 24.252. panic: malloc ΓòÉΓòÉΓòÉ
  15573.  
  15574. panic: malloc 
  15575.  
  15576. (P) Something requested a negative number of bytes of malloc. 
  15577.  
  15578.  
  15579. ΓòÉΓòÉΓòÉ 24.253. panic: mapstart ΓòÉΓòÉΓòÉ
  15580.  
  15581. panic: mapstart 
  15582.  
  15583. (P) The compiler is screwed up with respect to the map() function. 
  15584.  
  15585.  
  15586. ΓòÉΓòÉΓòÉ 24.254. panic: null array ΓòÉΓòÉΓòÉ
  15587.  
  15588. panic: null array 
  15589.  
  15590. (P) One of the internal array routines was passed a null AV pointer. 
  15591.  
  15592.  
  15593. ΓòÉΓòÉΓòÉ 24.255. panic: pad_alloc ΓòÉΓòÉΓòÉ
  15594.  
  15595. panic: pad_alloc 
  15596.  
  15597. (P) The compiler got confused about which scratch pad it was allocating and 
  15598. freeing temporaries and lexicals from. 
  15599.  
  15600.  
  15601. ΓòÉΓòÉΓòÉ 24.256. panic: pad_free curpad ΓòÉΓòÉΓòÉ
  15602.  
  15603. panic: pad_free curpad 
  15604.  
  15605. (P) The compiler got confused about which scratch pad it was allocating and 
  15606. freeing temporaries and lexicals from. 
  15607.  
  15608.  
  15609. ΓòÉΓòÉΓòÉ 24.257. panic: pad_free po ΓòÉΓòÉΓòÉ
  15610.  
  15611. panic: pad_free po 
  15612.  
  15613. (P) An invalid scratch pad offset was detected internally. 
  15614.  
  15615.  
  15616. ΓòÉΓòÉΓòÉ 24.258. panic: pad_reset curpad ΓòÉΓòÉΓòÉ
  15617.  
  15618. panic: pad_reset curpad 
  15619.  
  15620. (P) The compiler got confused about which scratch pad it was allocating and 
  15621. freeing temporaries and lexicals from. 
  15622.  
  15623.  
  15624. ΓòÉΓòÉΓòÉ 24.259. panic: pad_sv po ΓòÉΓòÉΓòÉ
  15625.  
  15626. panic: pad_sv po 
  15627.  
  15628. (P) An invalid scratch pad offset was detected internally. 
  15629.  
  15630.  
  15631. ΓòÉΓòÉΓòÉ 24.260. panic: pad_swipe curpad ΓòÉΓòÉΓòÉ
  15632.  
  15633. panic: pad_swipe curpad 
  15634.  
  15635. (P) The compiler got confused about which scratch pad it was allocating and 
  15636. freeing temporaries and lexicals from. 
  15637.  
  15638.  
  15639. ΓòÉΓòÉΓòÉ 24.261. panic: pad_swipe po ΓòÉΓòÉΓòÉ
  15640.  
  15641. panic: pad_swipe po 
  15642.  
  15643. (P) An invalid scratch pad offset was detected internally. 
  15644.  
  15645.  
  15646. ΓòÉΓòÉΓòÉ 24.262. panic: pp_iter ΓòÉΓòÉΓòÉ
  15647.  
  15648. panic: pp_iter 
  15649.  
  15650. (P) The foreach iterator got called in a non-loop context frame. 
  15651.  
  15652.  
  15653. ΓòÉΓòÉΓòÉ 24.263. panic: realloc ΓòÉΓòÉΓòÉ
  15654.  
  15655. panic: realloc 
  15656.  
  15657. (P) Something requested a negative number of bytes of realloc. 
  15658.  
  15659.  
  15660. ΓòÉΓòÉΓòÉ 24.264. panic: restartop ΓòÉΓòÉΓòÉ
  15661.  
  15662. panic: restartop 
  15663.  
  15664. (P) Some internal routine requested a goto (or something like it), and didn't 
  15665. supply the destination. 
  15666.  
  15667.  
  15668. ΓòÉΓòÉΓòÉ 24.265. panic: return ΓòÉΓòÉΓòÉ
  15669.  
  15670. panic: return 
  15671.  
  15672. (P) We popped the context stack to a subroutine or eval context, and then 
  15673. discovered it wasn't a subroutine or eval context. 
  15674.  
  15675.  
  15676. ΓòÉΓòÉΓòÉ 24.266. panic: scan_num ΓòÉΓòÉΓòÉ
  15677.  
  15678. panic: scan_num 
  15679.  
  15680. (P) scan_num() got called on something that wasn't a number. 
  15681.  
  15682.  
  15683. ΓòÉΓòÉΓòÉ 24.267. panic: sv_insert ΓòÉΓòÉΓòÉ
  15684.  
  15685. panic: sv_insert 
  15686.  
  15687. (P) The sv_insert() routine was told to remove more string than there was 
  15688. string. 
  15689.  
  15690.  
  15691. ΓòÉΓòÉΓòÉ 24.268. panic: top_env ΓòÉΓòÉΓòÉ
  15692.  
  15693. panic: top_env 
  15694.  
  15695. (P) The compiler attempted to do a goto, or something weird like that. 
  15696.  
  15697.  
  15698. ΓòÉΓòÉΓòÉ 24.269. panic: yylex ΓòÉΓòÉΓòÉ
  15699.  
  15700. panic: yylex 
  15701.  
  15702. (P) The lexer got into a bad state while processing a case modifier. 
  15703.  
  15704.  
  15705. ΓòÉΓòÉΓòÉ 24.270. Parens missing around "%s" list ΓòÉΓòÉΓòÉ
  15706.  
  15707. Parens missing around "%s" list 
  15708.  
  15709. (W) You said something like 
  15710.  
  15711.     my $foo, $bar = @_;
  15712.  
  15713. when you meant 
  15714.  
  15715.     my ($foo, $bar) = @_;
  15716.  
  15717. Remember that "my" and "local" bind closer than comma. 
  15718.  
  15719.  
  15720. ΓòÉΓòÉΓòÉ 24.271. Perl %3.3f required--this is only version %s, stopped ΓòÉΓòÉΓòÉ
  15721.  
  15722. Perl %3.3f required--this is only version %s, stopped 
  15723.  
  15724. (F) The module in question uses features of a version of Perl more recent than 
  15725. the currently running version.  How long has it been since you upgraded, 
  15726. anyway?  See perlfunc/require. 
  15727.  
  15728.  
  15729. ΓòÉΓòÉΓòÉ 24.272. Permission denied ΓòÉΓòÉΓòÉ
  15730.  
  15731. Permission denied 
  15732.  
  15733. (F) The setuid emulator in suidperl decided you were up to no good. 
  15734.  
  15735.  
  15736. ΓòÉΓòÉΓòÉ 24.273. pid %d not a child ΓòÉΓòÉΓòÉ
  15737.  
  15738. pid %d not a child 
  15739.  
  15740. (W) A warning peculiar to VMS.  Waitpid() was asked to wait for a process which 
  15741. isn't a subprocess of the current process.  While this is fine from VMS' 
  15742. perspective, it's probably not what you intended. 
  15743.  
  15744.  
  15745. ΓòÉΓòÉΓòÉ 24.274. POSIX getpgrp can't take an argument ΓòÉΓòÉΓòÉ
  15746.  
  15747. POSIX getpgrp can't take an argument 
  15748.  
  15749. (F) Your C compiler uses POSIX getpgrp(), which takes no argument, unlike the 
  15750. BSD version, which takes a pid. 
  15751.  
  15752.  
  15753. ΓòÉΓòÉΓòÉ 24.275. Possible memory corruption: %s overflowed 3rd argument ΓòÉΓòÉΓòÉ
  15754.  
  15755. Possible memory corruption: %s overflowed 3rd argument 
  15756.  
  15757. (F) An ioctl() or fcntl() returned more than Perl was bargaining for. Perl 
  15758. guesses a reasonable buffer size, but puts a sentinel byte at the end of the 
  15759. buffer just in case.  This sentinel byte got clobbered, and Perl assumes that 
  15760. memory is now corrupted.  See perlfunc/ioctl. 
  15761.  
  15762.  
  15763. ΓòÉΓòÉΓòÉ 24.276. Precedence problem: open %s should be open(%s) ΓòÉΓòÉΓòÉ
  15764.  
  15765. Precedence problem: open %s should be open(%s) 
  15766.  
  15767. (S) The old irregular construct 
  15768.  
  15769.     open FOO || die;
  15770.  
  15771. is now misinterpreted as 
  15772.  
  15773.     open(FOO || die);
  15774.  
  15775. because of the strict regularization of Perl 5's grammar into unary and list 
  15776. operators.  (The old open was a little of both.) You must put parens around the 
  15777. filehandle, or use the new "or" operator instead of "||". 
  15778.  
  15779.  
  15780. ΓòÉΓòÉΓòÉ 24.277. print on closed filehandle %s ΓòÉΓòÉΓòÉ
  15781.  
  15782. print on closed filehandle %s 
  15783.  
  15784. (W) The filehandle you're printing on got itself closed sometime before now. 
  15785. Check your logic flow. 
  15786.  
  15787.  
  15788. ΓòÉΓòÉΓòÉ 24.278. printf on closed filehandle %s ΓòÉΓòÉΓòÉ
  15789.  
  15790. printf on closed filehandle %s 
  15791.  
  15792. (W) The filehandle you're writing to got itself closed sometime before now. 
  15793. Check your logic flow. 
  15794.  
  15795.  
  15796. ΓòÉΓòÉΓòÉ 24.279. Probable precedence problem on %s ΓòÉΓòÉΓòÉ
  15797.  
  15798. Probable precedence problem on %s 
  15799.  
  15800. (W) The compiler found a bare word where it expected a conditional, which often 
  15801. indicates that an || or && was parsed as part of the last argument of the 
  15802. previous construct, for example: 
  15803.  
  15804.     open FOO || die;
  15805.  
  15806.  
  15807. ΓòÉΓòÉΓòÉ 24.280. Prototype mismatch: (%s) vs (%s) ΓòÉΓòÉΓòÉ
  15808.  
  15809. Prototype mismatch: (%s) vs (%s) 
  15810.  
  15811. (S) The subroutine being defined had a predeclared (forward) declaration with a 
  15812. different function prototype. 
  15813.  
  15814.  
  15815. ΓòÉΓòÉΓòÉ 24.281. Read on closed filehandle <%s> ΓòÉΓòÉΓòÉ
  15816.  
  15817. Read on closed filehandle <%s> 
  15818.  
  15819. (W) The filehandle you're reading from got itself closed sometime before now. 
  15820. Check your logic flow. 
  15821.  
  15822.  
  15823. ΓòÉΓòÉΓòÉ 24.282. Reallocation too large: %lx ΓòÉΓòÉΓòÉ
  15824.  
  15825. Reallocation too large: %lx 
  15826.  
  15827. (F) You can't allocate more than 64K on an MSDOS machine. 
  15828.  
  15829.  
  15830. ΓòÉΓòÉΓòÉ 24.283. Recompile perl with  ΓòÉΓòÉΓòÉ
  15831.  
  15832. -DDEBUGGING to use -D switch 
  15833.  
  15834. Recompile perl with -DDEBUGGING to use -D switch 
  15835.  
  15836. (F) You can't use the -D option unless the code to produce the desired output 
  15837. is compiled into Perl, which entails some overhead, which is why it's currently 
  15838. left out of your copy. 
  15839.  
  15840.  
  15841. ΓòÉΓòÉΓòÉ 24.284. Recursive inheritance detected ΓòÉΓòÉΓòÉ
  15842.  
  15843. Recursive inheritance detected 
  15844.  
  15845. (F) More than 100 levels of inheritance were used.  Probably indicates an 
  15846. unintended loop in your inheritance hierarchy. 
  15847.  
  15848.  
  15849. ΓòÉΓòÉΓòÉ 24.285. Reference miscount in sv_replace() ΓòÉΓòÉΓòÉ
  15850.  
  15851. Reference miscount in sv_replace() 
  15852.  
  15853. (W) The internal sv_replace() function was handed a new SV with a reference 
  15854. count of other than 1. 
  15855.  
  15856.  
  15857. ΓòÉΓòÉΓòÉ 24.286. regexp memory corruption ΓòÉΓòÉΓòÉ
  15858.  
  15859. regexp memory corruption 
  15860.  
  15861. (P) The regular expression engine got confused by what the regular expression 
  15862. compiler gave it. 
  15863.  
  15864.  
  15865. ΓòÉΓòÉΓòÉ 24.287. regexp out of space ΓòÉΓòÉΓòÉ
  15866.  
  15867. regexp out of space 
  15868.  
  15869. (P) A "can't happen" error, because safemalloc() should have caught it earlier. 
  15870.  
  15871.  
  15872. ΓòÉΓòÉΓòÉ 24.288. regexp too big ΓòÉΓòÉΓòÉ
  15873.  
  15874. regexp too big 
  15875.  
  15876. (F) The current implementation of regular expression uses shorts as address 
  15877. offsets within a string.  Unfortunately this means that if the regular 
  15878. expression compiles to longer than 32767, it'll blow up. Usually when you want 
  15879. a regular expression this big, there is a better way to do it with multiple 
  15880. statements.  See perlre. 
  15881.  
  15882.  
  15883. ΓòÉΓòÉΓòÉ 24.289. Reversed %s= operator ΓòÉΓòÉΓòÉ
  15884.  
  15885. Reversed %s= operator 
  15886.  
  15887. (W) You wrote your assignment operator backwards.  The = must always comes 
  15888. last, to avoid ambiguity with subsequent unary operators. 
  15889.  
  15890.  
  15891. ΓòÉΓòÉΓòÉ 24.290. Runaway format ΓòÉΓòÉΓòÉ
  15892.  
  15893. Runaway format 
  15894.  
  15895. (F) Your format contained the ~~ repeat-until-blank sequence, but it produced 
  15896. 200 lines at once, and the 200th line looked exactly like the 199th line. 
  15897. Apparently you didn't arrange for the arguments to exhaust themselves, either 
  15898. by using ^ instead of @ (for scalar variables), or by shifting or popping (for 
  15899. array variables).  See perlform. 
  15900.  
  15901.  
  15902. ΓòÉΓòÉΓòÉ 24.291. Scalar value @%s[%s] better written as $%s[%s] ΓòÉΓòÉΓòÉ
  15903.  
  15904. Scalar value @%s[%s] better written as $%s[%s] 
  15905.  
  15906. (W) You've used an array slice (indicated by @) to select a single value of an 
  15907. array.  Generally it's better to ask for a scalar value (indicated by $). The 
  15908. difference is that $foo[&bar] always behaves like a scalar, both when assigning 
  15909. to it and when evaluating its argument, while @foo[&bar] behaves like a list 
  15910. when you assign to it, and provides a list context to its subscript, which can 
  15911. do weird things if you're only expecting one subscript. 
  15912.  
  15913. On the other hand, if you were actually hoping to treat the array element as a 
  15914. list, you need to look into how references work, since Perl will not magically 
  15915. convert between scalars and lists for you.  See perlref. 
  15916.  
  15917.  
  15918. ΓòÉΓòÉΓòÉ 24.292. Script is not setuid/setgid in suidperl ΓòÉΓòÉΓòÉ
  15919.  
  15920. Script is not setuid/setgid in suidperl 
  15921.  
  15922. (F) Oddly, the suidperl program was invoked on a script with its setuid or 
  15923. setgid bit set.  This doesn't make much sense. 
  15924.  
  15925.  
  15926. ΓòÉΓòÉΓòÉ 24.293. Search pattern not terminated ΓòÉΓòÉΓòÉ
  15927.  
  15928. Search pattern not terminated 
  15929.  
  15930. (F) The lexer couldn't find the final delimiter of a // or m{} construct. 
  15931. Remember that bracketing delimiters count nesting level. 
  15932.  
  15933.  
  15934. ΓòÉΓòÉΓòÉ 24.294. seek() on unopened file ΓòÉΓòÉΓòÉ
  15935.  
  15936. seek() on unopened file 
  15937.  
  15938. (W) You tried to use the seek() function on a filehandle that was either never 
  15939. opened or has been closed since. 
  15940.  
  15941.  
  15942. ΓòÉΓòÉΓòÉ 24.295. select not implemented ΓòÉΓòÉΓòÉ
  15943.  
  15944. select not implemented 
  15945.  
  15946. (F) This machine doesn't implement the select() system call. 
  15947.  
  15948.  
  15949. ΓòÉΓòÉΓòÉ 24.296. sem%s not implemented ΓòÉΓòÉΓòÉ
  15950.  
  15951. sem%s not implemented 
  15952.  
  15953. (F) You don't have System V semaphore IPC on your system. 
  15954.  
  15955.  
  15956. ΓòÉΓòÉΓòÉ 24.297. semi-panic: attempt to dup freed string ΓòÉΓòÉΓòÉ
  15957.  
  15958. semi-panic: attempt to dup freed string 
  15959.  
  15960. (S) The internal newSVsv() routine was called to duplicate a scalar that had 
  15961. previously been marked as free. 
  15962.  
  15963.  
  15964. ΓòÉΓòÉΓòÉ 24.298. Semicolon seems to be missing ΓòÉΓòÉΓòÉ
  15965.  
  15966. Semicolon seems to be missing 
  15967.  
  15968. (W) A nearby syntax error was probably caused by a missing semicolon, or 
  15969. possibly some other missing operator, such as a comma. 
  15970.  
  15971.  
  15972. ΓòÉΓòÉΓòÉ 24.299. Send on closed socket ΓòÉΓòÉΓòÉ
  15973.  
  15974. Send on closed socket 
  15975.  
  15976. (W) The filehandle you're sending to got itself closed sometime before now. 
  15977. Check your logic flow. 
  15978.  
  15979.  
  15980. ΓòÉΓòÉΓòÉ 24.300. Sequence (?#... not terminated ΓòÉΓòÉΓòÉ
  15981.  
  15982. Sequence (?#... not terminated 
  15983.  
  15984. (F) A regular expression comment must be terminated by a closing parenthesis. 
  15985. Embedded parens aren't allowed.  See perlre. 
  15986.  
  15987.  
  15988. ΓòÉΓòÉΓòÉ 24.301. Sequence (?%s...) not implemented ΓòÉΓòÉΓòÉ
  15989.  
  15990. Sequence (?%s...) not implemented 
  15991.  
  15992. (F) A proposed regular expression extension has the character reserved but has 
  15993. not yet been written.  See perlre. 
  15994.  
  15995.  
  15996. ΓòÉΓòÉΓòÉ 24.302. Sequence (?%s...) not recognized ΓòÉΓòÉΓòÉ
  15997.  
  15998. Sequence (?%s...) not recognized 
  15999.  
  16000. (F) You used a regular expression extension that doesn't make sense. See 
  16001. perlre. 
  16002.  
  16003.  
  16004. ΓòÉΓòÉΓòÉ 24.303. setegid() not implemented ΓòÉΓòÉΓòÉ
  16005.  
  16006. setegid() not implemented 
  16007.  
  16008. (F) You tried to assign to $), and your operating system doesn't support the 
  16009. setegid() system call (or equivalent), or at least Configure didn't think so. 
  16010.  
  16011.  
  16012. ΓòÉΓòÉΓòÉ 24.304. seteuid() not implemented ΓòÉΓòÉΓòÉ
  16013.  
  16014. seteuid() not implemented 
  16015.  
  16016. (F) You tried to assign to $>, and your operating system doesn't support the 
  16017. seteuid() system call (or equivalent), or at least Configure didn't think so. 
  16018.  
  16019.  
  16020. ΓòÉΓòÉΓòÉ 24.305. setrgid() not implemented ΓòÉΓòÉΓòÉ
  16021.  
  16022. setrgid() not implemented 
  16023.  
  16024. (F) You tried to assign to $(, and your operating system doesn't support the 
  16025. setrgid() system call (or equivalent), or at least Configure didn't think so. 
  16026.  
  16027.  
  16028. ΓòÉΓòÉΓòÉ 24.306. setruid() not implemented ΓòÉΓòÉΓòÉ
  16029.  
  16030. setruid() not implemented 
  16031.  
  16032. (F) You tried to assign to $<, and your operating system doesn't support the 
  16033. setruid() system call (or equivalent), or at least Configure didn't think so. 
  16034.  
  16035.  
  16036. ΓòÉΓòÉΓòÉ 24.307. Setuid/gid script is writable by world ΓòÉΓòÉΓòÉ
  16037.  
  16038. Setuid/gid script is writable by world 
  16039.  
  16040. (F) The setuid emulator won't run a script that is writable by the world, 
  16041. because the world might have written on it already. 
  16042.  
  16043.  
  16044. ΓòÉΓòÉΓòÉ 24.308. shm%s not implemented ΓòÉΓòÉΓòÉ
  16045.  
  16046. shm%s not implemented 
  16047.  
  16048. (F) You don't have System V shared memory IPC on your system. 
  16049.  
  16050.  
  16051. ΓòÉΓòÉΓòÉ 24.309. shutdown() on closed fd ΓòÉΓòÉΓòÉ
  16052.  
  16053. shutdown() on closed fd 
  16054.  
  16055. (W) You tried to do a shutdown on a closed socket.  Seems a bit superfluous. 
  16056.  
  16057.  
  16058. ΓòÉΓòÉΓòÉ 24.310. SIG%s handler "%s" not defined. ΓòÉΓòÉΓòÉ
  16059.  
  16060. SIG%s handler "%s" not defined. 
  16061.  
  16062. (W) The signal handler named in %SIG doesn't, in fact, exist.  Perhaps you put 
  16063. it into the wrong package? 
  16064.  
  16065.  
  16066. ΓòÉΓòÉΓòÉ 24.311. sort is now a reserved word ΓòÉΓòÉΓòÉ
  16067.  
  16068. sort is now a reserved word 
  16069.  
  16070. (F) An ancient error message that almost nobody ever runs into anymore. But 
  16071. before sort was a keyword, people sometimes used it as a filehandle. 
  16072.  
  16073.  
  16074. ΓòÉΓòÉΓòÉ 24.312. Sort subroutine didn't return a numeric value ΓòÉΓòÉΓòÉ
  16075.  
  16076. Sort subroutine didn't return a numeric value 
  16077.  
  16078. (F) A sort comparison routine must return a number.  You probably blew it by 
  16079. not using <=> or cmp, or by not using them correctly. See perlfunc/sort. 
  16080.  
  16081.  
  16082. ΓòÉΓòÉΓòÉ 24.313. Sort subroutine didn't return single value ΓòÉΓòÉΓòÉ
  16083.  
  16084. Sort subroutine didn't return single value 
  16085.  
  16086. (F) A sort comparison subroutine may not return a list value with more or less 
  16087. than one element.  See perlfunc/sort. 
  16088.  
  16089.  
  16090. ΓòÉΓòÉΓòÉ 24.314. Split loop ΓòÉΓòÉΓòÉ
  16091.  
  16092. Split loop 
  16093.  
  16094. (P) The split was looping infinitely.  (Obviously, a split shouldn't iterate 
  16095. more times than there are characters of input, which is what happened.) See 
  16096. perlfunc/split. 
  16097.  
  16098.  
  16099. ΓòÉΓòÉΓòÉ 24.315. Stat on unopened file <%s> ΓòÉΓòÉΓòÉ
  16100.  
  16101. Stat on unopened file <%s> 
  16102.  
  16103. (W) You tried to use the stat() function (or an equivalent file test) on a 
  16104. filehandle that was either never opened or has been closed since. 
  16105.  
  16106.  
  16107. ΓòÉΓòÉΓòÉ 24.316. Statement unlikely to be reached ΓòÉΓòÉΓòÉ
  16108.  
  16109. Statement unlikely to be reached 
  16110.  
  16111. (W) You did an exec() with some statement after it other than a die(). This is 
  16112. almost always an error, because exec() never returns unless there was a 
  16113. failure.  You probably wanted to use system() instead, which does return.  To 
  16114. suppress this warning, put the exec() in a block by itself. 
  16115.  
  16116.  
  16117. ΓòÉΓòÉΓòÉ 24.317. Subroutine %s redefined ΓòÉΓòÉΓòÉ
  16118.  
  16119. Subroutine %s redefined 
  16120.  
  16121. (W) You redefined a subroutine.  To suppress this warning, say 
  16122.  
  16123.     {
  16124.         local $^W = 0;
  16125.         eval "sub name { ... }";
  16126.     }
  16127.  
  16128.  
  16129. ΓòÉΓòÉΓòÉ 24.318. Substitution loop ΓòÉΓòÉΓòÉ
  16130.  
  16131. Substitution loop 
  16132.  
  16133. (P) The substitution was looping infinitely.  (Obviously, a substitution 
  16134. shouldn't iterate more times than there are characters of input, which is what 
  16135. happened.) See the discussion of substitution in perlop/"Quote and Quotelike 
  16136. Operators". 
  16137.  
  16138.  
  16139. ΓòÉΓòÉΓòÉ 24.319. Substitution pattern not terminated ΓòÉΓòÉΓòÉ
  16140.  
  16141. Substitution pattern not terminated 
  16142.  
  16143. (F) The lexer couldn't find the interior delimiter of a s/// or s{}{} 
  16144. construct.  Remember that bracketing delimiters count nesting level. 
  16145.  
  16146.  
  16147. ΓòÉΓòÉΓòÉ 24.320. Substitution replacement not terminated ΓòÉΓòÉΓòÉ
  16148.  
  16149. Substitution replacement not terminated 
  16150.  
  16151. (F) The lexer couldn't find the final delimiter of a s/// or s{}{} construct. 
  16152. Remember that bracketing delimiters count nesting level. 
  16153.  
  16154.  
  16155. ΓòÉΓòÉΓòÉ 24.321. substr outside of string ΓòÉΓòÉΓòÉ
  16156.  
  16157. substr outside of string 
  16158.  
  16159. (W) You tried to reference a substr() that pointed outside of a string. That 
  16160. is, the absolute value of the offset was larger than the length of the string. 
  16161. See perlfunc/substr. 
  16162.  
  16163.  
  16164. ΓòÉΓòÉΓòÉ 24.322. suidperl is no longer needed since... ΓòÉΓòÉΓòÉ
  16165.  
  16166. suidperl is no longer needed since... 
  16167.  
  16168. (F) Your Perl was compiled with -DSETUID_SCRIPTS_ARE_SECURE_NOW, but a version 
  16169. of the setuid emulator somehow got run anyway. 
  16170.  
  16171.  
  16172. ΓòÉΓòÉΓòÉ 24.323. syntax error ΓòÉΓòÉΓòÉ
  16173.  
  16174. syntax error 
  16175.  
  16176. (F) Probably means you had a syntax error.  Common reasons include: 
  16177.  
  16178.     A keyword is misspelled.
  16179.     A semicolon is missing.
  16180.     A comma is missing.
  16181.     An opening or closing parenthesis is missing.
  16182.     An opening or closing brace is missing.
  16183.     A closing quote is missing.
  16184.  
  16185. Often there will be another error message associated with the syntax error 
  16186. giving more information.  (Sometimes it helps to turn on -w.) The error message 
  16187. itself often tells you where it was in the line when it decided to give up. 
  16188. Sometimes the actual error is several tokens before this, since Perl is good at 
  16189. understanding random input. Occasionally the line number may be misleading, and 
  16190. once in a blue moon the only way to figure out what's triggering the error is 
  16191. to call perl -c repeatedly, chopping away half the program each time to see if 
  16192. the error went away.  Sort of the cybernetic version of 20 questions. 
  16193.  
  16194.  
  16195. ΓòÉΓòÉΓòÉ 24.324. syntax error at line %d: `%s' unexpected ΓòÉΓòÉΓòÉ
  16196.  
  16197. syntax error at line %d: `%s' unexpected 
  16198.  
  16199. (A) You've accidentally run your script through the Bourne shell instead of 
  16200. Perl.  Check the <#!> line, or manually feed your script into Perl yourself. 
  16201.  
  16202.  
  16203. ΓòÉΓòÉΓòÉ 24.325. System V IPC is not implemented on this machine ΓòÉΓòÉΓòÉ
  16204.  
  16205. System V IPC is not implemented on this machine 
  16206.  
  16207. (F) You tried to do something with a function beginning with "sem", "shm" or 
  16208. "msg".  See perlfunc/semctl, for example. 
  16209.  
  16210.  
  16211. ΓòÉΓòÉΓòÉ 24.326. Syswrite on closed filehandle ΓòÉΓòÉΓòÉ
  16212.  
  16213. Syswrite on closed filehandle 
  16214.  
  16215. (W) The filehandle you're writing to got itself closed sometime before now. 
  16216. Check your logic flow. 
  16217.  
  16218.  
  16219. ΓòÉΓòÉΓòÉ 24.327. tell() on unopened file ΓòÉΓòÉΓòÉ
  16220.  
  16221. tell() on unopened file 
  16222.  
  16223. (W) You tried to use the tell() function on a filehandle that was either never 
  16224. opened or has been closed since. 
  16225.  
  16226.  
  16227. ΓòÉΓòÉΓòÉ 24.328. Test on unopened file <%s> ΓòÉΓòÉΓòÉ
  16228.  
  16229. Test on unopened file <%s> 
  16230.  
  16231. (W) You tried to invoke a file test operator on a filehandle that isn't open. 
  16232. Check your logic.  See also perlfunc/-X. 
  16233.  
  16234.  
  16235. ΓòÉΓòÉΓòÉ 24.329. That use of $[ is unsupported ΓòÉΓòÉΓòÉ
  16236.  
  16237. That use of $[ is unsupported 
  16238.  
  16239. (F) Assignment to $[ is now strictly circumscribed, and interpreted as a 
  16240. compiler directive.  You may only say one of 
  16241.  
  16242.     $[ = 0;
  16243.     $[ = 1;
  16244.     ...
  16245.     local $[ = 0;
  16246.     local $[ = 1;
  16247.     ...
  16248.  
  16249. This is to prevent the problem of one module changing the array base out from 
  16250. under another module inadvertently.  See perlvar/$[. 
  16251.  
  16252.  
  16253. ΓòÉΓòÉΓòÉ 24.330. The %s function is unimplemented ΓòÉΓòÉΓòÉ
  16254.  
  16255. The %s function is unimplemented 
  16256.  
  16257. The function indicated isn't implemented on this architecture, according to the 
  16258. probings of Configure. 
  16259.  
  16260.  
  16261. ΓòÉΓòÉΓòÉ 24.331. The crypt() function is unimplemented due to excessive paranoia. ΓòÉΓòÉΓòÉ
  16262.  
  16263. The crypt() function is unimplemented due to excessive paranoia. 
  16264.  
  16265. (F) Configure couldn't find the crypt() function on your machine, probably 
  16266. because your vendor didn't supply it, probably because they think the U.S. 
  16267. Govermnment thinks it's a secret, or at least that they will continue to 
  16268. pretend that it is.  And if you quote me on that, I will deny it. 
  16269.  
  16270.  
  16271. ΓòÉΓòÉΓòÉ 24.332. The stat preceding -l _ wasn't an lstat ΓòÉΓòÉΓòÉ
  16272.  
  16273. The stat preceding -l _ wasn't an lstat 
  16274.  
  16275. (F) It makes no sense to test the current stat buffer for symbolic linkhood if 
  16276. the last stat that wrote to the stat buffer already went past the symlink to 
  16277. get to the real file.  Use an actual filename instead. 
  16278.  
  16279.  
  16280. ΓòÉΓòÉΓòÉ 24.333. times not implemented ΓòÉΓòÉΓòÉ
  16281.  
  16282. times not implemented 
  16283.  
  16284. (F) Your version of the C library apparently doesn't do times().  I suspect 
  16285. you're not running on Unix. 
  16286.  
  16287.  
  16288. ΓòÉΓòÉΓòÉ 24.334. Too few args to syscall ΓòÉΓòÉΓòÉ
  16289.  
  16290. Too few args to syscall 
  16291.  
  16292. (F) There has to be at least one argument to syscall() to specify the system 
  16293. call to call, silly dilly. 
  16294.  
  16295.  
  16296. ΓòÉΓòÉΓòÉ 24.335. Too many ('s ΓòÉΓòÉΓòÉ
  16297.  
  16298. Too many ('s 
  16299.  
  16300.  
  16301. ΓòÉΓòÉΓòÉ 24.336. Too many )'s ΓòÉΓòÉΓòÉ
  16302.  
  16303. Too many )'s 
  16304.  
  16305. (A) You've accidentally run your script through csh instead of Perl.  Check the 
  16306. <#!> line, or manually feed your script into Perl yourself. 
  16307.  
  16308.  
  16309. ΓòÉΓòÉΓòÉ 24.337. Too many args to syscall ΓòÉΓòÉΓòÉ
  16310.  
  16311. Too many args to syscall 
  16312.  
  16313. (F) Perl only supports a maximum of 14 args to syscall(). 
  16314.  
  16315.  
  16316. ΓòÉΓòÉΓòÉ 24.338. Too many arguments for %s ΓòÉΓòÉΓòÉ
  16317.  
  16318. Too many arguments for %s 
  16319.  
  16320. (F) The function requires fewer arguments than you specified. 
  16321.  
  16322.  
  16323. ΓòÉΓòÉΓòÉ 24.339. trailing \ in regexp ΓòÉΓòÉΓòÉ
  16324.  
  16325. trailing \ in regexp 
  16326.  
  16327. (F) The regular expression ends with an unbackslashed backslash.  Backslash it. 
  16328. See perlre. 
  16329.  
  16330.  
  16331. ΓòÉΓòÉΓòÉ 24.340. Translation pattern not terminated ΓòÉΓòÉΓòÉ
  16332.  
  16333. Translation pattern not terminated 
  16334.  
  16335. (F) The lexer couldn't find the interior delimiter of a tr/// or tr[][] 
  16336. construct. 
  16337.  
  16338.  
  16339. ΓòÉΓòÉΓòÉ 24.341. Translation replacement not terminated ΓòÉΓòÉΓòÉ
  16340.  
  16341. Translation replacement not terminated 
  16342.  
  16343. (F) The lexer couldn't find the final delimiter of a tr/// or tr[][] construct. 
  16344.  
  16345.  
  16346. ΓòÉΓòÉΓòÉ 24.342. truncate not implemented ΓòÉΓòÉΓòÉ
  16347.  
  16348. truncate not implemented 
  16349.  
  16350. (F) Your machine doesn't implement a file truncation mechanism that Configure 
  16351. knows about. 
  16352.  
  16353.  
  16354. ΓòÉΓòÉΓòÉ 24.343. Type of arg %d to %s must be %s (not %s) ΓòÉΓòÉΓòÉ
  16355.  
  16356. Type of arg %d to %s must be %s (not %s) 
  16357.  
  16358. (F) This function requires the argument in that position to be of a certain 
  16359. type.  Arrays must be @NAME or @{EXPR}.  Hashes must be %NAME or %{EXPR}.  No 
  16360. implicit dereferencing is allowed--use the {EXPR} forms as an explicit 
  16361. dereference.  See perlref. 
  16362.  
  16363.  
  16364. ΓòÉΓòÉΓòÉ 24.344. umask: argument is missing initial 0 ΓòÉΓòÉΓòÉ
  16365.  
  16366. umask: argument is missing initial 0 
  16367.  
  16368. (W) A umask of 222 is incorrect.  It should be 0222, since octal literals 
  16369. always start with 0 in Perl, as in C. 
  16370.  
  16371.  
  16372. ΓòÉΓòÉΓòÉ 24.345. Unable to create sub named "%s" ΓòÉΓòÉΓòÉ
  16373.  
  16374. Unable to create sub named "%s" 
  16375.  
  16376. (F) You attempted to create or access a subroutine with an illegal name. 
  16377.  
  16378.  
  16379. ΓòÉΓòÉΓòÉ 24.346. Unbalanced context: %d more PUSHes than POPs ΓòÉΓòÉΓòÉ
  16380.  
  16381. Unbalanced context: %d more PUSHes than POPs 
  16382.  
  16383. (W) The exit code detected an internal inconsistency in how many execution 
  16384. contexts were entered and left. 
  16385.  
  16386.  
  16387. ΓòÉΓòÉΓòÉ 24.347. Unbalanced saves: %d more saves than restores ΓòÉΓòÉΓòÉ
  16388.  
  16389. Unbalanced saves: %d more saves than restores 
  16390.  
  16391. (W) The exit code detected an internal inconsistency in how many values were 
  16392. temporarily localized. 
  16393.  
  16394.  
  16395. ΓòÉΓòÉΓòÉ 24.348. Unbalanced scopes: %d more ENTERs than LEAVEs ΓòÉΓòÉΓòÉ
  16396.  
  16397. Unbalanced scopes: %d more ENTERs than LEAVEs 
  16398.  
  16399. (W) The exit code detected an internal inconsistency in how many blocks were 
  16400. entered and left. 
  16401.  
  16402.  
  16403. ΓòÉΓòÉΓòÉ 24.349. Unbalanced tmps: %d more allocs than frees ΓòÉΓòÉΓòÉ
  16404.  
  16405. Unbalanced tmps: %d more allocs than frees 
  16406.  
  16407. (W) The exit code detected an internal inconsistency in how many mortal scalars 
  16408. were allocated and freed. 
  16409.  
  16410.  
  16411. ΓòÉΓòÉΓòÉ 24.350. Undefined format "%s" called ΓòÉΓòÉΓòÉ
  16412.  
  16413. Undefined format "%s" called 
  16414.  
  16415. (F) The format indicated doesn't seem to exist.  Perhaps it's really in another 
  16416. package?  See perlform. 
  16417.  
  16418.  
  16419. ΓòÉΓòÉΓòÉ 24.351. Undefined sort subroutine "%s" called ΓòÉΓòÉΓòÉ
  16420.  
  16421. Undefined sort subroutine "%s" called 
  16422.  
  16423. (F) The sort comparison routine specified doesn't seem to exist.  Perhaps it's 
  16424. in a different package?  See perlfunc/sort. 
  16425.  
  16426.  
  16427. ΓòÉΓòÉΓòÉ 24.352. Undefined subroutine &%s called ΓòÉΓòÉΓòÉ
  16428.  
  16429. Undefined subroutine &%s called 
  16430.  
  16431. (F) The subroutine indicated hasn't been defined, or if it was, it has since 
  16432. been undefined. 
  16433.  
  16434.  
  16435. ΓòÉΓòÉΓòÉ 24.353. Undefined subroutine called ΓòÉΓòÉΓòÉ
  16436.  
  16437. Undefined subroutine called 
  16438.  
  16439. (F) The anonymous subroutine you're trying to call hasn't been defined, or if 
  16440. it was, it has since been undefined. 
  16441.  
  16442.  
  16443. ΓòÉΓòÉΓòÉ 24.354. Undefined subroutine in sort ΓòÉΓòÉΓòÉ
  16444.  
  16445. Undefined subroutine in sort 
  16446.  
  16447. (F) The sort comparison routine specified is declared but doesn't seem to have 
  16448. been defined yet.  See perlfunc/sort. 
  16449.  
  16450.  
  16451. ΓòÉΓòÉΓòÉ 24.355. Undefined top format "%s" called ΓòÉΓòÉΓòÉ
  16452.  
  16453. Undefined top format "%s" called 
  16454.  
  16455. (F) The format indicated doesn't seem to exist.  Perhaps it's really in another 
  16456. package?  See perlform. 
  16457.  
  16458.  
  16459. ΓòÉΓòÉΓòÉ 24.356. unexec of %s into %s failed! ΓòÉΓòÉΓòÉ
  16460.  
  16461. unexec of %s into %s failed! 
  16462.  
  16463. (F) The unexec() routine failed for some reason.  See your local FSF 
  16464. representative, who probably put it there in the first place. 
  16465.  
  16466.  
  16467. ΓòÉΓòÉΓòÉ 24.357. Unknown BYTEORDER ΓòÉΓòÉΓòÉ
  16468.  
  16469. Unknown BYTEORDER 
  16470.  
  16471. (F) There are no byteswapping functions for a machine with this byte order. 
  16472.  
  16473.  
  16474. ΓòÉΓòÉΓòÉ 24.358. unmatched () in regexp ΓòÉΓòÉΓòÉ
  16475.  
  16476. unmatched () in regexp 
  16477.  
  16478. (F) Unbackslashed parentheses must always be balanced in regular expressions. 
  16479. If you're a vi user, the % key is valuable for finding the matching paren.  See 
  16480. perlre. 
  16481.  
  16482.  
  16483. ΓòÉΓòÉΓòÉ 24.359. Unmatched right bracket ΓòÉΓòÉΓòÉ
  16484.  
  16485. Unmatched right bracket 
  16486.  
  16487. (F) The lexer counted more closing curly brackets (braces) than opening ones, 
  16488. so you're probably missing an opening bracket.  As a general rule, you'll find 
  16489. the missing one (so to speak) near the place you were last editing. 
  16490.  
  16491.  
  16492. ΓòÉΓòÉΓòÉ 24.360. unmatched [] in regexp ΓòÉΓòÉΓòÉ
  16493.  
  16494. unmatched [] in regexp 
  16495.  
  16496. (F) The brackets around a character class must match.  If you wish to include a 
  16497. closing bracket in a character class, backslash it or put it first. See perlre. 
  16498.  
  16499.  
  16500. ΓòÉΓòÉΓòÉ 24.361. Unquoted string "%s" may clash with future reserved word ΓòÉΓòÉΓòÉ
  16501.  
  16502. Unquoted string "%s" may clash with future reserved word 
  16503.  
  16504. (W) You used a bare word that might someday be claimed as a reserved word. It's 
  16505. best to put such a word in quotes, or capitalize it somehow, or insert an 
  16506. underbar into it.  You might also declare it as a subroutine. 
  16507.  
  16508.  
  16509. ΓòÉΓòÉΓòÉ 24.362. Unrecognized character \%03o ignored ΓòÉΓòÉΓòÉ
  16510.  
  16511. Unrecognized character \%03o ignored 
  16512.  
  16513. (S) A garbage character was found in the input, and ignored, in case it's a 
  16514. weird control character on an EBCDIC machine, or some such. 
  16515.  
  16516.  
  16517. ΓòÉΓòÉΓòÉ 24.363. Unrecognized signal name "%s" ΓòÉΓòÉΓòÉ
  16518.  
  16519. Unrecognized signal name "%s" 
  16520.  
  16521. (F) You specified a signal name to the kill() function that was not recognized. 
  16522. Say kill -l in your shell to see the valid signal names on your system. 
  16523.  
  16524.  
  16525. ΓòÉΓòÉΓòÉ 24.364. Unrecognized switch: -%s ΓòÉΓòÉΓòÉ
  16526.  
  16527. Unrecognized switch: -%s 
  16528.  
  16529. (F) You specified an illegal option to Perl.  Don't do that. (If you think you 
  16530. didn't do that, check the #! line to see if it's supplying the bad switch on 
  16531. your behalf.) 
  16532.  
  16533.  
  16534. ΓòÉΓòÉΓòÉ 24.365. Unsuccessful %s on filename containing newline ΓòÉΓòÉΓòÉ
  16535.  
  16536. Unsuccessful %s on filename containing newline 
  16537.  
  16538. (W) A file operation was attempted on a filename, and that operation failed, 
  16539. PROBABLY because the filename contained a newline, PROBABLY because you forgot 
  16540. to chop() or chomp() it off.  See perlfunc/chop. 
  16541.  
  16542.  
  16543. ΓòÉΓòÉΓòÉ 24.366. Unsupported directory function "%s" called ΓòÉΓòÉΓòÉ
  16544.  
  16545. Unsupported directory function "%s" called 
  16546.  
  16547. (F) Your machine doesn't support opendir() and readdir(). 
  16548.  
  16549.  
  16550. ΓòÉΓòÉΓòÉ 24.367. Unsupported function %s ΓòÉΓòÉΓòÉ
  16551.  
  16552. Unsupported function %s 
  16553.  
  16554. (F) This machines doesn't implement the indicated function, apparently. At 
  16555. least, Configure doesn't think so. 
  16556.  
  16557.  
  16558. ΓòÉΓòÉΓòÉ 24.368. Unsupported socket function "%s" called ΓòÉΓòÉΓòÉ
  16559.  
  16560. Unsupported socket function "%s" called 
  16561.  
  16562. (F) Your machine doesn't support the Berkeley socket mechanism, or at least 
  16563. that's what Configure thought. 
  16564.  
  16565.  
  16566. ΓòÉΓòÉΓòÉ 24.369. Unterminated <> operator ΓòÉΓòÉΓòÉ
  16567.  
  16568. Unterminated <> operator 
  16569.  
  16570. (F) The lexer saw a left angle bracket in a place where it was expecting a 
  16571. term, so it's looking for the corresponding right angle bracket, and not 
  16572. finding it.  Chances are you left some needed parentheses out earlier in the 
  16573. line, and you really meant a "less than". 
  16574.  
  16575.  
  16576. ΓòÉΓòÉΓòÉ 24.370. Use of $# is deprecated ΓòÉΓòÉΓòÉ
  16577.  
  16578. Use of $# is deprecated 
  16579.  
  16580. (D) This was an ill-advised attempt to emulate a poorly defined awk feature. 
  16581. Use an explicit printf() or sprintf() instead. 
  16582.  
  16583.  
  16584. ΓòÉΓòÉΓòÉ 24.371. Use of $* is deprecated ΓòÉΓòÉΓòÉ
  16585.  
  16586. Use of $* is deprecated 
  16587.  
  16588. (D) This variable magically turned on multiline pattern matching, both for you 
  16589. and for any luckless subroutine that you happen to call.  You should use the 
  16590. new //m and //s modifiers now to do that without the dangerous 
  16591. action-at-a-distance effects of $*. 
  16592.  
  16593.  
  16594. ΓòÉΓòÉΓòÉ 24.372. Use of %s in printf format not supported ΓòÉΓòÉΓòÉ
  16595.  
  16596. Use of %s in printf format not supported 
  16597.  
  16598. (F) You attempted to use a feature of printf that is accessible only from C. 
  16599. This usually means there's a better way to do it in Perl. 
  16600.  
  16601.  
  16602. ΓòÉΓòÉΓòÉ 24.373. Use of %s is deprecated ΓòÉΓòÉΓòÉ
  16603.  
  16604. Use of %s is deprecated 
  16605.  
  16606. (D) The construct indicated is no longer recommended for use, generally because 
  16607. there's a better way to do it, and also because the old way has bad side 
  16608. effects. 
  16609.  
  16610.  
  16611. ΓòÉΓòÉΓòÉ 24.374. Use of bare << to mean <<"" is deprecated ΓòÉΓòÉΓòÉ
  16612.  
  16613. Use of bare << to mean <<"" is deprecated 
  16614.  
  16615. (D) You are now encouraged to use the explicitly quoted form if you wish to use 
  16616. a blank line as the terminator of the here-document. 
  16617.  
  16618.  
  16619. ΓòÉΓòÉΓòÉ 24.375. Use of implicit split to @_ is deprecated ΓòÉΓòÉΓòÉ
  16620.  
  16621. Use of implicit split to @_ is deprecated 
  16622.  
  16623. (D) It makes a lot of work for the compiler when you clobber a subroutine's 
  16624. argument list, so it's better if you assign the results of a split() explicitly 
  16625. to an array (or list). 
  16626.  
  16627.  
  16628. ΓòÉΓòÉΓòÉ 24.376. Use of uninitialized value ΓòÉΓòÉΓòÉ
  16629.  
  16630. Use of uninitialized value 
  16631.  
  16632. (W) An undefined value was used as if it were already defined.  It was 
  16633. interpreted as a "" or a 0, but maybe it was a mistake.  To suppress this 
  16634. warning assign an initial value to your variables. 
  16635.  
  16636.  
  16637. ΓòÉΓòÉΓòÉ 24.377. Useless use of %s in void context ΓòÉΓòÉΓòÉ
  16638.  
  16639. Useless use of %s in void context 
  16640.  
  16641. (W) You did something without a side effect in a context that does nothing with 
  16642. the return value, such as a statement that doesn't return a value from a block, 
  16643. or the left side of a scalar comma operator.  Very often this points not to 
  16644. stupidity on your part, but a failure of Perl to parse your program the way you 
  16645. thought it would.  For example, you'd get this if you mixed up your C 
  16646. precedence with Python precedence and said 
  16647.  
  16648.     $one, $two = 1, 2;
  16649.  
  16650. when you meant to say 
  16651.  
  16652.     ($one, $two) = (1, 2);
  16653.  
  16654. Another common error is to use ordinary parentheses to construct a list 
  16655. reference when you should be using square or curly brackets, for example, if 
  16656. you say 
  16657.  
  16658.     $array = (1,2);
  16659.  
  16660. when you should have said 
  16661.  
  16662.     $array = [1,2];
  16663.  
  16664. The square brackets explicitly turn a list value into a scalar value, while 
  16665. parentheses do not.  So when a parenthesized list is evaluated in a scalar 
  16666. context, the comma is treated like C's comma operator, which throws away the 
  16667. left argument, which is not what you want.  See perlref for more on this. 
  16668.  
  16669.  
  16670. ΓòÉΓòÉΓòÉ 24.378. Variable "%s" is not exported ΓòÉΓòÉΓòÉ
  16671.  
  16672. Variable "%s" is not exported 
  16673.  
  16674. (F) While "use strict" in effect, you referred to a global variable that you 
  16675. apparently thought was imported from another module, because something else of 
  16676. the same name (usually a subroutine) is exported by that module.  It usually 
  16677. means you put the wrong funny character on the front of your variable. 
  16678.  
  16679.  
  16680. ΓòÉΓòÉΓòÉ 24.379. Variable syntax. ΓòÉΓòÉΓòÉ
  16681.  
  16682. Variable syntax. 
  16683.  
  16684. (A) You've accidentally run your script through csh instead of Perl.  Check the 
  16685. <#!> line, or manually feed your script into Perl yourself. 
  16686.  
  16687.  
  16688. ΓòÉΓòÉΓòÉ 24.380. Warning: unable to close filehandle %s properly. ΓòÉΓòÉΓòÉ
  16689.  
  16690. Warning: unable to close filehandle %s properly. 
  16691.  
  16692. (S) The implicit close() done by an open() got an error indication on the 
  16693. close(0.  This usually indicates your filesystem ran out of disk space. 
  16694.  
  16695.  
  16696. ΓòÉΓòÉΓòÉ 24.381. Warning: Use of "%s" without parens is ambiguous ΓòÉΓòÉΓòÉ
  16697.  
  16698. Warning: Use of "%s" without parens is ambiguous 
  16699.  
  16700. (S) You wrote a unary operator followed by something that looks like a binary 
  16701. operator that could also have been interpreted as a term or unary operator. 
  16702. For instance, if you know that the rand function has a default argument of 1.0, 
  16703. and you write 
  16704.  
  16705.     rand + 5;
  16706.  
  16707. you may THINK you wrote the same thing as 
  16708.  
  16709.     rand() + 5;
  16710.  
  16711. but in actual fact, you got 
  16712.  
  16713.     rand(+5);
  16714.  
  16715. So put in parens to say what you really mean. 
  16716.  
  16717.  
  16718. ΓòÉΓòÉΓòÉ 24.382. Write on closed filehandle ΓòÉΓòÉΓòÉ
  16719.  
  16720. Write on closed filehandle 
  16721.  
  16722. (W) The filehandle you're writing to got itself closed sometime before now. 
  16723. Check your logic flow. 
  16724.  
  16725.  
  16726. ΓòÉΓòÉΓòÉ 24.383. X outside of string ΓòÉΓòÉΓòÉ
  16727.  
  16728. X outside of string 
  16729.  
  16730. (F) You had a pack template that specified a relative position before the 
  16731. beginning of the string being unpacked.  See perlfunc/pack. 
  16732.  
  16733.  
  16734. ΓòÉΓòÉΓòÉ 24.384. x outside of string ΓòÉΓòÉΓòÉ
  16735.  
  16736. x outside of string 
  16737.  
  16738. (F) You had a pack template that specified a relative position after the end of 
  16739. the string being unpacked.  See perlfunc/pack. 
  16740.  
  16741.  
  16742. ΓòÉΓòÉΓòÉ 24.385. Xsub "%s" called in sort ΓòÉΓòÉΓòÉ
  16743.  
  16744. Xsub "%s" called in sort 
  16745.  
  16746. (F) The use of an external subroutine as a sort comparison is not yet 
  16747. supported. 
  16748.  
  16749.  
  16750. ΓòÉΓòÉΓòÉ 24.386. Xsub called in sort ΓòÉΓòÉΓòÉ
  16751.  
  16752. Xsub called in sort 
  16753.  
  16754. (F) The use of an external subroutine as a sort comparison is not yet 
  16755. supported. 
  16756.  
  16757.  
  16758. ΓòÉΓòÉΓòÉ 24.387. You can't use -l on a filehandle ΓòÉΓòÉΓòÉ
  16759.  
  16760. You can't use -l on a filehandle 
  16761.  
  16762. (F) A filehandle represents an opened file, and when you opened the file it 
  16763. already went past any symlink you are presumably trying to look for. Use a 
  16764. filename instead. 
  16765.  
  16766.  
  16767. ΓòÉΓòÉΓòÉ 24.388. YOU HAVEN'T DISABLED SET-ID SCRIPTS IN THE KERNEL YET! ΓòÉΓòÉΓòÉ
  16768.  
  16769. YOU HAVEN'T DISABLED SET-ID SCRIPTS IN THE KERNEL YET! 
  16770.  
  16771. (F) And you probably never will, since you probably don't have the sources to 
  16772. your kernel, and your vendor probably doesn't give a rip about what you want. 
  16773. Your best bet is to use the wrapsuid script in the eg directory to put a setuid 
  16774. C wrapper around your script. 
  16775.  
  16776.  
  16777. ΓòÉΓòÉΓòÉ 24.389. You need to quote "%s" ΓòÉΓòÉΓòÉ
  16778.  
  16779. You need to quote "%s" 
  16780.  
  16781. (W) You assigned a bareword as a signal handler name.  Unfortunately, you 
  16782. already have a subroutine of that name declared, which means that Perl 5 will 
  16783. try to call the subroutine when the assignment is executed, which is probably 
  16784. not what you want.  (If it IS what you want, put an & in front.) 
  16785.  
  16786.  
  16787. ΓòÉΓòÉΓòÉ 24.390. [gs]etsockopt() on closed fd ΓòÉΓòÉΓòÉ
  16788.  
  16789. [gs]etsockopt() on closed fd 
  16790.  
  16791. (W) You tried to get or set a socket option on a closed socket. Did you forget 
  16792. to check the return value of your socket() call? See perlfunc/getsockopt. 
  16793.  
  16794.  
  16795. ΓòÉΓòÉΓòÉ 24.391. \1 better written as $1 ΓòÉΓòÉΓòÉ
  16796.  
  16797. \1 better written as $1 
  16798.  
  16799. (W) Outside of patterns, backreferences live on as variables.  The use of 
  16800. backslashes is grandfathered on the righthand side of a substitution, but 
  16801. stylistically it's better to use the variable form because other Perl 
  16802. programmers will expect it, and it works better if there are more than 9 
  16803. backreferences. 
  16804.  
  16805.  
  16806. ΓòÉΓòÉΓòÉ 24.392. '|' and '<' may not both be specified on command line ΓòÉΓòÉΓòÉ
  16807.  
  16808. '|' and '<' may not both be specified on command line 
  16809.  
  16810. (F) An error peculiar to VMS.  Perl does its own command line redirection, and 
  16811. found that STDIN was a pipe, and that you also tried to redirect STDIN using 
  16812. '<'.  Only one STDIN stream to a customer, please. 
  16813.  
  16814.  
  16815. ΓòÉΓòÉΓòÉ 24.393. '|' and '>' may not both be specified on command line ΓòÉΓòÉΓòÉ
  16816.  
  16817. '|' and '>' may not both be specified on command line 
  16818.  
  16819. (F) An error peculiar to VMS.  Perl does its own command line redirection, and 
  16820. thinks you tried to redirect stdout both to a file and into a pipe to another 
  16821. command.  You need to choose one or the other, though nothing's stopping you 
  16822. from piping into a program or Perl script which 'splits' output into two 
  16823. streams, such as 
  16824.  
  16825.     open(OUT,">$ARGV[0]") or die "Can't write to $ARGV[0]: $!";
  16826.     while (<STDIN>) {
  16827.         print;
  16828.         print OUT;
  16829.     }
  16830.     close OUT;
  16831.  
  16832.  
  16833. ΓòÉΓòÉΓòÉ 25. Section - perlform ΓòÉΓòÉΓòÉ
  16834.  
  16835. NAME 
  16836.  
  16837. perlform - Perl formats 
  16838.  
  16839. DESCRIPTION 
  16840.  
  16841. Perl has a mechanism to help you generate simple reports and charts.  To 
  16842. facilitate this, Perl helps you code up your output page close to how it will 
  16843. look when it's printed.  It can keep track of things like how many lines on a 
  16844. page, what page you're on, when to print page headers, etc.  Keywords are 
  16845. borrowed from FORTRAN: format() to declare and write() to execute; see their 
  16846. entries in perlfunc.  Fortunately, the layout is much more legible, more like 
  16847. BASIC's PRINT USING statement.  Think of it as a poor man's nroff(1). 
  16848.  
  16849. Formats, like packages and subroutines, are declared rather than executed, so 
  16850. they may occur at any point in your program.  (Usually it's best to keep them 
  16851. all together though.) They have their own namespace apart from all the other 
  16852. "types" in Perl.  This means that if you have a function named "Foo", it is not 
  16853. the same thing as having a format named "Foo". However, the default name for 
  16854. the format associated with a given filehandle is the same as the name of the 
  16855. filehandle.  Thus, the default format for STDOUT is name "STDOUT", and the 
  16856. default format for filehandle TEMP is name "TEMP".  They just look the same. 
  16857. They aren't. 
  16858.  
  16859. Output record formats are declared as follows: 
  16860.  
  16861.     format NAME =
  16862.     FORMLIST
  16863.     .
  16864.  
  16865. If name is omitted, format "STDOUT" is defined.  FORMLIST consists of a 
  16866. sequence of lines, each of which may be of one of three types: 
  16867.  
  16868.    1. A comment, indicated by putting a '#' in the first column. 
  16869.  
  16870.    2. A "picture" line giving the format for one output line. 
  16871.  
  16872.    3. An argument line supplying values to plug into the previous picture line. 
  16873.  
  16874.  Picture lines are printed exactly as they look, except for certain fields that 
  16875.  substitute values into the line.  Each field in a picture line starts with 
  16876.  either "@" (at) or "^" (caret).  These lines do not undergo any kind of 
  16877.  variable interpolation.  The at field (not to be confused with the array 
  16878.  marker @) is the normal kind of field; the other kind, caret fields, are used 
  16879.  to do rudimentary multi-line text block filling.  The length of the field is 
  16880.  supplied by padding out the field with multiple "<", ">", or "|" characters to 
  16881.  specify, respectively, left justification, right justification, or centering. 
  16882.  If the variable would exceed the width specified, it is truncated. 
  16883.  
  16884.  As an alternate form of right justification, you may also use "#" characters 
  16885.  (with an optional ".") to specify a numeric field.  This way you can line up 
  16886.  the decimal points.  If any value supplied for these fields contains a 
  16887.  newline, only the text up to the newline is printed. Finally, the special 
  16888.  field "@*" can be used for printing multi-line, non-truncated values; it 
  16889.  should appear by itself on a line. 
  16890.  
  16891.  The values are specified on the following line in the same order as the 
  16892.  picture fields.  The expressions providing the values should be separated by 
  16893.  commas.  The expressions are all evaluated in a list context before the line 
  16894.  is processed, so a single list expression could produce multiple list 
  16895.  elements.  The expressions may be spread out to more than one line if enclosed 
  16896.  in braces.  If so, the opening brace must be the first token on the first 
  16897.  line. 
  16898.  
  16899.  Picture fields that begin with ^ rather than @ are treated specially. With a # 
  16900.  field, the field is blanked out if the value is undefined.  For other field 
  16901.  types, the caret enables a kind of fill mode.  Instead of an arbitrary 
  16902.  expression, the value supplied must be a scalar variable name that contains a 
  16903.  text string.  Perl puts as much text as it can into the field, and then chops 
  16904.  off the front of the string so that the next time the variable is referenced, 
  16905.  more of the text can be printed.  (Yes, this means that the variable itself is 
  16906.  altered during execution of the write() call, and is not returned.)  Normally 
  16907.  you would use a sequence of fields in a vertical stack to print out a block of 
  16908.  text.  You might wish to end the final field with the text "...", which will 
  16909.  appear in the output if the text was too long to appear in its entirety.  You 
  16910.  can change which characters are legal to break on by changing the variable $: 
  16911.  (that's $FORMAT_LINE_BREAK_CHARACTERS if you're using the English module) to a 
  16912.  list of the desired characters. 
  16913.  
  16914.  Using caret fields can produce variable length records.  If the text to be 
  16915.  formatted is short, you can suppress blank lines by putting a "~" (tilde) 
  16916.  character anywhere in the line.  The tilde will be translated to a space upon 
  16917.  output.  If you put a second tilde contiguous to the first, the line will be 
  16918.  repeated until all the fields on the line are exhausted.  (If you use a field 
  16919.  of the at variety, the expression you supply had better not give the same 
  16920.  value every time forever!) 
  16921.  
  16922.  Top-of-form processing is by default handled by a format with the same name as 
  16923.  the current filehandle with "_TOP" concatenated to it. It's triggered at the 
  16924.  top of each page.  See <perlfunc/write()>. 
  16925.  
  16926.  Examples: 
  16927.  
  16928.    # a report on the /etc/passwd file
  16929.    format STDOUT_TOP =
  16930.                            Passwd File
  16931.    Name                Login    Office   Uid   Gid Home
  16932.    ------------------------------------------------------------------
  16933.    .
  16934.    format STDOUT =
  16935.    @<<<<<<<<<<<<<<<<<< @||||||| @<<<<<<@>>>> @>>>> @<<<<<<<<<<<<<<<<<
  16936.    $name,              $login,  $office,$uid,$gid, $home
  16937.    .
  16938.  
  16939.    # a report from a bug report form
  16940.    format STDOUT_TOP =
  16941.                            Bug Reports
  16942.    @<<<<<<<<<<<<<<<<<<<<<<<     @|||         @>>>>>>>>>>>>>>>>>>>>>>>
  16943.    $system,                      $%,         $date
  16944.    ------------------------------------------------------------------
  16945.    .
  16946.    format STDOUT =
  16947.    Subject: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  16948.             $subject
  16949.    Index: @<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  16950.           $index,                       $description
  16951.    Priority: @<<<<<<<<<< Date: @<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  16952.              $priority,        $date,   $description
  16953.    From: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  16954.          $from,                         $description
  16955.    Assigned to: @<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  16956.                 $programmer,            $description
  16957.    ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  16958.                                         $description
  16959.    ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  16960.                                         $description
  16961.    ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  16962.                                         $description
  16963.    ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  16964.                                         $description
  16965.    ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<...
  16966.                                         $description
  16967.    .
  16968.  
  16969.  It is possible to intermix print()s with write()s on the same output channel, 
  16970.  but you'll have to handle $- ($FORMAT_LINES_LEFT) yourself. 
  16971.  
  16972.  Format Variables 
  16973.  
  16974.  The current format name is stored in the variable $~ ($FORMAT_NAME), and the 
  16975.  current top of form format name is in $^ ($FORMAT_TOP_NAME). The current 
  16976.  output page number is stored in $% ($FORMAT_PAGE_NUMBER), and the number of 
  16977.  lines on the page is in $= ($FORMAT_LINES_PER_PAGE). Whether to autoflush 
  16978.  output on this handle is stored in $| ($OUTPUT_AUTOFLUSH).  The string output 
  16979.  before each top of page (except the first) is stored in $^L 
  16980.  ($FORMAT_FORMFEED).  These variables are set on a per-filehandle basis, so 
  16981.  you'll need to select() into a different one to affect them: 
  16982.  
  16983.       select((select(OUTF),
  16984.               $~ = "My_Other_Format",
  16985.               $^ = "My_Top_Format"
  16986.              )[0]);
  16987.  
  16988.  Pretty ugly, eh?  It's a common idiom though, so don't be too surprised when 
  16989.  you see it.  You can at least use a temporary variable to hold the previous 
  16990.  filehandle: (this is a much better approach in general, because not only does 
  16991.  legibility improve, you now have intermediary stage in the expression to 
  16992.  single-step the debugger through): 
  16993.  
  16994.       $ofh = select(OUTF);
  16995.       $~ = "My_Other_Format";
  16996.       $^ = "My_Top_Format";
  16997.       select($ofh);
  16998.  
  16999.  If you use the English module, you can even read the variable names: 
  17000.  
  17001.       use English;
  17002.       $ofh = select(OUTF);
  17003.       $FORMAT_NAME     = "My_Other_Format";
  17004.       $FORMAT_TOP_NAME = "My_Top_Format";
  17005.       select($ofh);
  17006.  
  17007.  But you still have those funny select()s.  So just use the FileHandle module. 
  17008.  Now, you can access these special variables using lower-case method names 
  17009.  instead: 
  17010.  
  17011.       use FileHandle;
  17012.       format_name     OUTF "My_Other_Format";
  17013.       format_top_name OUTF "My_Top_Format";
  17014.  
  17015.  Much better! 
  17016.  
  17017.  NOTES 
  17018.  
  17019.  Since the values line may contain arbitrary expressions (for at fields, not 
  17020.  caret fields), you can farm out more sophisticated processing to other 
  17021.  functions, like sprintf() or one of your own.  For example: 
  17022.  
  17023.       format Ident =
  17024.           @<<<<<<<<<<<<<<<
  17025.           &commify($n)
  17026.       .
  17027.  
  17028.  To get a real at or caret into the field, do this: 
  17029.  
  17030.       format Ident =
  17031.       I have an @ here.
  17032.               "@"
  17033.       .
  17034.  
  17035.  To center a whole line of text, do something like this: 
  17036.  
  17037.       format Ident =
  17038.       @|||||||||||||||||||||||||||||||||||||||||||||||
  17039.               "Some text line"
  17040.       .
  17041.  
  17042.  There is no builtin way to say " float this to the right hand side of the 
  17043.  page, however wide it is."  You have to specify where it goes. The truly 
  17044.  desperate can generate their own format on the fly, based on the current 
  17045.  number of columns, and then eval() it: 
  17046.  
  17047.       $format  = "format STDOUT = \n";
  17048.                . '^' . '<' x $cols . "\n";
  17049.                . '$entry' . "\n";
  17050.                . "\t^" . "<" x ($cols-8) . "~~\n";
  17051.                . '$entry' . "\n";
  17052.                . ".\n";
  17053.       print $format if $Debugging;
  17054.       eval $format;
  17055.       die $@ if $@;
  17056.  
  17057.  Which would generate a format looking something like this: 
  17058.  
  17059.    format STDOUT =
  17060.    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  17061.    $entry
  17062.            ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<~~
  17063.    $entry
  17064.    .
  17065.  
  17066.  Here's a little program that's somewhat like fmt(1): 
  17067.  
  17068.    format =
  17069.    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~~
  17070.    $_
  17071.  
  17072.    .
  17073.  
  17074.    $/ = '';
  17075.    while (<>) {
  17076.        s/\s*\n\s*/ /g;
  17077.        write;
  17078.    }
  17079.  
  17080.  Footers 
  17081.  
  17082.  While $FORMAT_TOP_NAME contains the name of the current header format, there 
  17083.  is no corresponding mechanism to automatically do the same thing for a footer. 
  17084.  Not knowing how big a format is going to be until you evaluate it is one of 
  17085.  the major problems.  It's on the TODO list. 
  17086.  
  17087.  Here's one strategy:  If you have a fixed-size footer, you can get footers by 
  17088.  checking $FORMAT_LINES_LEFT before each write() and print the footer yourself 
  17089.  if necessary. 
  17090.  
  17091.  Here's another strategy; open a pipe to yourself, using open(MESELF, "|-") 
  17092.  (see perlfunc/open()) and always write() to MESELF instead of STDOUT.  Have 
  17093.  your child process postprocesses its STDIN to rearrange headers and footers 
  17094.  however you like.  Not very convenient, but doable. 
  17095.  
  17096.  Accessing Formatting Internals 
  17097.  
  17098.  For low-level access to the formatting mechanism.  you may use formline() and 
  17099.  access $^A (the $ACCUMULATOR variable) directly. 
  17100.  
  17101.  For example: 
  17102.  
  17103.       $str = formline <<'END', 1,2,3;
  17104.       @<<<  @|||  @>>>
  17105.       END
  17106.  
  17107.       print "Wow, I just stored `$^A' in the accumulator!\n";
  17108.  
  17109.  Or to make an swrite() subroutine which is to write() what sprintf() is to 
  17110.  printf(), do this: 
  17111.  
  17112.       use Carp;
  17113.       sub swrite {
  17114.           croak "usage: swrite PICTURE ARGS" unless @_;
  17115.           my $format = shift;
  17116.           $^A = "";
  17117.           formline($format,@_);
  17118.           return $^A;
  17119.       }
  17120.  
  17121.       $string = swrite(<<'END', 1, 2, 3);
  17122.    Check me out
  17123.    @<<<  @|||  @>>>
  17124.    END
  17125.       print $string;
  17126.  
  17127.  WARNING 
  17128.  
  17129.  Lexical variables (declared with "my") are not visible within a format unless 
  17130.  the format is declared within the scope of the lexical variable.  (They 
  17131.  weren't visible at all before version 5.001.)  Furthermore, lexical aliases 
  17132.  will not be compiled correctly: see perlfunc/my for other issues. 
  17133.  
  17134.  
  17135. ΓòÉΓòÉΓòÉ 26. Section - perlipc ΓòÉΓòÉΓòÉ
  17136.  
  17137. NAME 
  17138.  
  17139. perlipc - Perl interprocess communication (signals, fifos, pipes, safe 
  17140. subprocceses, sockets, and semaphores) 
  17141.  
  17142. DESCRIPTION 
  17143.  
  17144. The basic IPC facilities of Perl are built out of the good old Unix signals, 
  17145. named pipes, pipe opens, the Berkeley socket routines, and SysV IPC calls. 
  17146. Each is used in slightly different situations. 
  17147.  
  17148. Signals 
  17149.  
  17150. Perl uses a simple signal handling model: the %SIG hash contains names or 
  17151. references of user-installed signal handlers.  These handlers will be called 
  17152. with an argument which is the name of the signal that triggered it.  A signal 
  17153. may be generated intentionally from a particular keyboard sequence like 
  17154. control-C or control-Z, sent to you from an another process, or triggered 
  17155. automatically by the kernel when special events transpire, like a child process 
  17156. exiting, your process running out of stack space, or hitting file size limit. 
  17157.  
  17158. For example, to trap an interrupt signal, set up a handler like this. Notice 
  17159. how all we do is set with a global variable and then raise an exception. 
  17160. That's because on most systems libraries are not re-entrant, so calling any 
  17161. print() functions (or even anything that needs to malloc(3) more memory) could 
  17162. in theory trigger a memory fault and subsequent core dump. 
  17163.  
  17164.     sub catch_zap {
  17165.         my $signame = shift;
  17166.         $shucks++;
  17167.         die "Somebody sent me a SIG$signame";
  17168.     }
  17169.     $SIG{INT} = 'catch_zap';  # could fail in modules
  17170.     $SIG{INT} = \&catch_zap;  # best strategy
  17171.  
  17172. The names of the signals are the ones listed out by kill -l on your system, or 
  17173. you can retrieve them from the Config module.  Set up an @signame list indexed 
  17174. by number to get the name and a %signo table indexed by name to get the number: 
  17175.  
  17176.     use Config;
  17177.     defined $Config{sig_name} || die "No sigs?";
  17178.     foreach $name (split(' ', $Config{sig_name})) {
  17179.         $signo{$name} = $i;
  17180.         $signame[$i] = $name;
  17181.         $i++;
  17182.     }
  17183.  
  17184. So to check whether signal 17 and SIGALRM were the same, just do this: 
  17185.  
  17186.     print "signal #17 = $signame[17]\n";
  17187.     if ($signo{ALRM}) {
  17188.         print "SIGALRM is $signo{ALRM}\n";
  17189.     }
  17190.  
  17191. You may also choose to assign the strings 'IGNORE' or 'DEFAULT' as the handler, 
  17192. in which case Perl will try to discard the signal or do the default thing. 
  17193. Some signals can be neither trapped nor ignored, such as the KILL and STOP (but 
  17194. not the TSTP) signals.  One strategy for temporarily ignoring signals is to use 
  17195. a local() statement, which will be automatically restored once your block is 
  17196. exited.  (Remember that local() values are "inherited" by functions called from 
  17197. within that block.) 
  17198.  
  17199.     sub precious {
  17200.         local $SIG{INT} = 'IGNORE';
  17201.         &more_functions;
  17202.     }
  17203.     sub more_functions {
  17204.         # interrupts still ignored, for now...
  17205.     }
  17206.  
  17207. Sending a signal to a negative process ID means that you send the signal to the 
  17208. entire Unix process-group.  This code send a hang-up signal to all processes in 
  17209. the current process group except for the current process itself: 
  17210.  
  17211.     {
  17212.         local $SIG{HUP} = 'IGNORE';
  17213.         kill HUP => -$$;
  17214.         # snazzy writing of: kill('HUP', -$$)
  17215.     }
  17216.  
  17217. Another interesting signal to send is signal number zero.  This doesn't 
  17218. actually affect another process, but instead checks whether it's alive or has 
  17219. changed its UID. 
  17220.  
  17221.     unless (kill 0 => $kid_pid) {
  17222.         warn "something wicked happened to $kid_pid";
  17223.     }
  17224.  
  17225. You might also want to employ anonymous functions for simple signal handlers: 
  17226.  
  17227.     $SIG{INT} = sub { die "\nOutta here!\n" };
  17228.  
  17229. But that will be problematic for the more complicated handlers that need to 
  17230. re-install themselves.  Because Perl's signal mechanism is currently based on 
  17231. the signal(3) function from the C library, you may somtimes be so misfortunate 
  17232. as to run on systems where that function is "broken", that is, it behaves in 
  17233. the old unreliable SysV way rather than the newer, more reasonable BSD and 
  17234. POSIX fashion.  So you'll see defensive people writing signal handlers like 
  17235. this: 
  17236.  
  17237.     sub REAPER {
  17238.         $SIG{CHLD} = \&REAPER;  # loathe sysV
  17239.         $waitedpid = wait;
  17240.     }
  17241.     $SIG{CHLD} = \&REAPER;
  17242.     # now do something that forks...
  17243.  
  17244. or even the more elaborate: 
  17245.  
  17246.     use POSIX "wait_h";
  17247.     sub REAPER {
  17248.         my $child;
  17249.         $SIG{CHLD} = \&REAPER;  # loathe sysV
  17250.         while ($child = waitpid(-1,WNOHANG)) {
  17251.             $Kid_Status{$child} = $?;
  17252.         }
  17253.     }
  17254.     $SIG{CHLD} = \&REAPER;
  17255.     # do something that forks...
  17256.  
  17257. Signal handling is also used for timeouts in Unix,  While safely protected 
  17258. within an eval{} block, you set a signal handler to trap alarm signals and then 
  17259. schedule to have one delivered to you in some number of seconds.  Then try your 
  17260. blocking operation, clearing the alarm when it's done but not before you've 
  17261. exited your eval{} block.  If it goes off, you'll use die() to jump out of the 
  17262. block, much as you might using longjmp() or throw() in other languages. 
  17263.  
  17264. Here's an example: 
  17265.  
  17266.     eval {
  17267.         local $SIG{ALRM} = sub { die "alarm clock restart" };
  17268.         alarm 10;
  17269.         flock(FH, 2);   # blocking write lock
  17270.         alarm 0;
  17271.     };
  17272.     if ($@ and $@ !~ /alarm clock restart/) { die }
  17273.  
  17274. For more complex signal handling, you might see the standard POSIX module. 
  17275. Lamentably, this is almost entirely undocumented, but the t/lib/posix.t file 
  17276. from the Perl source distribution has some examples in it. 
  17277.  
  17278. Named Pipes 
  17279.  
  17280. A named pipe (often referred to as a FIFO) is an old Unix IPC mechanism for 
  17281. processes communicating on the same machine.  It works just like a regular, 
  17282. connected anonymous pipes, except that the processes rendezvous using a 
  17283. filename and don't have to be related. 
  17284.  
  17285. To create a named pipe, use the Unix command mknod(1) or on some systems, 
  17286. mkfifo(1).  These may not be in your normal path. 
  17287.  
  17288.     # system return val is backwards, so && not ||
  17289.     #
  17290.     $ENV{PATH} .= ":/etc:/usr/etc";
  17291.     if  (      system('mknod',  $path, 'p')
  17292.             && system('mkfifo', $path) )
  17293.     {
  17294.         die "mk{nod,fifo} $path failed;
  17295.     }
  17296.  
  17297. A fifo is convenient when you want to connect a process to an unrelated one. 
  17298. When you open a fifo, the program will block until there's something on the 
  17299. other end. 
  17300.  
  17301. For example, let's say you'd like to have your .signature file be a named pipe 
  17302. that has a Perl program on the other end.  Now every time any program (like a 
  17303. mailer, newsreader, finger program, etc.) tries to read from that file, the 
  17304. reading program will block and your program will supply the the new signature. 
  17305. We'll use the pipe-checking file test -p to find out whether anyone (or 
  17306. anything) has accidentally removed our fifo. 
  17307.  
  17308.     chdir; # go home
  17309.     $FIFO = '.signature';
  17310.     $ENV{PATH} .= ":/etc:/usr/games";
  17311.  
  17312.     while (1) {
  17313.         unless (-p $FIFO) {
  17314.             unlink $FIFO;
  17315.             system('mknod', $FIFO, 'p')
  17316.                 && die "can't mknod $FIFO: $!";
  17317.         }
  17318.  
  17319.         # next line blocks until there's a reader
  17320.         open (FIFO, "> $FIFO") || die "can't write $FIFO: $!";
  17321.         print FIFO "John Smith (smith\@host.org)\n", `fortune -s`;
  17322.         close FIFO;
  17323.         sleep 2;    # to avoid dup sigs
  17324.     }
  17325.  
  17326. Using open() for IPC 
  17327.  
  17328. Perl's basic open() statement can also be used for unidirectional interprocess 
  17329. communication by either appending or prepending a pipe symbol to the second 
  17330. argument to open().  Here's how to start something up a child process you 
  17331. intend to write to: 
  17332.  
  17333.     open(SPOOLER, "| cat -v | lpr -h 2>/dev/null")
  17334.                     || die "can't fork: $!";
  17335.     local $SIG{PIPE} = sub { die "spooler pipe broke" };
  17336.     print SPOOLER "stuff\n";
  17337.     close SPOOLER || die "bad spool: $! $?";
  17338.  
  17339. And here's how to start up a child process you intend to read from: 
  17340.  
  17341.     open(STATUS, "netstat -an 2>&1 |")
  17342.                     || die "can't fork: $!";
  17343.     while (<STATUS>) {
  17344.         next if /^(tcp|udp)/;
  17345.         print;
  17346.     }
  17347.     close SPOOLER || die "bad netstat: $! $?";
  17348.  
  17349. If one can be sure that a particular program is a Perl script that is expecting 
  17350. filenames in @ARGV, the clever programmer can write something like this: 
  17351.  
  17352.     $ program f1 "cmd1|" - f2 "cmd2|" f3 < tmpfile
  17353.  
  17354. and irrespective of which shell it's called from, the Perl program will read 
  17355. from the file f1, the process cmd1, standard input (tmpfile in this case), the 
  17356. f2 file, the cmd2 command, and finally the f3 file.  Pretty nifty, eh? 
  17357.  
  17358. You might notice that you could use backticks for much the same effect as 
  17359. opening a pipe for reading: 
  17360.  
  17361.     print grep { !/^(tcp|udp)/ } `netstat -an 2>&1`;
  17362.     die "bad netstat" if $?;
  17363.  
  17364. While this is true on the surface, it's much more efficient to process the file 
  17365. one line or record at a time because then you don't have to read the whole 
  17366. thing into memory at once. It also gives you finer control of the whole 
  17367. process, letting you to kill off the child process early if you'd like. 
  17368.  
  17369. Be careful to check both the open() and the close() return values.  If you're 
  17370. writing to a pipe, you should also trap SIGPIPE.  Otherwise, think of what 
  17371. happens when you start up a pipe to a command that doesn't exist: the open() 
  17372. will in all likelihood succeed (it only reflects the fork()'s success), but 
  17373. then your output will fail--spectacularly.  Perl can't know whether the command 
  17374. worked because your command is actually running in a separate process whose 
  17375. exec() might have failed.  Therefore, while readers of bogus commands just 
  17376. return a quick end of file, writers to bogus command will trigger a signal 
  17377. they'd better be prepared to handle.  Consider: 
  17378.  
  17379.     open(FH, "|bogus");
  17380.     print FH "bang\n";
  17381.     close FH;
  17382.  
  17383. Safe Pipe Opens 
  17384.  
  17385. Another interesting approach to IPC is making your single program go 
  17386. multiprocess and communicate between (or even amongst) yourselves.  The open() 
  17387. function will accept a file argument of either "-|" or "|-" to do a very 
  17388. interesting thing: it forks a child connected to the filehandle you've opened. 
  17389. The child is running the same program as the parent.  This is useful for safely 
  17390. opening a file when running under an assumed UID or GID, for example.  If you 
  17391. open a pipe to minus, you can write to the filehandle you opened and your kid 
  17392. will find it in his STDIN.  If you open a pipe from minus, you can read from 
  17393. the filehandle you opened whatever your kid writes to his STDOUT. 
  17394.  
  17395.     use English;
  17396.     my $sleep_count = 0;
  17397.  
  17398.     do {
  17399.         $pid = open(KID_TO_WRITE, "|-");
  17400.         unless (defined $pid) {
  17401.             warn "cannot fork: $!";
  17402.             die "bailing out" if $sleep_count++ > 6;
  17403.             sleep 10;
  17404.         }
  17405.     } until defined $pid;
  17406.  
  17407.     if ($pid) {  # parent
  17408.         print KID_TO_WRITE @some_data;
  17409.         close(KID_TO_WRITE) || warn "kid exited $?";
  17410.     } else {     # child
  17411.         ($EUID, $EGID) = ($UID, $GID); # suid progs only
  17412.         open (FILE, "> /safe/file")
  17413.             || die "can't open /safe/file: $!";
  17414.         while (<STDIN>) {
  17415.             print FILE; # child's STDIN is parent's KID
  17416.         }
  17417.         exit;  # don't forget this
  17418.     }
  17419.  
  17420. Another common use for this construct is when you need to execute something 
  17421. without the shell's interference.  With system(), it's straigh-forward, but you 
  17422. can't use a pipe open or backticks safely. That's because there's no way to 
  17423. stop the shell from getting its hands on your arguments.  Instead, use 
  17424. lower-level control to call exec() directly. 
  17425.  
  17426. Here's a safe backtick or pipe open for read: 
  17427.  
  17428.     # add error processing as above
  17429.     $pid = open(KID_TO_READ, "-|");
  17430.  
  17431.     if ($pid) {   # parent
  17432.         while (<KID_TO_READ>) {
  17433.             # do something interesting
  17434.         }
  17435.         close(KID_TO_READ) || warn "kid exited $?";
  17436.  
  17437.     } else {      # child
  17438.         ($EUID, $EGID) = ($UID, $GID); # suid only
  17439.         exec($program, @options, @args)
  17440.             || die "can't exec program: $!";
  17441.         # NOTREACHED
  17442.     }
  17443.  
  17444. And here's a safe pipe open for writing: 
  17445.  
  17446.     # add error processing as above
  17447.     $pid = open(KID_TO_WRITE, "|-");
  17448.     $SIG{ALRM} = sub { die "whoops, $program pipe broke" };
  17449.  
  17450.     if ($pid) {  # parent
  17451.         for (@data) {
  17452.             print KID_TO_WRITE;
  17453.         }
  17454.         close(KID_TO_WRITE) || warn "kid exited $?";
  17455.  
  17456.     } else {     # child
  17457.         ($EUID, $EGID) = ($UID, $GID);
  17458.         exec($program, @options, @args)
  17459.             || die "can't exec program: $!";
  17460.         # NOTREACHED
  17461.     }
  17462.  
  17463. Note that these operations are full Unix forks, which means they may not be 
  17464. correctly implemented on alien systems.  Additionally, these are not true 
  17465. multithreading.  If you'd like to learn more about threading, see the modules 
  17466. file mentioned below in the L<SEE ALSO> section. 
  17467.  
  17468. Bidirectional Communication 
  17469.  
  17470. While this works reasonably well for unidirectional communication, what about 
  17471. bidirectional communication?  The obvious thing you'd like to do doesn't 
  17472. actually work: 
  17473.  
  17474.     open(PROG_FOR_READING_AND_WRITING, "| some program |")
  17475.  
  17476. and if you forget to use the -w flag, then you'll miss out entirely on the 
  17477. diagnostic message: 
  17478.  
  17479.     Can't do bidirectional pipe at -e line 1.
  17480.  
  17481. If you really want to, you can use the standard open2() library function to 
  17482. catch both ends.  There's also an open3() for tridirectional I/O so you can 
  17483. also catch your child's STDERR, but doing so would then require an awkward 
  17484. select() loop and wouldn't allow you to use normal Perl input operations. 
  17485.  
  17486. If you look at its source, you'll see that open2() uses low-level primitives 
  17487. like Unix pipe() and exec() to create all the connections. While it might have 
  17488. been slightly more efficient by using socketpair(), it would have then been 
  17489. even less portable than it already is.  The open2() and open3() functions are 
  17490. unlikely to work anywhere except on a Unix system or some other one purporting 
  17491. to be POSIX compliant. 
  17492.  
  17493. Here's an example of using open2(): 
  17494.  
  17495.     use FileHandle;
  17496.     use IPC::Open2;
  17497.     $pid = open2( \*Reader, \*Writer, "cat -u -n" );
  17498.     Writer->autoflush(); # default here, actually
  17499.     print Writer "stuff\n";
  17500.     $got = <Reader>;
  17501.  
  17502. The problem with this is that Unix buffering is going to really ruin your day. 
  17503. Even though your Writer filehandle is autoflushed, and the process on the other 
  17504. end will get your data in a timely manner, you can't usually do anything to 
  17505. force it to actually give it back to you in a similarly quick fashion.  In this 
  17506. case, we could, because we gave cat a -u flag to make it unbuffered.  But very 
  17507. few Unix commands are designed to operate over pipes, so this seldom works 
  17508. unless you yourself wrote the program on the other end of the double-ended 
  17509. pipe. 
  17510.  
  17511. A solution to this is the non-standard Comm.pl library.  It uses pseudo-ttys to 
  17512. make your program behave more reasonably: 
  17513.  
  17514.     require 'Comm.pl';
  17515.     $ph = open_proc('cat -n');
  17516.     for (1..10) {
  17517.         print $ph "a line\n";
  17518.         print "got back ", scalar <$ph>;
  17519.     }
  17520.  
  17521. This way you don't have to have control over the source code of the program 
  17522. you're using.  The Comm library also has expect() and interact() functions. 
  17523. Find the library (and hopefully its successor IPC::Chat) at your nearest CPAN 
  17524. archive as detailed in the L<SEE ALSO> section below. 
  17525.  
  17526. Sockets: Client/Server Communication 
  17527.  
  17528. While not limited to Unix-derived operating systems (e.g. WinSock on PCs 
  17529. provides socket support, as do some VMS libraries), you may not have sockets on 
  17530. your system, in which this section probably isn't going to do you much good. 
  17531. With sockets, you can do both virtual circuits (i.e. TCP streams) and datagrams 
  17532. (i.e. UDP packets).  You may be able to do even more depending on your system. 
  17533.  
  17534. The Perl function calls for dealing with sockets have the same names as the 
  17535. corresponding system calls in C, but their arguments tend to differ for two 
  17536. reasons: first, Perl filehandles work differently than C file descriptors. 
  17537. Second, Perl already knows the length of its strings, so you don't need to pass 
  17538. that information. 
  17539.  
  17540. One of the major problems with old socket code in Perl was that it used 
  17541. hard-coded values for some of the constants, which severely hurt portability. 
  17542. If you ever see code that does anything like explicitly setting $AF_INET = 2, 
  17543. you know you're in for big trouble:  An immeasurably superior approach is to 
  17544. use the Socket module, which more reliably grants access to various constants 
  17545. and functions you'll need. 
  17546.  
  17547. Internet TCP Clients and Servers 
  17548.  
  17549. Use Internet-domain sockets when you want to do client-server communication 
  17550. that might extend to machines outside of your own system. 
  17551.  
  17552. Here's a sample TCP client using Internet-domain sockets: 
  17553.  
  17554.     #!/usr/bin/perl -w
  17555.     require 5.002;
  17556.     use strict;
  17557.     use Socket;
  17558.     my ($remote,$port, $iaddr, $paddr, $proto, $line);
  17559.  
  17560.     $remote  = shift || 'localhost';
  17561.     $port    = shift || 2345;  # random port
  17562.     if ($port =~ /\D/) { $port = getservbyname($port, 'tcp') }
  17563.     die "No port" unless $port;
  17564.     $iaddr   = inet_aton($remote)               || die "no host: $remote";
  17565.     $paddr   = sockaddr_in($port, $iaddr);
  17566.  
  17567.     $proto   = getprotobyname('tcp');
  17568.     socket(SOCK, PF_INET, SOCK_STREAM, $proto)  || die "socket: $!";
  17569.     connect(SOCK, $paddr)    || die "connect: $!";
  17570.     while ($line = <SOCK>) {
  17571.         print $line;
  17572.     }
  17573.  
  17574.     close (SOCK)            || die "close: $!";
  17575.     exit;
  17576.  
  17577. And here's a corresponding server to go along with it.  We'll leave the address 
  17578. as INADDR_ANY so that the kernel can choose the appropriate interface on 
  17579. multihomed hosts.  If you want sit on a particular interface (like the external 
  17580. side of a gateway or firewall machine), you should fill this in with your real 
  17581. address instead. 
  17582.  
  17583.     #!/usr/bin/perl -Tw
  17584.     require 5.002;
  17585.     use strict;
  17586.     BEGIN { $ENV{PATH} = '/usr/ucb:/bin' }
  17587.     use Socket;
  17588.     use Carp;
  17589.  
  17590.     sub logmsg { print "$0 $$: @_ at ", scalar localtime, "\n" }
  17591.  
  17592.     my $port = shift || 2345;
  17593.     my $proto = getprotobyname('tcp');
  17594.     socket(Server, PF_INET, SOCK_STREAM, $proto)        || die "socket: $!";
  17595.     setsockopt(Server, SOL_SOCKET, SO_REUSEADDR,
  17596.                                         pack("l", 1))   || die "setsockopt: $!";
  17597.     bind(Server, sockaddr_in($port, INADDR_ANY))        || die "bind: $!";
  17598.     listen(Server,SOMAXCONN)                            || die "listen: $!";
  17599.  
  17600.     logmsg "server started on port $port";
  17601.  
  17602.     my $paddr;
  17603.  
  17604.     $SIG{CHLD} = \&REAPER;
  17605.  
  17606.     for ( ; $paddr = accept(Client,Server); close Client) {
  17607.         my($port,$iaddr) = sockaddr_in($paddr);
  17608.         my $name = gethostbyaddr($iaddr,AF_INET);
  17609.  
  17610.         logmsg "connection from $name [",
  17611.                 inet_ntoa($iaddr), "]
  17612.                 at port $port";
  17613.  
  17614.         print CLIENT "Hello there, $name, it's now ",
  17615.                         scalar localtime, "\n";
  17616.     }
  17617.  
  17618. And here's a multithreaded version.  It's multithreaded in that like most 
  17619. typical servers, it spawns (forks) a slave server to handle the client request 
  17620. so that the master server can quickly go back to service a new client. 
  17621.  
  17622.     #!/usr/bin/perl -Tw
  17623.     require 5.002;
  17624.     use strict;
  17625.     BEGIN { $ENV{PATH} = '/usr/ucb:/bin' }
  17626.     use Socket;
  17627.     use Carp;
  17628.  
  17629.     sub spawn;  # forward declaration
  17630.     sub logmsg { print "$0 $$: @_ at ", scalar localtime, "\n" }
  17631.  
  17632.     my $port = shift || 2345;
  17633.     my $proto = getprotobyname('tcp');
  17634.     socket(Server, PF_INET, SOCK_STREAM, $proto)        || die "socket: $!";
  17635.     setsockopt(Server, SOL_SOCKET, SO_REUSEADDR,
  17636.                                         pack("l", 1))   || die "setsockopt: $!";
  17637.     bind(Server, sockaddr_in($port, INADDR_ANY))        || die "bind: $!";
  17638.     listen(Server,SOMAXCONN)                            || die "listen: $!";
  17639.  
  17640.     logmsg "server started on port $port";
  17641.  
  17642.     my $waitedpid = 0;
  17643.     my $paddr;
  17644.  
  17645.     sub REAPER {
  17646.         $SIG{CHLD} = \&REAPER;  # loathe sysV
  17647.         $waitedpid = wait;
  17648.         logmsg "reaped $waitedpid" . ($? ? " with exit $?" : '');
  17649.     }
  17650.  
  17651.     $SIG{CHLD} = \&REAPER;
  17652.  
  17653.     for ( $waitedpid = 0;
  17654.           ($paddr = accept(Client,Server)) || $waitedpid;
  17655.           $waitedpid = 0, close Client)
  17656.     {
  17657.         next if $waitedpid;
  17658.         my($port,$iaddr) = sockaddr_in($paddr);
  17659.         my $name = gethostbyaddr($iaddr,AF_INET);
  17660.  
  17661.         logmsg "connection from $name [",
  17662.                 inet_ntoa($iaddr), "]
  17663.                 at port $port";
  17664.  
  17665.         spawn sub {
  17666.             print "Hello there, $name, it's now ", scalar localtime, "\n";
  17667.             exec '/usr/games/fortune'
  17668.                 or confess "can't exec fortune: $!";
  17669.         };
  17670.  
  17671.     }
  17672.  
  17673.     sub spawn {
  17674.         my $coderef = shift;
  17675.  
  17676.         unless (@_ == 0 && $coderef && ref($coderef) eq 'CODE') {
  17677.             confess "usage: spawn CODEREF";
  17678.         }
  17679.  
  17680.         my $pid;
  17681.         if (!defined($pid = fork)) {
  17682.             logmsg "cannot fork: $!";
  17683.             return;
  17684.         } elsif ($pid) {
  17685.             logmsg "begat $pid";
  17686.             return; # i'm the parent
  17687.         }
  17688.         # else i'm the child -- go spawn
  17689.  
  17690.         open(STDIN,  "<&Client")   || die "can't dup client to stdin";
  17691.         open(STDOUT, ">&Client")   || die "can't dup client to stdout";
  17692.         ## open(STDERR, ">&STDOUT") || die "can't dup stdout to stderr";
  17693.         exit &$coderef();
  17694.     }
  17695.  
  17696. This server takes the trouble to clone off a child version via fork() for each 
  17697. incoming request.  That way it can handle many requests at once, which you 
  17698. might not always want.  Even if you don't fork(), the listen() will allow that 
  17699. many pending connections.  Forking servers have to be particularly careful 
  17700. about cleaning up their dead children (called "zombies" in Unix parlance), 
  17701. because otherwise you'll quickly fill up your process table. 
  17702.  
  17703. We suggest that you use the -T flag to use taint checking (see perlsec) even if 
  17704. we aren't running setuid or setgid.  This is always a good idea for servers and 
  17705. other programs run on behalf of someone else (like CGI scripts), because it 
  17706. lessens the chances that people from the outside will be able to compromise 
  17707. your system. 
  17708.  
  17709. Let's look at another TCP client.  This one connects to the TCP "time" service 
  17710. on a number of different machines and shows how far their clocks differ from 
  17711. the system on which it's being run: 
  17712.  
  17713.     #!/usr/bin/perl  -w
  17714.     require 5.002;
  17715.     use strict;
  17716.     use Socket;
  17717.  
  17718.     my $SECS_of_70_YEARS = 2208988800;
  17719.     sub ctime { scalar localtime(shift) }
  17720.  
  17721.     my $iaddr = gethostbyname('localhost');
  17722.     my $proto = getprotobyname('tcp');
  17723.     my $port = getservbyname('time', 'tcp');
  17724.     my $paddr = sockaddr_in(0, $iaddr);
  17725.     my($host);
  17726.  
  17727.     $| = 1;
  17728.     printf "%-24s %8s %s\n",  "localhost", 0, ctime(time());
  17729.  
  17730.     foreach $host (@ARGV) {
  17731.         printf "%-24s ", $host;
  17732.         my $hisiaddr = inet_aton($host)     || die "unknown host";
  17733.         my $hispaddr = sockaddr_in($port, $hisiaddr);
  17734.         socket(SOCKET, PF_INET, SOCK_STREAM, $proto)   || die "socket: $!";
  17735.         connect(SOCKET, $hispaddr)          || die "bind: $!";
  17736.         my $rtime = '    ';
  17737.         read(SOCKET, $rtime, 4);
  17738.         close(SOCKET);
  17739.         my $histime = unpack("N", $rtime) - $SECS_of_70_YEARS ;
  17740.         printf "%8d %s\n", $histime - time, ctime($histime);
  17741.     }
  17742.  
  17743. Unix-Domain TCP Clients and Servers 
  17744.  
  17745. That's fine for Internet-domain clients and servers, but what local 
  17746. communications?  While you can use the same setup, sometimes you don't want to. 
  17747. Unix-domain sockets are local to the current host, and are often used 
  17748. internally to implement pipes.  Unlike Internet domain sockets, UNIX domain 
  17749. sockets can show up in the file system with an ls(1) listing. 
  17750.  
  17751.     $ ls -l /dev/log
  17752.     srw-rw-rw-  1 root            0 Oct 31 07:23 /dev/log
  17753.  
  17754. You can test for these with Perl's -S file test: 
  17755.  
  17756.     unless ( -S '/dev/log' ) {
  17757.         die "something's wicked with the print system";
  17758.     }
  17759.  
  17760. Here's a sample Unix-domain client: 
  17761.  
  17762.     #!/usr/bin/perl -w
  17763.     require 5.002;
  17764.     use Socket;
  17765.     use strict;
  17766.     my ($rendezvous, $line);
  17767.  
  17768.     $rendezvous = shift || '/tmp/catsock';
  17769.     socket(SOCK, PF_UNIX, SOCK_STREAM, 0)       || die "socket: $!";
  17770.     connect(SOCK, sockaddr_un($remote))         || die "connect: $!";
  17771.     while ($line = <SOCK>) {
  17772.         print $line;
  17773.     }
  17774.     exit;
  17775.  
  17776. And here's a corresponding server. 
  17777.  
  17778.     #!/usr/bin/perl -Tw
  17779.     require 5.002;
  17780.     use strict;
  17781.     use Socket;
  17782.     use Carp;
  17783.  
  17784.     BEGIN { $ENV{PATH} = '/usr/ucb:/bin' }
  17785.  
  17786.     my $NAME = '/tmp/catsock';
  17787.     my $uaddr = sockaddr_un($NAME);
  17788.     my $proto = getprotobyname('tcp');
  17789.  
  17790.     socket(Server,PF_UNIX,SOCK_STREAM,0)        || die "socket: $!";
  17791.     unlink($NAME);
  17792.     bind  (Server, $uaddr)                      || die "bind: $!";
  17793.     listen(Server,SOMAXCONN)                    || die "listen: $!";
  17794.  
  17795.     logmsg "server started on $NAME";
  17796.  
  17797.     $SIG{CHLD} = \&REAPER;
  17798.  
  17799.     for ( $waitedpid = 0;
  17800.           accept(Client,Server) || $waitedpid;
  17801.           $waitedpid = 0, close Client)
  17802.     {
  17803.         next if $waitedpid;
  17804.         logmsg "connection on $NAME";
  17805.         spawn sub {
  17806.             print "Hello there, it's now ", scalar localtime, "\n";
  17807.             exec '/usr/games/fortune' or die "can't exec fortune: $!";
  17808.         };
  17809.     }
  17810.  
  17811. As you see, it's remarkably similar to the Internet domain TCP server, so much 
  17812. so, in fact, that we've omitted several duplicate functions--spawn(), logmsg(), 
  17813. ctime(), and REAPER()--which are exactly the same as in the other server. 
  17814.  
  17815. So why would you ever want to use a Unix domain socket instead of a simpler 
  17816. named pipe?  Because a named pipe doesn't give you sessions.  You can't tell 
  17817. one process's data from another's.  With socket programming, you get a separate 
  17818. session for each client: that's why accept() takes two arguments. 
  17819.  
  17820. For example, let's say that you have a long running database server daemon that 
  17821. you want folks from the World Wide Web to be able to access, but only if they 
  17822. go through a CGI interface.  You'd have a small, simple CGI program that does 
  17823. whatever checks and logging you feel like, and then acts as a Unix-domain 
  17824. client and connects to your private server. 
  17825.  
  17826. UDP: Message Passing 
  17827.  
  17828. Another kind of client-server setup is one that uses not connections, but 
  17829. messages.  UDP communications involve much lower overhead but also provide less 
  17830. reliability, as there are no promises that messages will arrive at all, let 
  17831. alone in order and unmangled.  Still, UDP offers some advantages over TCP, 
  17832. including being able to "broadcast" or "multicast" to a whole bunch of 
  17833. destination hosts at once (usually on your local subnet).  If you find yourself 
  17834. overly concerned about reliability and start building checks into your message 
  17835. system, then you probably should just use TCP to start with. 
  17836.  
  17837. Here's a UDP program similar to the sample Internet TCP client given above. 
  17838. However, instead of checking one host at a time, the UDP version will check 
  17839. many of them asynchronously by simulating a multicast and then using select() 
  17840. to do a timed-out wait for I/O.  To do something similar with TCP, you'd have 
  17841. to use a different socket handle for each host. 
  17842.  
  17843.     #!/usr/bin/perl -w
  17844.     use strict;
  17845.     require 5.002;
  17846.     use Socket;
  17847.     use Sys::Hostname;
  17848.  
  17849.     my ( $count, $hisiaddr, $hispaddr, $histime,
  17850.          $host, $iaddr, $paddr, $port, $proto,
  17851.          $rin, $rout, $rtime, $SECS_of_70_YEARS);
  17852.  
  17853.     $SECS_of_70_YEARS      = 2208988800;
  17854.  
  17855.     $iaddr = gethostbyname(hostname());
  17856.     $proto = getprotobyname('udp');
  17857.     $port = getservbyname('time', 'udp');
  17858.     $paddr = sockaddr_in(0, $iaddr); # 0 means let kernel pick
  17859.  
  17860.     socket(SOCKET, PF_INET, SOCK_DGRAM, $proto)   || die "socket: $!";
  17861.     bind(SOCKET, $paddr)                          || die "bind: $!";
  17862.  
  17863.     $| = 1;
  17864.     printf "%-12s %8s %s\n",  "localhost", 0, scalar localtime time;
  17865.     $count = 0;
  17866.     for $host (@ARGV) {
  17867.         $count++;
  17868.         $hisiaddr = inet_aton($host)    || die "unknown host";
  17869.         $hispaddr = sockaddr_in($port, $hisiaddr);
  17870.         defined(send(SOCKET, 0, 0, $hispaddr))    || die "send $host: $!";
  17871.     }
  17872.  
  17873.     $rin = '';
  17874.     vec($rin, fileno(SOCKET), 1) = 1;
  17875.  
  17876.     # timeout after 10.0 seconds
  17877.     while ($count && select($rout = $rin, undef, undef, 10.0)) {
  17878.         $rtime = '';
  17879.         ($hispaddr = recv(SOCKET, $rtime, 4, 0))        || die "recv: $!";
  17880.         ($port, $hisiaddr) = sockaddr_in($hispaddr);
  17881.         $host = gethostbyaddr($hisiaddr, AF_INET);
  17882.         $histime = unpack("N", $rtime) - $SECS_of_70_YEARS ;
  17883.         printf "%-12s ", $host;
  17884.         printf "%8d %s\n", $histime - time, scalar localtime($histime);
  17885.         $count--;
  17886.     }
  17887.  
  17888. SysV IPC 
  17889.  
  17890. While System V IPC isn't so widely used as sockets, it still has some 
  17891. interesting uses.  You can't, however, effectively use SysV IPC or Berkeley 
  17892. mmap() to have shared memory so as to share a variable amongst several 
  17893. processes.  That's because Perl would reallocate your string when you weren't 
  17894. wanting it to. 
  17895.  
  17896. Here's a small example showing shared memory usage. 
  17897.  
  17898.     $IPC_PRIVATE = 0;
  17899.     $IPC_RMID = 0;
  17900.     $size = 2000;
  17901.     $key = shmget($IPC_PRIVATE, $size , 0777 );
  17902.     die unless defined $key;
  17903.  
  17904.     $message = "Message #1";
  17905.     shmwrite($key, $message, 0, 60 ) || die "$!";
  17906.     shmread($key,$buff,0,60) || die "$!";
  17907.  
  17908.     print $buff,"\n";
  17909.  
  17910.     print "deleting $key\n";
  17911.     shmctl($key ,$IPC_RMID, 0) || die "$!";
  17912.  
  17913. Here's an example of a semaphore: 
  17914.  
  17915.     $IPC_KEY = 1234;
  17916.     $IPC_RMID = 0;
  17917.     $IPC_CREATE = 0001000;
  17918.     $key = semget($IPC_KEY, $nsems , 0666 | $IPC_CREATE );
  17919.     die if !defined($key);
  17920.     print "$key\n";
  17921.  
  17922. Put this code in a separate file to be run in more that one process Call the 
  17923. file take: 
  17924.  
  17925.     # create a semaphore
  17926.  
  17927.     $IPC_KEY = 1234;
  17928.     $key = semget($IPC_KEY,  0 , 0 );
  17929.     die if !defined($key);
  17930.  
  17931.     $semnum = 0;
  17932.     $semflag = 0;
  17933.  
  17934.     # 'take' semaphore
  17935.     # wait for semaphore to be zero
  17936.     $semop = 0;
  17937.     $opstring1 = pack("sss", $semnum, $semop, $semflag);
  17938.  
  17939.     # Increment the semaphore count
  17940.     $semop = 1;
  17941.     $opstring2 = pack("sss", $semnum, $semop,  $semflag);
  17942.     $opstring = $opstring1 . $opstring2;
  17943.  
  17944.     semop($key,$opstring) || die "$!";
  17945.  
  17946. Put this code in a separate file to be run in more that one process Call this 
  17947. file give: 
  17948.  
  17949.     # 'give' the semaphore
  17950.     # run this in the original process and you will see
  17951.     # that the second process continues
  17952.  
  17953.     $IPC_KEY = 1234;
  17954.     $key = semget($IPC_KEY, 0, 0);
  17955.     die if !defined($key);
  17956.  
  17957.     $semnum = 0;
  17958.     $semflag = 0;
  17959.  
  17960.     # Decrement the semaphore count
  17961.     $semop = -1;
  17962.     $opstring = pack("sss", $semnum, $semop, $semflag);
  17963.  
  17964.     semop($key,$opstring) || die "$!";
  17965.  
  17966. WARNING 
  17967.  
  17968. The SysV IPC code above was written long ago, and it's definitely clunky 
  17969. looking.  It should at the very least be made to use strict and require 
  17970. "sys/ipc.ph".  Better yet, perhaps someone should create an IPC::SysV module 
  17971. the way we have the Socket module for normal client-server communications. 
  17972.  
  17973. (... time passes) 
  17974.  
  17975. Voila!  Check out the IPC::SysV modules written by Jack Shirazi.  You can find 
  17976. them at a CPAN store near you. 
  17977.  
  17978. NOTES 
  17979.  
  17980. If you are running under version 5.000 (dubious) or 5.001, you can still use 
  17981. most of the examples in this document.  You may have to remove the use strict 
  17982. and some of the my() statements for 5.000, and for both you'll have to load in 
  17983. version 1.2 of the Socket.pm module, which was/is/shall-be included in 
  17984. perl5.001o. 
  17985.  
  17986. Most of these routines quietly but politely return undef when they fail instead 
  17987. of causing your program to die right then and there due to an uncaught 
  17988. exception.  (Actually, some of the new Socket conversion functions  croak() on 
  17989. bad arguments.)  It is therefore essential that you should check the return 
  17990. values fo these functions.  Always begin your socket programs this way for 
  17991. optimal success, and don't forget to add -T taint checking flag to the 
  17992. pound-bang line for servers: 
  17993.  
  17994.     #!/usr/bin/perl -w
  17995.     require 5.002;
  17996.     use strict;
  17997.     use sigtrap;
  17998.     use Socket;
  17999.  
  18000. BUGS 
  18001.  
  18002. All these routines create system-specific portability problems.  As noted 
  18003. elsewhere, Perl is at the mercy of your C libraries for much of its system 
  18004. behaviour.  It's probably safest to assume broken SysV semantics for signals 
  18005. and to stick with simple TCP and UDP socket operations; e.g. don't try to pass 
  18006. open filedescriptors over a local UDP datagram socket if you want your code to 
  18007. stand a chance of being portable. 
  18008.  
  18009. Because few vendors provide C libraries that are safely re-entrant, the prudent 
  18010. programmer will do little else within a handler beyond die() to raise an 
  18011. exception and longjmp(3) out. 
  18012.  
  18013. AUTHOR 
  18014.  
  18015. Tom Christiansen, with occasional vestiges of Larry Wall's original version. 
  18016.  
  18017. SEE ALSO 
  18018.  
  18019. Besides the obvious functions in perlfunc, you should also check out the 
  18020. modules file at your nearest CPAN site.  (See perlmod or best yet, the Perl FAQ 
  18021. for a description of what CPAN is and where to get it.) Section 5 of the 
  18022. modules file is devoted to "Networking, Device Control (modems) and 
  18023. Interprocess Communication", and contains numerous unbundled modules numerous 
  18024. networking modules, Chat and Expect operations, CGI programming, DCE, FTP, IPC, 
  18025. NNTP, Proxy, Ptty, RPC, SNMP, SMTP, Telnet, Threads, and ToolTalk--just to name 
  18026. a few. 
  18027.  
  18028.  
  18029. ΓòÉΓòÉΓòÉ 27. Section - perlsec ΓòÉΓòÉΓòÉ
  18030.  
  18031. NAME 
  18032.  
  18033. perlsec - Perl security 
  18034.  
  18035. DESCRIPTION 
  18036.  
  18037. Perl is designed to make it easy to write secure setuid and setgid scripts. 
  18038. Unlike shells, which are based on multiple substitution passes on each line of 
  18039. the script, Perl uses a more conventional evaluation scheme with fewer hidden 
  18040. "gotchas".  Additionally, since the language has more built-in functionality, 
  18041. it has to rely less upon external (and possibly untrustworthy) programs to 
  18042. accomplish its purposes. 
  18043.  
  18044. Beyond the obvious problems that stem from giving special privileges to such 
  18045. flexible systems as scripts, on many operating systems, setuid scripts are 
  18046. inherently insecure right from the start.  This is because that between the 
  18047. time that the kernel opens up the file to see what to run, and when the now 
  18048. setuid interpreter it ran turns around and reopens the file so it can interpret 
  18049. it, things may have changed, especially if you have symbolic links on your 
  18050. system. 
  18051.  
  18052. Fortunately, sometimes this kernel "feature" can be disabled. Unfortunately, 
  18053. there are two ways to disable it.  The system can simply outlaw scripts with 
  18054. the setuid bit set, which doesn't help much. Alternately, it can simply ignore 
  18055. the setuid bit on scripts.  If the latter is true, Perl can emulate the setuid 
  18056. and setgid mechanism when it notices the otherwise useless setuid/gid bits on 
  18057. Perl scripts.  It does this via a special executable called suidperl that is 
  18058. automatically invoked for you if it's needed. 
  18059.  
  18060. If, however, the kernel setuid script feature isn't disabled, Perl will 
  18061. complain loudly that your setuid script is insecure.  You'll need to either 
  18062. disable the kernel setuid script feature, or put a C wrapper around the script. 
  18063. See the program wrapsuid in the eg directory of your Perl distribution for how 
  18064. to go about doing this. 
  18065.  
  18066. There are some systems on which setuid scripts are free of this inherent 
  18067. security bug.  For example, recent releases of Solaris are like this.  On such 
  18068. systems, when the kernel passes the name of the setuid script to open to the 
  18069. interpreter, rather than using a pathname subject to mettling, it instead 
  18070. passes /dev/fd/3.  This is a special file already opened on the script, so that 
  18071. there can be no race condition for evil scripts to exploit.  On these systems, 
  18072. Perl should be compiled with -DSETUID_SCRIPTS_ARE_SECURE_NOW.  The Configure 
  18073. program that builds Perl tries to figure this out for itself. 
  18074.  
  18075. When executing a setuid script, or when you have turned on taint checking 
  18076. explicitly using the -T flag, Perl takes special precautions to prevent you 
  18077. from falling into any obvious traps.  (In some ways, a Perl script is more 
  18078. secure than the corresponding C program.)  Any command line argument, 
  18079. environment variable, or input is marked as "tainted", and may not be used, 
  18080. directly or indirectly, in any command that invokes a subshell, or in any 
  18081. command that modifies files, directories, or processes.  Any variable that is 
  18082. set within an expression that has previously referenced a tainted value also 
  18083. becomes tainted (even if it is logically impossible for the tainted value to 
  18084. influence the variable). For example: 
  18085.  
  18086.     $foo = shift;               # $foo is tainted
  18087.     $bar = $foo,'bar';          # $bar is also tainted
  18088.     $xxx = <>;                  # Tainted
  18089.     $path = $ENV{'PATH'};       # Tainted, but see below
  18090.     $abc = 'abc';               # Not tainted
  18091.  
  18092.     system "echo $foo";         # Insecure
  18093.     system "/bin/echo", $foo;   # Secure (doesn't use sh)
  18094.     system "echo $bar";         # Insecure
  18095.     system "echo $abc";         # Insecure until PATH set
  18096.  
  18097.     $ENV{'PATH'} = '/bin:/usr/bin';
  18098.     $ENV{'IFS'} = '' if $ENV{'IFS'} ne '';
  18099.  
  18100.     $path = $ENV{'PATH'};       # Not tainted
  18101.     system "echo $abc";         # Is secure now!
  18102.  
  18103.     open(FOO,"$foo");           # OK
  18104.     open(FOO,">$foo");          # Not OK
  18105.  
  18106.     open(FOO,"echo $foo|");     # Not OK, but...
  18107.     open(FOO,"-|") || exec 'echo', $foo;        # OK
  18108.  
  18109.     $zzz = `echo $foo`;         # Insecure, zzz tainted
  18110.  
  18111.     unlink $abc,$foo;           # Insecure
  18112.     umask $foo;                 # Insecure
  18113.  
  18114.     exec "echo $foo";           # Insecure
  18115.     exec "echo", $foo;          # Secure (doesn't use sh)
  18116.     exec "sh", '-c', $foo;      # Considered secure, alas
  18117.  
  18118. The taintedness is associated with each scalar value, so some elements of an 
  18119. array can be tainted, and others not. 
  18120.  
  18121. If you try to do something insecure, you will get a fatal error saying 
  18122. something like "Insecure dependency" or "Insecure PATH".  Note that you can 
  18123. still write an insecure system call or exec, but only by explicitly doing 
  18124. something like the last example above.  You can also bypass the tainting 
  18125. mechanism by referencing subpatterns--Perl presumes that if you reference a 
  18126. substring using $1, $2, etc, you knew what you were doing when you wrote the 
  18127. pattern: 
  18128.  
  18129.     $ARGV[0] =~ /^-P(\w+)$/;
  18130.     $printer = $1;              # Not tainted
  18131.  
  18132. This is fairly secure since \w+ doesn't match shell metacharacters. Use of /.+/ 
  18133. would have been insecure, but Perl doesn't check for that, so you must be 
  18134. careful with your patterns.  This is the ONLY mechanism for untainting user 
  18135. supplied filenames if you want to do file operations on them (unless you make 
  18136. $> equal to $< ). 
  18137.  
  18138. For "Insecure $ENV{PATH}" messages, you need to set $ENV{'PATH'} to a known 
  18139. value, and each directory in the path must be non-writable by the world. A 
  18140. frequently voiced gripe is that you can get this message even if the pathname 
  18141. to an executable is fully qualified.  But Perl can't know that the executable 
  18142. in question isn't going to execute some other program depending on the PATH. 
  18143.  
  18144. It's also possible to get into trouble with other operations that don't care 
  18145. whether they use tainted values.  Make judicious use of the file tests in 
  18146. dealing with any user-supplied filenames.  When possible, do opens and such 
  18147. after setting $ = $<>.  (Remember group IDs, too!) Perl doesn't prevent you 
  18148. from opening tainted filenames for reading, so be careful what you print out. 
  18149. The tainting mechanism is intended to prevent stupid mistakes, not to remove 
  18150. the need for thought. 
  18151.  
  18152. This gives us a reasonably safe way to open a file or pipe: just reset the id 
  18153. set to the original IDs.  Here's a way to do backticks reasonably safely. 
  18154. Notice how the exec() is not called with a string that the shell could expand. 
  18155. By the time we get to the exec(), tainting is turned off, however, so be 
  18156. careful what you call and what you pass it. 
  18157.  
  18158.     die unless defined $pid = open(KID, "-|");
  18159.     if ($pid) {           # parent
  18160.         while (<KID>) {
  18161.             # do something
  18162.         }
  18163.         close KID;
  18164.     } else {
  18165.         $> = $<;
  18166.         $) = $(;  # BUG: initgroups() not called
  18167.         exec 'program', 'arg1', 'arg2';
  18168.         die "can't exec program: $!";
  18169.     }
  18170.  
  18171. For those even more concerned about safety, see the Safe and Safe CGI modules 
  18172. at a CPAN site near you.  See perlmod for a list of CPAN sites. 
  18173.  
  18174.  
  18175. ΓòÉΓòÉΓòÉ 28. Section - perltrap ΓòÉΓòÉΓòÉ
  18176.  
  18177. NAME 
  18178.  
  18179. perltrap - Perl traps for the unwary 
  18180.  
  18181. DESCRIPTION 
  18182.  
  18183. The biggest trap of all is forgetting to use the -w switch; see perlrun.  The 
  18184. second biggest trap is not making your entire program runnable under use 
  18185. strict. 
  18186.  
  18187. Awk Traps 
  18188.  
  18189. Accustomed awk users should take special note of the following: 
  18190.  
  18191.      The English module, loaded via 
  18192.  
  18193.                 use English;
  18194.  
  18195.       allows you to refer to special variables (like $RS) as though they were 
  18196.       in awk; see perlvar for details. 
  18197.  
  18198.      Semicolons are required after all simple statements in Perl (except at 
  18199.       the end of a block).  Newline is not a statement delimiter. 
  18200.  
  18201.      Curly brackets are required on ifs and whiles. 
  18202.  
  18203.      Variables begin with "$" or "@" in Perl. 
  18204.  
  18205.      Arrays index from 0.  Likewise string positions in substr() and index(). 
  18206.  
  18207.      You have to decide whether your array has numeric or string indices. 
  18208.  
  18209.      Associative array values do not spring into existence upon mere 
  18210.       reference. 
  18211.  
  18212.      You have to decide whether you want to use string or numeric comparisons. 
  18213.  
  18214.      Reading an input line does not split it for you.  You get to split it 
  18215.       yourself to an array.  And split() operator has different arguments. 
  18216.  
  18217.      The current input line is normally in $_, not $0.  It generally does not 
  18218.       have the newline stripped.  ($0 is the name of the program executed.) 
  18219.       See perlvar. 
  18220.  
  18221.      $<digit> does not refer to fields--it refers to substrings matched by the 
  18222.       last match pattern. 
  18223.  
  18224.      The print() statement does not add field and record separators unless you 
  18225.       set $, and $..  You can set $OFS and $ORS if you're using the English 
  18226.       module. 
  18227.  
  18228.      You must open your files before you print to them. 
  18229.  
  18230.      The range operator is "..", not comma.  The comma operator works as in C. 
  18231.  
  18232.      The match operator is "=~", not "~".  ("~" is the one's complement 
  18233.       operator, as in C.) 
  18234.  
  18235.      The exponentiation operator is "**", not "^".  "^" is the XOR operator, 
  18236.       as in C.  (You know, one could get the feeling that awk is basically 
  18237.       incompatible with C.) 
  18238.  
  18239.      The concatenation operator is ".", not the null string.  (Using the null 
  18240.       string would render /pat/ /pat/ unparsable, since the third slash would 
  18241.       be interpreted as a division operator--the tokener is in fact slightly 
  18242.       context sensitive for operators like "/", "?", and ">". And in fact, "." 
  18243.       itself can be the beginning of a number.) 
  18244.  
  18245.      The next, exit, and continue keywords work differently. 
  18246.  
  18247.      The following variables work differently: 
  18248.  
  18249.                   Awk       Perl
  18250.                   ARGC      $#ARGV or scalar @ARGV
  18251.                   ARGV[0]   $0
  18252.                   FILENAME  $ARGV
  18253.                   FNR       $. - something
  18254.                   FS        (whatever you like)
  18255.                   NF        $#Fld, or some such
  18256.                   NR        $.
  18257.                   OFMT      $#
  18258.                   OFS       $,
  18259.                   ORS       $\
  18260.                   RLENGTH   length($&)
  18261.                   RS        $/
  18262.                   RSTART    length($`)
  18263.                   SUBSEP    $;
  18264.  
  18265.      You cannot set $RS to a pattern, only a string. 
  18266.  
  18267.      When in doubt, run the awk construct through a2p and see what it gives 
  18268.       you. 
  18269.  
  18270.  C Traps 
  18271.  
  18272.  Cerebral C programmers should take note of the following: 
  18273.  
  18274.      Curly brackets are required on if's and while's. 
  18275.  
  18276.      You must use elsif rather than else if. 
  18277.  
  18278.      The break and continue keywords from C become in Perl last and next, 
  18279.       respectively. Unlike in C, these do NOT work within a do { } while 
  18280.       construct. 
  18281.  
  18282.      There's no switch statement.  (But it's easy to build one on the fly.) 
  18283.  
  18284.      Variables begin with "$" or "@" in Perl. 
  18285.  
  18286.      printf() does not implement the "*" format for interpolating field 
  18287.       widths, but it's trivial to use interpolation of double-quoted strings to 
  18288.       achieve the same effect. 
  18289.  
  18290.      Comments begin with "#", not "/*". 
  18291.  
  18292.      You can't take the address of anything, although a similar operator in 
  18293.       Perl 5 is the backslash, which creates a reference. 
  18294.  
  18295.      ARGV must be capitalized.  $ARGV[0] is C's argv[1], and argv[0] ends up 
  18296.       in $0. 
  18297.  
  18298.      System calls such as link(), unlink(), rename(), etc. return nonzero for 
  18299.       success, not 0. 
  18300.  
  18301.      Signal handlers deal with signal names, not numbers.  Use kill -l to find 
  18302.       their names on your system. 
  18303.  
  18304.  Sed Traps 
  18305.  
  18306.  Seasoned sed programmers should take note of the following: 
  18307.  
  18308.      Backreferences in substitutions use "$" rather than "\". 
  18309.  
  18310.      The pattern matching metacharacters "(", ")", and "|" do not have 
  18311.       backslashes in front. 
  18312.  
  18313.      The range operator is ..., rather than comma. 
  18314.  
  18315.  Shell Traps 
  18316.  
  18317.  Sharp shell programmers should take note of the following: 
  18318.  
  18319.      The backtick operator does variable interpretation without regard to the 
  18320.       presence of single quotes in the command. 
  18321.  
  18322.      The backtick operator does no translation of the return value, unlike 
  18323.       csh. 
  18324.  
  18325.      Shells (especially csh) do several levels of substitution on each command 
  18326.       line.  Perl does substitution only in certain constructs such as double 
  18327.       quotes, backticks, angle brackets, and search patterns. 
  18328.  
  18329.      Shells interpret scripts a little bit at a time.  Perl compiles the 
  18330.       entire program before executing it (except for BEGIN blocks, which 
  18331.       execute at compile time). 
  18332.  
  18333.      The arguments are available via @ARGV, not $1, $2, etc. 
  18334.  
  18335.      The environment is not automatically made available as separate scalar 
  18336.       variables. 
  18337.  
  18338.  Perl Traps 
  18339.  
  18340.  Practicing Perl Programmers should take note of the following: 
  18341.  
  18342.      Remember that many operations behave differently in a list context than 
  18343.       they do in a scalar one.  See perldata for details. 
  18344.  
  18345.      Avoid barewords if you can, especially all lower-case ones. You can't 
  18346.       tell just by looking at it whether a bareword is a function or a string. 
  18347.       By using quotes on strings and parens on function calls, you won't ever 
  18348.       get them confused. 
  18349.  
  18350.      You cannot discern from mere inspection which built-ins are unary 
  18351.       operators (like chop() and chdir()) and which are list operators (like 
  18352.       print() and unlink()). (User-defined subroutines can only be list 
  18353.       operators, never unary ones.)  See perlop. 
  18354.  
  18355.      People have a hard time remembering that some functions default to $_, or 
  18356.       @ARGV, or whatever, but that others which you might expect to do not. 
  18357.  
  18358.      The <FH> construct is not the name of the filehandle, it is a readline 
  18359.       operation on that handle.  The data read is only assigned to $_ if the 
  18360.       file read is the sole condition in a while loop: 
  18361.  
  18362.                 while (<FH>)      { }
  18363.                 while ($_ = <FH>) { }..
  18364.                 <FH>;  # data discarded!
  18365.  
  18366.      Remember not to use "=" when you need "=~"; these two constructs are 
  18367.       quite different: 
  18368.  
  18369.                 $x =  /foo/;
  18370.                 $x =~ /foo/;
  18371.  
  18372.      The do {} construct isn't a real loop that you can use loop control on. 
  18373.  
  18374.      Use my() for local variables whenever you can get away with it (but see 
  18375.       perlform for where you can't). Using local() actually gives a local value 
  18376.       to a global variable, which leaves you open to unforeseen side-effects of 
  18377.       dynamic scoping. 
  18378.  
  18379.      If you localize an exported variable in a module, its exported value will 
  18380.       not change.  The local name becomes an alias to a new value but the 
  18381.       external name is still an alias for the original. 
  18382.  
  18383.  Perl4 Traps 
  18384.  
  18385.  Penitent Perl 4 Programmers should take note of the following incompatible 
  18386.  changes that occurred between release 4 and release 5: 
  18387.  
  18388.      @ now always interpolates an array in double-quotish strings.  Some 
  18389.       programs may now need to use backslash to protect any @ that shouldn't 
  18390.       interpolate. 
  18391.  
  18392.      Barewords that used to look like strings to Perl will now look like 
  18393.       subroutine calls if a subroutine by that name is defined before the 
  18394.       compiler sees them. For example: 
  18395.  
  18396.                 sub SeeYa { die "Hasta la vista, baby!" }
  18397.                 $SIG{'QUIT'} = SeeYa;
  18398.  
  18399.       In Perl 4, that set the signal handler; in Perl 5, it actually calls the 
  18400.       function!  You may use the -w switch to find such places. 
  18401.  
  18402.      Symbols starting with _ are no longer forced into package main, except 
  18403.       for $_ itself (and @_, etc.). 
  18404.  
  18405.      Double-colon is now a valid package separator in an identifier.  Thus 
  18406.       these behave differently in perl4 vs. perl5: 
  18407.  
  18408.                 print "$a::$b::$c\n";
  18409.                 print "$var::abc::xyz\n";
  18410.  
  18411.      s'$lhs'$rhs' now does no interpolation on either side.  It used to 
  18412.       interpolate $lhs but not $rhs. 
  18413.  
  18414.      The second and third arguments of splice() are now evaluated in scalar 
  18415.       context (as the book says) rather than list context. 
  18416.  
  18417.      These are now semantic errors because of precedence: 
  18418.  
  18419.                 shift @list + 20;
  18420.                 $n = keys %map + 20;
  18421.  
  18422.       Because if that were to work, then this couldn't: 
  18423.  
  18424.                 sleep $dormancy + 20;
  18425.  
  18426.      The precedence of assignment operators is now the same as the precedence 
  18427.       of assignment.  Perl 4 mistakenly gave them the precedence of the 
  18428.       associated operator.  So you now must parenthesize them in expressions 
  18429.       like 
  18430.  
  18431.                 /foo/ ? ($a += 2) : ($a -= 2);
  18432.  
  18433.       Otherwise 
  18434.  
  18435.                 /foo/ ? $a += 2 : $a -= 2;
  18436.  
  18437.       would be erroneously parsed as 
  18438.  
  18439.                 (/foo/ ? $a += 2 : $a) -= 2;
  18440.  
  18441.       On the other hand, 
  18442.  
  18443.                 $a += /foo/ ? 1 : 2;
  18444.  
  18445.       now works as a C programmer would expect. 
  18446.  
  18447.      open FOO || die is now incorrect.  You need parens around the filehandle. 
  18448.       While temporarily supported, using such a construct will generate a 
  18449.       non-fatal (but non-suppressible) warning. 
  18450.  
  18451.      The elements of argument lists for formats are now evaluated in list 
  18452.       context.  This means you can interpolate list values now. 
  18453.  
  18454.      You can't do a goto into a block that is optimized away.  Darn. 
  18455.  
  18456.      It is no longer syntactically legal to use whitespace as the name of a 
  18457.       variable, or as a delimiter for any kind of quote construct. Double darn. 
  18458.  
  18459.      The caller() function now returns a false value in a scalar context if 
  18460.       there is no caller.  This lets library files determine if they're being 
  18461.       required. 
  18462.  
  18463.      m//g now attaches its state to the searched string rather than the 
  18464.       regular expression. 
  18465.  
  18466.      reverse is no longer allowed as the name of a sort subroutine. 
  18467.  
  18468.      taintperl is no longer a separate executable.  There is now a -T switch 
  18469.       to turn on tainting when it isn't turned on automatically. 
  18470.  
  18471.      Double-quoted strings may no longer end with an unescaped $ or @. 
  18472.  
  18473.      The archaic while/if BLOCK BLOCK syntax is no longer supported. 
  18474.  
  18475.      Negative array subscripts now count from the end of the array. 
  18476.  
  18477.      The comma operator in a scalar context is now guaranteed to give a scalar 
  18478.       context to its arguments. 
  18479.  
  18480.      The ** operator now binds more tightly than unary minus. It was 
  18481.       documented to work this way before, but didn't. 
  18482.  
  18483.      Setting $#array lower now discards array elements. 
  18484.  
  18485.      delete() is not guaranteed to return the old value for tie()d arrays, 
  18486.       since this capability may be onerous for some modules to implement. 
  18487.  
  18488.      The construct "this is $$x" used to interpolate the pid at that point, 
  18489.       but now tries to dereference $x.  $$ by itself still works fine, however. 
  18490.  
  18491.      The meaning of foreach has changed slightly when it is iterating over a 
  18492.       list which is not an array.  This used to assign the list to a temporary 
  18493.       array, but no longer does so (for efficiency).  This means that you'll 
  18494.       now be iterating over the actual values, not over copies of the values. 
  18495.       Modifications to the loop variable can change the original values.  To 
  18496.       retain Perl 4 semantics you need to assign your list explicitly to a 
  18497.       temporary array and then iterate over that.  For example, you might need 
  18498.       to change 
  18499.  
  18500.                 foreach $var (grep /x/, @list) { ... }
  18501.  
  18502.       to 
  18503.  
  18504.                 foreach $var (my @tmp = grep /x/, @list) { ... }
  18505.  
  18506.       Otherwise changing $var will clobber the values of @list.  (This most 
  18507.       often happens when you use $_ for the loop variable, and call subroutines 
  18508.       in the loop that don't properly localize $_.) 
  18509.  
  18510.      Some error messages will be different. 
  18511.  
  18512.      Some bugs may have been inadvertently removed. 
  18513.  
  18514.  
  18515. ΓòÉΓòÉΓòÉ 29. Section - perlstyle ΓòÉΓòÉΓòÉ
  18516.  
  18517. NAME 
  18518.  
  18519. perlstyle - Perl style guide 
  18520.  
  18521. DESCRIPTION 
  18522.  
  18523. Each programmer will, of course, have his or her own preferences in regards to 
  18524. formatting, but there are some general guidelines that will make your programs 
  18525. easier to read, understand, and maintain. 
  18526.  
  18527. The most important thing is to run your programs under the -w flag at all 
  18528. times.  You may turn it off explicitly for particular portions of code via the 
  18529. $^W variable if you must.  You should also always run under use strict or know 
  18530. the reason why not. The <use sigtrap> and even <use diagnostics> pragmas may 
  18531. also prove useful. 
  18532.  
  18533. Regarding aesthetics of code lay out, about the only thing Larry cares strongly 
  18534. about is that the closing curly brace of a multi-line BLOCK should line up with 
  18535. the keyword that started the construct. Beyond that, he has other preferences 
  18536. that aren't so strong: 
  18537.  
  18538.      4-column indent. 
  18539.  
  18540.      Opening curly on same line as keyword, if possible, otherwise line up. 
  18541.  
  18542.      Space before the opening curly of a multiline BLOCK. 
  18543.  
  18544.      One-line BLOCK may be put on one line, including curlies. 
  18545.  
  18546.      No space before the semicolon. 
  18547.  
  18548.      Semicolon omitted in "short" one-line BLOCK. 
  18549.  
  18550.      Space around most operators. 
  18551.  
  18552.      Space around a "complex" subscript (inside brackets). 
  18553.  
  18554.      Blank lines between chunks that do different things. 
  18555.  
  18556.      Uncuddled elses. 
  18557.  
  18558.      No space between function name and its opening paren. 
  18559.  
  18560.      Space after each comma. 
  18561.  
  18562.      Long lines broken after an operator (except "and" and "or"). 
  18563.  
  18564.      Space after last paren matching on current line. 
  18565.  
  18566.      Line up corresponding items vertically. 
  18567.  
  18568.      Omit redundant punctuation as long as clarity doesn't suffer. 
  18569.  
  18570.  Larry has his reasons for each of these things, but he doen't claim that 
  18571.  everyone else's mind works the same as his does. 
  18572.  
  18573.  Here are some other more substantive style issues to think about: 
  18574.  
  18575.      Just because you CAN do something a particular way doesn't mean that you 
  18576.       SHOULD do it that way.  Perl is designed to give you several ways to do 
  18577.       anything, so consider picking the most readable one.  For instance 
  18578.  
  18579.                 open(FOO,$foo) || die "Can't open $foo: $!";
  18580.  
  18581.       is better than 
  18582.  
  18583.                 die "Can't open $foo: $!" unless open(FOO,$foo);
  18584.  
  18585.       because the second way hides the main point of the statement in a 
  18586.       modifier.  On the other hand 
  18587.  
  18588.                 print "Starting analysis\n" if $verbose;
  18589.  
  18590.       is better than 
  18591.  
  18592.                 $verbose && print "Starting analysis\n";
  18593.  
  18594.       since the main point isn't whether the user typed -v or not. Similarly, 
  18595.       just because an operator lets you assume default arguments doesn't mean 
  18596.       that you have to make use of the defaults.  The defaults are there for 
  18597.       lazy systems programmers writing one-shot programs.  If you want your 
  18598.       program to be readable, consider supplying the argument. Along the same 
  18599.       lines, just because you CAN omit parentheses in many places doesn't mean 
  18600.       that you ought to: 
  18601.  
  18602.                 return print reverse sort num values %array;
  18603.                 return print(reverse(sort num (values(%array))));
  18604.  
  18605.       When in doubt, parenthesize.  At the very least it will let some poor 
  18606.       schmuck bounce on the % key in vi. Even if you aren't in doubt, consider 
  18607.       the mental welfare of the person who has to maintain the code after you, 
  18608.       and who will probably put parens in the wrong place. 
  18609.  
  18610.      Don't go through silly contortions to exit a loop at the top or the 
  18611.       bottom, when Perl provides the last operator so you can exit in the 
  18612.       middle.  Just "outdent" it a little to make it more visible: 
  18613.  
  18614.                 LINE:
  18615.                     for (;;) {
  18616.                         statements;
  18617.                       last LINE if $foo;
  18618.                         next LINE if /^#/;
  18619.                         statements;
  18620.                     }
  18621.  
  18622.      Don't be afraid to use loop labels--they're there to enhance readability 
  18623.       as well as to allow multi-level loop breaks.  See the previous example. 
  18624.  
  18625.      Avoid using grep() (or map()) or `backticks` in a void context, that is, 
  18626.       when you just throw away their return values.  Those functions all have 
  18627.       return values, so use them.  Otherwise use a foreach() loop or the 
  18628.       system() function instead. 
  18629.  
  18630.      For portability, when using features that may not be implemented on every 
  18631.       machine, test the construct in an eval to see if it fails.  If you know 
  18632.       what version or patchlevel a particular feature was implemented, you can 
  18633.       test $] ($PERL_VERSION in English) to see if it will be there.  The 
  18634.       Config module will also let you interrogate values determined by the 
  18635.       Configure program when Perl was installed. 
  18636.  
  18637.      Choose mnemonic identifiers.  If you can't remember what mnemonic means, 
  18638.       you've got a problem. 
  18639.  
  18640.      While short identifiers like $gotit are probably ok, use underscores to 
  18641.       separate words.  It is generally easier to read $var_names_like_this than 
  18642.       $VarNamesLikeThis, especially for non-native speakers of English. It's 
  18643.       also a simple rule that works consistently with VAR_NAMES_LIKE_THIS. 
  18644.       Package names are sometimes an exception to this rule.  Perl informally 
  18645.       reserves lowercase module names for "pragma" modules like integer and 
  18646.       strict.  Other modules should begin with a capital letter and use mixed 
  18647.       case, but probably without underscores due to limitations in primitive 
  18648.       filesystems' representations of module names as files that must fit into 
  18649.       a few sparse bites. 
  18650.  
  18651.      You may find it helpful to use letter case to indicate the scope or 
  18652.       nature of a variable. For example: 
  18653.  
  18654.                 $ALL_CAPS_HERE   constants only (beware clashes with perl vars!)
  18655.                 $Some_Caps_Here  package-wide global/static
  18656.                 $no_caps_here    function scope my() or local() variables
  18657.  
  18658.       Function and method names seem to work best as all lowercase. E.g., 
  18659.       $obj->as_string(). You can use a leading underscore to indicate that a 
  18660.       variable or function should not be used outside the package that defined 
  18661.       it. 
  18662.  
  18663.      If you have a really hairy regular expression, use the /x modifier and 
  18664.       put in some whitespace to make it look a little less like line noise. 
  18665.       Don't use slash as a delimiter when your regexp has slashes or 
  18666.       backslashes. 
  18667.  
  18668.      Use the new "and" and "or" operators to avoid having to parenthesize list 
  18669.       operators so much, and to reduce the incidence of punctuational operators 
  18670.       like && and ||.  Call your subroutines as if they were functions or list 
  18671.       operators to avoid excessive ampersands and parens. 
  18672.  
  18673.      Use here documents instead of repeated print() statements. 
  18674.  
  18675.      Line up corresponding things vertically, especially if it'd be too long 
  18676.       to fit on one line anyway. 
  18677.  
  18678.                 $IDX = $ST_MTIME;
  18679.                 $IDX = $ST_ATIME       if $opt_u;
  18680.                 $IDX = $ST_CTIME       if $opt_c;
  18681.                 $IDX = $ST_SIZE        if $opt_s;
  18682.  
  18683.                 mkdir $tmpdir, 0700 or die "can't mkdir $tmpdir: $!";
  18684.                 chdir($tmpdir)      or die "can't chdir $tmpdir: $!";
  18685.                 mkdir 'tmp',   0777 or die "can't mkdir $tmpdir/tmp: $!";
  18686.  
  18687.      Always check the return codes of system calls.  Good error messages 
  18688.       should go to STDERR, include which program caused the problem, what the 
  18689.       failed system call and arguments were, and VERY IMPORTANT) should contain 
  18690.       the standard system error message for what went wrong.  Here's a simple 
  18691.       but sufficient example: 
  18692.  
  18693.                 opendir(D, $dir)     or die "can't opendir $dir: $!";
  18694.  
  18695.      Line up your translations when it makes sense: 
  18696.  
  18697.                 tr [abc]
  18698.                    [xyz];
  18699.  
  18700.      Think about reusability.  Why waste brainpower on a one-shot when you 
  18701.       might want to do something like it again?  Consider generalizing your 
  18702.       code.  Consider writing a module or object class.  Consider making your 
  18703.       code run cleanly with use strict and -w in effect.  Consider giving away 
  18704.       your code.  Consider changing your whole world view.  Consider... oh, 
  18705.       never mind. 
  18706.  
  18707.      Be consistent. 
  18708.  
  18709.      Be nice. 
  18710.  
  18711.  
  18712. ΓòÉΓòÉΓòÉ 30. Section - perlxs ΓòÉΓòÉΓòÉ
  18713.  
  18714. NAME 
  18715.  
  18716. perlxs - XS language reference manual 
  18717.  
  18718. DESCRIPTION 
  18719.  
  18720. Introduction 
  18721.  
  18722. XS is a language used to create an extension interface between Perl and some C 
  18723. library which one wishes to use with Perl.  The XS interface is combined with 
  18724. the library to create a new library which can be linked to Perl.  An XSUB is a 
  18725. function in the XS language and is the core component of the Perl application 
  18726. interface. 
  18727.  
  18728. The XS compiler is called xsubpp.  This compiler will embed the constructs 
  18729. necessary to let an XSUB, which is really a C function in disguise, manipulate 
  18730. Perl values and creates the glue necessary to let Perl access the XSUB.  The 
  18731. compiler uses typemaps to determine how to map C function parameters and 
  18732. variables to Perl values.  The default typemap handles many common C types.  A 
  18733. supplement typemap must be created to handle special structures and types for 
  18734. the library being linked. 
  18735.  
  18736. See perlxstut for a tutorial on the whole extension creation process. 
  18737.  
  18738. On The Road 
  18739.  
  18740. Many of the examples which follow will concentrate on creating an interface 
  18741. between Perl and the ONC+ RPC bind library functions. Specifically, the 
  18742. rpcb_gettime() function will be used to demonstrate many features of the XS 
  18743. language.  This function has two parameters; the first is an input parameter 
  18744. and the second is an output parameter.  The function also returns a status 
  18745. value. 
  18746.  
  18747.         bool_t rpcb_gettime(const char *host, time_t *timep);
  18748.  
  18749. From C this function will be called with the following statements. 
  18750.  
  18751.      #include <rpc/rpc.h>
  18752.      bool_t status;
  18753.      time_t timep;
  18754.      status = rpcb_gettime( "localhost", &timep );
  18755.  
  18756. If an XSUB is created to offer a direct translation between this function and 
  18757. Perl, then this XSUB will be used from Perl with the following code. The 
  18758. $status and $timep variables will contain the output of the function. 
  18759.  
  18760.      use RPC;
  18761.      $status = rpcb_gettime( "localhost", $timep );
  18762.  
  18763. The following XS file shows an XS subroutine, or XSUB, which demonstrates one 
  18764. possible interface to the rpcb_gettime() function.  This XSUB represents a 
  18765. direct translation between C and Perl and so preserves the interface even from 
  18766. Perl. This XSUB will be invoked from Perl with the usage shown above.  Note 
  18767. that the first three #include statements, for EXTERN.h, perl.h, and XSUB.h, 
  18768. will always be present at the beginning of an XS file.  This approach and 
  18769. others will be expanded later in this document. 
  18770.  
  18771.      #include "EXTERN.h"
  18772.      #include "perl.h"
  18773.      #include "XSUB.h"
  18774.      #include <rpc/rpc.h>
  18775.  
  18776.      MODULE = RPC  PACKAGE = RPC
  18777.  
  18778.      bool_t
  18779.      rpcb_gettime(host,timep)
  18780.           char *host
  18781.           time_t &timep
  18782.           OUTPUT:
  18783.           timep
  18784.  
  18785. Any extension to Perl, including those containing XSUBs, should have a Perl 
  18786. module to serve as the bootstrap which pulls the extension into Perl.  This 
  18787. module will export the extension's functions and variables to the Perl program 
  18788. and will cause the extension's XSUBs to be linked into Perl. The following 
  18789. module will be used for most of the examples in this document and should be 
  18790. used from Perl with the use command as shown earlier.  Perl modules are 
  18791. explained in more detail later in this document. 
  18792.  
  18793.      package RPC;
  18794.  
  18795.      require Exporter;
  18796.      require DynaLoader;
  18797.      @ISA = qw(Exporter DynaLoader);
  18798.      @EXPORT = qw( rpcb_gettime );
  18799.  
  18800.      bootstrap RPC;
  18801.      1;
  18802.  
  18803. Throughout this document a variety of interfaces to the rpcb_gettime() XSUB 
  18804. will be explored.  The XSUBs will take their parameters in different orders or 
  18805. will take different numbers of parameters.  In each case the XSUB is an 
  18806. abstraction between Perl and the real C rpcb_gettime() function, and the XSUB 
  18807. must always ensure that the real rpcb_gettime() function is called with the 
  18808. correct parameters.  This abstraction will allow the programmer to create a 
  18809. more Perl-like interface to the C function. 
  18810.  
  18811. The Anatomy of an XSUB 
  18812.  
  18813. The following XSUB allows a Perl program to access a C library function called 
  18814. sin().  The XSUB will imitate the C function which takes a single argument and 
  18815. returns a single value. 
  18816.  
  18817.      double
  18818.      sin(x)
  18819.        double x
  18820.  
  18821. When using C pointers the indirection operator * should be considered part of 
  18822. the type and the address operator & should be considered part of the variable, 
  18823. as is demonstrated in the rpcb_gettime() function above.  See the section on 
  18824. typemaps for more about handling qualifiers and unary operators in C types. 
  18825.  
  18826. The function name and the return type must be placed on separate lines. 
  18827.  
  18828.   INCORRECT                        CORRECT
  18829.  
  18830.   double sin(x)                    double
  18831.     double x                       sin(x)
  18832.                                      double x
  18833.  
  18834. The function body may be indented or left-adjusted.  The following example 
  18835. shows a function with its body left-adjusted.  Most examples in this document 
  18836. will indent the body. 
  18837.  
  18838.   CORRECT
  18839.  
  18840.   double
  18841.   sin(x)
  18842.   double x
  18843.  
  18844. The Argument Stack 
  18845.  
  18846. The argument stack is used to store the values which are sent as parameters to 
  18847. the XSUB and to store the XSUB's return value.  In reality all Perl functions 
  18848. keep their values on this stack at the same time, each limited to its own range 
  18849. of positions on the stack.  In this document the first position on that stack 
  18850. which belongs to the active function will be referred to as position 0 for that 
  18851. function. 
  18852.  
  18853. XSUBs refer to their stack arguments with the macro ST(x), where x refers to a 
  18854. position in this XSUB's part of the stack.  Position 0 for that function would 
  18855. be known to the XSUB as ST(0).  The XSUB's incoming parameters and outgoing 
  18856. return values always begin at ST(0).  For many simple cases the xsubpp compiler 
  18857. will generate the code necessary to handle the argument stack by embedding code 
  18858. fragments found in the typemaps.  In more complex cases the programmer must 
  18859. supply the code. 
  18860.  
  18861. The RETVAL Variable 
  18862.  
  18863. The RETVAL variable is a magic variable which always matches the return type of 
  18864. the C library function.  The xsubpp compiler will supply this variable in each 
  18865. XSUB and by default will use it to hold the return value of the C library 
  18866. function being called.  In simple cases the value of RETVAL will be placed in 
  18867. ST(0) of the argument stack where it can be received by Perl as the return 
  18868. value of the XSUB. 
  18869.  
  18870. If the XSUB has a return type of void then the compiler will not supply a 
  18871. RETVAL variable for that function.  When using the PPCODE: directive the RETVAL 
  18872. variable may not be needed. 
  18873.  
  18874. The MODULE Keyword 
  18875.  
  18876. The MODULE keyword is used to start the XS code and to specify the package of 
  18877. the functions which are being defined.  All text preceding the first MODULE 
  18878. keyword is considered C code and is passed through to the output untouched. 
  18879. Every XS module will have a bootstrap function which is used to hook the XSUBs 
  18880. into Perl.  The package name of this bootstrap function will match the value of 
  18881. the last MODULE statement in the XS source files.  The value of MODULE should 
  18882. always remain constant within the same XS file, though this is not required. 
  18883.  
  18884. The following example will start the XS code and will place all functions in a 
  18885. package named RPC. 
  18886.  
  18887.      MODULE = RPC
  18888.  
  18889. The PACKAGE Keyword 
  18890.  
  18891. When functions within an XS source file must be separated into packages the 
  18892. PACKAGE keyword should be used.  This keyword is used with the MODULE keyword 
  18893. and must follow immediately after it when used. 
  18894.  
  18895.      MODULE = RPC  PACKAGE = RPC
  18896.  
  18897.      [ XS code in package RPC ]
  18898.  
  18899.      MODULE = RPC  PACKAGE = RPCB
  18900.  
  18901.      [ XS code in package RPCB ]
  18902.  
  18903.      MODULE = RPC  PACKAGE = RPC
  18904.  
  18905.      [ XS code in package RPC ]
  18906.  
  18907. Although this keyword is optional and in some cases provides redundant 
  18908. information it should always be used.  This keyword will ensure that the XSUBs 
  18909. appear in the desired package. 
  18910.  
  18911. The PREFIX Keyword 
  18912.  
  18913. The PREFIX keyword designates prefixes which should be removed from the Perl 
  18914. function names.  If the C function is rpcb_gettime() and the PREFIX value is 
  18915. rpcb_ then Perl will see this function as gettime(). 
  18916.  
  18917. This keyword should follow the PACKAGE keyword when used. If PACKAGE is not 
  18918. used then PREFIX should follow the MODULE keyword. 
  18919.  
  18920.      MODULE = RPC  PREFIX = rpc_
  18921.  
  18922.      MODULE = RPC  PACKAGE = RPCB  PREFIX = rpcb_
  18923.  
  18924. The OUTPUT: Keyword 
  18925.  
  18926. The OUTPUT: keyword indicates that certain function parameters should be 
  18927. updated (new values made visible to Perl) when the XSUB terminates or that 
  18928. certain values should be returned to the calling Perl function.  For simple 
  18929. functions, such as the sin() function above, the RETVAL variable is 
  18930. automatically designated as an output value.  In more complex functions the 
  18931. xsubpp compiler will need help to determine which variables are output 
  18932. variables. 
  18933.  
  18934. This keyword will normally be used to complement the CODE:  keyword. The RETVAL 
  18935. variable is not recognized as an output variable when the CODE: keyword is 
  18936. present.  The OUTPUT:  keyword is used in this situation to tell the compiler 
  18937. that RETVAL really is an output variable. 
  18938.  
  18939. The OUTPUT: keyword can also be used to indicate that function parameters are 
  18940. output variables.  This may be necessary when a parameter has been modified 
  18941. within the function and the programmer would like the update to be seen by 
  18942. Perl. 
  18943.  
  18944.      bool_t
  18945.      rpcb_gettime(host,timep)
  18946.           char *host
  18947.           time_t &timep
  18948.           OUTPUT:
  18949.           timep
  18950.  
  18951. The OUTPUT: keyword will also allow an output parameter to be mapped to a 
  18952. matching piece of code rather than to a typemap. 
  18953.  
  18954.      bool_t
  18955.      rpcb_gettime(host,timep)
  18956.           char *host
  18957.           time_t &timep
  18958.           OUTPUT:
  18959.           timep sv_setnv(ST(1), (double)timep);
  18960.  
  18961. The CODE: Keyword 
  18962.  
  18963. This keyword is used in more complicated XSUBs which require special handling 
  18964. for the C function.  The RETVAL variable is available but will not be returned 
  18965. unless it is specified under the OUTPUT: keyword. 
  18966.  
  18967. The following XSUB is for a C function which requires special handling of its 
  18968. parameters.  The Perl usage is given first. 
  18969.  
  18970.      $status = rpcb_gettime( "localhost", $timep );
  18971.  
  18972. The XSUB follows. 
  18973.  
  18974.      bool_t
  18975.      rpcb_gettime(host,timep)
  18976.           char *host
  18977.           time_t timep
  18978.           CODE:
  18979.                RETVAL = rpcb_gettime( host, &timep );
  18980.           OUTPUT:
  18981.           timep
  18982.           RETVAL
  18983.  
  18984. The INIT: Keyword 
  18985.  
  18986. The INIT: keyword allows initialization to be inserted into the XSUB before the 
  18987. compiler generates the call to the C function.  Unlike the CODE: keyword above, 
  18988. this keyword does not affect the way the compiler handles RETVAL. 
  18989.  
  18990.     bool_t
  18991.     rpcb_gettime(host,timep)
  18992.           char *host
  18993.           time_t &timep
  18994.           INIT:
  18995.           printf("# Host is %s\n", host );
  18996.           OUTPUT:
  18997.           timep
  18998.  
  18999. The NO_INIT Keyword 
  19000.  
  19001. The NO_INIT keyword is used to indicate that a function parameter is being used 
  19002. as only an output value.  The xsubpp compiler will normally generate code to 
  19003. read the values of all function parameters from the argument stack and assign 
  19004. them to C variables upon entry to the function.  NO_INIT will tell the compiler 
  19005. that some parameters will be used for output rather than for input and that 
  19006. they will be handled before the function terminates. 
  19007.  
  19008. The following example shows a variation of the rpcb_gettime() function. This 
  19009. function uses the timep variable as only an output variable and does not care 
  19010. about its initial contents. 
  19011.  
  19012.      bool_t
  19013.      rpcb_gettime(host,timep)
  19014.           char *host
  19015.           time_t &timep = NO_INIT
  19016.           OUTPUT:
  19017.           timep
  19018.  
  19019. Initializing Function Parameters 
  19020.  
  19021. Function parameters are normally initialized with their values from the 
  19022. argument stack.  The typemaps contain the code segments which are used to 
  19023. transfer the Perl values to the C parameters.  The programmer, however, is 
  19024. allowed to override the typemaps and supply alternate initialization code. 
  19025.  
  19026. The following code demonstrates how to supply initialization code for function 
  19027. parameters.  The initialization code is eval'd by the compiler before it is 
  19028. added to the output so anything which should be interpreted literally, such as 
  19029. double quotes, must be protected with backslashes. 
  19030.  
  19031.      bool_t
  19032.      rpcb_gettime(host,timep)
  19033.           char *host = (char *)SvPV(ST(0),na);
  19034.           time_t &timep = 0;
  19035.           OUTPUT:
  19036.           timep
  19037.  
  19038. This should not be used to supply default values for parameters.  One would 
  19039. normally use this when a function parameter must be processed by another 
  19040. library function before it can be used.  Default parameters are covered in the 
  19041. next section. 
  19042.  
  19043. Default Parameter Values 
  19044.  
  19045. Default values can be specified for function parameters by placing an 
  19046. assignment statement in the parameter list.  The default value may be a number 
  19047. or a string.  Defaults should always be used on the right-most parameters only. 
  19048.  
  19049. To allow the XSUB for rpcb_gettime() to have a default host value the 
  19050. parameters to the XSUB could be rearranged.  The XSUB will then call the real 
  19051. rpcb_gettime() function with the parameters in the correct order.  Perl will 
  19052. call this XSUB with either of the following statements. 
  19053.  
  19054.      $status = rpcb_gettime( $timep, $host );
  19055.  
  19056.      $status = rpcb_gettime( $timep );
  19057.  
  19058. The XSUB will look like the code  which  follows.  A  CODE: block  is used to 
  19059. call the real rpcb_gettime() function with the parameters in the correct order 
  19060. for that function. 
  19061.  
  19062.      bool_t
  19063.      rpcb_gettime(timep,host="localhost")
  19064.           char *host
  19065.           time_t timep = NO_INIT
  19066.           CODE:
  19067.                RETVAL = rpcb_gettime( host, &timep );
  19068.           OUTPUT:
  19069.           timep
  19070.           RETVAL
  19071.  
  19072. The PREINIT: Keyword 
  19073.  
  19074. The PREINIT: keyword allows extra variables to be declared before the typemaps 
  19075. are expanded.  If a variable is declared in a CODE: block then that variable 
  19076. will follow any typemap code.  This may result in a C syntax error.  To force 
  19077. the variable to be declared before the typemap code, place it into a PREINIT: 
  19078. block.  The PREINIT: keyword may be used one or more times within an XSUB. 
  19079.  
  19080. The following examples are equivalent, but if the code is using complex 
  19081. typemaps then the first example is safer. 
  19082.  
  19083.      bool_t
  19084.      rpcb_gettime(timep)
  19085.           time_t timep = NO_INIT
  19086.           PREINIT:
  19087.           char *host = "localhost";
  19088.           CODE:
  19089.           RETVAL = rpcb_gettime( host, &timep );
  19090.           OUTPUT:
  19091.           timep
  19092.           RETVAL
  19093.  
  19094. A correct, but error-prone example. 
  19095.  
  19096.      bool_t
  19097.      rpcb_gettime(timep)
  19098.           time_t timep = NO_INIT
  19099.           CODE:
  19100.           char *host = "localhost";
  19101.           RETVAL = rpcb_gettime( host, &timep );
  19102.           OUTPUT:
  19103.           timep
  19104.           RETVAL
  19105.  
  19106. The INPUT: Keyword 
  19107.  
  19108. The XSUB's parameters are usually evaluated immediately after entering the 
  19109. XSUB.  The INPUT: keyword can be used to force those parameters to be evaluated 
  19110. a little later.  The INPUT: keyword can be used multiple times within an XSUB 
  19111. and can be used to list one or more input variables.  This keyword is used with 
  19112. the PREINIT: keyword. 
  19113.  
  19114. The following example shows how the input parameter timep can be evaluated 
  19115. late, after a PREINIT. 
  19116.  
  19117.     bool_t
  19118.     rpcb_gettime(host,timep)
  19119.           char *host
  19120.           PREINIT:
  19121.           time_t tt;
  19122.           INPUT:
  19123.           time_t timep
  19124.           CODE:
  19125.                RETVAL = rpcb_gettime( host, &tt );
  19126.                timep = tt;
  19127.           OUTPUT:
  19128.           timep
  19129.           RETVAL
  19130.  
  19131. The next example shows each input parameter evaluated late. 
  19132.  
  19133.     bool_t
  19134.     rpcb_gettime(host,timep)
  19135.           PREINIT:
  19136.           time_t tt;
  19137.           INPUT:
  19138.           char *host
  19139.           PREINIT:
  19140.           char *h;
  19141.           INPUT:
  19142.           time_t timep
  19143.           CODE:
  19144.                h = host;
  19145.                RETVAL = rpcb_gettime( h, &tt );
  19146.                timep = tt;
  19147.           OUTPUT:
  19148.           timep
  19149.           RETVAL
  19150.  
  19151. Variable-length Parameter Lists 
  19152.  
  19153. XSUBs can have variable-length parameter lists by specifying an ellipsis (...) 
  19154. in the parameter list.  This use of the ellipsis is similar to that found in 
  19155. ANSI C.  The programmer is able to determine the number of arguments passed to 
  19156. the XSUB by examining the items variable which the xsubpp compiler supplies for 
  19157. all XSUBs.  By using this mechanism one can create an XSUB which accepts a list 
  19158. of parameters of unknown length. 
  19159.  
  19160. The host parameter for the rpcb_gettime() XSUB can be optional so the ellipsis 
  19161. can be used to indicate that the XSUB will take a variable number of 
  19162. parameters.  Perl should be able to call this XSUB with either of the following 
  19163. statements. 
  19164.  
  19165.      $status = rpcb_gettime( $timep, $host );
  19166.  
  19167.      $status = rpcb_gettime( $timep );
  19168.  
  19169. The XS code, with ellipsis, follows. 
  19170.  
  19171.      bool_t
  19172.      rpcb_gettime(timep, ...)
  19173.           time_t timep = NO_INIT
  19174.           PREINIT:
  19175.           char *host = "localhost";
  19176.           CODE:
  19177.                   if( items > 1 )
  19178.                        host = (char *)SvPV(ST(1), na);
  19179.                   RETVAL = rpcb_gettime( host, &timep );
  19180.           OUTPUT:
  19181.           timep
  19182.           RETVAL
  19183.  
  19184. The PPCODE: Keyword 
  19185.  
  19186. The PPCODE: keyword is an alternate form of the CODE: keyword and is used to 
  19187. tell the xsubpp compiler that the programmer is supplying the code to control 
  19188. the argument stack for the XSUBs return values.  Occasionally one will want an 
  19189. XSUB to return a list of values rather than a single value. In these cases one 
  19190. must use PPCODE: and then explicitly push the list of values on the stack.  The 
  19191. PPCODE: and CODE:  keywords are not used together within the same XSUB. 
  19192.  
  19193. The following XSUB will call the C rpcb_gettime() function and will return its 
  19194. two output values, timep and status, to Perl as a single list. 
  19195.  
  19196.      void
  19197.      rpcb_gettime(host)
  19198.           char *host
  19199.           PREINIT:
  19200.           time_t  timep;
  19201.           bool_t  status;
  19202.           PPCODE:
  19203.           status = rpcb_gettime( host, &timep );
  19204.           EXTEND(sp, 2);
  19205.           PUSHs(sv_2mortal(newSViv(status)));
  19206.           PUSHs(sv_2mortal(newSViv(timep)));
  19207.  
  19208. Notice that the programmer must supply the C code necessary to have the real 
  19209. rpcb_gettime() function called and to have the return values properly placed on 
  19210. the argument stack. 
  19211.  
  19212. The void return type for this function tells the xsubpp compiler that the 
  19213. RETVAL variable is not needed or used and that it should not be created. In 
  19214. most scenarios the void return type should be used with the PPCODE: directive. 
  19215.  
  19216. The EXTEND() macro is used to make room on the argument stack for 2 return 
  19217. values.  The PPCODE: directive causes the xsubpp compiler to create a stack 
  19218. pointer called sp, and it is this pointer which is being used in the EXTEND() 
  19219. macro. The values are then pushed onto the stack with the PUSHs() macro. 
  19220.  
  19221. Now the rpcb_gettime() function can be used from Perl with the following 
  19222. statement. 
  19223.  
  19224.      ($status, $timep) = rpcb_gettime("localhost");
  19225.  
  19226. Returning Undef And Empty Lists 
  19227.  
  19228. Occasionally the programmer will want to simply return undef or an empty list 
  19229. if a function fails rather than a separate status value.  The rpcb_gettime() 
  19230. function offers just this situation.  If the function succeeds we would like to 
  19231. have it return the time and if it fails we would like to have undef returned. 
  19232. In the following Perl code the value of $timep will either be undef or it will 
  19233. be a valid time. 
  19234.  
  19235.      $timep = rpcb_gettime( "localhost" );
  19236.  
  19237. The following XSUB uses the void return type to disable the generation of the 
  19238. RETVAL variable and uses a CODE: block to indicate to the compiler that the 
  19239. programmer has supplied all the necessary code.  The sv_newmortal() call will 
  19240. initialize the return value to undef, making that the default return value. 
  19241.  
  19242.      void
  19243.      rpcb_gettime(host)
  19244.           char *  host
  19245.           PREINIT:
  19246.           time_t  timep;
  19247.           bool_t x;
  19248.           CODE:
  19249.           ST(0) = sv_newmortal();
  19250.           if( rpcb_gettime( host, &timep ) )
  19251.                sv_setnv( ST(0), (double)timep);
  19252.  
  19253. The next example demonstrates how one would place an explicit undef in the 
  19254. return value, should the need arise. 
  19255.  
  19256.      void
  19257.      rpcb_gettime(host)
  19258.           char *  host
  19259.           PREINIT:
  19260.           time_t  timep;
  19261.           bool_t x;
  19262.           CODE:
  19263.           ST(0) = sv_newmortal();
  19264.           if( rpcb_gettime( host, &timep ) ){
  19265.                sv_setnv( ST(0), (double)timep);
  19266.           }
  19267.           else{
  19268.                ST(0) = &sv_undef;
  19269.           }
  19270.  
  19271. To return an empty list one must use a PPCODE: block and then not push return 
  19272. values on the stack. 
  19273.  
  19274.      void
  19275.      rpcb_gettime(host)
  19276.           char *host
  19277.           PREINIT:
  19278.           time_t  timep;
  19279.           PPCODE:
  19280.           if( rpcb_gettime( host, &timep ) )
  19281.                PUSHs(sv_2mortal(newSViv(timep)));
  19282.           else{
  19283.           /* Nothing pushed on stack, so an empty */
  19284.           /* list is implicitly returned. */
  19285.           }
  19286.  
  19287. The REQUIRE: Keyword 
  19288.  
  19289. The REQUIRE: keyword is used to indicate the minimum version of the xsubpp 
  19290. compiler needed to compile the XS module.  An XS module which contains the 
  19291. following statement will only compile with xsubpp version 1.922 or greater: 
  19292.  
  19293.         REQUIRE: 1.922
  19294.  
  19295. The CLEANUP: Keyword 
  19296.  
  19297. This keyword can be used when an XSUB requires special cleanup procedures 
  19298. before it terminates.  When the CLEANUP:  keyword is used it must follow any 
  19299. CODE:, PPCODE:, or OUTPUT: blocks which are present in the XSUB.  The code 
  19300. specified for the cleanup block will be added as the last statements in the 
  19301. XSUB. 
  19302.  
  19303. The BOOT: Keyword 
  19304.  
  19305. The BOOT: keyword is used to add code to the extension's bootstrap function. 
  19306. The bootstrap function is generated by the xsubpp compiler and normally holds 
  19307. the statements necessary to register any XSUBs with Perl. With the BOOT: 
  19308. keyword the programmer can tell the compiler to add extra statements to the 
  19309. bootstrap function. 
  19310.  
  19311. This keyword may be used any time after the first MODULE keyword and should 
  19312. appear on a line by itself.  The first blank line after the keyword will 
  19313. terminate the code block. 
  19314.  
  19315.      BOOT:
  19316.      # The following message will be printed when the
  19317.      # bootstrap function executes.
  19318.      printf("Hello from the bootstrap!\n");
  19319.  
  19320. The VERSIONCHECK: Keyword 
  19321.  
  19322. The VERSIONCHECK: keyword corresponds to xsubpp's -versioncheck and 
  19323. -noversioncheck options.  This keyword overrides the commandline options. 
  19324. Version checking is enabled by default.  When version checking is enabled the 
  19325. XS module will attempt to verify that its version matches the version of the PM 
  19326. module. 
  19327.  
  19328. To enable version checking: 
  19329.  
  19330.     VERSIONCHECK: ENABLE
  19331.  
  19332. To disable version checking: 
  19333.  
  19334.     VERSIONCHECK: DISABLE
  19335.  
  19336. The PROTOTYPES: Keyword 
  19337.  
  19338. The PROTOTYPES: keyword corresponds to xsubpp's -prototypes and -noprototypes 
  19339. options.  This keyword overrides the commandline options. Prototypes are 
  19340. enabled by default.  When prototypes are enabled XSUBs will be given Perl 
  19341. prototypes.  This keyword may be used multiple times in an XS module to enable 
  19342. and disable prototypes for different parts of the module. 
  19343.  
  19344. To enable prototypes: 
  19345.  
  19346.     PROTOTYPES: ENABLE
  19347.  
  19348. To disable prototypes: 
  19349.  
  19350.     PROTOTYPES: DISABLE
  19351.  
  19352. The PROTOTYPE: Keyword 
  19353.  
  19354. This keyword is similar to the PROTOTYPES: keyword above but can be used to 
  19355. force xsubpp to use a specific prototype for the XSUB.  This keyword overrides 
  19356. all other prototype options and keywords but affects only the current XSUB. 
  19357. Consult perlsub/Prototypes for information about Perl prototypes. 
  19358.  
  19359.     bool_t
  19360.     rpcb_gettime(timep, ...)
  19361.           time_t timep = NO_INIT
  19362.           PROTOTYPE: $;$
  19363.           PREINIT:
  19364.           char *host = "localhost";
  19365.           CODE:
  19366.                   if( items > 1 )
  19367.                        host = (char *)SvPV(ST(1), na);
  19368.                   RETVAL = rpcb_gettime( host, &timep );
  19369.           OUTPUT:
  19370.           timep
  19371.           RETVAL
  19372.  
  19373. The ALIAS: Keyword 
  19374.  
  19375. The ALIAS: keyword allows an XSUB to have two more more unique Perl names and 
  19376. to know which of those names was used when it was invoked.  The Perl names may 
  19377. be fully-qualified with package names.  Each alias is given an index.  The 
  19378. compiler will setup a variable called ix which contain the index of the alias 
  19379. which was used.  When the XSUB is called with its declared name ix will be 0. 
  19380.  
  19381. The following example will create aliases FOO::gettime() and BAR::getit() for 
  19382. this function. 
  19383.  
  19384.     bool_t
  19385.     rpcb_gettime(host,timep)
  19386.           char *host
  19387.           time_t &timep
  19388.           ALIAS:
  19389.             FOO::gettime = 1
  19390.             BAR::getit = 2
  19391.           INIT:
  19392.           printf("# ix = %d\n", ix );
  19393.           OUTPUT:
  19394.           timep
  19395.  
  19396. The INCLUDE: Keyword 
  19397.  
  19398. This keyword can be used to pull other files into the XS module.  The other 
  19399. files may have XS code.  INCLUDE: can also be used to run a command to generate 
  19400. the XS code to be pulled into the module. 
  19401.  
  19402. The file Rpcb1.xsh contains our rpcb_gettime() function: 
  19403.  
  19404.     bool_t
  19405.     rpcb_gettime(host,timep)
  19406.           char *host
  19407.           time_t &timep
  19408.           OUTPUT:
  19409.           timep
  19410.  
  19411. The XS module can use INCLUDE: to pull that file into it. 
  19412.  
  19413.     INCLUDE: Rpcb1.xsh
  19414.  
  19415. If the parameters to the INCLUDE: keyword are followed by a pipe (|) then the 
  19416. compiler will interpret the parameters as a command. 
  19417.  
  19418.     INCLUDE: cat Rpcb1.xsh |
  19419.  
  19420. The CASE: Keyword 
  19421.  
  19422. The CASE: keyword allows an XSUB to have multiple distinct parts with each part 
  19423. acting as a virtual XSUB.  CASE: is greedy and if it is used then all other XS 
  19424. keywords must be contained within a CASE:.  This means nothing may precede the 
  19425. first CASE: in the XSUB and anything following the last CASE: is included in 
  19426. that case. 
  19427.  
  19428. A CASE: might switch via a parameter of the XSUB, via the ix ALIAS: variable 
  19429. (see L<"The ALIAS: Keyword">), or maybe via the items variable (see 
  19430. L<"Variable-length Parameter Lists">).  The last CASE: becomes the default case 
  19431. if it is not associated with a conditional.  The following example shows CASE 
  19432. switched via ix with a function rpcb_gettime() having an alias x_gettime(). 
  19433. When the function is called as rpcb_gettime() it's parameters are the usual 
  19434. C<(char *host, time_t *timep)>, but when the function is called as x_gettime() 
  19435. is parameters are reversed, (time_t *timep, char *host). 
  19436.  
  19437.     long
  19438.     rpcb_gettime(a,b)
  19439.       CASE: ix == 1
  19440.           ALIAS:
  19441.           x_gettime = 1
  19442.           INPUT:
  19443.           # 'a' is timep, 'b' is host
  19444.           char *b
  19445.           time_t a = NO_INIT
  19446.           CODE:
  19447.                RETVAL = rpcb_gettime( b, &a );
  19448.           OUTPUT:
  19449.           a
  19450.           RETVAL
  19451.       CASE:
  19452.           # 'a' is host, 'b' is timep
  19453.           char *a
  19454.           time_t &b = NO_INIT
  19455.           OUTPUT:
  19456.           b
  19457.           RETVAL
  19458.  
  19459. That function can be called with either of the following statements.  Note the 
  19460. different argument lists. 
  19461.  
  19462.         $status = rpcb_gettime( $host, $timep );
  19463.  
  19464.         $status = x_gettime( $timep, $host );
  19465.  
  19466. The & Unary Operator 
  19467.  
  19468. The & unary operator is used to tell the compiler that it should dereference 
  19469. the object when it calls the C function.  This is used when a CODE: block is 
  19470. not used and the object is a not a pointer type (the object is an int or long 
  19471. but not a int* or long*). 
  19472.  
  19473. The following XSUB will generate incorrect C code.  The xsubpp compiler will 
  19474. turn this into code which calls rpcb_gettime() with parameters C<(char *host, 
  19475. time_t timep)>, but the real rpcb_gettime() wants the timep parameter to be of 
  19476. type time_t* rather than time_t. 
  19477.  
  19478.     bool_t
  19479.     rpcb_gettime(host,timep)
  19480.           char *host
  19481.           time_t timep
  19482.           OUTPUT:
  19483.           timep
  19484.  
  19485. That problem is corrected by using the & operator.  The xsubpp compiler will 
  19486. now turn this into code which calls rpcb_gettime() correctly with parameters 
  19487. (char *host, time_t *timep).  It does this by carrying the & through, so the 
  19488. function call looks like rpcb_gettime(host, &timep). 
  19489.  
  19490.     bool_t
  19491.     rpcb_gettime(host,timep)
  19492.           char *host
  19493.           time_t &timep
  19494.           OUTPUT:
  19495.           timep
  19496.  
  19497. Inserting Comments and C Preprocessor Directives 
  19498.  
  19499. Comments and C preprocessor directives are allowed within CODE:, PPCODE:, 
  19500. BOOT:, and CLEANUP: blocks.  The compiler will pass the preprocessor directives 
  19501. through untouched and will remove the commented lines.  Comments can be added 
  19502. to XSUBs by placing a # at the beginning of the line.  Care should be taken to 
  19503. avoid making the comment look like a C preprocessor directive, lest it be 
  19504. interpreted as such. 
  19505.  
  19506. Using XS With C++ 
  19507.  
  19508. If a function is defined as a C++ method then it will assume its first argument 
  19509. is an object pointer.  The object pointer will be stored in a variable called 
  19510. THIS.  The object should have been created by C++ with the new() function and 
  19511. should be blessed by Perl with the sv_setref_pv() macro.  The blessing of the 
  19512. object by Perl can be handled by a typemap.  An example typemap is shown at the 
  19513. end of this section. 
  19514.  
  19515. If the method is defined as static it will call the C++ function using the 
  19516. class::method() syntax.  If the method is not static the function will be 
  19517. called using the THIS->method() syntax. 
  19518.  
  19519. The next examples will use the following C++ class. 
  19520.  
  19521.      class colors {
  19522.           public:
  19523.           colors();
  19524.           ~colors();
  19525.           int blue();
  19526.           void set_blue( int );
  19527.  
  19528.           private:
  19529.           int c_blue;
  19530.      };
  19531.  
  19532. The XSUBs for the blue() and set_blue() methods are defined with the class name 
  19533. but the parameter for the object (THIS, or "self") is implicit and is not 
  19534. listed. 
  19535.  
  19536.      int
  19537.      color::blue()
  19538.  
  19539.      void
  19540.      color::set_blue( val )
  19541.           int val
  19542.  
  19543. Both functions will expect an object as the first parameter.  The xsubpp 
  19544. compiler will call that object THIS and will use it to call the specified 
  19545. method.  So in the C++ code the blue() and set_blue() methods will be called in 
  19546. the following manner. 
  19547.  
  19548.      RETVAL = THIS->blue();
  19549.  
  19550.      THIS->set_blue( val );
  19551.  
  19552. If the function's name is DESTROY then the C++ delete function will be called 
  19553. and THIS will be given as its parameter. 
  19554.  
  19555.      void
  19556.      color::DESTROY()
  19557.  
  19558. The C++ code will call delete. 
  19559.  
  19560.      delete THIS;
  19561.  
  19562. If the function's name is new then the C++ new function will be called to 
  19563. create a dynamic C++ object.  The XSUB will expect the class name, which will 
  19564. be kept in a variable called CLASS, to be given as the first argument. 
  19565.  
  19566.      color *
  19567.      color::new()
  19568.  
  19569. The C++ code will call new. 
  19570.  
  19571.         RETVAL = new color();
  19572.  
  19573. The following is an example of a typemap that could be used for this C++ 
  19574. example. 
  19575.  
  19576.     TYPEMAP
  19577.     color *             O_OBJECT
  19578.  
  19579.     OUTPUT
  19580.     # The Perl object is blessed into 'CLASS', which should be a
  19581.     # char* having the name of the package for the blessing.
  19582.     O_OBJECT
  19583.         sv_setref_pv( $arg, CLASS, (void*)$var );
  19584.  
  19585.     INPUT
  19586.     O_OBJECT
  19587.         if( sv_isobject($arg) && (SvTYPE(SvRV($arg)) == SVt_PVMG) )
  19588.                 $var = ($type)SvIV((SV*)SvRV( $arg ));
  19589.         else{
  19590.                 warn( \"${Package}::$func_name() -- $var is not a blessed SV reference\" );
  19591.                 XSRETURN_UNDEF;
  19592.         }
  19593.  
  19594. Interface Strategy 
  19595.  
  19596. When designing an interface between Perl and a C library a straight translation 
  19597. from C to XS is often sufficient.  The interface will often be very C-like and 
  19598. occasionally nonintuitive, especially when the C function modifies one of its 
  19599. parameters.  In cases where the programmer wishes to create a more Perl-like 
  19600. interface the following strategy may help to identify the more critical parts 
  19601. of the interface. 
  19602.  
  19603. Identify the C functions which modify their parameters.  The XSUBs for these 
  19604. functions may be able to return lists to Perl, or may be candidates to return 
  19605. undef or an empty list in case of failure. 
  19606.  
  19607. Identify which values are used by only the C and XSUB functions themselves.  If 
  19608. Perl does not need to access the contents of the value then it may not be 
  19609. necessary to provide a translation for that value from C to Perl. 
  19610.  
  19611. Identify the pointers in the C function parameter lists and return values. 
  19612. Some pointers can be handled in XS with the & unary operator on the variable 
  19613. name while others will require the use of the * operator on the type name.  In 
  19614. general it is easier to work with the & operator. 
  19615.  
  19616. Identify the structures used by the C functions.  In many cases it may be 
  19617. helpful to use the T_PTROBJ typemap for these structures so they can be 
  19618. manipulated by Perl as blessed objects. 
  19619.  
  19620. Perl Objects And C Structures 
  19621.  
  19622. When dealing with C structures one should select either T_PTROBJ or T_PTRREF 
  19623. for the XS type.  Both types are designed to handle pointers to complex 
  19624. objects.  The T_PTRREF type will allow the Perl object to be unblessed while 
  19625. the T_PTROBJ type requires that the object be blessed. By using T_PTROBJ one 
  19626. can achieve a form of type-checking because the XSUB will attempt to verify 
  19627. that the Perl object is of the expected type. 
  19628.  
  19629. The following XS code shows the getnetconfigent() function which is used with 
  19630. ONC+ TIRPC.  The getnetconfigent() function will return a pointer to a C 
  19631. structure and has the C prototype shown below.  The example will demonstrate 
  19632. how the C pointer will become a Perl reference.  Perl will consider this 
  19633. reference to be a pointer to a blessed object and will attempt to call a 
  19634. destructor for the object.  A destructor will be provided in the XS source to 
  19635. free the memory used by getnetconfigent(). Destructors in XS can be created by 
  19636. specifying an XSUB function whose name ends with the word DESTROY.  XS 
  19637. destructors can be used to free memory which may have been malloc'd by another 
  19638. XSUB. 
  19639.  
  19640.      struct netconfig *getnetconfigent(const char *netid);
  19641.  
  19642. A typedef will be created for struct netconfig.  The Perl object will be 
  19643. blessed in a class matching the name of the C type, with the tag Ptr appended, 
  19644. and the name should not have embedded spaces if it will be a Perl package name. 
  19645. The destructor will be placed in a class corresponding to the class of the 
  19646. object and the PREFIX keyword will be used to trim the name to the word DESTROY 
  19647. as Perl will expect. 
  19648.  
  19649.      typedef struct netconfig Netconfig;
  19650.  
  19651.      MODULE = RPC  PACKAGE = RPC
  19652.  
  19653.      Netconfig *
  19654.      getnetconfigent(netid)
  19655.           char *netid
  19656.  
  19657.      MODULE = RPC  PACKAGE = NetconfigPtr  PREFIX = rpcb_
  19658.  
  19659.      void
  19660.      rpcb_DESTROY(netconf)
  19661.           Netconfig *netconf
  19662.           CODE:
  19663.           printf("Now in NetconfigPtr::DESTROY\n");
  19664.           free( netconf );
  19665.  
  19666. This example requires the following typemap entry.  Consult the typemap section 
  19667. for more information about adding new typemaps for an extension. 
  19668.  
  19669.      TYPEMAP
  19670.      Netconfig *  T_PTROBJ
  19671.  
  19672. This example will be used with the following Perl statements. 
  19673.  
  19674.      use RPC;
  19675.      $netconf = getnetconfigent("udp");
  19676.  
  19677. When Perl destroys the object referenced by $netconf it will send the object to 
  19678. the supplied XSUB DESTROY function.  Perl cannot determine, and does not care, 
  19679. that this object is a C struct and not a Perl object.  In this sense, there is 
  19680. no difference between the object created by the getnetconfigent() XSUB and an 
  19681. object created by a normal Perl subroutine. 
  19682.  
  19683. The Typemap 
  19684.  
  19685. The typemap is a collection of code fragments which are used by the xsubpp 
  19686. compiler to map C function parameters and values to Perl values.  The typemap 
  19687. file may consist of three sections labeled TYPEMAP, INPUT, and OUTPUT.  The 
  19688. INPUT section tells the compiler how to translate Perl values into variables of 
  19689. certain C types.  The OUTPUT section tells the compiler how to translate the 
  19690. values from certain C types into values Perl can understand.  The TYPEMAP 
  19691. section tells the compiler which of the INPUT and OUTPUT code fragments should 
  19692. be used to map a given C type to a Perl value. Each of the sections of the 
  19693. typemap must be preceded by one of the TYPEMAP, INPUT, or OUTPUT keywords. 
  19694.  
  19695. The default typemap in the ext directory of the Perl source contains many 
  19696. useful types which can be used by Perl extensions.  Some extensions define 
  19697. additional typemaps which they keep in their own directory.  These additional 
  19698. typemaps may reference INPUT and OUTPUT maps in the main typemap.  The xsubpp 
  19699. compiler will allow the extension's own typemap to override any mappings which 
  19700. are in the default typemap. 
  19701.  
  19702. Most extensions which require a custom typemap will need only the TYPEMAP 
  19703. section of the typemap file.  The custom typemap used in the getnetconfigent() 
  19704. example shown earlier demonstrates what may be the typical use of extension 
  19705. typemaps.  That typemap is used to equate a C structure with the T_PTROBJ 
  19706. typemap.  The typemap used by getnetconfigent() is shown here.  Note that the C 
  19707. type is separated from the XS type with a tab and that the C unary operator * 
  19708. is considered to be a part of the C type name. 
  19709.  
  19710.      TYPEMAP
  19711.      Netconfig *<tab>T_PTROBJ
  19712.  
  19713. EXAMPLES 
  19714.  
  19715. File RPC.xs: Interface to some ONC+ RPC bind library functions. 
  19716.  
  19717.      #include "EXTERN.h"
  19718.      #include "perl.h"
  19719.      #include "XSUB.h"
  19720.  
  19721.      #include <rpc/rpc.h>
  19722.  
  19723.      typedef struct netconfig Netconfig;
  19724.  
  19725.      MODULE = RPC  PACKAGE = RPC
  19726.  
  19727.      void
  19728.      rpcb_gettime(host="localhost")
  19729.           char *host
  19730.           PREINIT:
  19731.           time_t  timep;
  19732.           CODE:
  19733.           ST(0) = sv_newmortal();
  19734.           if( rpcb_gettime( host, &timep ) )
  19735.                sv_setnv( ST(0), (double)timep );
  19736.  
  19737.      Netconfig *
  19738.      getnetconfigent(netid="udp")
  19739.           char *netid
  19740.  
  19741.      MODULE = RPC  PACKAGE = NetconfigPtr  PREFIX = rpcb_
  19742.  
  19743.      void
  19744.      rpcb_DESTROY(netconf)
  19745.           Netconfig *netconf
  19746.           CODE:
  19747.           printf("NetconfigPtr::DESTROY\n");
  19748.           free( netconf );
  19749.  
  19750. File typemap: Custom typemap for RPC.xs. 
  19751.  
  19752.      TYPEMAP
  19753.      Netconfig *  T_PTROBJ
  19754.  
  19755. File RPC.pm: Perl module for the RPC extension. 
  19756.  
  19757.      package RPC;
  19758.  
  19759.      require Exporter;
  19760.      require DynaLoader;
  19761.      @ISA = qw(Exporter DynaLoader);
  19762.      @EXPORT = qw(rpcb_gettime getnetconfigent);
  19763.  
  19764.      bootstrap RPC;
  19765.      1;
  19766.  
  19767. File rpctest.pl: Perl test program for the RPC extension. 
  19768.  
  19769.      use RPC;
  19770.  
  19771.      $netconf = getnetconfigent();
  19772.      $a = rpcb_gettime();
  19773.      print "time = $a\n";
  19774.      print "netconf = $netconf\n";
  19775.  
  19776.      $netconf = getnetconfigent("tcp");
  19777.      $a = rpcb_gettime("poplar");
  19778.      print "time = $a\n";
  19779.      print "netconf = $netconf\n";
  19780.  
  19781. XS VERSION 
  19782.  
  19783. This document covers features supported by xsubpp 1.931. 
  19784.  
  19785. AUTHOR 
  19786.  
  19787. Dean Roehrich <roehrich@cray.com> Jan 25, 1996 
  19788.  
  19789.  
  19790. ΓòÉΓòÉΓòÉ 31. Section - perlxstut ΓòÉΓòÉΓòÉ
  19791.  
  19792. NAME 
  19793.  
  19794. perlXStut - Tutorial for XSUB's 
  19795.  
  19796. DESCRIPTION 
  19797.  
  19798. This tutorial will educate the reader on the steps involved in creating a Perl 
  19799. extension.  The reader is assumed to have access to perlguts and perlxs. 
  19800.  
  19801. This tutorial starts with very simple examples and becomes more complex, with 
  19802. each new example adding new features.  Certain concepts may not be completely 
  19803. explained until later in the tutorial in order to slowly ease the reader into 
  19804. building extensions. 
  19805.  
  19806. VERSION CAVEAT 
  19807.  
  19808. This tutorial tries hard to keep up with the latest development versions of 
  19809. Perl.  This often means that it is sometimes in advance of the latest released 
  19810. version of Perl, and that certain features described here might not work on 
  19811. earlier versions.  This section will keep track of when various features were 
  19812. added to Perl 5. 
  19813.  
  19814.      In version 5.002 before version 5.002b1h, the test.pl file was not 
  19815.       automatically created by xsubpp.  This means that you cannot say "make 
  19816.       test" to run the test script.  You will need to add the following line 
  19817.       before the "use extension" statement: 
  19818.  
  19819.                     use lib './blib';
  19820.  
  19821.      In versions 5.000 and 5.001, instead of using the above line, you will 
  19822.       need to use the following line: 
  19823.  
  19824.                     BEGIN { unshift(@INC, "./blib") }
  19825.  
  19826.      This document assumes that the executable named "perl" is Perl version 5. 
  19827.       Some systems may have installed Perl version 5 as "perl5". 
  19828.  
  19829.  DYNAMIC VERSUS STATIC 
  19830.  
  19831.  It is commonly thought that if a system does not have the capability to 
  19832.  dynamically load a library, you cannot build XSUB's.  This is incorrect. You 
  19833.  can build them, but you must link the XSUB's subroutines with the rest of 
  19834.  Perl, creating a new executable.  This situation is similar to Perl 4. 
  19835.  
  19836.  This tutorial can still be used on such a system.  The XSUB build mechanism 
  19837.  will check the system and build a dynamically-loadable library if possible, or 
  19838.  else a static library and then, optionally, a new statically-linked executable 
  19839.  with that static library linked in. 
  19840.  
  19841.  Should you wish to build a statically-linked executable on a system which can 
  19842.  dynamically load libraries, you may, in all the following examples, where the 
  19843.  command "make" with no arguments is executed, run the command "make perl" 
  19844.  instead. 
  19845.  
  19846.  If you have generated such a statically-linked executable by choice, then 
  19847.  instead of saying "make test", you should say "make test_static".  On systems 
  19848.  that cannot build dynamically-loadable libraries at all, simply saying "make 
  19849.  test" is sufficient. 
  19850.  
  19851.  EXAMPLE 1 
  19852.  
  19853.  Our first extension will be very simple.  When we call the routine in the 
  19854.  extension, it will print out a well-known message and return. 
  19855.  
  19856.  Run "h2xs -A -n mytest".  This creates a directory named mytest, possibly 
  19857.  under ext/ if that directory exists in the current working directory.  Several 
  19858.  files will be created in the mytest dir, including MANIFEST, Makefile.PL, 
  19859.  mytest.pm, mytest.xs, test.pl, and Changes. 
  19860.  
  19861.  The MANIFEST file contains the names of all the files created. 
  19862.  
  19863.  The file Makefile.PL should look something like this: 
  19864.  
  19865.           use ExtUtils::MakeMaker;
  19866.           # See lib/ExtUtils/MakeMaker.pm for details of how to influence
  19867.           # the contents of the Makefile that is written.
  19868.           WriteMakefile(
  19869.               'NAME'      => 'mytest',
  19870.               'VERSION_FROM' => 'mytest.pm', # finds $VERSION
  19871.               'LIBS'      => [''],   # e.g., '-lm'
  19872.               'DEFINE'    => '',     # e.g., '-DHAVE_SOMETHING'
  19873.               'INC'       => '',     # e.g., '-I/usr/include/other'
  19874.           );
  19875.  
  19876.  The file mytest.pm should start with something like this: 
  19877.  
  19878.           package mytest;
  19879.  
  19880.           require Exporter;
  19881.           require DynaLoader;
  19882.  
  19883.           @ISA = qw(Exporter DynaLoader);
  19884.           # Items to export into callers namespace by default. Note: do not export
  19885.           # names by default without a very good reason. Use EXPORT_OK instead.
  19886.           # Do not simply export all your public functions/methods/constants.
  19887.           @EXPORT = qw(
  19888.  
  19889.           );
  19890.           $VERSION = '0.01';
  19891.  
  19892.           bootstrap mytest $VERSION;
  19893.  
  19894.           # Preloaded methods go here.
  19895.  
  19896.           # Autoload methods go after __END__, and are processed by the autosplit program.
  19897.  
  19898.           1;
  19899.           __END__
  19900.           # Below is the stub of documentation for your module. You better edit it!
  19901.  
  19902.  And the mytest.xs file should look something like this: 
  19903.  
  19904.           #ifdef __cplusplus
  19905.           extern "C" {
  19906.           #endif
  19907.           #include "EXTERN.h"
  19908.           #include "perl.h"
  19909.           #include "XSUB.h"
  19910.           #ifdef __cplusplus
  19911.           }
  19912.           #endif
  19913.  
  19914.           MODULE = mytest         PACKAGE = mytest
  19915.  
  19916.  Let's edit the .xs file by adding this to the end of the file: 
  19917.  
  19918.           void
  19919.           hello()
  19920.                   CODE:
  19921.                   printf("Hello, world!\n");
  19922.  
  19923.  Now we'll run "perl Makefile.PL".  This will create a real Makefile, which 
  19924.  make needs.  It's output looks something like: 
  19925.  
  19926.           % perl Makefile.PL
  19927.           Checking if your kit is complete...
  19928.           Looks good
  19929.           Writing Makefile for mytest
  19930.           %
  19931.  
  19932.  Now, running make will produce output that looks something like this (some 
  19933.  long lines shortened for clarity): 
  19934.  
  19935.           % make
  19936.           umask 0 && cp mytest.pm ./blib/mytest.pm
  19937.           perl xsubpp -typemap typemap mytest.xs >mytest.tc && mv mytest.tc mytest.c
  19938.           cc -c mytest.c
  19939.           Running Mkbootstrap for mytest ()
  19940.           chmod 644 mytest.bs
  19941.           LD_RUN_PATH="" ld -o ./blib/PA-RISC1.1/auto/mytest/mytest.sl -b mytest.o
  19942.           chmod 755 ./blib/PA-RISC1.1/auto/mytest/mytest.sl
  19943.           cp mytest.bs ./blib/PA-RISC1.1/auto/mytest/mytest.bs
  19944.           chmod 644 ./blib/PA-RISC1.1/auto/mytest/mytest.bs
  19945.  
  19946.  Now, although there is already a test.pl template ready for us, for this 
  19947.  example only, we'll create a special test script.  Create a file called hello 
  19948.  that looks like this: 
  19949.  
  19950.  Now we'll create a test script, test1.pl in the mytest directory.  It should 
  19951.  look like this: 
  19952.  
  19953.           #! /opt/perl5/bin/perl
  19954.  
  19955.           use lib './blib';
  19956.  
  19957.           use mytest;
  19958.  
  19959.           mytest::hello();
  19960.  
  19961.  Now we run the script and we should see the following output: 
  19962.  
  19963.           % perl hello
  19964.           Hello, world!
  19965.           %
  19966.  
  19967.  EXAMPLE 2 
  19968.  
  19969.  Now let's add to our extension a subroutine that will take a single argument 
  19970.  and return 0 if the argument is even, 1 if the argument is odd. 
  19971.  
  19972.  Add the following to the end of mytest.xs: 
  19973.  
  19974.           int
  19975.           is_even(input)
  19976.                   int     input
  19977.                   CODE:
  19978.                   RETVAL = (input % 2 == 0);
  19979.                   OUTPUT:
  19980.                   RETVAL
  19981.  
  19982.  There must be some white space at the start of the "int input" line, and there 
  19983.  must not be a semi-colon at the end of the line (as you'd expect in a C 
  19984.  program). 
  19985.  
  19986.  Any white space may be between the "int" and "input".  It is also okay for the 
  19987.  four lines starting at the "CODE:" line to not be indented.  However, for 
  19988.  readability purposes, it is suggested that you indent them 8 spaces (or one 
  19989.  normal tab stop). 
  19990.  
  19991.  Now re-run make to rebuild our new shared library. 
  19992.  
  19993.  Now perform the same steps as before, generating a Makefile from the 
  19994.  Makefile.PL file, and running make. 
  19995.  
  19996.  In order to test that our extension works, we now need to look at the file 
  19997.  test.pl.  This file is set up to imitate the same kind of testing structure 
  19998.  that Perl itself has.  Within the test script, you perform a number of tests 
  19999.  to confirm the behavior of the extension, printing "ok" when the test is 
  20000.  correct, "not ok" when it is not. 
  20001.  
  20002.  Let's change the print statement in the BEGIN block to print "1..4" and add 
  20003.  the following code to the end of the file: 
  20004.  
  20005.           print &mytest::is_even(0) == 1 ? "ok 2" : "not ok 2", "\n";
  20006.           print &mytest::is_even(1) == 0 ? "ok 3" : "not ok 3", "\n";
  20007.           print &mytest::is_even(2) == 1 ? "ok 4" : "not ok 4", "\n";
  20008.  
  20009.  We will be calling the test script through the command "make test".  You 
  20010.  should see output that looks something like this: 
  20011.  
  20012.           % make test
  20013.           PERL_DL_NONLAZY=1 /opt/perl5.002b2/bin/perl (lots of -I arguments) test.pl
  20014.           1..4
  20015.           ok 1
  20016.           ok 2
  20017.           ok 3
  20018.           ok 4
  20019.           %
  20020.  
  20021.  WHAT HAS GONE ON? 
  20022.  
  20023.  The program h2xs is the starting point for creating extensions.  In later 
  20024.  examples we'll see how we can use h2xs to read header files and generate 
  20025.  templates to connect to C routines. 
  20026.  
  20027.  h2xs creates a number of files in the extension directory.  The file 
  20028.  Makefile.PL is a perl script which will generate a true Makefile to build the 
  20029.  extension.  We'll take a closer look at it later. 
  20030.  
  20031.  The files <extension>.pm and <extension>.xs contain the meat of the extension. 
  20032.  The .xs file holds the C routines that make up the extension.  The .pm file 
  20033.  contains routines that tell Perl how to load your extension. 
  20034.  
  20035.  Generating and invoking the Makefile created a directory blib (which stands 
  20036.  for "build library") in the current working directory.  This directory will 
  20037.  contain the shared library that we will build.  Once we have tested it, we can 
  20038.  install it into its final location. 
  20039.  
  20040.  Invoking the test script via "make test" did something very important.  It 
  20041.  invoked perl with all those -I arguments so that it could find the various 
  20042.  files that are part of the extension. 
  20043.  
  20044.  It is very important that while you are still testing extensions that you use 
  20045.  "make test".  If you try to run the test script all by itself, you will get a 
  20046.  fatal error. 
  20047.  
  20048.  Another reason it is important to use "make test" to run your test script is 
  20049.  that if you are testing an upgrade to an already-existing version, using "make 
  20050.  test" insures that you use your new extension, not the already-existing 
  20051.  version. 
  20052.  
  20053.  Finally, our test scripts do two important things.  First of all, they place 
  20054.  the directory "blib" at the head of the @INC array.  Placing this inside a 
  20055.  BEGIN block assures us that Perl will look in the blib directory hierarchy 
  20056.  before looking in the system directories.  This could be important if you are 
  20057.  upgrading an already-existing extension and do not want to disturb the system 
  20058.  version until you are ready to install it. 
  20059.  
  20060.  When Perl sees a use extension;, it searches for a file with the same name as 
  20061.  the use'd extension that has a .pm suffix.  If that file cannot be found, Perl 
  20062.  dies with a fatal error.  The default search path is contained in the @INC 
  20063.  array. 
  20064.  
  20065.  In our case, mytest.pm tells perl that it will need the Exporter and Dynamic 
  20066.  Loader extensions.  It then sets the @ISA and @EXPORT arrays and the $VERSION 
  20067.  scalar; finally it tells perl to bootstrap the module.  Perl will call its 
  20068.  dynamic loader routine (if there is one) and load the shared library. 
  20069.  
  20070.  The two arrays that are set in the .pm file are very important.  The @ISA 
  20071.  array contains a list of other packages in which to search for methods (or 
  20072.  subroutines) that do not exist in the current package.  The @EXPORT array 
  20073.  tells Perl which of the extension's routines should be placed into the calling 
  20074.  package's namespace. 
  20075.  
  20076.  It's important to select what to export carefully.  Do NOT export method names 
  20077.  and do NOT export anything else by default without a good reason. 
  20078.  
  20079.  As a general rule, if the module is trying to be object-oriented then don't 
  20080.  export anything.  If it's just a collection of functions then you can export 
  20081.  any of the functions via another array, called @EXPORT_OK. 
  20082.  
  20083.  See perlmod for more information. 
  20084.  
  20085.  The $VERSION variable is used to ensure that the .pm file and the shared 
  20086.  library are "in sync" with each other.  Any time you make changes to the 
  20087.  
  20088.  EXAMPLE 3 
  20089.  
  20090.  Our third extension will take one argument as its input, round off that value, 
  20091.  and set the argument to the rounded value. 
  20092.  
  20093.  Add the following to the end of mytest.xs: 
  20094.  
  20095.           void
  20096.           round(arg)
  20097.                   double  arg
  20098.                   CODE:
  20099.                   if (arg > 0.0) {
  20100.                           arg = floor(arg + 0.5);
  20101.                   } else if (arg < 0.0) {
  20102.                           arg = ceil(arg - 0.5);
  20103.                   } else {
  20104.                           arg = 0.0;
  20105.                   }
  20106.                   OUTPUT:
  20107.                   arg
  20108.  
  20109.  Edit the Makefile.PL file so that the corresponding line looks like this: 
  20110.  
  20111.           'LIBS'      => ['-lm'],   # e.g., '-lm'
  20112.  
  20113.  Generate the Makefile and run make.  Change the BEGIN block to print out 
  20114.  "1..9" and add the following to test.pl: 
  20115.  
  20116.           $i = -1.5; &mytest::round($i); print $i == -2.0 ? "ok 5" : "not ok 5", "\n";
  20117.           $i = -1.1; &mytest::round($i); print $i == -1.0 ? "ok 6" : "not ok 6", "\n";
  20118.           $i = 0.0; &mytest::round($i); print $i == 0.0 ? "ok 7" : "not ok 7", "\n";
  20119.           $i = 0.5; &mytest::round($i); print $i == 1.0 ? "ok 8" : "not ok 8", "\n";
  20120.           $i = 1.2; &mytest::round($i); print $i == 1.0 ? "ok 9" : "not ok 9", "\n";
  20121.  
  20122.  Running "make test" should now print out that all nine tests are okay. 
  20123.  
  20124.  You might be wondering if you can round a constant.  To see what happens, add 
  20125.  the following line to test.pl temporarily: 
  20126.  
  20127.           &mytest::round(3);
  20128.  
  20129.  Run "make test" and notice that Perl dies with a fatal error.  Perl won't let 
  20130.  you change the value of constants! 
  20131.  
  20132.  WHAT'S NEW HERE? 
  20133.  
  20134.  Two things are new here.  First, we've made some changes to Makefile.PL. In 
  20135.  this case, we've specified an extra library to link in, in this case the math 
  20136.  library, libm.  We'll talk later about how to write XSUBs that can call every 
  20137.  routine in a library. 
  20138.  
  20139.  Second, the value of the function is being passed back not as the function's 
  20140.  return value, but through the same variable that was passed into the function. 
  20141.  
  20142.  INPUT AND OUTPUT PARAMETERS 
  20143.  
  20144.  You specify the parameters that will be passed into the XSUB just after you 
  20145.  declare the function return value and name.  The list of parameters looks very 
  20146.  C-like, but the lines must be indented by a tab stop, and each line may not 
  20147.  have an ending semi-colon. 
  20148.  
  20149.  The list of output parameters occurs after the OUTPUT: directive.  The use of 
  20150.  RETVAL tells Perl that you wish to send this value back as the return value of 
  20151.  the XSUB function.  In Example 3, the value we wanted returned was contained 
  20152.  in the same variable we passed in, so we listed it (and not RETVAL) in the 
  20153.  OUTPUT: section. 
  20154.  
  20155.  THE XSUBPP COMPILER 
  20156.  
  20157.  The compiler xsubpp takes the XS code in the .xs file and converts it into C 
  20158.  code, placing it in a file whose suffix is .c.  The C code created makes heavy 
  20159.  use of the C functions within Perl. 
  20160.  
  20161.  THE TYPEMAP FILE 
  20162.  
  20163.  The xsubpp compiler uses rules to convert from Perl's data types (scalar, 
  20164.  array, etc.) to C's data types (int, char *, etc.).  These rules are stored in 
  20165.  the typemap file ($PERLLIB/ExtUtils/typemap).  This file is split into three 
  20166.  parts. 
  20167.  
  20168.  The first part attempts to map various C data types to a coded flag, which has 
  20169.  some correspondence with the various Perl types.  The second part contains C 
  20170.  code which xsubpp uses for input parameters.  The third part contains C code 
  20171.  which xsubpp uses for output parameters.  We'll talk more about the C code 
  20172.  later. 
  20173.  
  20174.  Let's now take a look at a portion of the .c file created for our extension. 
  20175.  
  20176.           XS(XS_mytest_round)
  20177.           {
  20178.               dXSARGS;
  20179.               if (items != 1)
  20180.                   croak("Usage: mytest::round(arg)");
  20181.               {
  20182.                   double  arg = (double)SvNV(ST(0));      /* XXXXX */
  20183.                   if (arg > 0.0) {
  20184.                           arg = floor(arg + 0.5);
  20185.                   } else if (arg < 0.0) {
  20186.                           arg = ceil(arg - 0.5);
  20187.                   } else {
  20188.                           arg = 0.0;
  20189.                   }
  20190.                   sv_setnv(ST(0), (double)arg);   /* XXXXX */
  20191.               }
  20192.               XSRETURN(1);
  20193.           }
  20194.  
  20195.  Notice the two lines marked with "XXXXX".  If you check the first section of 
  20196.  the typemap file, you'll see that doubles are of type T_DOUBLE.  In the INPUT 
  20197.  section, an argument that is T_DOUBLE is assigned to the variable arg by 
  20198.  calling the routine SvNV on something, then casting it to double, then 
  20199.  assigned to the variable arg.  Similarly, in the OUTPUT section, once arg has 
  20200.  its final value, it is passed to the sv_setnv function to be passed back to 
  20201.  the calling subroutine.  These two functions are explained in perlguts; we'll 
  20202.  talk more later about what that "ST(0)" means in the section on the argument 
  20203.  stack. 
  20204.  
  20205.  WARNING 
  20206.  
  20207.  In general, it's not a good idea to write extensions that modify their input 
  20208.  parameters, as in Example 3.  However, in order to better accomodate calling 
  20209.  pre-existing C routines, which often do modify their input parameters, this 
  20210.  behavior is tolerated.  The next example will show how to do this. 
  20211.  
  20212.  [Examples 4 and 5 have not been re-worked yet and are not included.] 
  20213.  
  20214.  SPECIFYING ARGUMENTS TO XSUBPP 
  20215.  
  20216.  After completing Example 5, we now have an easy way to simulate some real-life 
  20217.  libraries whose interfaces may not be the cleanest in the world. We shall now 
  20218.  continue with a discussion of the arguments passed to the xsubpp compiler. 
  20219.  
  20220.  When you specify arguments in the .xs file, you are really passing three 
  20221.  pieces of information for each one listed.  The first piece is the order of 
  20222.  that argument relative to the others (first, second, etc).  The second is the 
  20223.  type of argument, and consists of the type declaration of the argument (e.g., 
  20224.  int, char*, etc).  The third piece is the exact way in which the argument 
  20225.  should be used in the call to the library function from this XSUB.  This would 
  20226.  mean whether or not to place a "&" before the argument or not, meaning the 
  20227.  argument expects to be passed the address of the specified data type. 
  20228.  
  20229.  There is a difference between the two arguments in this hypothetical function: 
  20230.  
  20231.           int
  20232.           foo(a,b)
  20233.                   char    &a
  20234.                   char *  b
  20235.  
  20236.  The first argument to this function would be treated as a char and assigned to 
  20237.  the variable a, and its address would be passed into the function foo. The 
  20238.  second argument would be treated as a string pointer and assigned to the 
  20239.  variable b.  The value of b would be passed into the function foo.  The actual 
  20240.  call to the function foo that xsubpp generates would look like this: 
  20241.  
  20242.           foo(&a, b);
  20243.  
  20244.  In other words, whatever is in the last column (or the variable name) is what 
  20245.  is passed into the C function. 
  20246.  
  20247.  You should take great pains to try to pass the function the type of variable 
  20248.  it wants, when possible.  It will save you a lot of trouble in the long run. 
  20249.  
  20250.  THE ARGUMENT STACK 
  20251.  
  20252.  If we look at any of the C code generated by any of the examples except 
  20253.  example 1, you will notice a number of references to ST(n), where n is usually 
  20254.  0.  The "ST" is actually a macro that points to the n'th argument on the 
  20255.  argument stack.  ST(0) is thus the first argument passed to the XSUB, ST(1) is 
  20256.  the second argument, and so on. 
  20257.  
  20258.  When you list the arguments to the XSUB in the .xs file, that tell xsubpp 
  20259.  which argument corresponds to which of the argument stack (i.e., the first one 
  20260.  listed is the first argument, and so on).  You invite disaster if you do not 
  20261.  list them in the same order as the function expects them. 
  20262.  
  20263.  EXTENDING YOUR EXTENSION 
  20264.  
  20265.  Sometimes you might want to provide some extra methods or subroutines to 
  20266.  assist in making the interface between Perl and your extension simpler or 
  20267.  easier to understand.  These routines should live in the .pm file. Whether 
  20268.  they are automatically loaded when the extension itself is loaded or only 
  20269.  loaded when called depends on where in the .pm file the subroutine definition 
  20270.  is placed. 
  20271.  
  20272.  DOCUMENTING YOUR EXTENSION 
  20273.  
  20274.  There is absolutely no excuse for not documenting your extension. 
  20275.  Documentation belongs in the .pm file.  This file will be fed to pod2man, and 
  20276.  the documentation embedded within it converted to man page format, then placed 
  20277.  in the blib directory.  It will be copied to Perl's man page directory when 
  20278.  the extension is installed. 
  20279.  
  20280.  You may intersperse documentation and Perl code within the .pm file. In fact, 
  20281.  if you want to use method autoloading, you must do this, as the comment inside 
  20282.  the .pm file explains. 
  20283.  
  20284.  See perlpod for more information about the pod format. 
  20285.  
  20286.  INSTALLING YOUR EXTENSION 
  20287.  
  20288.  Once your extension is complete and passes all its tests, installing it is 
  20289.  quite simple: you simply run "make install".  You will either need to have 
  20290.  write permission into the directories where Perl is installed, or ask your 
  20291.  system administrator to run the make for you. 
  20292.  
  20293.  SEE ALSO 
  20294.  
  20295.  For more information, consult perlguts, perlxs, perlmod, and perlpod. 
  20296.  
  20297.  Author 
  20298.  
  20299.  Jeff Okamoto <okamoto@corp.hp.com> 
  20300.  
  20301.  Reviewed and assisted by Dean Roehrich, Ilya Zakharevich, Andreas Koenig, and 
  20302.  Tim Bunce. 
  20303.  
  20304.  Last Changed 
  20305.  
  20306.  1996/1/19 
  20307.  
  20308.  
  20309. ΓòÉΓòÉΓòÉ 32. Section - perlguts ΓòÉΓòÉΓòÉ
  20310.  
  20311. NAME 
  20312.  
  20313. perlguts - Perl's Internal Functions 
  20314.  
  20315. DESCRIPTION 
  20316.  
  20317. This document attempts to describe some of the internal functions of the Perl 
  20318. executable.  It is far from complete and probably contains many errors. Please 
  20319. refer any questions or comments to the author below. 
  20320.  
  20321. Datatypes 
  20322.  
  20323. Perl has three typedefs that handle Perl's three main data types: 
  20324.  
  20325.     SV  Scalar Value
  20326.     AV  Array Value
  20327.     HV  Hash Value
  20328.  
  20329. Each typedef has specific routines that manipulate the various data types. 
  20330.  
  20331. What is an "IV"? 
  20332.  
  20333. Perl uses a special typedef IV which is large enough to hold either an integer 
  20334. or a pointer. 
  20335.  
  20336. Perl also uses two special typedefs, I32 and I16, which will always be at least 
  20337. 32-bits and 16-bits long, respectively. 
  20338.  
  20339. Working with SV's 
  20340.  
  20341. An SV can be created and loaded with one command.  There are four types of 
  20342. values that can be loaded: an integer value (IV), a double (NV), a string, 
  20343. (PV), and another scalar (SV). 
  20344.  
  20345. The four routines are: 
  20346.  
  20347.     SV*  newSViv(IV);
  20348.     SV*  newSVnv(double);
  20349.     SV*  newSVpv(char*, int);
  20350.     SV*  newSVsv(SV*);
  20351.  
  20352. To change the value of an *already-existing* SV, there are five routines: 
  20353.  
  20354.     void  sv_setiv(SV*, IV);
  20355.     void  sv_setnv(SV*, double);
  20356.     void  sv_setpvn(SV*, char*, int)
  20357.     void  sv_setpv(SV*, char*);
  20358.     void  sv_setsv(SV*, SV*);
  20359.  
  20360. Notice that you can choose to specify the length of the string to be assigned 
  20361. by using sv_setpvn or newSVpv, or you may allow Perl to calculate the length by 
  20362. using sv_setpv or by specifying 0 as the second argument to newSVpv.  Be 
  20363. warned, though, that Perl will determine the string's length by using strlen, 
  20364. which depends on the string terminating with a NUL character. 
  20365.  
  20366. To access the actual value that an SV points to, you can use the macros: 
  20367.  
  20368.     SvIV(SV*)
  20369.     SvNV(SV*)
  20370.     SvPV(SV*, STRLEN len)
  20371.  
  20372. which will automatically coerce the actual scalar type into an IV, double, or 
  20373. string. 
  20374.  
  20375. In the SvPV macro, the length of the string returned is placed into the 
  20376. variable len (this is a macro, so you do not use &len).  If you do not care 
  20377. what the length of the data is, use the global variable na.  Remember, however, 
  20378. that Perl allows arbitrary strings of data that may both contain NUL's and not 
  20379. be terminated by a NUL. 
  20380.  
  20381. If you simply want to know if the scalar value is TRUE, you can use: 
  20382.  
  20383.     SvTRUE(SV*)
  20384.  
  20385. Although Perl will automatically grow strings for you, if you need to force 
  20386. Perl to allocate more memory for your SV, you can use the macro 
  20387.  
  20388.     SvGROW(SV*, STRLEN newlen)
  20389.  
  20390. which will determine if more memory needs to be allocated.  If so, it will call 
  20391. the function sv_grow.  Note that SvGROW can only increase, not decrease, the 
  20392. allocated memory of an SV. 
  20393.  
  20394. If you have an SV and want to know what kind of data Perl thinks is stored in 
  20395. it, you can use the following macros to check the type of SV you have. 
  20396.  
  20397.     SvIOK(SV*)
  20398.     SvNOK(SV*)
  20399.     SvPOK(SV*)
  20400.  
  20401. You can get and set the current length of the string stored in an SV with the 
  20402. following macros: 
  20403.  
  20404.     SvCUR(SV*)
  20405.     SvCUR_set(SV*, I32 val)
  20406.  
  20407. You can also get a pointer to the end of the string stored in the SV with the 
  20408. macro: 
  20409.  
  20410.     SvEND(SV*)
  20411.  
  20412. But note that these last three macros are valid only if SvPOK() is true. 
  20413.  
  20414. If you want to append something to the end of string stored in an SV*, you can 
  20415. use the following functions: 
  20416.  
  20417.     void  sv_catpv(SV*, char*);
  20418.     void  sv_catpvn(SV*, char*, int);
  20419.     void  sv_catsv(SV*, SV*);
  20420.  
  20421. The first function calculates the length of the string to be appended by using 
  20422. strlen.  In the second, you specify the length of the string yourself.  The 
  20423. third function extends the string stored in the first SV with the string stored 
  20424. in the second SV.  It also forces the second SV to be interpreted as a string. 
  20425.  
  20426. If you know the name of a scalar variable, you can get a pointer to its SV by 
  20427. using the following: 
  20428.  
  20429.     SV*  perl_get_sv("varname", FALSE);
  20430.  
  20431. This returns NULL if the variable does not exist. 
  20432.  
  20433. If you want to know if this variable (or any other SV) is actually defined, you 
  20434. can call: 
  20435.  
  20436.     SvOK(SV*)
  20437.  
  20438. The scalar undef value is stored in an SV instance called sv_undef.  Its 
  20439. address can be used whenever an SV* is needed. 
  20440.  
  20441. There are also the two values sv_yes and sv_no, which contain Boolean TRUE and 
  20442. FALSE values, respectively.  Like sv_undef, their addresses can be used 
  20443. whenever an SV* is needed. 
  20444.  
  20445. Do not be fooled into thinking that (SV *) 0 is the same as &sv_undef. Take 
  20446. this code: 
  20447.  
  20448.     SV* sv = (SV*) 0;
  20449.     if (I-am-to-return-a-real-value) {
  20450.             sv = sv_2mortal(newSViv(42));
  20451.     }
  20452.     sv_setsv(ST(0), sv);
  20453.  
  20454. This code tries to return a new SV (which contains the value 42) if it should 
  20455. return a real value, or undef otherwise.  Instead it has returned a null 
  20456. pointer which, somewhere down the line, will cause a segmentation violation, or 
  20457. just weird results.  Change the zero to &sv_undef in the first line and all 
  20458. will be well. 
  20459.  
  20460. To free an SV that you've created, call SvREFCNT_dec(SV*).  Normally this call 
  20461. is not necessary.  See the section on MORTALITY. 
  20462.  
  20463. What's Really Stored in an SV? 
  20464.  
  20465. Recall that the usual method of determining the type of scalar you have is to 
  20466. use Sv*OK macros.  Since a scalar can be both a number and a string, usually 
  20467. these macros will always return TRUE and calling the Sv*V macros will do the 
  20468. appropriate conversion of string to integer/double or integer/double to string. 
  20469.  
  20470. If you really need to know if you have an integer, double, or string pointer in 
  20471. an SV, you can use the following three macros instead: 
  20472.  
  20473.     SvIOKp(SV*)
  20474.     SvNOKp(SV*)
  20475.     SvPOKp(SV*)
  20476.  
  20477. These will tell you if you truly have an integer, double, or string pointer 
  20478. stored in your SV.  The "p" stands for private. 
  20479.  
  20480. In general, though, it's best to just use the Sv*V macros. 
  20481.  
  20482. Working with AV's 
  20483.  
  20484. There are two ways to create and load an AV.  The first method just creates an 
  20485. empty AV: 
  20486.  
  20487.     AV*  newAV();
  20488.  
  20489. The second method both creates the AV and initially populates it with SV's: 
  20490.  
  20491.     AV*  av_make(I32 num, SV **ptr);
  20492.  
  20493. The second argument points to an array containing num SV*'s.  Once the AV has 
  20494. been created, the SV's can be destroyed, if so desired. 
  20495.  
  20496. Once the AV has been created, the following operations are possible on AV's: 
  20497.  
  20498.     void  av_push(AV*, SV*);
  20499.     SV*   av_pop(AV*);
  20500.     SV*   av_shift(AV*);
  20501.     void  av_unshift(AV*, I32 num);
  20502.  
  20503. These should be familiar operations, with the exception of av_unshift. This 
  20504. routine adds num elements at the front of the array with the undef value.  You 
  20505. must then use av_store (described below) to assign values to these new 
  20506. elements. 
  20507.  
  20508. Here are some other functions: 
  20509.  
  20510.     I32   av_len(AV*); /* Returns highest index value in array */
  20511.     SV**  av_fetch(AV*, I32 key, I32 lval);
  20512.             /* Fetches value at key offset, but it stores an undef value
  20513.                at the offset if lval is non-zero */
  20514.     SV**  av_store(AV*, I32 key, SV* val);
  20515.             /* Stores val at offset key */
  20516.  
  20517. Take note that av_fetch and av_store return SV**'s, not SV*'s. 
  20518.  
  20519.     void  av_clear(AV*);
  20520.             /* Clear out all elements, but leave the array */
  20521.     void  av_undef(AV*);
  20522.             /* Undefines the array, removing all elements */
  20523.     void  av_extend(AV*, I32 key);
  20524.             /* Extend the array to a total of key elements */
  20525.  
  20526. If you know the name of an array variable, you can get a pointer to its AV by 
  20527. using the following: 
  20528.  
  20529.     AV*  perl_get_av("varname", FALSE);
  20530.  
  20531. This returns NULL if the variable does not exist. 
  20532.  
  20533. Working with HV's 
  20534.  
  20535. To create an HV, you use the following routine: 
  20536.  
  20537.     HV*  newHV();
  20538.  
  20539. Once the HV has been created, the following operations are possible on HV's: 
  20540.  
  20541.     SV**  hv_store(HV*, char* key, U32 klen, SV* val, U32 hash);
  20542.     SV**  hv_fetch(HV*, char* key, U32 klen, I32 lval);
  20543.  
  20544. The klen parameter is the length of the key being passed in.  The val argument 
  20545. contains the SV pointer to the scalar being stored, and hash is the 
  20546. pre-computed hash value (zero if you want hv_store to calculate it for you). 
  20547. The lval parameter indicates whether this fetch is actually a part of a store 
  20548. operation. 
  20549.  
  20550. Remember that hv_store and hv_fetch return SV**'s and not just SV*.  In order 
  20551. to access the scalar value, you must first dereference the return value. 
  20552. However, you should check to make sure that the return value is not NULL before 
  20553. dereferencing it. 
  20554.  
  20555. These two functions check if a hash table entry exists, and deletes it. 
  20556.  
  20557.     bool  hv_exists(HV*, char* key, U32 klen);
  20558.     SV*   hv_delete(HV*, char* key, U32 klen, I32 flags);
  20559.  
  20560. And more miscellaneous functions: 
  20561.  
  20562.     void   hv_clear(HV*);
  20563.             /* Clears all entries in hash table */
  20564.     void   hv_undef(HV*);
  20565.             /* Undefines the hash table */
  20566.  
  20567. Perl keeps the actual data in linked list of structures with a typedef of HE. 
  20568. These contain the actual key and value pointers (plus extra administrative 
  20569. overhead).  The key is a string pointer; the value is an SV*.  However, once 
  20570. you have an HE*, to get the actual key and value, use the routines specified 
  20571. below. 
  20572.  
  20573.     I32    hv_iterinit(HV*);
  20574.             /* Prepares starting point to traverse hash table */
  20575.     HE*    hv_iternext(HV*);
  20576.             /* Get the next entry, and return a pointer to a
  20577.                structure that has both the key and value */
  20578.     char*  hv_iterkey(HE* entry, I32* retlen);
  20579.             /* Get the key from an HE structure and also return
  20580.                the length of the key string */
  20581.     SV*    hv_iterval(HV*, HE* entry);
  20582.             /* Return a SV pointer to the value of the HE
  20583.                structure */
  20584.     SV*    hv_iternextsv(HV*, char** key, I32* retlen);
  20585.             /* This convenience routine combines hv_iternext,
  20586.                hv_iterkey, and hv_iterval.  The key and retlen
  20587.                arguments are return values for the key and its
  20588.                length.  The value is returned in the SV* argument */
  20589.  
  20590. If you know the name of a hash variable, you can get a pointer to its HV by 
  20591. using the following: 
  20592.  
  20593.     HV*  perl_get_hv("varname", FALSE);
  20594.  
  20595. This returns NULL if the variable does not exist. 
  20596.  
  20597. The hash algorithm, for those who are interested, is: 
  20598.  
  20599.     i = klen;
  20600.     hash = 0;
  20601.     s = key;
  20602.     while (i--)
  20603.         hash = hash * 33 + *s++;
  20604.  
  20605. References 
  20606.  
  20607. References are a special type of scalar that point to other data types 
  20608. (including references). 
  20609.  
  20610. To create a reference, use the following command: 
  20611.  
  20612.     SV* newRV((SV*) thing);
  20613.  
  20614. The thing argument can be any of an SV*, AV*, or HV*.  Once you have a 
  20615. reference, you can use the following macro to dereference the reference: 
  20616.  
  20617.     SvRV(SV*)
  20618.  
  20619. then call the appropriate routines, casting the returned SV* to either an AV* 
  20620. or HV*, if required. 
  20621.  
  20622. To determine if an SV is a reference, you can use the following macro: 
  20623.  
  20624.     SvROK(SV*)
  20625.  
  20626. To actually discover what the reference refers to, you must use the following 
  20627. macro and then check the value returned. 
  20628.  
  20629.     SvTYPE(SvRV(SV*))
  20630.  
  20631. The most useful types that will be returned are: 
  20632.  
  20633.     SVt_IV    Scalar
  20634.     SVt_NV    Scalar
  20635.     SVt_PV    Scalar
  20636.     SVt_PVAV  Array
  20637.     SVt_PVHV  Hash
  20638.     SVt_PVCV  Code
  20639.     SVt_PVMG  Blessed Scalar
  20640.  
  20641. Blessed References and Class Objects 
  20642.  
  20643. References are also used to support object-oriented programming.  In the OO 
  20644. lexicon, an object is simply a reference that has been blessed into a package 
  20645. (or class).  Once blessed, the programmer may now use the reference to access 
  20646. the various methods in the class. 
  20647.  
  20648. A reference can be blessed into a package with the following function: 
  20649.  
  20650.     SV* sv_bless(SV* sv, HV* stash);
  20651.  
  20652. The sv argument must be a reference.  The stash argument specifies which class 
  20653. the reference will belong to.  See the section on L<Stashes> for information on 
  20654. converting class names into stashes. 
  20655.  
  20656. /* Still under construction */ 
  20657.  
  20658. Upgrades rv to reference if not already one.  Creates new SV for rv to point 
  20659. to. If classname is non-null, the SV is blessed into the specified class. SV is 
  20660. returned. 
  20661.  
  20662.         SV* newSVrv(SV* rv, char* classname);
  20663.  
  20664. Copies integer or double into an SV whose reference is rv.  SV is blessed if 
  20665. classname is non-null. 
  20666.  
  20667.         SV* sv_setref_iv(SV* rv, char* classname, IV iv);
  20668.         SV* sv_setref_nv(SV* rv, char* classname, NV iv);
  20669.  
  20670. Copies pointer (not a string!) into an SV whose reference is rv. SV is blessed 
  20671. if classname is non-null. 
  20672.  
  20673.         SV* sv_setref_pv(SV* rv, char* classname, PV iv);
  20674.  
  20675. Copies string into an SV whose reference is rv. Set length to 0 to let Perl 
  20676. calculate the string length. SV is blessed if classname is non-null. 
  20677.  
  20678.         SV* sv_setref_pvn(SV* rv, char* classname, PV iv, int length);
  20679.         int sv_isa(SV* sv, char* name);
  20680.         int sv_isobject(SV* sv);
  20681.  
  20682. Creating New Variables 
  20683.  
  20684. To create a new Perl variable, which can be accessed from your Perl script, use 
  20685. the following routines, depending on the variable type. 
  20686.  
  20687.     SV*  perl_get_sv("varname", TRUE);
  20688.     AV*  perl_get_av("varname", TRUE);
  20689.     HV*  perl_get_hv("varname", TRUE);
  20690.  
  20691. Notice the use of TRUE as the second parameter.  The new variable can now be 
  20692. set, using the routines appropriate to the data type. 
  20693.  
  20694. There are additional bits that may be OR'ed with the TRUE argument to enable 
  20695. certain extra features.  Those bits are: 
  20696.  
  20697.     0x02  Marks the variable as multiply defined, thus preventing the
  20698.           "Indentifier <varname> used only once: possible typo" warning.
  20699.     0x04  Issues a "Had to create <varname> unexpectedly" warning if
  20700.           the variable didn't actually exist.  This is useful if
  20701.           you expected the variable to already exist and want to propagate
  20702.           this warning back to the user.
  20703.  
  20704. If the varname argument does not contain a package specifier, it is created in 
  20705. the current package. 
  20706.  
  20707. XSUB's and the Argument Stack 
  20708.  
  20709. The XSUB mechanism is a simple way for Perl programs to access C subroutines. 
  20710. An XSUB routine will have a stack that contains the arguments from the Perl 
  20711. program, and a way to map from the Perl data structures to a C equivalent. 
  20712.  
  20713. The stack arguments are accessible through the ST(n) macro, which returns the 
  20714. n'th stack argument.  Argument 0 is the first argument passed in the Perl 
  20715. subroutine call.  These arguments are SV*, and can be used anywhere an SV* is 
  20716. used. 
  20717.  
  20718. Most of the time, output from the C routine can be handled through use of the 
  20719. RETVAL and OUTPUT directives.  However, there are some cases where the argument 
  20720. stack is not already long enough to handle all the return values. An example is 
  20721. the POSIX tzname() call, which takes no arguments, but returns two, the local 
  20722. timezone's standard and summer time abbreviations. 
  20723.  
  20724. To handle this situation, the PPCODE directive is used and the stack is 
  20725. extended using the macro: 
  20726.  
  20727.     EXTEND(sp, num);
  20728.  
  20729. where sp is the stack pointer, and num is the number of elements the stack 
  20730. should be extended by. 
  20731.  
  20732. Now that there is room on the stack, values can be pushed on it using the 
  20733. macros to push IV's, doubles, strings, and SV pointers respectively: 
  20734.  
  20735.     PUSHi(IV)
  20736.     PUSHn(double)
  20737.     PUSHp(char*, I32)
  20738.     PUSHs(SV*)
  20739.  
  20740. And now the Perl program calling tzname, the two values will be assigned as in: 
  20741.  
  20742.     ($standard_abbrev, $summer_abbrev) = POSIX::tzname;
  20743.  
  20744. An alternate (and possibly simpler) method to pushing values on the stack is to 
  20745. use the macros: 
  20746.  
  20747.     XPUSHi(IV)
  20748.     XPUSHn(double)
  20749.     XPUSHp(char*, I32)
  20750.     XPUSHs(SV*)
  20751.  
  20752. These macros automatically adjust the stack for you, if needed. 
  20753.  
  20754. For more information, consult perlxs. 
  20755.  
  20756. Mortality 
  20757.  
  20758. In Perl, values are normally "immortal" -- that is, they are not freed unless 
  20759. explicitly done so (via the Perl undef call or other routines in Perl itself). 
  20760.  
  20761. Add cruft about reference counts. 
  20762.  
  20763.         int SvREFCNT(SV* sv);
  20764.         void SvREFCNT_inc(SV* sv);
  20765.         void SvREFCNT_dec(SV* sv);
  20766.  
  20767. In the above example with tzname, we needed to create two new SV's to push onto 
  20768. the argument stack, that being the two strings.  However, we don't want these 
  20769. new SV's to stick around forever because they will eventually be copied into 
  20770. the SV's that hold the two scalar variables. 
  20771.  
  20772. An SV (or AV or HV) that is "mortal" acts in all ways as a normal "immortal" 
  20773. SV, AV, or HV, but is only valid in the "current context".  When the Perl 
  20774. interpreter leaves the current context, the mortal SV, AV, or HV is 
  20775. automatically freed.  Generally the "current context" means a single Perl 
  20776. statement. 
  20777.  
  20778. To create a mortal variable, use the functions: 
  20779.  
  20780.     SV*  sv_newmortal()
  20781.     SV*  sv_2mortal(SV*)
  20782.     SV*  sv_mortalcopy(SV*)
  20783.  
  20784. The first call creates a mortal SV, the second converts an existing SV to a 
  20785. mortal SV, the third creates a mortal copy of an existing SV. 
  20786.  
  20787. The mortal routines are not just for SV's -- AV's and HV's can be made mortal 
  20788. by passing their address (and casting them to SV*) to the sv_2mortal or 
  20789. sv_mortalcopy routines. 
  20790.  
  20791. > From Ilya: Beware that the sv_2mortal() call is eventually equivalent to 
  20792. svREFCNT_dec(). A value can happily be mortal in two different contexts, and it 
  20793. will be svREFCNT_dec()ed twice, once on exit from these contexts. It can also 
  20794. be mortal twice in the same context. This means that you should be very careful 
  20795. to make a value mortal exactly as many times as it is needed. The value that go 
  20796. to the Perl stack should be mortal. 
  20797.  
  20798. You should be careful about creating mortal variables.  It is possible for 
  20799. strange things to happen should you make the same value mortal within multiple 
  20800. contexts. 
  20801.  
  20802. Stashes 
  20803.  
  20804. A stash is a hash table (associative array) that contains all of the different 
  20805. objects that are contained within a package.  Each key of the stash is a symbol 
  20806. name (shared by all the different types of objects that have the same name), 
  20807. and each value in the hash table is called a GV (for Glob Value).  This GV in 
  20808. turn contains references to the various objects of that name, including (but 
  20809. not limited to) the following: 
  20810.  
  20811.     Scalar Value
  20812.     Array Value
  20813.     Hash Value
  20814.     File Handle
  20815.     Directory Handle
  20816.     Format
  20817.     Subroutine
  20818.  
  20819. Perl stores various stashes in a separate GV structure (for global variable) 
  20820. but represents them with an HV structure.  The keys in this larger GV are the 
  20821. various package names; the values are the GV*'s which are stashes.  It may help 
  20822. to think of a stash purely as an HV, and that the term "GV" means the global 
  20823. variable hash. 
  20824.  
  20825. To get the stash pointer for a particular package, use the function: 
  20826.  
  20827.     HV*  gv_stashpv(char* name, I32 create)
  20828.     HV*  gv_stashsv(SV*, I32 create)
  20829.  
  20830. The first function takes a literal string, the second uses the string stored in 
  20831. the SV.  Remember that a stash is just a hash table, so you get back an HV*. 
  20832. The create flag will create a new package if it is set. 
  20833.  
  20834. The name that gv_stash*v wants is the name of the package whose symbol table 
  20835. you want.  The default package is called main.  If you have multiply nested 
  20836. packages, pass their names to gv_stash*v, separated by :: as in the Perl 
  20837. language itself. 
  20838.  
  20839. Alternately, if you have an SV that is a blessed reference, you can find out 
  20840. the stash pointer by using: 
  20841.  
  20842.     HV*  SvSTASH(SvRV(SV*));
  20843.  
  20844. then use the following to get the package name itself: 
  20845.  
  20846.     char*  HvNAME(HV* stash);
  20847.  
  20848. If you need to return a blessed value to your Perl script, you can use the 
  20849. following function: 
  20850.  
  20851.     SV*  sv_bless(SV*, HV* stash)
  20852.  
  20853. where the first argument, an SV*, must be a reference, and the second argument 
  20854. is a stash.  The returned SV* can now be used in the same way as any other SV. 
  20855.  
  20856. For more information on references and blessings, consult perlref. 
  20857.  
  20858. Magic 
  20859.  
  20860. [This section still under construction.  Ignore everything here.  Post no 
  20861. bills.  Everything not permitted is forbidden.] 
  20862.  
  20863. # Version 6, 1995/1/27 
  20864.  
  20865. Any SV may be magical, that is, it has special features that a normal SV does 
  20866. not have.  These features are stored in the SV structure in a linked list of 
  20867. struct magic's, typedef'ed to MAGIC. 
  20868.  
  20869.     struct magic {
  20870.         MAGIC*      mg_moremagic;
  20871.         MGVTBL*     mg_virtual;
  20872.         U16         mg_private;
  20873.         char        mg_type;
  20874.         U8          mg_flags;
  20875.         SV*         mg_obj;
  20876.         char*       mg_ptr;
  20877.         I32         mg_len;
  20878.     };
  20879.  
  20880. Note this is current as of patchlevel 0, and could change at any time. 
  20881.  
  20882. Assigning Magic 
  20883.  
  20884. Perl adds magic to an SV using the sv_magic function: 
  20885.  
  20886.     void sv_magic(SV* sv, SV* obj, int how, char* name, I32 namlen);
  20887.  
  20888. The sv argument is a pointer to the SV that is to acquire a new magical 
  20889. feature. 
  20890.  
  20891. If sv is not already magical, Perl uses the SvUPGRADE macro to set the SVt_PVMG 
  20892. flag for the sv.  Perl then continues by adding it to the beginning of the 
  20893. linked list of magical features.  Any prior entry of the same type of magic is 
  20894. deleted.  Note that this can be overriden, and multiple instances of the same 
  20895. type of magic can be associated with an SV. 
  20896.  
  20897. The name and namlem arguments are used to associate a string with the magic, 
  20898. typically the name of a variable. namlem is stored in the mg_len field and if 
  20899. name is non-null and namlem >= 0 a malloc'd copy of the name is stored in 
  20900. mg_ptr field. 
  20901.  
  20902. The sv_magic function uses how to determine which, if any, predefined "Magic 
  20903. Virtual Table" should be assigned to the mg_virtual field. See the "Magic 
  20904. Virtual Table" section below.  The how argument is also stored in the mg_type 
  20905. field. 
  20906.  
  20907. The obj argument is stored in the mg_obj field of the MAGIC structure.  If it 
  20908. is not the same as the sv argument, the reference count of the obj object is 
  20909. incremented.  If it is the same, or if the how argument is "#", or if it is a 
  20910. null pointer, then obj is merely stored, without the reference count being 
  20911. incremented. 
  20912.  
  20913. There is also a function to add magic to an HV: 
  20914.  
  20915.     void hv_magic(HV *hv, GV *gv, int how);
  20916.  
  20917. This simply calls sv_magic and coerces the gv argument into an SV. 
  20918.  
  20919. To remove the magic from an SV, call the function sv_unmagic: 
  20920.  
  20921.     void sv_unmagic(SV *sv, int type);
  20922.  
  20923. The type argument should be equal to the how value when the SV was initially 
  20924. made magical. 
  20925.  
  20926. Magic Virtual Tables 
  20927.  
  20928. The mg_virtual field in the MAGIC structure is a pointer to a MGVTBL, which is 
  20929. a structure of function pointers and stands for "Magic Virtual Table" to handle 
  20930. the various operations that might be applied to that variable. 
  20931.  
  20932. The MGVTBL has five pointers to the following routine types: 
  20933.  
  20934.     int  (*svt_get)(SV* sv, MAGIC* mg);
  20935.     int  (*svt_set)(SV* sv, MAGIC* mg);
  20936.     U32  (*svt_len)(SV* sv, MAGIC* mg);
  20937.     int  (*svt_clear)(SV* sv, MAGIC* mg);
  20938.     int  (*svt_free)(SV* sv, MAGIC* mg);
  20939.  
  20940. This MGVTBL structure is set at compile-time in perl.h and there are currently 
  20941. 19 types (or 21 with overloading turned on).  These different structures 
  20942. contain pointers to various routines that perform additional actions depending 
  20943. on which function is being called. 
  20944.  
  20945.     Function pointer    Action taken
  20946.     ----------------    ------------
  20947.     svt_get             Do something after the value of the SV is retrieved.
  20948.     svt_set             Do something after the SV is assigned a value.
  20949.     svt_len             Report on the SV's length.
  20950.     svt_clear           Clear something the SV represents.
  20951.     svt_free            Free any extra storage associated with the SV.
  20952.  
  20953. For instance, the MGVTBL structure called vtbl_sv (which corresponds to an 
  20954. mg_type of '\0') contains: 
  20955.  
  20956.     { magic_get, magic_set, magic_len, 0, 0 }
  20957.  
  20958. Thus, when an SV is determined to be magical and of type '\0', if a get 
  20959. operation is being performed, the routine magic_get is called.  All the various 
  20960. routines for the various magical types begin with magic_. 
  20961.  
  20962. The current kinds of Magic Virtual Tables are: 
  20963.  
  20964.     mg_type  MGVTBL              Type of magicalness
  20965.     -------  ------              -------------------
  20966.     \0       vtbl_sv             Regexp???
  20967.     A        vtbl_amagic         Operator Overloading
  20968.     a        vtbl_amagicelem     Operator Overloading
  20969.     c        0                   Used in Operator Overloading
  20970.     B        vtbl_bm             Boyer-Moore???
  20971.     E        vtbl_env            %ENV hash
  20972.     e        vtbl_envelem        %ENV hash element
  20973.     g        vtbl_mglob          Regexp /g flag???
  20974.     I        vtbl_isa            @ISA array
  20975.     i        vtbl_isaelem        @ISA array element
  20976.     L        0 (but sets RMAGICAL)     Perl Module/Debugger???
  20977.     l        vtbl_dbline         Debugger?
  20978.     P        vtbl_pack           Tied Array or Hash
  20979.     p        vtbl_packelem       Tied Array or Hash element
  20980.     q        vtbl_packelem       Tied Scalar or Handle
  20981.     S        vtbl_sig            Signal Hash
  20982.     s        vtbl_sigelem        Signal Hash element
  20983.     t        vtbl_taint          Taintedness
  20984.     U        vtbl_uvar           ???
  20985.     v        vtbl_vec            Vector
  20986.     x        vtbl_substr         Substring???
  20987.     *        vtbl_glob           GV???
  20988.     #        vtbl_arylen         Array Length
  20989.     .        vtbl_pos            $. scalar variable
  20990.     ~        Reserved for extensions, but multiple extensions may clash
  20991.  
  20992. When an upper-case and lower-case letter both exist in the table, then the 
  20993. upper-case letter is used to represent some kind of composite type (a list or a 
  20994. hash), and the lower-case letter is used to represent an element of that 
  20995. composite type. 
  20996.  
  20997. Finding Magic 
  20998.  
  20999.     MAGIC* mg_find(SV*, int type); /* Finds the magic pointer of that type */
  21000.  
  21001. This routine returns a pointer to the MAGIC structure stored in the SV. If the 
  21002. SV does not have that magical feature, NULL is returned.  Also, if the SV is 
  21003. not of type SVt_PVMG, Perl may core-dump. 
  21004.  
  21005.     int mg_copy(SV* sv, SV* nsv, char* key, STRLEN klen);
  21006.  
  21007. This routine checks to see what types of magic sv has.  If the mg_type field is 
  21008. an upper-case letter, then the mg_obj is copied to nsv, but the mg_type field 
  21009. is changed to be the lower-case letter. 
  21010.  
  21011. Double-Typed SV's 
  21012.  
  21013. Scalar variables normally contain only one type of value, an integer, double, 
  21014. pointer, or reference.  Perl will automatically convert the actual scalar data 
  21015. from the stored type into the requested type. 
  21016.  
  21017. Some scalar variables contain more than one type of scalar data.  For example, 
  21018. the variable $! contains either the numeric value of errno or its string 
  21019. equivalent from either strerror or sys_errlist[]. 
  21020.  
  21021. To force multiple data values into an SV, you must do two things: use the 
  21022. sv_set*v routines to add the additional scalar type, then set a flag so that 
  21023. Perl will believe it contains more than one type of data.  The four macros to 
  21024. set the flags are: 
  21025.  
  21026.         SvIOK_on
  21027.         SvNOK_on
  21028.         SvPOK_on
  21029.         SvROK_on
  21030.  
  21031. The particular macro you must use depends on which sv_set*v routine you called 
  21032. first.  This is because every sv_set*v routine turns on only the bit for the 
  21033. particular type of data being set, and turns off all the rest. 
  21034.  
  21035. For example, to create a new Perl variable called "dberror" that contains both 
  21036. the numeric and descriptive string error values, you could use the following 
  21037. code: 
  21038.  
  21039.     extern int  dberror;
  21040.     extern char *dberror_list;
  21041.     SV* sv = perl_get_sv("dberror", TRUE);
  21042.     sv_setiv(sv, (IV) dberror);
  21043.     sv_setpv(sv, dberror_list[dberror]);
  21044.     SvIOK_on(sv);
  21045.  
  21046. If the order of sv_setiv and sv_setpv had been reversed, then the macro 
  21047. SvPOK_on would need to be called instead of SvIOK_on. 
  21048.  
  21049. Calling Perl Routines from within C Programs 
  21050.  
  21051. There are four routines that can be used to call a Perl subroutine from within 
  21052. a C program.  These four are: 
  21053.  
  21054.     I32  perl_call_sv(SV*, I32);
  21055.     I32  perl_call_pv(char*, I32);
  21056.     I32  perl_call_method(char*, I32);
  21057.     I32  perl_call_argv(char*, I32, register char**);
  21058.  
  21059. The routine most often used is perl_call_sv.  The SV* argument contains either 
  21060. the name of the Perl subroutine to be called, or a reference to the subroutine. 
  21061. The second argument consists of flags that control the context in which the 
  21062. subroutine is called, whether or not the subroutine is being passed arguments, 
  21063. how errors should be trapped, and how to treat return values. 
  21064.  
  21065. All four routines return the number of arguments that the subroutine returned 
  21066. on the Perl stack. 
  21067.  
  21068. When using any of these routines (except perl_call_argv), the programmer must 
  21069. manipulate the Perl stack.  These include the following macros and functions: 
  21070.  
  21071.     dSP
  21072.     PUSHMARK()
  21073.     PUTBACK
  21074.     SPAGAIN
  21075.     ENTER
  21076.     SAVETMPS
  21077.     FREETMPS
  21078.     LEAVE
  21079.     XPUSH*()
  21080.     POP*()
  21081.  
  21082. For more information, consult perlcall. 
  21083.  
  21084. Memory Allocation 
  21085.  
  21086. It is strongly suggested that you use the version of malloc that is distributed 
  21087. with Perl.  It keeps pools of various sizes of unallocated memory in order to 
  21088. more quickly satisfy allocation requests. However, on some platforms, it may 
  21089. cause spurious malloc or free errors. 
  21090.  
  21091.     New(x, pointer, number, type);
  21092.     Newc(x, pointer, number, type, cast);
  21093.     Newz(x, pointer, number, type);
  21094.  
  21095. These three macros are used to initially allocate memory.  The first argument x 
  21096. was a "magic cookie" that was used to keep track of who called the macro, to 
  21097. help when debugging memory problems.  However, the current code makes no use of 
  21098. this feature (Larry has switched to using a run-time memory checker), so this 
  21099. argument can be any number. 
  21100.  
  21101. The second argument pointer will point to the newly allocated memory. The third 
  21102. and fourth arguments number and type specify how many of the specified type of 
  21103. data structure should be allocated.  The argument type is passed to sizeof. 
  21104. The final argument to Newc, cast, should be used if the pointer argument is 
  21105. different from the type argument. 
  21106.  
  21107. Unlike the New and Newc macros, the Newz macro calls memzero to zero out all 
  21108. the newly allocated memory. 
  21109.  
  21110.     Renew(pointer, number, type);
  21111.     Renewc(pointer, number, type, cast);
  21112.     Safefree(pointer)
  21113.  
  21114. These three macros are used to change a memory buffer size or to free a piece 
  21115. of memory no longer needed.  The arguments to Renew and Renewc match those of 
  21116. New and Newc with the exception of not needing the "magic cookie" argument. 
  21117.  
  21118.     Move(source, dest, number, type);
  21119.     Copy(source, dest, number, type);
  21120.     Zero(dest, number, type);
  21121.  
  21122. These three macros are used to move, copy, or zero out previously allocated 
  21123. memory.  The source and dest arguments point to the source and destination 
  21124. starting points.  Perl will move, copy, or zero out number instances of the 
  21125. size of the type data structure (using the sizeof function). 
  21126.  
  21127. API LISTING 
  21128.  
  21129. This is a listing of functions, macros, flags, and variables that may be useful 
  21130. to extension writers or that may be found while reading other extensions. 
  21131.  
  21132. Listing of Perl Internal API 
  21133.  
  21134.  
  21135. ΓòÉΓòÉΓòÉ 33. Listing of Perl Internal API ΓòÉΓòÉΓòÉ
  21136.  
  21137. Listing of Perl Internal API 
  21138.  
  21139.       AvFILL 
  21140.       av_clear 
  21141.       av_extend 
  21142.       av_fetch 
  21143.       av_len 
  21144.       av_make 
  21145.       av_pop 
  21146.       av_push 
  21147.       av_shift 
  21148.       av_store 
  21149.       av_undef 
  21150.       av_unshift 
  21151.       CLASS 
  21152.       Copy 
  21153.       croak 
  21154.       CvSTASH 
  21155.       DBsingle 
  21156.       DBsub 
  21157.       dMARK 
  21158.       dORIGMARK 
  21159.       dSP 
  21160.       dXSARGS 
  21161.       ENTER 
  21162.       EXTEND 
  21163.       FREETMPS 
  21164.       G_ARRAY 
  21165.       G_DISCARD 
  21166.       G_EVAL 
  21167.       GIMME 
  21168.       G_NOARGS 
  21169.       G_SCALAR 
  21170.       gv_stashpv 
  21171.       gv_stashsv 
  21172.       GvSV 
  21173.       he_free 
  21174.       hv_clear 
  21175.       hv_delete 
  21176.       hv_exists 
  21177.       hv_fetch 
  21178.       hv_iterinit 
  21179.       hv_iterkey 
  21180.       hv_iternext 
  21181.       hv_iternextsv 
  21182.       hv_iterval 
  21183.       hv_magic 
  21184.       HvNAME 
  21185.       hv_store 
  21186.       hv_undef 
  21187.       isALNUM 
  21188.       isALPHA 
  21189.       isDIGIT 
  21190.       isLOWER 
  21191.       isSPACE 
  21192.       isUPPER 
  21193.       items 
  21194.       LEAVE 
  21195.       MARK 
  21196.       mg_clear 
  21197.       mg_copy 
  21198.       mg_find 
  21199.       mg_free 
  21200.       mg_get 
  21201.       mg_len 
  21202.       mg_magical 
  21203.       mg_set 
  21204.       Move 
  21205.       na 
  21206.       New 
  21207.       Newc 
  21208.       Newz 
  21209.       newAV 
  21210.       newHV 
  21211.       newRV 
  21212.       newSV 
  21213.       newSViv 
  21214.       newSVnv 
  21215.       newSVpv 
  21216.       newSVrv 
  21217.       newSVsv 
  21218.       newXS 
  21219.       newXSproto 
  21220.       Nullav 
  21221.       Nullch 
  21222.       Nullcv 
  21223.       Nullhv 
  21224.       Nullsv 
  21225.       ORIGMARK 
  21226.       perl_alloc 
  21227.       perl_call_argv 
  21228.       perl_call_method 
  21229.       perl_call_pv 
  21230.       perl_call_sv 
  21231.       perl_construct 
  21232.       perl_destruct 
  21233.       perl_eval_sv 
  21234.       perl_free 
  21235.       perl_get_av 
  21236.       perl_get_cv 
  21237.       perl_get_hv 
  21238.       perl_get_sv 
  21239.       perl_parse 
  21240.       perl_require_pv 
  21241.       perl_run 
  21242.       POPi 
  21243.       POPl 
  21244.       POPp 
  21245.       POPn 
  21246.       POPs 
  21247.       PUSHMARK 
  21248.       PUSHi 
  21249.       PUSHn 
  21250.       PUSHp 
  21251.       PUSHs 
  21252.       PUTBACK 
  21253.       Renew 
  21254.       Renewc 
  21255.       RETVAL 
  21256.       safefree 
  21257.       safemalloc 
  21258.       saferealloc 
  21259.       savepv 
  21260.       savepvn 
  21261.       SAVETMPS 
  21262.       SP 
  21263.       SPAGAIN 
  21264.       ST 
  21265.       strEQ 
  21266.       strGE 
  21267.       strGT 
  21268.       strLE 
  21269.       strLT 
  21270.       strNE 
  21271.       strnEQ 
  21272.       strnNE 
  21273.       sv_2mortal 
  21274.       sv_bless 
  21275.       sv_catpv 
  21276.       sv_catpvn 
  21277.       sv_catsv 
  21278.       SvCUR 
  21279.       SvCUR_set 
  21280.       SvEND 
  21281.       SvGROW 
  21282.       SvIOK 
  21283.       SvIOK_off 
  21284.       SvIOK_on 
  21285.       SvIOKp 
  21286.       sv_isa 
  21287.       SvIV 
  21288.       sv_isobject 
  21289.       SvIVX 
  21290.       SvLEN 
  21291.       sv_magic 
  21292.       sv_mortalcopy 
  21293.       SvOK 
  21294.       sv_newmortal 
  21295.       sv_no 
  21296.       SvNIOK 
  21297.       SvNIOK_off 
  21298.       SvNIOKp 
  21299.       SvNOK 
  21300.       SvNOK_off 
  21301.       SvNOK_on 
  21302.       SvNOKp 
  21303.       SvNV 
  21304.       SvNVX 
  21305.       SvPOK 
  21306.       SvPOK_off 
  21307.       SvPOK_on 
  21308.       SvPOKp 
  21309.       SvPV 
  21310.       SvPVX 
  21311.       SvREFCNT 
  21312.       SvREFCNT_dec 
  21313.       SvREFCNT_inc 
  21314.       SvROK 
  21315.       SvROK_off 
  21316.       SvROK_on 
  21317.       SvRV 
  21318.       sv_setiv 
  21319.       sv_setnv 
  21320.       sv_setpv 
  21321.       sv_setpvn 
  21322.       sv_setref_iv 
  21323.       sv_setref_nv 
  21324.       sv_setref_pv 
  21325.       sv_setref_pvn 
  21326.       sv_setsv 
  21327.       SvSTASH 
  21328.       SVt_IV 
  21329.       SVt_PV 
  21330.       SVt_PVAV 
  21331.       SVt_PVCV 
  21332.       SVt_PVHV 
  21333.       SVt_PVMG 
  21334.       SVt_NV 
  21335.       SvTRUE 
  21336.       SvTYPE 
  21337.       svtype 
  21338.       SvUPGRADE 
  21339.       sv_undef 
  21340.       sv_usepvn 
  21341.       sv_yes 
  21342.       THIS 
  21343.       toLOWER 
  21344.       toUPPER 
  21345.       warn 
  21346.       XPUSHi 
  21347.       XPUSHn 
  21348.       XPUSHp 
  21349.       XPUSHs 
  21350.       XSRETURN 
  21351.       XSRETURN_EMPTY 
  21352.       XSRETURN_NO 
  21353.       XSRETURN_UNDEF 
  21354.       XSRETURN_YES 
  21355.       Zero 
  21356.  
  21357.  
  21358. ΓòÉΓòÉΓòÉ 33.1. AvFILL ΓòÉΓòÉΓòÉ
  21359.  
  21360. AvFILL 
  21361.  
  21362. See av_len. 
  21363.  
  21364.  
  21365. ΓòÉΓòÉΓòÉ 33.2. av_clear ΓòÉΓòÉΓòÉ
  21366.  
  21367. av_clear 
  21368.  
  21369. Clears an array, making it empty. 
  21370.  
  21371.         void    av_clear _((AV* ar));
  21372.  
  21373.  
  21374. ΓòÉΓòÉΓòÉ 33.3. av_extend ΓòÉΓòÉΓòÉ
  21375.  
  21376. av_extend 
  21377.  
  21378. Pre-extend an array.  The key is the index to which the array should be 
  21379. extended. 
  21380.  
  21381.         void    av_extend _((AV* ar, I32 key));
  21382.  
  21383.  
  21384. ΓòÉΓòÉΓòÉ 33.4. av_fetch ΓòÉΓòÉΓòÉ
  21385.  
  21386. av_fetch 
  21387.  
  21388. Returns the SV at the specified index in the array.  The key is the index.  If 
  21389. lval is set then the fetch will be part of a store.  Check that the return 
  21390. value is non-null before dereferencing it to a SV*. 
  21391.  
  21392.         SV**    av_fetch _((AV* ar, I32 key, I32 lval));
  21393.  
  21394.  
  21395. ΓòÉΓòÉΓòÉ 33.5. av_len ΓòÉΓòÉΓòÉ
  21396.  
  21397. av_len 
  21398.  
  21399. Returns the highest index in the array.  Returns -1 if the array is empty. 
  21400.  
  21401.         I32     av_len _((AV* ar));
  21402.  
  21403.  
  21404. ΓòÉΓòÉΓòÉ 33.6. av_make ΓòÉΓòÉΓòÉ
  21405.  
  21406. av_make 
  21407.  
  21408. Creats a new AV and populates it with a list of SVs.  The SVs are copied into 
  21409. the array, so they may be freed after the call to av_make. 
  21410.  
  21411.         AV*     av_make _((I32 size, SV** svp));
  21412.  
  21413.  
  21414. ΓòÉΓòÉΓòÉ 33.7. av_pop ΓòÉΓòÉΓòÉ
  21415.  
  21416. av_pop 
  21417.  
  21418. Pops an SV off the end of the array.  Returns &sv_undef if the array is empty. 
  21419.  
  21420.         SV*     av_pop _((AV* ar));
  21421.  
  21422.  
  21423. ΓòÉΓòÉΓòÉ 33.8. av_push ΓòÉΓòÉΓòÉ
  21424.  
  21425. av_push 
  21426.  
  21427. Pushes an SV onto the end of the array. 
  21428.  
  21429.         void    av_push _((AV* ar, SV* val));
  21430.  
  21431.  
  21432. ΓòÉΓòÉΓòÉ 33.9. av_shift ΓòÉΓòÉΓòÉ
  21433.  
  21434. av_shift 
  21435.  
  21436. Shifts an SV off the beginning of the array. 
  21437.  
  21438.         SV*     av_shift _((AV* ar));
  21439.  
  21440.  
  21441. ΓòÉΓòÉΓòÉ 33.10. av_store ΓòÉΓòÉΓòÉ
  21442.  
  21443. av_store 
  21444.  
  21445. Stores an SV in an array.  The array index is specified as key.  The return 
  21446. value will be null if the operation failed, otherwise it can be dereferenced to 
  21447. get the original SV*. 
  21448.  
  21449.         SV**    av_store _((AV* ar, I32 key, SV* val));
  21450.  
  21451.  
  21452. ΓòÉΓòÉΓòÉ 33.11. av_undef ΓòÉΓòÉΓòÉ
  21453.  
  21454. av_undef 
  21455.  
  21456. Undefines the array. 
  21457.  
  21458.         void    av_undef _((AV* ar));
  21459.  
  21460.  
  21461. ΓòÉΓòÉΓòÉ 33.12. av_unshift ΓòÉΓòÉΓòÉ
  21462.  
  21463. av_unshift 
  21464.  
  21465. Unshift an SV onto the beginning of the array. 
  21466.  
  21467.         void    av_unshift _((AV* ar, I32 num));
  21468.  
  21469.  
  21470. ΓòÉΓòÉΓòÉ 33.13. CLASS ΓòÉΓòÉΓòÉ
  21471.  
  21472. CLASS 
  21473.  
  21474. Variable which is setup by xsubpp to indicate the class name for a C++ XS 
  21475. constructor.  This is always a char*.  See THIS and perlxs. 
  21476.  
  21477.  
  21478. ΓòÉΓòÉΓòÉ 33.14. Copy ΓòÉΓòÉΓòÉ
  21479.  
  21480. Copy 
  21481.  
  21482. The XSUB-writer's interface to the C memcpy function.  The s is the source, d 
  21483. is the destination, n is the number of items, and t is the type. 
  21484.  
  21485.         (void) Copy( s, d, n, t );
  21486.  
  21487.  
  21488. ΓòÉΓòÉΓòÉ 33.15. croak ΓòÉΓòÉΓòÉ
  21489.  
  21490. croak 
  21491.  
  21492. This is the XSUB-writer's interface to Perl's die function.  Use this function 
  21493. the same way you use the C printf function.  See warn. 
  21494.  
  21495.  
  21496. ΓòÉΓòÉΓòÉ 33.16. CvSTASH ΓòÉΓòÉΓòÉ
  21497.  
  21498. CvSTASH 
  21499.  
  21500. Returns the stash of the CV. 
  21501.  
  21502.         HV * CvSTASH( SV* sv )
  21503.  
  21504.  
  21505. ΓòÉΓòÉΓòÉ 33.17. DBsingle ΓòÉΓòÉΓòÉ
  21506.  
  21507. DBsingle 
  21508.  
  21509. When Perl is run in debugging mode, with the -d switch, this SV is a boolean 
  21510. which indicates whether subs are being single-stepped. Single-stepping is 
  21511. automatically turned on after every step.  See DBsub. 
  21512.  
  21513.  
  21514. ΓòÉΓòÉΓòÉ 33.18. DBsub ΓòÉΓòÉΓòÉ
  21515.  
  21516. DBsub 
  21517.  
  21518. When Perl is run in debugging mode, with the -d switch, this GV contains the SV 
  21519. which holds the name of the sub being debugged.  See DBsingle. The sub name can 
  21520. be found by 
  21521.  
  21522.         SvPV( GvSV( DBsub ), na )
  21523.  
  21524.  
  21525. ΓòÉΓòÉΓòÉ 33.19. dMARK ΓòÉΓòÉΓòÉ
  21526.  
  21527. dMARK 
  21528.  
  21529. Declare a stack marker for the XSUB.  See MARK and dORIGMARK. 
  21530.  
  21531.  
  21532. ΓòÉΓòÉΓòÉ 33.20. dORIGMARK ΓòÉΓòÉΓòÉ
  21533.  
  21534. dORIGMARK 
  21535.  
  21536. Saves the original stack mark for the XSUB.  See ORIGMARK. 
  21537.  
  21538.  
  21539. ΓòÉΓòÉΓòÉ 33.21. dSP ΓòÉΓòÉΓòÉ
  21540.  
  21541. dSP 
  21542.  
  21543. Declares a stack pointer for the XSUB.  See SP. 
  21544.  
  21545.  
  21546. ΓòÉΓòÉΓòÉ 33.22. dXSARGS ΓòÉΓòÉΓòÉ
  21547.  
  21548. dXSARGS 
  21549.  
  21550. Sets up stack and mark pointers for an XSUB, calling dSP and dMARK.  This is 
  21551. usually handled automatically by xsubpp.  Declares the items variable to 
  21552. indicate the number of items on the stack. 
  21553.  
  21554.  
  21555. ΓòÉΓòÉΓòÉ 33.23. ENTER ΓòÉΓòÉΓòÉ
  21556.  
  21557. ENTER 
  21558.  
  21559. Opening bracket on a callback.  See LEAVE and perlcall. 
  21560.  
  21561.         ENTER;
  21562.  
  21563.  
  21564. ΓòÉΓòÉΓòÉ 33.24. EXTEND ΓòÉΓòÉΓòÉ
  21565.  
  21566. EXTEND 
  21567.  
  21568. Used to extend the argument stack for an XSUB's return values. 
  21569.  
  21570.         EXTEND( sp, int x );
  21571.  
  21572.  
  21573. ΓòÉΓòÉΓòÉ 33.25. FREETMPS ΓòÉΓòÉΓòÉ
  21574.  
  21575. FREETMPS 
  21576.  
  21577. Closing bracket for temporaries on a callback.  See SAVETMPS and perlcall. 
  21578.  
  21579.         FREETMPS;
  21580.  
  21581.  
  21582. ΓòÉΓòÉΓòÉ 33.26. G_ARRAY ΓòÉΓòÉΓòÉ
  21583.  
  21584. G_ARRAY 
  21585.  
  21586. Used to indicate array context.  See GIMME and perlcall. 
  21587.  
  21588.  
  21589. ΓòÉΓòÉΓòÉ 33.27. G_DISCARD ΓòÉΓòÉΓòÉ
  21590.  
  21591. G_DISCARD 
  21592.  
  21593. Indicates that arguments returned from a callback should be discarded.  See 
  21594. perlcall. 
  21595.  
  21596.  
  21597. ΓòÉΓòÉΓòÉ 33.28. G_EVAL ΓòÉΓòÉΓòÉ
  21598.  
  21599. G_EVAL 
  21600.  
  21601. Used to force a Perl eval wrapper around a callback.  See perlcall. 
  21602.  
  21603.  
  21604. ΓòÉΓòÉΓòÉ 33.29. GIMME ΓòÉΓòÉΓòÉ
  21605.  
  21606. GIMME 
  21607.  
  21608. The XSUB-writer's equivalent to Perl's wantarray.  Returns G_SCALAR or G_ARRAY 
  21609. for scalar or array context. 
  21610.  
  21611.  
  21612. ΓòÉΓòÉΓòÉ 33.30. G_NOARGS ΓòÉΓòÉΓòÉ
  21613.  
  21614. G_NOARGS 
  21615.  
  21616. Indicates that no arguments are being sent to a callback.  See perlcall. 
  21617.  
  21618.  
  21619. ΓòÉΓòÉΓòÉ 33.31. G_SCALAR ΓòÉΓòÉΓòÉ
  21620.  
  21621. G_SCALAR 
  21622.  
  21623. Used to indicate scalar context.  See GIMME and perlcall. 
  21624.  
  21625.  
  21626. ΓòÉΓòÉΓòÉ 33.32. gv_stashpv ΓòÉΓòÉΓòÉ
  21627.  
  21628. gv_stashpv 
  21629.  
  21630. Returns a pointer to the stash for a specified package.  If create is set then 
  21631. the package will be created if it does not already exist.  If create is not set 
  21632. and the package does not exist then NULL is returned. 
  21633.  
  21634.         HV*     gv_stashpv _((char* name, I32 create));
  21635.  
  21636.  
  21637. ΓòÉΓòÉΓòÉ 33.33. gv_stashsv ΓòÉΓòÉΓòÉ
  21638.  
  21639. gv_stashsv 
  21640.  
  21641. Returns a pointer to the stash for a specified package.  See gv_stashpv. 
  21642.  
  21643.         HV*     gv_stashsv _((SV* sv, I32 create));
  21644.  
  21645.  
  21646. ΓòÉΓòÉΓòÉ 33.34. GvSV ΓòÉΓòÉΓòÉ
  21647.  
  21648. GvSV 
  21649.  
  21650. Return the SV from the GV. 
  21651.  
  21652.  
  21653. ΓòÉΓòÉΓòÉ 33.35. he_free ΓòÉΓòÉΓòÉ
  21654.  
  21655. he_free 
  21656.  
  21657. Releases a hash entry from an iterator.  See hv_iternext. 
  21658.  
  21659.  
  21660. ΓòÉΓòÉΓòÉ 33.36. hv_clear ΓòÉΓòÉΓòÉ
  21661.  
  21662. hv_clear 
  21663.  
  21664. Clears a hash, making it empty. 
  21665.  
  21666.         void    hv_clear _((HV* tb));
  21667.  
  21668.  
  21669. ΓòÉΓòÉΓòÉ 33.37. hv_delete ΓòÉΓòÉΓòÉ
  21670.  
  21671. hv_delete 
  21672.  
  21673. Deletes a key/value pair in the hash.  The value SV is removed from the hash 
  21674. and returned to the caller.  The lken is the length of the key.  The flags 
  21675. value will normally be zero; if set to G_DISCARD then null will be returned. 
  21676.  
  21677.         SV*     hv_delete _((HV* tb, char* key, U32 klen, I32 flags));
  21678.  
  21679.  
  21680. ΓòÉΓòÉΓòÉ 33.38. hv_exists ΓòÉΓòÉΓòÉ
  21681.  
  21682. hv_exists 
  21683.  
  21684. Returns a boolean indicating whether the specified hash key exists.  The lken 
  21685. is the length of the key. 
  21686.  
  21687.         bool    hv_exists _((HV* tb, char* key, U32 klen));
  21688.  
  21689.  
  21690. ΓòÉΓòÉΓòÉ 33.39. hv_fetch ΓòÉΓòÉΓòÉ
  21691.  
  21692. hv_fetch 
  21693.  
  21694. Returns the SV which corresponds to the specified key in the hash.  The lken is 
  21695. the length of the key.  If lval is set then the fetch will be part of a store. 
  21696. Check that the return value is non-null before dereferencing it to a SV*. 
  21697.  
  21698.         SV**    hv_fetch _((HV* tb, char* key, U32 klen, I32 lval));
  21699.  
  21700.  
  21701. ΓòÉΓòÉΓòÉ 33.40. hv_iterinit ΓòÉΓòÉΓòÉ
  21702.  
  21703. hv_iterinit 
  21704.  
  21705. Prepares a starting point to traverse a hash table. 
  21706.  
  21707.         I32     hv_iterinit _((HV* tb));
  21708.  
  21709.  
  21710. ΓòÉΓòÉΓòÉ 33.41. hv_iterkey ΓòÉΓòÉΓòÉ
  21711.  
  21712. hv_iterkey 
  21713.  
  21714. Returns the key from the current position of the hash iterator.  See 
  21715. hv_iterinit. 
  21716.  
  21717.         char*   hv_iterkey _((HE* entry, I32* retlen));
  21718.  
  21719.  
  21720. ΓòÉΓòÉΓòÉ 33.42. hv_iternext ΓòÉΓòÉΓòÉ
  21721.  
  21722. hv_iternext 
  21723.  
  21724. Returns entries from a hash iterator.  See hv_iterinit. 
  21725.  
  21726.         HE*     hv_iternext _((HV* tb));
  21727.  
  21728.  
  21729. ΓòÉΓòÉΓòÉ 33.43. hv_iternextsv ΓòÉΓòÉΓòÉ
  21730.  
  21731. hv_iternextsv 
  21732.  
  21733. Performs an hv_iternext, hv_iterkey, and hv_iterval in one operation. 
  21734.  
  21735.         SV *    hv_iternextsv _((HV* hv, char** key, I32* retlen));
  21736.  
  21737.  
  21738. ΓòÉΓòÉΓòÉ 33.44. hv_iterval ΓòÉΓòÉΓòÉ
  21739.  
  21740. hv_iterval 
  21741.  
  21742. Returns the value from the current position of the hash iterator.  See 
  21743. hv_iterkey. 
  21744.  
  21745.         SV*     hv_iterval _((HV* tb, HE* entry));
  21746.  
  21747.  
  21748. ΓòÉΓòÉΓòÉ 33.45. hv_magic ΓòÉΓòÉΓòÉ
  21749.  
  21750. hv_magic 
  21751.  
  21752. Adds magic to a hash.  See sv_magic. 
  21753.  
  21754.         void    hv_magic _((HV* hv, GV* gv, int how));
  21755.  
  21756.  
  21757. ΓòÉΓòÉΓòÉ 33.46. HvNAME ΓòÉΓòÉΓòÉ
  21758.  
  21759. HvNAME 
  21760.  
  21761. Returns the package name of a stash.  See SvSTASH, CvSTASH. 
  21762.  
  21763.         char *HvNAME (HV* stash)
  21764.  
  21765.  
  21766. ΓòÉΓòÉΓòÉ 33.47. hv_store ΓòÉΓòÉΓòÉ
  21767.  
  21768. hv_store 
  21769.  
  21770. Stores an SV in a hash.  The hash key is specified as key and klen is the 
  21771. length of the key.  The hash parameter is the pre-computed hash value; if it is 
  21772. zero then Perl will compute it.  The return value will be null if the operation 
  21773. failed, otherwise it can be dereferenced to get the original SV*. 
  21774.  
  21775.         SV**    hv_store _((HV* tb, char* key, U32 klen, SV* val, U32 hash));
  21776.  
  21777.  
  21778. ΓòÉΓòÉΓòÉ 33.48. hv_undef ΓòÉΓòÉΓòÉ
  21779.  
  21780. hv_undef 
  21781.  
  21782. Undefines the hash. 
  21783.  
  21784.         void    hv_undef _((HV* tb));
  21785.  
  21786.  
  21787. ΓòÉΓòÉΓòÉ 33.49. isALNUM ΓòÉΓòÉΓòÉ
  21788.  
  21789. isALNUM 
  21790.  
  21791. Returns a boolean indicating whether the C char is an ascii alphanumeric 
  21792. character or digit. 
  21793.  
  21794.         int isALNUM (char c)
  21795.  
  21796.  
  21797. ΓòÉΓòÉΓòÉ 33.50. isALPHA ΓòÉΓòÉΓòÉ
  21798.  
  21799. isALPHA 
  21800.  
  21801. Returns a boolean indicating whether the C char is an ascii alphanumeric 
  21802. character. 
  21803.  
  21804.         int isALPHA (char c)
  21805.  
  21806.  
  21807. ΓòÉΓòÉΓòÉ 33.51. isDIGIT ΓòÉΓòÉΓòÉ
  21808.  
  21809. isDIGIT 
  21810.  
  21811. Returns a boolean indicating whether the C char is an ascii digit. 
  21812.  
  21813.         int isDIGIT (char c)
  21814.  
  21815.  
  21816. ΓòÉΓòÉΓòÉ 33.52. isLOWER ΓòÉΓòÉΓòÉ
  21817.  
  21818. isLOWER 
  21819.  
  21820. Returns a boolean indicating whether the C char is a lowercase character. 
  21821.  
  21822.         int isLOWER (char c)
  21823.  
  21824.  
  21825. ΓòÉΓòÉΓòÉ 33.53. isSPACE ΓòÉΓòÉΓòÉ
  21826.  
  21827. isSPACE 
  21828.  
  21829. Returns a boolean indicating whether the C char is whitespace. 
  21830.  
  21831.         int isSPACE (char c)
  21832.  
  21833.  
  21834. ΓòÉΓòÉΓòÉ 33.54. isUPPER ΓòÉΓòÉΓòÉ
  21835.  
  21836. isUPPER 
  21837.  
  21838. Returns a boolean indicating whether the C char is an uppercase character. 
  21839.  
  21840.         int isUPPER (char c)
  21841.  
  21842.  
  21843. ΓòÉΓòÉΓòÉ 33.55. items ΓòÉΓòÉΓòÉ
  21844.  
  21845. items 
  21846.  
  21847. Variable which is setup by xsubpp to indicate the number of items on the stack. 
  21848. See perlxs. 
  21849.  
  21850.  
  21851. ΓòÉΓòÉΓòÉ 33.56. LEAVE ΓòÉΓòÉΓòÉ
  21852.  
  21853. LEAVE 
  21854.  
  21855. Closing bracket on a callback.  See ENTER and perlcall. 
  21856.  
  21857.         LEAVE;
  21858.  
  21859.  
  21860. ΓòÉΓòÉΓòÉ 33.57. MARK ΓòÉΓòÉΓòÉ
  21861.  
  21862. MARK 
  21863.  
  21864. Stack marker for the XSUB.  See dMARK. 
  21865.  
  21866.  
  21867. ΓòÉΓòÉΓòÉ 33.58. mg_clear ΓòÉΓòÉΓòÉ
  21868.  
  21869. mg_clear 
  21870.  
  21871. Clear something magical that the SV represents.  See sv_magic. 
  21872.  
  21873.         int     mg_clear _((SV* sv));
  21874.  
  21875.  
  21876. ΓòÉΓòÉΓòÉ 33.59. mg_copy ΓòÉΓòÉΓòÉ
  21877.  
  21878. mg_copy 
  21879.  
  21880. Copies the magic from one SV to another.  See sv_magic. 
  21881.  
  21882.         int     mg_copy _((SV *, SV *, char *, STRLEN));
  21883.  
  21884.  
  21885. ΓòÉΓòÉΓòÉ 33.60. mg_find ΓòÉΓòÉΓòÉ
  21886.  
  21887. mg_find 
  21888.  
  21889. Finds the magic pointer for type matching the SV.  See sv_magic. 
  21890.  
  21891.         MAGIC*  mg_find _((SV* sv, int type));
  21892.  
  21893.  
  21894. ΓòÉΓòÉΓòÉ 33.61. mg_free ΓòÉΓòÉΓòÉ
  21895.  
  21896. mg_free 
  21897.  
  21898. Free any magic storage used by the SV.  See sv_magic. 
  21899.  
  21900.         int     mg_free _((SV* sv));
  21901.  
  21902.  
  21903. ΓòÉΓòÉΓòÉ 33.62. mg_get ΓòÉΓòÉΓòÉ
  21904.  
  21905. mg_get 
  21906.  
  21907. Do magic after a value is retrieved from the SV.  See sv_magic. 
  21908.  
  21909.         int     mg_get _((SV* sv));
  21910.  
  21911.  
  21912. ΓòÉΓòÉΓòÉ 33.63. mg_len ΓòÉΓòÉΓòÉ
  21913.  
  21914. mg_len 
  21915.  
  21916. Report on the SV's length.  See sv_magic. 
  21917.  
  21918.         U32     mg_len _((SV* sv));
  21919.  
  21920.  
  21921. ΓòÉΓòÉΓòÉ 33.64. mg_magical ΓòÉΓòÉΓòÉ
  21922.  
  21923. mg_magical 
  21924.  
  21925. Turns on the magical status of an SV.  See sv_magic. 
  21926.  
  21927.         void    mg_magical _((SV* sv));
  21928.  
  21929.  
  21930. ΓòÉΓòÉΓòÉ 33.65. mg_set ΓòÉΓòÉΓòÉ
  21931.  
  21932. mg_set 
  21933.  
  21934. Do magic after a value is assigned to the SV.  See sv_magic. 
  21935.  
  21936.         int     mg_set _((SV* sv));
  21937.  
  21938.  
  21939. ΓòÉΓòÉΓòÉ 33.66. Move ΓòÉΓòÉΓòÉ
  21940.  
  21941. Move 
  21942.  
  21943. The XSUB-writer's interface to the C memmove function.  The s is the source, d 
  21944. is the destination, n is the number of items, and t is the type. 
  21945.  
  21946.         (void) Move( s, d, n, t );
  21947.  
  21948.  
  21949. ΓòÉΓòÉΓòÉ 33.67. na ΓòÉΓòÉΓòÉ
  21950.  
  21951. na 
  21952.  
  21953. A variable which may be used with SvPV to tell Perl to calculate the string 
  21954. length. 
  21955.  
  21956.  
  21957. ΓòÉΓòÉΓòÉ 33.68. New ΓòÉΓòÉΓòÉ
  21958.  
  21959. New 
  21960.  
  21961. The XSUB-writer's interface to the C malloc function. 
  21962.  
  21963.         void * New( x, void *ptr, int size, type )
  21964.  
  21965.  
  21966. ΓòÉΓòÉΓòÉ 33.69. Newc ΓòÉΓòÉΓòÉ
  21967.  
  21968. Newc 
  21969.  
  21970. The XSUB-writer's interface to the C malloc function, with cast. 
  21971.  
  21972.         void * Newc( x, void *ptr, int size, type, cast )
  21973.  
  21974.  
  21975. ΓòÉΓòÉΓòÉ 33.70. Newz ΓòÉΓòÉΓòÉ
  21976.  
  21977. Newz 
  21978.  
  21979. The XSUB-writer's interface to the C malloc function.  The allocated memory is 
  21980. zeroed with memzero. 
  21981.  
  21982.         void * Newz( x, void *ptr, int size, type )
  21983.  
  21984.  
  21985. ΓòÉΓòÉΓòÉ 33.71. newAV ΓòÉΓòÉΓòÉ
  21986.  
  21987. newAV 
  21988.  
  21989. Creates a new AV.  The refcount is set to 1. 
  21990.  
  21991.         AV*     newAV _((void));
  21992.  
  21993.  
  21994. ΓòÉΓòÉΓòÉ 33.72. newHV ΓòÉΓòÉΓòÉ
  21995.  
  21996. newHV 
  21997.  
  21998. Creates a new HV.  The refcount is set to 1. 
  21999.  
  22000.         HV*     newHV _((void));
  22001.  
  22002.  
  22003. ΓòÉΓòÉΓòÉ 33.73. newRV ΓòÉΓòÉΓòÉ
  22004.  
  22005. newRV 
  22006.  
  22007. Creates an RV wrapper for an SV.  The refcount for the original SV is 
  22008. incremented. 
  22009.  
  22010.         SV*     newRV _((SV* ref));
  22011.  
  22012.  
  22013. ΓòÉΓòÉΓòÉ 33.74. newSV ΓòÉΓòÉΓòÉ
  22014.  
  22015. newSV 
  22016.  
  22017. Creates a new SV.  The len parameter indicates the number of bytes of 
  22018. pre-allocated string space the SV should have.  The refcount for the new SV is 
  22019. set to 1. 
  22020.  
  22021.         SV*     newSV _((STRLEN len));
  22022.  
  22023.  
  22024. ΓòÉΓòÉΓòÉ 33.75. newSViv ΓòÉΓòÉΓòÉ
  22025.  
  22026. newSViv 
  22027.  
  22028. Creates a new SV and copies an integer into it.  The refcount for the SV is set 
  22029. to 1. 
  22030.  
  22031.         SV*     newSViv _((IV i));
  22032.  
  22033.  
  22034. ΓòÉΓòÉΓòÉ 33.76. newSVnv ΓòÉΓòÉΓòÉ
  22035.  
  22036. newSVnv 
  22037.  
  22038. Creates a new SV and copies a double into it.  The refcount for the SV is set 
  22039. to 1. 
  22040.  
  22041.         SV*     newSVnv _((NV i));
  22042.  
  22043.  
  22044. ΓòÉΓòÉΓòÉ 33.77. newSVpv ΓòÉΓòÉΓòÉ
  22045.  
  22046. newSVpv 
  22047.  
  22048. Creates a new SV and copies a string into it.  The refcount for the SV is set 
  22049. to 1.  If len is zero then Perl will compute the length. 
  22050.  
  22051.         SV*     newSVpv _((char* s, STRLEN len));
  22052.  
  22053.  
  22054. ΓòÉΓòÉΓòÉ 33.78. newSVrv ΓòÉΓòÉΓòÉ
  22055.  
  22056. newSVrv 
  22057.  
  22058. Creates a new SV for the RV, rv, to point to.  If rv is not an RV then it will 
  22059. be upgraded one.  If classname is non-null then the new SV will be blessed in 
  22060. the specified package.  The new SV is returned and its refcount is 1. 
  22061.  
  22062.         SV*     newSVrv _((SV* rv, char* classname));
  22063.  
  22064.  
  22065. ΓòÉΓòÉΓòÉ 33.79. newSVsv ΓòÉΓòÉΓòÉ
  22066.  
  22067. newSVsv 
  22068.  
  22069. Creates a new SV which is an exact duplicate of the orignal SV. 
  22070.  
  22071.         SV*     newSVsv _((SV* old));
  22072.  
  22073.  
  22074. ΓòÉΓòÉΓòÉ 33.80. newXS ΓòÉΓòÉΓòÉ
  22075.  
  22076. newXS 
  22077.  
  22078. Used by xsubpp to hook up XSUBs as Perl subs. 
  22079.  
  22080.  
  22081. ΓòÉΓòÉΓòÉ 33.81. newXSproto ΓòÉΓòÉΓòÉ
  22082.  
  22083. newXSproto 
  22084.  
  22085. Used by xsubpp to hook up XSUBs as Perl subs.  Adds Perl prototypes to the 
  22086. subs. 
  22087.  
  22088.  
  22089. ΓòÉΓòÉΓòÉ 33.82. Nullav ΓòÉΓòÉΓòÉ
  22090.  
  22091. Nullav 
  22092.  
  22093. Null AV pointer. 
  22094.  
  22095.  
  22096. ΓòÉΓòÉΓòÉ 33.83. Nullch ΓòÉΓòÉΓòÉ
  22097.  
  22098. Nullch 
  22099.  
  22100. Null character pointer. 
  22101.  
  22102.  
  22103. ΓòÉΓòÉΓòÉ 33.84. Nullcv ΓòÉΓòÉΓòÉ
  22104.  
  22105. Nullcv 
  22106.  
  22107. Null CV pointer. 
  22108.  
  22109.  
  22110. ΓòÉΓòÉΓòÉ 33.85. Nullhv ΓòÉΓòÉΓòÉ
  22111.  
  22112. Nullhv 
  22113.  
  22114. Null HV pointer. 
  22115.  
  22116.  
  22117. ΓòÉΓòÉΓòÉ 33.86. Nullsv ΓòÉΓòÉΓòÉ
  22118.  
  22119. Nullsv 
  22120.  
  22121. Null SV pointer. 
  22122.  
  22123.  
  22124. ΓòÉΓòÉΓòÉ 33.87. ORIGMARK ΓòÉΓòÉΓòÉ
  22125.  
  22126. ORIGMARK 
  22127.  
  22128. The original stack mark for the XSUB.  See dORIGMARK. 
  22129.  
  22130.  
  22131. ΓòÉΓòÉΓòÉ 33.88. perl_alloc ΓòÉΓòÉΓòÉ
  22132.  
  22133. perl_alloc 
  22134.  
  22135. Allocates a new Perl interpreter.  See perlembed. 
  22136.  
  22137.  
  22138. ΓòÉΓòÉΓòÉ 33.89. perl_call_argv ΓòÉΓòÉΓòÉ
  22139.  
  22140. perl_call_argv 
  22141.  
  22142. Performs a callback to the specified Perl sub.  See perlcall. 
  22143.  
  22144.         I32     perl_call_argv _((char* subname, I32 flags, char** argv));
  22145.  
  22146.  
  22147. ΓòÉΓòÉΓòÉ 33.90. perl_call_method ΓòÉΓòÉΓòÉ
  22148.  
  22149. perl_call_method 
  22150.  
  22151. Performs a callback to the specified Perl method.  The blessed object must be 
  22152. on the stack.  See perlcall. 
  22153.  
  22154.         I32     perl_call_method _((char* methname, I32 flags));
  22155.  
  22156.  
  22157. ΓòÉΓòÉΓòÉ 33.91. perl_call_pv ΓòÉΓòÉΓòÉ
  22158.  
  22159. perl_call_pv 
  22160.  
  22161. Performs a callback to the specified Perl sub.  See perlcall. 
  22162.  
  22163.         I32     perl_call_pv _((char* subname, I32 flags));
  22164.  
  22165.  
  22166. ΓòÉΓòÉΓòÉ 33.92. perl_call_sv ΓòÉΓòÉΓòÉ
  22167.  
  22168. perl_call_sv 
  22169.  
  22170. Performs a callback to the Perl sub whose name is in the SV.  See perlcall. 
  22171.  
  22172.         I32     perl_call_sv _((SV* sv, I32 flags));
  22173.  
  22174.  
  22175. ΓòÉΓòÉΓòÉ 33.93. perl_construct ΓòÉΓòÉΓòÉ
  22176.  
  22177. perl_construct 
  22178.  
  22179. Initializes a new Perl interpreter.  See perlembed. 
  22180.  
  22181.  
  22182. ΓòÉΓòÉΓòÉ 33.94. perl_destruct ΓòÉΓòÉΓòÉ
  22183.  
  22184. perl_destruct 
  22185.  
  22186. Shuts down a Perl interpreter.  See perlembed. 
  22187.  
  22188.  
  22189. ΓòÉΓòÉΓòÉ 33.95. perl_eval_sv ΓòÉΓòÉΓòÉ
  22190.  
  22191. perl_eval_sv 
  22192.  
  22193. Tells Perl to eval the string in the SV. 
  22194.  
  22195.         I32     perl_eval_sv _((SV* sv, I32 flags));
  22196.  
  22197.  
  22198. ΓòÉΓòÉΓòÉ 33.96. perl_free ΓòÉΓòÉΓòÉ
  22199.  
  22200. perl_free 
  22201.  
  22202. Releases a Perl interpreter.  See perlembed. 
  22203.  
  22204.  
  22205. ΓòÉΓòÉΓòÉ 33.97. perl_get_av ΓòÉΓòÉΓòÉ
  22206.  
  22207. perl_get_av 
  22208.  
  22209. Returns the AV of the specified Perl array.  If create is set and the Perl 
  22210. variable does not exist then it will be created.  If create is not set and the 
  22211. variable does not exist then null is returned. 
  22212.  
  22213.         AV*     perl_get_av _((char* name, I32 create));
  22214.  
  22215.  
  22216. ΓòÉΓòÉΓòÉ 33.98. perl_get_cv ΓòÉΓòÉΓòÉ
  22217.  
  22218. perl_get_cv 
  22219.  
  22220. Returns the CV of the specified Perl sub.  If create is set and the Perl 
  22221. variable does not exist then it will be created.  If create is not set and the 
  22222. variable does not exist then null is returned. 
  22223.  
  22224.         CV*     perl_get_cv _((char* name, I32 create));
  22225.  
  22226.  
  22227. ΓòÉΓòÉΓòÉ 33.99. perl_get_hv ΓòÉΓòÉΓòÉ
  22228.  
  22229. perl_get_hv 
  22230.  
  22231. Returns the HV of the specified Perl hash.  If create is set and the Perl 
  22232. variable does not exist then it will be created.  If create is not set and the 
  22233. variable does not exist then null is returned. 
  22234.  
  22235.         HV*     perl_get_hv _((char* name, I32 create));
  22236.  
  22237.  
  22238. ΓòÉΓòÉΓòÉ 33.100. perl_get_sv ΓòÉΓòÉΓòÉ
  22239.  
  22240. perl_get_sv 
  22241.  
  22242. Returns the SV of the specified Perl scalar.  If create is set and the Perl 
  22243. variable does not exist then it will be created.  If create is not set and the 
  22244. variable does not exist then null is returned. 
  22245.  
  22246.         SV*     perl_get_sv _((char* name, I32 create));
  22247.  
  22248.  
  22249. ΓòÉΓòÉΓòÉ 33.101. perl_parse ΓòÉΓòÉΓòÉ
  22250.  
  22251. perl_parse 
  22252.  
  22253. Tells a Perl interpreter to parse a Perl script.  See perlembed. 
  22254.  
  22255.  
  22256. ΓòÉΓòÉΓòÉ 33.102. perl_require_pv ΓòÉΓòÉΓòÉ
  22257.  
  22258. perl_require_pv 
  22259.  
  22260. Tells Perl to require a module. 
  22261.  
  22262.         void    perl_require_pv _((char* pv));
  22263.  
  22264.  
  22265. ΓòÉΓòÉΓòÉ 33.103. perl_run ΓòÉΓòÉΓòÉ
  22266.  
  22267. perl_run 
  22268.  
  22269. Tells a Perl interpreter to run.  See perlembed. 
  22270.  
  22271.  
  22272. ΓòÉΓòÉΓòÉ 33.104. POPi ΓòÉΓòÉΓòÉ
  22273.  
  22274. POPi 
  22275.  
  22276. Pops an integer off the stack. 
  22277.  
  22278.         int POPi();
  22279.  
  22280.  
  22281. ΓòÉΓòÉΓòÉ 33.105. POPl ΓòÉΓòÉΓòÉ
  22282.  
  22283. POPl 
  22284.  
  22285. Pops a long off the stack. 
  22286.  
  22287.         long POPl();
  22288.  
  22289.  
  22290. ΓòÉΓòÉΓòÉ 33.106. POPp ΓòÉΓòÉΓòÉ
  22291.  
  22292. POPp 
  22293.  
  22294. Pops a string off the stack. 
  22295.  
  22296.         char * POPp();
  22297.  
  22298.  
  22299. ΓòÉΓòÉΓòÉ 33.107. POPn ΓòÉΓòÉΓòÉ
  22300.  
  22301. POPn 
  22302.  
  22303. Pops a double off the stack. 
  22304.  
  22305.         double POPn();
  22306.  
  22307.  
  22308. ΓòÉΓòÉΓòÉ 33.108. POPs ΓòÉΓòÉΓòÉ
  22309.  
  22310. POPs 
  22311.  
  22312. Pops an SV off the stack. 
  22313.  
  22314.         SV* POPs();
  22315.  
  22316.  
  22317. ΓòÉΓòÉΓòÉ 33.109. PUSHMARK ΓòÉΓòÉΓòÉ
  22318.  
  22319. PUSHMARK 
  22320.  
  22321. Opening bracket for arguments on a callback.  See PUTBACK and perlcall. 
  22322.  
  22323.         PUSHMARK(p)
  22324.  
  22325.  
  22326. ΓòÉΓòÉΓòÉ 33.110. PUSHi ΓòÉΓòÉΓòÉ
  22327.  
  22328. PUSHi 
  22329.  
  22330. Push an integer onto the stack.  The stack must have room for this element. See 
  22331. XPUSHi. 
  22332.  
  22333.         PUSHi(int d)
  22334.  
  22335.  
  22336. ΓòÉΓòÉΓòÉ 33.111. PUSHn ΓòÉΓòÉΓòÉ
  22337.  
  22338. PUSHn 
  22339.  
  22340. Push a double onto the stack.  The stack must have room for this element. See 
  22341. XPUSHn. 
  22342.  
  22343.         PUSHn(double d)
  22344.  
  22345.  
  22346. ΓòÉΓòÉΓòÉ 33.112. PUSHp ΓòÉΓòÉΓòÉ
  22347.  
  22348. PUSHp 
  22349.  
  22350. Push a string onto the stack.  The stack must have room for this element. The 
  22351. len indicates the length of the string.  See XPUSHp. 
  22352.  
  22353.         PUSHp(char *c, int len )
  22354.  
  22355.  
  22356. ΓòÉΓòÉΓòÉ 33.113. PUSHs ΓòÉΓòÉΓòÉ
  22357.  
  22358. PUSHs 
  22359.  
  22360. Push an SV onto the stack.  The stack must have room for this element.  See 
  22361. XPUSHs. 
  22362.  
  22363.         PUSHs(sv)
  22364.  
  22365.  
  22366. ΓòÉΓòÉΓòÉ 33.114. PUTBACK ΓòÉΓòÉΓòÉ
  22367.  
  22368. PUTBACK 
  22369.  
  22370. Closing bracket for XSUB arguments.  This is usually handled by xsubpp. See 
  22371. PUSHMARK and perlcall for other uses. 
  22372.  
  22373.         PUTBACK;
  22374.  
  22375.  
  22376. ΓòÉΓòÉΓòÉ 33.115. Renew ΓòÉΓòÉΓòÉ
  22377.  
  22378. Renew 
  22379.  
  22380. The XSUB-writer's interface to the C realloc function. 
  22381.  
  22382.         void * Renew( void *ptr, int size, type )
  22383.  
  22384.  
  22385. ΓòÉΓòÉΓòÉ 33.116. Renewc ΓòÉΓòÉΓòÉ
  22386.  
  22387. Renewc 
  22388.  
  22389. The XSUB-writer's interface to the C realloc function, with cast. 
  22390.  
  22391.         void * Renewc( void *ptr, int size, type, cast )
  22392.  
  22393.  
  22394. ΓòÉΓòÉΓòÉ 33.117. RETVAL ΓòÉΓòÉΓòÉ
  22395.  
  22396. RETVAL 
  22397.  
  22398. Variable which is setup by xsubpp to hold the return value for an XSUB. This is 
  22399. always the proper type for the XSUB.  See perlxs. 
  22400.  
  22401.  
  22402. ΓòÉΓòÉΓòÉ 33.118. safefree ΓòÉΓòÉΓòÉ
  22403.  
  22404. safefree 
  22405.  
  22406. The XSUB-writer's interface to the C free function. 
  22407.  
  22408.  
  22409. ΓòÉΓòÉΓòÉ 33.119. safemalloc ΓòÉΓòÉΓòÉ
  22410.  
  22411. safemalloc 
  22412.  
  22413. The XSUB-writer's interface to the C malloc function. 
  22414.  
  22415.  
  22416. ΓòÉΓòÉΓòÉ 33.120. saferealloc ΓòÉΓòÉΓòÉ
  22417.  
  22418. saferealloc 
  22419.  
  22420. The XSUB-writer's interface to the C realloc function. 
  22421.  
  22422.  
  22423. ΓòÉΓòÉΓòÉ 33.121. savepv ΓòÉΓòÉΓòÉ
  22424.  
  22425. savepv 
  22426.  
  22427. Copy a string to a safe spot.  This does not use an SV. 
  22428.  
  22429.         char*   savepv _((char* sv));
  22430.  
  22431.  
  22432. ΓòÉΓòÉΓòÉ 33.122. savepvn ΓòÉΓòÉΓòÉ
  22433.  
  22434. savepvn 
  22435.  
  22436. Copy a string to a safe spot.  The len indicates number of bytes to copy.  This 
  22437. does not use an SV. 
  22438.  
  22439.         char*   savepvn _((char* sv, I32 len));
  22440.  
  22441.  
  22442. ΓòÉΓòÉΓòÉ 33.123. SAVETMPS ΓòÉΓòÉΓòÉ
  22443.  
  22444. SAVETMPS 
  22445.  
  22446. Opening bracket for temporaries on a callback.  See FREETMPS and perlcall. 
  22447.  
  22448.         SAVETMPS;
  22449.  
  22450.  
  22451. ΓòÉΓòÉΓòÉ 33.124. SP ΓòÉΓòÉΓòÉ
  22452.  
  22453. SP 
  22454.  
  22455. Stack pointer.  This is usually handled by xsubpp.  See dSP and SPAGAIN. 
  22456.  
  22457.  
  22458. ΓòÉΓòÉΓòÉ 33.125. SPAGAIN ΓòÉΓòÉΓòÉ
  22459.  
  22460. SPAGAIN 
  22461.  
  22462. Refetch the stack pointer.  Used after a callback.  See perlcall. 
  22463.  
  22464.         SPAGAIN;
  22465.  
  22466.  
  22467. ΓòÉΓòÉΓòÉ 33.126. ST ΓòÉΓòÉΓòÉ
  22468.  
  22469. ST 
  22470.  
  22471. Used to access elements on the XSUB's stack. 
  22472.  
  22473.         SV* ST(int x)
  22474.  
  22475.  
  22476. ΓòÉΓòÉΓòÉ 33.127. strEQ ΓòÉΓòÉΓòÉ
  22477.  
  22478. strEQ 
  22479.  
  22480. Test two strings to see if they are equal.  Returns true or false. 
  22481.  
  22482.         int strEQ( char *s1, char *s2 )
  22483.  
  22484.  
  22485. ΓòÉΓòÉΓòÉ 33.128. strGE ΓòÉΓòÉΓòÉ
  22486.  
  22487. strGE 
  22488.  
  22489. Test two strings to see if the first, s1, is greater than or equal to the 
  22490. second, s2.  Returns true or false. 
  22491.  
  22492.         int strGE( char *s1, char *s2 )
  22493.  
  22494.  
  22495. ΓòÉΓòÉΓòÉ 33.129. strGT ΓòÉΓòÉΓòÉ
  22496.  
  22497. strGT 
  22498.  
  22499. Test two strings to see if the first, s1, is greater than the second, s2. 
  22500. Returns true or false. 
  22501.  
  22502.         int strGT( char *s1, char *s2 )
  22503.  
  22504.  
  22505. ΓòÉΓòÉΓòÉ 33.130. strLE ΓòÉΓòÉΓòÉ
  22506.  
  22507. strLE 
  22508.  
  22509. Test two strings to see if the first, s1, is less than or equal to the second, 
  22510. s2.  Returns true or false. 
  22511.  
  22512.         int strLE( char *s1, char *s2 )
  22513.  
  22514.  
  22515. ΓòÉΓòÉΓòÉ 33.131. strLT ΓòÉΓòÉΓòÉ
  22516.  
  22517. strLT 
  22518.  
  22519. Test two strings to see if the first, s1, is less than the second, s2.  Returns 
  22520. true or false. 
  22521.  
  22522.         int strLT( char *s1, char *s2 )
  22523.  
  22524.  
  22525. ΓòÉΓòÉΓòÉ 33.132. strNE ΓòÉΓòÉΓòÉ
  22526.  
  22527. strNE 
  22528.  
  22529. Test two strings to see if they are different.  Returns true or false. 
  22530.  
  22531.         int strNE( char *s1, char *s2 )
  22532.  
  22533.  
  22534. ΓòÉΓòÉΓòÉ 33.133. strnEQ ΓòÉΓòÉΓòÉ
  22535.  
  22536. strnEQ 
  22537.  
  22538. Test two strings to see if they are equal.  The len parameter indicates the 
  22539. number of bytes to compare.  Returns true or false. 
  22540.  
  22541.         int strnEQ( char *s1, char *s2 )
  22542.  
  22543.  
  22544. ΓòÉΓòÉΓòÉ 33.134. strnNE ΓòÉΓòÉΓòÉ
  22545.  
  22546. strnNE 
  22547.  
  22548. Test two strings to see if they are different.  The len parameter indicates the 
  22549. number of bytes to compare.  Returns true or false. 
  22550.  
  22551.         int strnNE( char *s1, char *s2, int len )
  22552.  
  22553.  
  22554. ΓòÉΓòÉΓòÉ 33.135. sv_2mortal ΓòÉΓòÉΓòÉ
  22555.  
  22556. sv_2mortal 
  22557.  
  22558. Marks an SV as mortal.  The SV will be destroyed when the current context ends. 
  22559.  
  22560.         SV*     sv_2mortal _((SV* sv));
  22561.  
  22562.  
  22563. ΓòÉΓòÉΓòÉ 33.136. sv_bless ΓòÉΓòÉΓòÉ
  22564.  
  22565. sv_bless 
  22566.  
  22567. Blesses an SV into a specified package.  The SV must be an RV.  The package 
  22568. must be designated by its stash (see gv_stashpv()).  The refcount of the SV is 
  22569. unaffected. 
  22570.  
  22571.         SV*     sv_bless _((SV* sv, HV* stash));
  22572.  
  22573.  
  22574. ΓòÉΓòÉΓòÉ 33.137. sv_catpv ΓòÉΓòÉΓòÉ
  22575.  
  22576. sv_catpv 
  22577.  
  22578. Concatenates the string onto the end of the string which is in the SV. 
  22579.  
  22580.         void    sv_catpv _((SV* sv, char* ptr));
  22581.  
  22582.  
  22583. ΓòÉΓòÉΓòÉ 33.138. sv_catpvn ΓòÉΓòÉΓòÉ
  22584.  
  22585. sv_catpvn 
  22586.  
  22587. Concatenates the string onto the end of the string which is in the SV.  The len 
  22588. indicates number of bytes to copy. 
  22589.  
  22590.         void    sv_catpvn _((SV* sv, char* ptr, STRLEN len));
  22591.  
  22592.  
  22593. ΓòÉΓòÉΓòÉ 33.139. sv_catsv ΓòÉΓòÉΓòÉ
  22594.  
  22595. sv_catsv 
  22596.  
  22597. Concatentates the string from SV ssv onto the end of the string in SV dsv. 
  22598.  
  22599.         void    sv_catsv _((SV* dsv, SV* ssv));
  22600.  
  22601.  
  22602. ΓòÉΓòÉΓòÉ 33.140. SvCUR ΓòÉΓòÉΓòÉ
  22603.  
  22604. SvCUR 
  22605.  
  22606. Returns the length of the string which is in the SV.  See SvLEN. 
  22607.  
  22608.         int SvCUR (SV* sv)
  22609.  
  22610.  
  22611. ΓòÉΓòÉΓòÉ 33.141. SvCUR_set ΓòÉΓòÉΓòÉ
  22612.  
  22613. SvCUR_set 
  22614.  
  22615. Set the length of the string which is in the SV.  See SvCUR. 
  22616.  
  22617.         SvCUR_set (SV* sv, int val )
  22618.  
  22619.  
  22620. ΓòÉΓòÉΓòÉ 33.142. SvEND ΓòÉΓòÉΓòÉ
  22621.  
  22622. SvEND 
  22623.  
  22624. Returns a pointer to the last character in the string which is in the SV. See 
  22625. SvCUR.  Access the character as 
  22626.  
  22627.         *SvEND(sv)
  22628.  
  22629.  
  22630. ΓòÉΓòÉΓòÉ 33.143. SvGROW ΓòÉΓòÉΓòÉ
  22631.  
  22632. SvGROW 
  22633.  
  22634. Expands the character buffer in the SV. 
  22635.  
  22636.         char * SvGROW( SV* sv, int len )
  22637.  
  22638.  
  22639. ΓòÉΓòÉΓòÉ 33.144. SvIOK ΓòÉΓòÉΓòÉ
  22640.  
  22641. SvIOK 
  22642.  
  22643. Returns a boolean indicating whether the SV contains an integer. 
  22644.  
  22645.         int SvIOK (SV* SV)
  22646.  
  22647.  
  22648. ΓòÉΓòÉΓòÉ 33.145. SvIOK_off ΓòÉΓòÉΓòÉ
  22649.  
  22650. SvIOK_off 
  22651.  
  22652. Unsets the IV status of an SV. 
  22653.  
  22654.         SvIOK_off (SV* sv)
  22655.  
  22656.  
  22657. ΓòÉΓòÉΓòÉ 33.146. SvIOK_on ΓòÉΓòÉΓòÉ
  22658.  
  22659. SvIOK_on 
  22660.  
  22661. Tells an SV that it is an integer. 
  22662.  
  22663.         SvIOK_on (SV* sv)
  22664.  
  22665.  
  22666. ΓòÉΓòÉΓòÉ 33.147. SvIOKp ΓòÉΓòÉΓòÉ
  22667.  
  22668. SvIOKp 
  22669.  
  22670. Returns a boolean indicating whether the SV contains an integer.  Checks the 
  22671. private setting.  Use SvIOK. 
  22672.  
  22673.         int SvIOKp (SV* SV)
  22674.  
  22675.  
  22676. ΓòÉΓòÉΓòÉ 33.148. sv_isa ΓòÉΓòÉΓòÉ
  22677.  
  22678. sv_isa 
  22679.  
  22680. Returns a boolean indicating whether the SV is blessed into the specified 
  22681. class.  This does not know how to check for subtype, so it doesn't work in an 
  22682. inheritance relationship. 
  22683.  
  22684.         int     sv_isa _((SV* sv, char* name));
  22685.  
  22686.  
  22687. ΓòÉΓòÉΓòÉ 33.149. SvIV ΓòÉΓòÉΓòÉ
  22688.  
  22689. SvIV 
  22690.  
  22691. Returns the integer which is in the SV. 
  22692.  
  22693.         int SvIV (SV* sv)
  22694.  
  22695.  
  22696. ΓòÉΓòÉΓòÉ 33.150. sv_isobject ΓòÉΓòÉΓòÉ
  22697.  
  22698. sv_isobject 
  22699.  
  22700. Returns a boolean indicating whether the SV is an RV pointing to a blessed 
  22701. object.  If the SV is not an RV, or if the object is not blessed, then this 
  22702. will return false. 
  22703.  
  22704.         int     sv_isobject _((SV* sv));
  22705.  
  22706.  
  22707. ΓòÉΓòÉΓòÉ 33.151. SvIVX ΓòÉΓòÉΓòÉ
  22708.  
  22709. SvIVX 
  22710.  
  22711. Returns the integer which is stored in the SV. 
  22712.  
  22713.         int  SvIVX (SV* sv);
  22714.  
  22715.  
  22716. ΓòÉΓòÉΓòÉ 33.152. SvLEN ΓòÉΓòÉΓòÉ
  22717.  
  22718. SvLEN 
  22719.  
  22720. Returns the size of the string buffer in the SV.  See SvCUR. 
  22721.  
  22722.         int SvLEN (SV* sv)
  22723.  
  22724.  
  22725. ΓòÉΓòÉΓòÉ 33.153. sv_magic ΓòÉΓòÉΓòÉ
  22726.  
  22727. sv_magic 
  22728.  
  22729. Adds magic to an SV. 
  22730.  
  22731.         void    sv_magic _((SV* sv, SV* obj, int how, char* name, I32 namlen));
  22732.  
  22733.  
  22734. ΓòÉΓòÉΓòÉ 33.154. sv_mortalcopy ΓòÉΓòÉΓòÉ
  22735.  
  22736. sv_mortalcopy 
  22737.  
  22738. Creates a new SV which is a copy of the original SV.  The new SV is marked as 
  22739. mortal. 
  22740.  
  22741.         SV*     sv_mortalcopy _((SV* oldsv));
  22742.  
  22743.  
  22744. ΓòÉΓòÉΓòÉ 33.155. SvOK ΓòÉΓòÉΓòÉ
  22745.  
  22746. SvOK 
  22747.  
  22748. Returns a boolean indicating whether the value is an SV. 
  22749.  
  22750.         int SvOK (SV* sv)
  22751.  
  22752.  
  22753. ΓòÉΓòÉΓòÉ 33.156. sv_newmortal ΓòÉΓòÉΓòÉ
  22754.  
  22755. sv_newmortal 
  22756.  
  22757. Creates a new SV which is mortal.  The refcount of the SV is set to 1. 
  22758.  
  22759.         SV*     sv_newmortal _((void));
  22760.  
  22761.  
  22762. ΓòÉΓòÉΓòÉ 33.157. sv_no ΓòÉΓòÉΓòÉ
  22763.  
  22764. sv_no 
  22765.  
  22766. This is the false SV.  See sv_yes.  Always refer to this as &sv_no. 
  22767.  
  22768.  
  22769. ΓòÉΓòÉΓòÉ 33.158. SvNIOK ΓòÉΓòÉΓòÉ
  22770.  
  22771. SvNIOK 
  22772.  
  22773. Returns a boolean indicating whether the SV contains a number, integer or 
  22774. double. 
  22775.  
  22776.         int SvNIOK (SV* SV)
  22777.  
  22778.  
  22779. ΓòÉΓòÉΓòÉ 33.159. SvNIOK_off ΓòÉΓòÉΓòÉ
  22780.  
  22781. SvNIOK_off 
  22782.  
  22783. Unsets the NV/IV status of an SV. 
  22784.  
  22785.         SvNIOK_off (SV* sv)
  22786.  
  22787.  
  22788. ΓòÉΓòÉΓòÉ 33.160. SvNIOKp ΓòÉΓòÉΓòÉ
  22789.  
  22790. SvNIOKp 
  22791.  
  22792. Returns a boolean indicating whether the SV contains a number, integer or 
  22793. double.  Checks the private setting.  Use SvNIOK. 
  22794.  
  22795.         int SvNIOKp (SV* SV)
  22796.  
  22797.  
  22798. ΓòÉΓòÉΓòÉ 33.161. SvNOK ΓòÉΓòÉΓòÉ
  22799.  
  22800. SvNOK 
  22801.  
  22802. Returns a boolean indicating whether the SV contains a double. 
  22803.  
  22804.         int SvNOK (SV* SV)
  22805.  
  22806.  
  22807. ΓòÉΓòÉΓòÉ 33.162. SvNOK_off ΓòÉΓòÉΓòÉ
  22808.  
  22809. SvNOK_off 
  22810.  
  22811. Unsets the NV status of an SV. 
  22812.  
  22813.         SvNOK_off (SV* sv)
  22814.  
  22815.  
  22816. ΓòÉΓòÉΓòÉ 33.163. SvNOK_on ΓòÉΓòÉΓòÉ
  22817.  
  22818. SvNOK_on 
  22819.  
  22820. Tells an SV that it is a double. 
  22821.  
  22822.         SvNOK_on (SV* sv)
  22823.  
  22824.  
  22825. ΓòÉΓòÉΓòÉ 33.164. SvNOKp ΓòÉΓòÉΓòÉ
  22826.  
  22827. SvNOKp 
  22828.  
  22829. Returns a boolean indicating whether the SV contains a double.  Checks the 
  22830. private setting.  Use SvNOK. 
  22831.  
  22832.         int SvNOKp (SV* SV)
  22833.  
  22834.  
  22835. ΓòÉΓòÉΓòÉ 33.165. SvNV ΓòÉΓòÉΓòÉ
  22836.  
  22837. SvNV 
  22838.  
  22839. Returns the double which is stored in the SV. 
  22840.  
  22841.         double SvNV (SV* sv);
  22842.  
  22843.  
  22844. ΓòÉΓòÉΓòÉ 33.166. SvNVX ΓòÉΓòÉΓòÉ
  22845.  
  22846. SvNVX 
  22847.  
  22848. Returns the double which is stored in the SV. 
  22849.  
  22850.         double SvNVX (SV* sv);
  22851.  
  22852.  
  22853. ΓòÉΓòÉΓòÉ 33.167. SvPOK ΓòÉΓòÉΓòÉ
  22854.  
  22855. SvPOK 
  22856.  
  22857. Returns a boolean indicating whether the SV contains a character string. 
  22858.  
  22859.         int SvPOK (SV* SV)
  22860.  
  22861.  
  22862. ΓòÉΓòÉΓòÉ 33.168. SvPOK_off ΓòÉΓòÉΓòÉ
  22863.  
  22864. SvPOK_off 
  22865.  
  22866. Unsets the PV status of an SV. 
  22867.  
  22868.         SvPOK_off (SV* sv)
  22869.  
  22870.  
  22871. ΓòÉΓòÉΓòÉ 33.169. SvPOK_on ΓòÉΓòÉΓòÉ
  22872.  
  22873. SvPOK_on 
  22874.  
  22875. Tells an SV that it is a string. 
  22876.  
  22877.         SvPOK_on (SV* sv)
  22878.  
  22879.  
  22880. ΓòÉΓòÉΓòÉ 33.170. SvPOKp ΓòÉΓòÉΓòÉ
  22881.  
  22882. SvPOKp 
  22883.  
  22884. Returns a boolean indicating whether the SV contains a character string. Checks 
  22885. the private setting.  Use SvPOK. 
  22886.  
  22887.         int SvPOKp (SV* SV)
  22888.  
  22889.  
  22890. ΓòÉΓòÉΓòÉ 33.171. SvPV ΓòÉΓòÉΓòÉ
  22891.  
  22892. SvPV 
  22893.  
  22894. Returns a pointer to the string in the SV, or a stringified form of the SV if 
  22895. the SV does not contain a string.  If len is na then Perl will handle the 
  22896. length on its own. 
  22897.  
  22898.         char * SvPV (SV* sv, int len )
  22899.  
  22900.  
  22901. ΓòÉΓòÉΓòÉ 33.172. SvPVX ΓòÉΓòÉΓòÉ
  22902.  
  22903. SvPVX 
  22904.  
  22905. Returns a pointer to the string in the SV.  The SV must contain a string. 
  22906.  
  22907.         char * SvPVX (SV* sv)
  22908.  
  22909.  
  22910. ΓòÉΓòÉΓòÉ 33.173. SvREFCNT ΓòÉΓòÉΓòÉ
  22911.  
  22912. SvREFCNT 
  22913.  
  22914. Returns the value of the object's refcount. 
  22915.  
  22916.         int SvREFCNT (SV* sv);
  22917.  
  22918.  
  22919. ΓòÉΓòÉΓòÉ 33.174. SvREFCNT_dec ΓòÉΓòÉΓòÉ
  22920.  
  22921. SvREFCNT_dec 
  22922.  
  22923. Decrements the refcount of the given SV. 
  22924.  
  22925.         void SvREFCNT_dec (SV* sv)
  22926.  
  22927.  
  22928. ΓòÉΓòÉΓòÉ 33.175. SvREFCNT_inc ΓòÉΓòÉΓòÉ
  22929.  
  22930. SvREFCNT_inc 
  22931.  
  22932. Increments the refcount of the given SV. 
  22933.  
  22934.         void SvREFCNT_inc (SV* sv)
  22935.  
  22936.  
  22937. ΓòÉΓòÉΓòÉ 33.176. SvROK ΓòÉΓòÉΓòÉ
  22938.  
  22939. SvROK 
  22940.  
  22941. Tests if the SV is an RV. 
  22942.  
  22943.         int SvROK (SV* sv)
  22944.  
  22945.  
  22946. ΓòÉΓòÉΓòÉ 33.177. SvROK_off ΓòÉΓòÉΓòÉ
  22947.  
  22948. SvROK_off 
  22949.  
  22950. Unsets the RV status of an SV. 
  22951.  
  22952.         SvROK_off (SV* sv)
  22953.  
  22954.  
  22955. ΓòÉΓòÉΓòÉ 33.178. SvROK_on ΓòÉΓòÉΓòÉ
  22956.  
  22957. SvROK_on 
  22958.  
  22959. Tells an SV that it is an RV. 
  22960.  
  22961.         SvROK_on (SV* sv)
  22962.  
  22963.  
  22964. ΓòÉΓòÉΓòÉ 33.179. SvRV ΓòÉΓòÉΓòÉ
  22965.  
  22966. SvRV 
  22967.  
  22968. Dereferences an RV to return the SV. 
  22969.  
  22970.         SV*     SvRV (SV* sv);
  22971.  
  22972.  
  22973. ΓòÉΓòÉΓòÉ 33.180. sv_setiv ΓòÉΓòÉΓòÉ
  22974.  
  22975. sv_setiv 
  22976.  
  22977. Copies an integer into the given SV. 
  22978.  
  22979.         void    sv_setiv _((SV* sv, IV num));
  22980.  
  22981.  
  22982. ΓòÉΓòÉΓòÉ 33.181. sv_setnv ΓòÉΓòÉΓòÉ
  22983.  
  22984. sv_setnv 
  22985.  
  22986. Copies a double into the given SV. 
  22987.  
  22988.         void    sv_setnv _((SV* sv, double num));
  22989.  
  22990.  
  22991. ΓòÉΓòÉΓòÉ 33.182. sv_setpv ΓòÉΓòÉΓòÉ
  22992.  
  22993. sv_setpv 
  22994.  
  22995. Copies a string into an SV.  The string must be null-terminated. 
  22996.  
  22997.         void    sv_setpv _((SV* sv, char* ptr));
  22998.  
  22999.  
  23000. ΓòÉΓòÉΓòÉ 33.183. sv_setpvn ΓòÉΓòÉΓòÉ
  23001.  
  23002. sv_setpvn 
  23003.  
  23004. Copies a string into an SV.  The len parameter indicates the number of bytes to 
  23005. be copied. 
  23006.  
  23007.         void    sv_setpvn _((SV* sv, char* ptr, STRLEN len));
  23008.  
  23009.  
  23010. ΓòÉΓòÉΓòÉ 33.184. sv_setref_iv ΓòÉΓòÉΓòÉ
  23011.  
  23012. sv_setref_iv 
  23013.  
  23014. Copies an integer into an SV, optionally blessing the SV.  The SV must be an 
  23015. RV.  The classname argument indicates the package for the blessing.  Set 
  23016. classname to Nullch to avoid the blessing.  The new SV will be returned and 
  23017. will have a refcount of 1. 
  23018.  
  23019.         SV*     sv_setref_iv _((SV *rv, char *classname, IV iv));
  23020.  
  23021.  
  23022. ΓòÉΓòÉΓòÉ 33.185. sv_setref_nv ΓòÉΓòÉΓòÉ
  23023.  
  23024. sv_setref_nv 
  23025.  
  23026. Copies a double into an SV, optionally blessing the SV.  The SV must be an RV. 
  23027. The classname argument indicates the package for the blessing.  Set classname 
  23028. to Nullch to avoid the blessing.  The new SV will be returned and will have a 
  23029. refcount of 1. 
  23030.  
  23031.         SV*     sv_setref_nv _((SV *rv, char *classname, double nv));
  23032.  
  23033.  
  23034. ΓòÉΓòÉΓòÉ 33.186. sv_setref_pv ΓòÉΓòÉΓòÉ
  23035.  
  23036. sv_setref_pv 
  23037.  
  23038. Copies a pointer into an SV, optionally blessing the SV.  The SV must be an RV. 
  23039. If the pv argument is NULL then sv_undef will be placed into the SV.  The 
  23040. classname argument indicates the package for the blessing.  Set classname to 
  23041. Nullch to avoid the blessing.  The new SV will be returned and will have a 
  23042. refcount of 1. 
  23043.  
  23044.         SV*     sv_setref_pv _((SV *rv, char *classname, void* pv));
  23045.  
  23046. Do not use with integral Perl types such as HV, AV, SV, CV, because those 
  23047. objects will become corrupted by the pointer copy process. 
  23048.  
  23049. Note that sv_setref_pvn copies the string while this copies the pointer. 
  23050.  
  23051.  
  23052. ΓòÉΓòÉΓòÉ 33.187. sv_setref_pvn ΓòÉΓòÉΓòÉ
  23053.  
  23054. sv_setref_pvn 
  23055.  
  23056. Copies a string into an SV, optionally blessing the SV.  The lenth of the 
  23057. string must be specified with n.  The SV must be an RV.  The classname argument 
  23058. indicates the package for the blessing.  Set classname to Nullch to avoid the 
  23059. blessing.  The new SV will be returned and will have a refcount of 1. 
  23060.  
  23061.         SV*     sv_setref_pvn _((SV *rv, char *classname, char* pv, I32 n));
  23062.  
  23063. Note that sv_setref_pv copies the pointer while this copies the string. 
  23064.  
  23065.  
  23066. ΓòÉΓòÉΓòÉ 33.188. sv_setsv ΓòÉΓòÉΓòÉ
  23067.  
  23068. sv_setsv 
  23069.  
  23070. Copies the contents of the source SV ssv into the destination SV dsv. 
  23071.  
  23072.         void    sv_setsv _((SV* dsv, SV* ssv));
  23073.  
  23074.  
  23075. ΓòÉΓòÉΓòÉ 33.189. SvSTASH ΓòÉΓòÉΓòÉ
  23076.  
  23077. SvSTASH 
  23078.  
  23079. Returns the stash of the SV. 
  23080.  
  23081.         HV * SvSTASH (SV* sv)
  23082.  
  23083.  
  23084. ΓòÉΓòÉΓòÉ 33.190. SVt_IV ΓòÉΓòÉΓòÉ
  23085.  
  23086. SVt_IV 
  23087.  
  23088. Integer type flag for scalars.  See svtype. 
  23089.  
  23090.  
  23091. ΓòÉΓòÉΓòÉ 33.191. SVt_PV ΓòÉΓòÉΓòÉ
  23092.  
  23093. SVt_PV 
  23094.  
  23095. Pointer type flag for scalars.  See svtype. 
  23096.  
  23097.  
  23098. ΓòÉΓòÉΓòÉ 33.192. SVt_PVAV ΓòÉΓòÉΓòÉ
  23099.  
  23100. SVt_PVAV 
  23101.  
  23102. Type flag for arrays.  See svtype. 
  23103.  
  23104.  
  23105. ΓòÉΓòÉΓòÉ 33.193. SVt_PVCV ΓòÉΓòÉΓòÉ
  23106.  
  23107. SVt_PVCV 
  23108.  
  23109. Type flag for code refs.  See svtype. 
  23110.  
  23111.  
  23112. ΓòÉΓòÉΓòÉ 33.194. SVt_PVHV ΓòÉΓòÉΓòÉ
  23113.  
  23114. SVt_PVHV 
  23115.  
  23116. Type flag for hashes.  See svtype. 
  23117.  
  23118.  
  23119. ΓòÉΓòÉΓòÉ 33.195. SVt_PVMG ΓòÉΓòÉΓòÉ
  23120.  
  23121. SVt_PVMG 
  23122.  
  23123. Type flag for blessed scalars.  See svtype. 
  23124.  
  23125.  
  23126. ΓòÉΓòÉΓòÉ 33.196. SVt_NV ΓòÉΓòÉΓòÉ
  23127.  
  23128. SVt_NV 
  23129.  
  23130. Double type flag for scalars.  See svtype. 
  23131.  
  23132.  
  23133. ΓòÉΓòÉΓòÉ 33.197. SvTRUE ΓòÉΓòÉΓòÉ
  23134.  
  23135. SvTRUE 
  23136.  
  23137. Returns a boolean indicating whether Perl would evaluate the SV as true or 
  23138. false, defined or undefined. 
  23139.  
  23140.         int SvTRUE (SV* sv)
  23141.  
  23142.  
  23143. ΓòÉΓòÉΓòÉ 33.198. SvTYPE ΓòÉΓòÉΓòÉ
  23144.  
  23145. SvTYPE 
  23146.  
  23147. Returns the type of the SV.  See svtype. 
  23148.  
  23149.         svtype  SvTYPE (SV* sv)
  23150.  
  23151.  
  23152. ΓòÉΓòÉΓòÉ 33.199. svtype ΓòÉΓòÉΓòÉ
  23153.  
  23154. svtype 
  23155.  
  23156. An enum of flags for Perl types.  These are found in the file sv.h in the 
  23157. svtype enum.  Test these flags with the SvTYPE macro. 
  23158.  
  23159.  
  23160. ΓòÉΓòÉΓòÉ 33.200. SvUPGRADE ΓòÉΓòÉΓòÉ
  23161.  
  23162. SvUPGRADE 
  23163.  
  23164. Used to upgrade an SV to a more complex form.  See svtype. 
  23165.  
  23166.  
  23167. ΓòÉΓòÉΓòÉ 33.201. sv_undef ΓòÉΓòÉΓòÉ
  23168.  
  23169. sv_undef 
  23170.  
  23171. This is the undef SV.  Always refer to this as &sv_undef. 
  23172.  
  23173.  
  23174. ΓòÉΓòÉΓòÉ 33.202. sv_usepvn ΓòÉΓòÉΓòÉ
  23175.  
  23176. sv_usepvn 
  23177.  
  23178. Tells an SV to use ptr to find its string value.  Normally the string is stored 
  23179. inside the SV; this allows the SV to use an outside string.  The string length, 
  23180. len, must be supplied.  This function will realloc the memory pointed to by 
  23181. ptr, so that pointer should not be freed or used by the programmer after giving 
  23182. it to sv_usepvn. 
  23183.  
  23184.         void    sv_usepvn _((SV* sv, char* ptr, STRLEN len));
  23185.  
  23186.  
  23187. ΓòÉΓòÉΓòÉ 33.203. sv_yes ΓòÉΓòÉΓòÉ
  23188.  
  23189. sv_yes 
  23190.  
  23191. This is the true SV.  See sv_no.  Always refer to this as &sv_yes. 
  23192.  
  23193.  
  23194. ΓòÉΓòÉΓòÉ 33.204. THIS ΓòÉΓòÉΓòÉ
  23195.  
  23196. THIS 
  23197.  
  23198. Variable which is setup by xsubpp to designate the object in a C++ XSUB. This 
  23199. is always the proper type for the C++ object.  See CLASS and perlxs. 
  23200.  
  23201.  
  23202. ΓòÉΓòÉΓòÉ 33.205. toLOWER ΓòÉΓòÉΓòÉ
  23203.  
  23204. toLOWER 
  23205.  
  23206. Converts the specified character to lowercase. 
  23207.  
  23208.         int toLOWER (char c)
  23209.  
  23210.  
  23211. ΓòÉΓòÉΓòÉ 33.206. toUPPER ΓòÉΓòÉΓòÉ
  23212.  
  23213. toUPPER 
  23214.  
  23215. Converts the specified character to uppercase. 
  23216.  
  23217.         int toUPPER (char c)
  23218.  
  23219.  
  23220. ΓòÉΓòÉΓòÉ 33.207. warn ΓòÉΓòÉΓòÉ
  23221.  
  23222. warn 
  23223.  
  23224. This is the XSUB-writer's interface to Perl's warn function.  Use this function 
  23225. the same way you use the C printf function.  See croak(). 
  23226.  
  23227.  
  23228. ΓòÉΓòÉΓòÉ 33.208. XPUSHi ΓòÉΓòÉΓòÉ
  23229.  
  23230. XPUSHi 
  23231.  
  23232. Push an integer onto the stack, extending the stack if necessary.  See PUSHi. 
  23233.  
  23234.         XPUSHi(int d)
  23235.  
  23236.  
  23237. ΓòÉΓòÉΓòÉ 33.209. XPUSHn ΓòÉΓòÉΓòÉ
  23238.  
  23239. XPUSHn 
  23240.  
  23241. Push a double onto the stack, extending the stack if necessary.  See PUSHn. 
  23242.  
  23243.         XPUSHn(double d)
  23244.  
  23245.  
  23246. ΓòÉΓòÉΓòÉ 33.210. XPUSHp ΓòÉΓòÉΓòÉ
  23247.  
  23248. XPUSHp 
  23249.  
  23250. Push a string onto the stack, extending the stack if necessary.  The len 
  23251. indicates the length of the string.  See PUSHp. 
  23252.  
  23253.         XPUSHp(char *c, int len)
  23254.  
  23255.  
  23256. ΓòÉΓòÉΓòÉ 33.211. XPUSHs ΓòÉΓòÉΓòÉ
  23257.  
  23258. XPUSHs 
  23259.  
  23260. Push an SV onto the stack, extending the stack if necessary.  See PUSHs. 
  23261.  
  23262.         XPUSHs(sv)
  23263.  
  23264.  
  23265. ΓòÉΓòÉΓòÉ 33.212. XSRETURN ΓòÉΓòÉΓòÉ
  23266.  
  23267. XSRETURN 
  23268.  
  23269. Return from XSUB, indicating number of items on the stack.  This is usually 
  23270. handled by xsubpp. 
  23271.  
  23272.         XSRETURN(x);
  23273.  
  23274.  
  23275. ΓòÉΓòÉΓòÉ 33.213. XSRETURN_EMPTY ΓòÉΓòÉΓòÉ
  23276.  
  23277. XSRETURN_EMPTY 
  23278.  
  23279. Return from an XSUB immediately. 
  23280.  
  23281.         XSRETURN_EMPTY;
  23282.  
  23283.  
  23284. ΓòÉΓòÉΓòÉ 33.214. XSRETURN_NO ΓòÉΓòÉΓòÉ
  23285.  
  23286. XSRETURN_NO 
  23287.  
  23288. Return false from an XSUB immediately. 
  23289.  
  23290.         XSRETURN_NO;
  23291.  
  23292.  
  23293. ΓòÉΓòÉΓòÉ 33.215. XSRETURN_UNDEF ΓòÉΓòÉΓòÉ
  23294.  
  23295. XSRETURN_UNDEF 
  23296.  
  23297. Return undef from an XSUB immediately. 
  23298.  
  23299.         XSRETURN_UNDEF;
  23300.  
  23301.  
  23302. ΓòÉΓòÉΓòÉ 33.216. XSRETURN_YES ΓòÉΓòÉΓòÉ
  23303.  
  23304. XSRETURN_YES 
  23305.  
  23306. Return true from an XSUB immediately. 
  23307.  
  23308.         XSRETURN_YES;
  23309.  
  23310.  
  23311. ΓòÉΓòÉΓòÉ 33.217. Zero ΓòÉΓòÉΓòÉ
  23312.  
  23313. Zero 
  23314.  
  23315. The XSUB-writer's interface to the C memzero function.  The d is the 
  23316. destination, n is the number of items, and t is the type. 
  23317.  
  23318.         (void) Zero( d, n, t );
  23319.  
  23320. Jeff Okamoto <okamoto@corp.hp.com> 
  23321.  
  23322. With lots of help and suggestions from Dean Roehrich, Malcolm Beattie, Andreas 
  23323. Koenig, Paul Hudson, Ilya Zakharevich, Paul Marquess, Neil Bowers, Matthew 
  23324. Green, Tim Bunce, and Spider Boardman. 
  23325.  
  23326. API Listing by Dean Roehrich <roehrich@cray.com>. 
  23327.  
  23328. Version 20: 1995/12/14 
  23329.  
  23330.  
  23331. ΓòÉΓòÉΓòÉ 34. Section - perlcall ΓòÉΓòÉΓòÉ
  23332.  
  23333. NAME 
  23334.  
  23335. perlcall - Perl calling conventions from C 
  23336.  
  23337. DESCRIPTION 
  23338.  
  23339. The purpose of this document is to show you how to call Perl subroutines 
  23340. directly from C, i.e. how to write callbacks. 
  23341.  
  23342. Apart from discussing the C interface provided by Perl for writing callbacks 
  23343. the document uses a series of examples to show how the interface actually works 
  23344. in practice.  In addition some techniques for coding callbacks are covered. 
  23345.  
  23346. Examples where callbacks are necessary include 
  23347.  
  23348. * An Error Handler 
  23349.  
  23350. You have created an XSUB interface to an application's C API. A fairly common 
  23351. feature in applications is to allow you to define a C function that will be 
  23352. called whenever something nasty occurs. What we would like is to be able to 
  23353. specify a Perl subroutine that will be called instead. 
  23354.  
  23355. * An Event Driven Program 
  23356.  
  23357. The classic example of where callbacks are used is when writing an event driven 
  23358. program like for an X windows application.  In this case your register 
  23359. functions to be called whenever specific events occur, e.g. a mouse button is 
  23360. pressed, the cursor moves into a window or a menu item is selected. 
  23361.  
  23362. Although the techniques described here are applicable when embedding Perl in a 
  23363. C program, this is not the primary goal of this document. There are other 
  23364. details that must be considered and are specific to embedding Perl. For details 
  23365. on embedding Perl in C refer to perlembed. 
  23366.  
  23367. Before you launch yourself head first into the rest of this document, it would 
  23368. be a good idea to have read the following two documents - perlxs and perlguts. 
  23369.  
  23370. THE PERL_CALL FUNCTIONS 
  23371.  
  23372. Although this stuff is easier to explain using examples, you first need be 
  23373. aware of a few important definitions. 
  23374.  
  23375. Perl has a number of C functions that allow you to call Perl subroutines.  They 
  23376. are 
  23377.  
  23378.     I32 perl_call_sv(SV* sv, I32 flags) ;
  23379.     I32 perl_call_pv(char *subname, I32 flags) ;
  23380.     I32 perl_call_method(char *methname, I32 flags) ;
  23381.     I32 perl_call_argv(char *subname, I32 flags, register char **argv) ;
  23382.  
  23383. The key function is perl_call_sv.  All the other functions are fairly simple 
  23384. wrappers which make it easier to call Perl subroutines in special cases. At the 
  23385. end of the day they will all call perl_call_sv to actually invoke the Perl 
  23386. subroutine. 
  23387.  
  23388. All the perl_call_* functions have a flags parameter which is used to pass a 
  23389. bit mask of options to Perl.  This bit mask operates identically for each of 
  23390. the functions.  The settings available in the bit mask are discussed in L<FLAG 
  23391. VALUES>. 
  23392.  
  23393. Each of the functions will now be discussed in turn. 
  23394.  
  23395. perl_call_sv 
  23396.  
  23397. perl_call_sv takes two parameters, the first, sv, is an SV*. This allows you to 
  23398. specify the Perl subroutine to be called either as a C string (which has first 
  23399. been converted to an SV) or a reference to a subroutine. The section, Using 
  23400. perl_call_sv, shows how you can make use of perl_call_sv. 
  23401.  
  23402. perl_call_pv 
  23403.  
  23404. The function, perl_call_pv, is similar to perl_call_sv except it expects its 
  23405. first parameter to be a C char* which identifies the Perl subroutine you want 
  23406. to call, e.g. perl_call_pv("fred", 0).  If the subroutine you want to call is 
  23407. in another package, just include the package name in the string, e.g. 
  23408. "pkg::fred". 
  23409.  
  23410. perl_call_method 
  23411.  
  23412. The function perl_call_method is used to call a method from a Perl class.  The 
  23413. parameter methname corresponds to the name of the method to be called.  Note 
  23414. that the class that the method belongs to is passed on the Perl stack rather 
  23415. than in the parameter list. This class can be either the name of the class (for 
  23416. a static method) or a reference to an object (for a virtual method).  See 
  23417. perlobj for more information on static and virtual methods and L<Using 
  23418. perl_call_method> for an example of using perl_call_method. 
  23419.  
  23420. perl_call_argv 
  23421.  
  23422. perl_call_argv calls the Perl subroutine specified by the C string stored in 
  23423. the subname parameter. It also takes the usual flags parameter.  The final 
  23424. parameter, argv, consists of a NULL terminated list of C strings to be passed 
  23425. as parameters to the Perl subroutine. See Using perl_call_argv. 
  23426.  
  23427. All the functions return an integer. This is a count of the number of items 
  23428. returned by the Perl subroutine. The actual items returned by the subroutine 
  23429. are stored on the Perl stack. 
  23430.  
  23431. As a general rule you should always check the return value from these 
  23432. functions.  Even if you are expecting only a particular number of values to be 
  23433. returned from the Perl subroutine, there is nothing to stop someone from doing 
  23434. something unexpected - don't say you haven't been warned. 
  23435.  
  23436. FLAG VALUES 
  23437.  
  23438. The flags parameter in all the perl_call_* functions is a bit mask which can 
  23439. consist of any combination of the symbols defined below, OR'ed together. 
  23440.  
  23441. G_SCALAR 
  23442.  
  23443. Calls the Perl subroutine in a scalar context.  This is the default context 
  23444. flag setting for all the perl_call_* functions. 
  23445.  
  23446. This flag has 2 effects 
  23447.  
  23448.    1. it indicates to the subroutine being called that it is executing in a 
  23449.       scalar context (if it executes wantarray the result will be false). 
  23450.  
  23451.    2. it ensures that only a scalar is actually returned from the subroutine. 
  23452.       The subroutine can, of course,  ignore the wantarray and return a list 
  23453.       anyway. If so, then only the last element of the list will be returned. 
  23454.  
  23455.  The value returned by the perl_call_* function indicates how may items have 
  23456.  been returned by the Perl subroutine - in this case it will be either 0 or 1. 
  23457.  
  23458.  If 0, then you have specified the G_DISCARD flag. 
  23459.  
  23460.  If 1, then the item actually returned by the Perl subroutine will be stored on 
  23461.  the Perl stack - the section Returning a Scalar shows how to access this value 
  23462.  on the stack.  Remember that regardless of how many items the Perl subroutine 
  23463.  returns, only the last one will be accessible from the stack - think of the 
  23464.  case where only one value is returned as being a list with only one element. 
  23465.  Any other items that were returned will not exist by the time control returns 
  23466.  from the perl_call_* function.  The section I<Returning a list in a scalar 
  23467.  context> shows an example of this behaviour. 
  23468.  
  23469.  G_ARRAY 
  23470.  
  23471.  Calls the Perl subroutine in a list context. 
  23472.  
  23473.  As with G_SCALAR, this flag has 2 effects 
  23474.  
  23475.    1. it indicates to the subroutine being called that it is executing in an 
  23476.       array context (if it executes wantarray the result will be true). 
  23477.  
  23478.    2. it ensures that all items returned from the subroutine will be accessible 
  23479.       when control returns from the perl_call_* function. 
  23480.  
  23481.  The value returned by the perl_call_* function indicates how may items have 
  23482.  been returned by the Perl subroutine. 
  23483.  
  23484.  If 0, the you have specified the G_DISCARD flag. 
  23485.  
  23486.  If not 0, then it will be a count of the number of items returned by the 
  23487.  subroutine. These items will be stored on the Perl stack.  The section 
  23488.  Returning a list of values gives an example of using the G_ARRAY flag and the 
  23489.  mechanics of accessing the returned items from the Perl stack. 
  23490.  
  23491.  G_DISCARD 
  23492.  
  23493.  By default, the perl_call_* functions place the items returned from by the 
  23494.  Perl subroutine on the stack.  If you are not interested in these items, then 
  23495.  setting this flag will make Perl get rid of them automatically for you.  Note 
  23496.  that it is still possible to indicate a context to the Perl subroutine by 
  23497.  using either G_SCALAR or G_ARRAY. 
  23498.  
  23499.  If you do not set this flag then it is very important that you make sure that 
  23500.  any temporaries (i.e. parameters passed to the Perl subroutine and values 
  23501.  returned from the subroutine) are disposed of yourself.  The section Returning 
  23502.  a Scalar gives details of how to explicitly dispose of these temporaries and 
  23503.  the section I<Using Perl to dispose of temporaries> discusses the specific 
  23504.  circumstances where you can ignore the problem and let Perl deal with it for 
  23505.  you. 
  23506.  
  23507.  G_NOARGS 
  23508.  
  23509.  Whenever a Perl subroutine is called using one of the perl_call_* functions, 
  23510.  it is assumed by default that parameters are to be passed to the subroutine. 
  23511.  If you are not passing any parameters to the Perl subroutine, you can save a 
  23512.  bit of time by setting this flag.  It has the effect of not creating the @_ 
  23513.  array for the Perl subroutine. 
  23514.  
  23515.  Although the functionality provided by this flag may seem straightforward, it 
  23516.  should be used only if there is a good reason to do so.  The reason for being 
  23517.  cautious is that even if you have specified the G_NOARGS flag, it is still 
  23518.  possible for the Perl subroutine that has been called to think that you have 
  23519.  passed it parameters. 
  23520.  
  23521.  In fact, what can happen is that the Perl subroutine you have called can 
  23522.  access the @_ array from a previous Perl subroutine.  This will occur when the 
  23523.  code that is executing the perl_call_* function has itself been called from 
  23524.  another Perl subroutine. The code below illustrates this 
  23525.  
  23526.       sub fred
  23527.         { print "@_\n"  }
  23528.  
  23529.       sub joe
  23530.         { &fred }
  23531.  
  23532.       &joe(1,2,3) ;
  23533.  
  23534.  This will print 
  23535.  
  23536.       1 2 3
  23537.  
  23538.  What has happened is that fred accesses the @_ array which belongs to joe. 
  23539.  
  23540.  G_EVAL 
  23541.  
  23542.  It is possible for the Perl subroutine you are calling to terminate 
  23543.  abnormally, e.g. by calling die explicitly or by not actually existing.  By 
  23544.  default, when either of these of events occurs, the process will terminate 
  23545.  immediately.  If though, you want to trap this type of event, specify the 
  23546.  G_EVAL flag.  It will put an eval { } around the subroutine call. 
  23547.  
  23548.  Whenever control returns from the perl_call_* function you need to check the 
  23549.  $@ variable as you would in a normal Perl script. 
  23550.  
  23551.  The value returned from the perl_call_* function is dependent on what other 
  23552.  flags have been specified and whether an error has occurred.  Here are all the 
  23553.  different cases that can occur 
  23554.  
  23555.      If the perl_call_* function returns normally, then the value returned is 
  23556.       as specified in the previous sections. 
  23557.  
  23558.      If G_DISCARD is specified, the return value will always be 0. 
  23559.  
  23560.      If G_ARRAY is specified and an error has occurred, the return value will 
  23561.       always be 0. 
  23562.  
  23563.      If G_SCALAR is specified and an error has occurred, the return value will 
  23564.       be 1 and the value on the top of the stack will be undef. This means that 
  23565.       if you have already detected the error by checking $@ and you want the 
  23566.       program to continue, you must remember to pop the undef from the stack. 
  23567.  
  23568.  See Using G_EVAL for details of using G_EVAL. 
  23569.  
  23570.  G_KEEPERR 
  23571.  
  23572.  You may have noticed that using the G_EVAL flag described above will always 
  23573.  clear the $@ variable and set it to a string describing the error iff there 
  23574.  was an error in the called code.  This unqualified resetting of $@ can be 
  23575.  problematic in the reliable identification of errors using the eval {} 
  23576.  mechanism, because the possibility exists that perl will call other code (end 
  23577.  of block processing code, for example) between the time the error causes $@ to 
  23578.  be set within eval {}, and the subsequent statement which checks for the value 
  23579.  of $@ gets executed in the user's script. 
  23580.  
  23581.  This scenario will mostly be applicable to code that is meant to be called 
  23582.  from within destructors, asynchronous callbacks, signal handlers, __DIE__ or 
  23583.  __WARN__ hooks, and tie functions.  In such situations, you will not want to 
  23584.  clear $@ at all, but simply to append any new errors to any existing value of 
  23585.  $@. 
  23586.  
  23587.  The G_KEEPERR flag is meant to be used in conjunction with G_EVAL in 
  23588.  perl_call_* functions that are used to implement such code.  This flag has no 
  23589.  effect when G_EVAL is not used. 
  23590.  
  23591.  When G_KEEPERR is used, any errors in the called code will be prefixed with 
  23592.  the string "\t(in cleanup)", and appended to the current value of $@. 
  23593.  
  23594.  The G_KEEPERR flag was introduced in Perl version 5.002. 
  23595.  
  23596.  See Using G_KEEPERR for an example of a situation that warrants the use of 
  23597.  this flag. 
  23598.  
  23599.  Determining the Context 
  23600.  
  23601.  As mentioned above, you can determine the context of the currently executing 
  23602.  subroutine in Perl with wantarray. The equivalent test can be made in C by 
  23603.  using the GIMME macro. This will return G_SCALAR if you have been called in a 
  23604.  scalar context and G_ARRAY if in an array context. An example of using the 
  23605.  GIMME macro is shown in section Using GIMME. 
  23606.  
  23607.  KNOWN PROBLEMS 
  23608.  
  23609.  This section outlines all known problems that exist in the perl_call_* 
  23610.  functions. 
  23611.  
  23612.    1. If you are intending to make use of both the G_EVAL and G_SCALAR flags in 
  23613.       your code, use a version of Perl greater than 5.000.  There is a bug in 
  23614.       version 5.000 of Perl which means that the combination of these two flags 
  23615.       will not work as described in the section FLAG VALUES. Specifically, if 
  23616.       the two flags are used when calling a subroutine and that subroutine does 
  23617.       not call die, the value returned by perl_call_* will be wrong. 
  23618.  
  23619.    2. In Perl 5.000 and 5.001 there is a problem with using perl_call_* if the 
  23620.       Perl sub you are calling attempts to trap a die. The symptom of this 
  23621.       problem is that the called Perl sub will continue to completion, but 
  23622.       whenever it attempts to pass control back to the XSUB, the program will 
  23623.       immediately terminate. For example, say you want to call this Perl sub 
  23624.  
  23625.                 sub fred
  23626.                 {
  23627.                     eval { die "Fatal Error" ; }
  23628.                     print "Trapped error: $@\n"
  23629.                         if $@ ;
  23630.                 }
  23631.  
  23632.       via this XSUB 
  23633.  
  23634.                 void
  23635.                 Call_fred()
  23636.                     CODE:
  23637.                     PUSHMARK(sp) ;
  23638.                     perl_call_pv("fred", G_DISCARD|G_NOARGS) ;
  23639.                     fprintf(stderr, "back in Call_fred\n") ;
  23640.  
  23641.       When Call_fred is executed it will print 
  23642.  
  23643.                 Trapped error: Fatal Error
  23644.  
  23645.       As control never returns to Call_fred, the "back in Call_fred" string 
  23646.       will not get printed. To work around this problem, you can either upgrade 
  23647.       to Perl 5.002 (or later), or use the G_EVAL flag with perl_call_* as 
  23648.       shown below 
  23649.  
  23650.                 void
  23651.                 Call_fred()
  23652.                     CODE:
  23653.                     PUSHMARK(sp) ;
  23654.                     perl_call_pv("fred", G_EVAL|G_DISCARD|G_NOARGS) ;
  23655.                     fprintf(stderr, "back in Call_fred\n") ;
  23656.  
  23657.  
  23658.  EXAMPLES 
  23659.  
  23660.  Enough of the definition talk, let's have a few examples. 
  23661.  
  23662.  Perl provides many macros to assist in accessing the Perl stack. Wherever 
  23663.  possible, these macros should always be used when interfacing to Perl 
  23664.  internals.  Hopefully this should make the code less vulnerable to any changes 
  23665.  made to Perl in the future. 
  23666.  
  23667.  Another point worth noting is that in the first series of examples I have made 
  23668.  use of only the perl_call_pv function.  This has been done to keep the code 
  23669.  simpler and ease you into the topic.  Wherever possible, if the choice is 
  23670.  between using perl_call_pv and perl_call_sv, you should always try to use 
  23671.  perl_call_sv.  See Using perl_call_sv for details. 
  23672.  
  23673.  No Parameters, Nothing returned 
  23674.  
  23675.  This first trivial example will call a Perl subroutine, PrintUID, to print out 
  23676.  the UID of the process. 
  23677.  
  23678.       sub PrintUID
  23679.       {
  23680.           print "UID is $<\n" ;
  23681.       }
  23682.  
  23683.  and here is a C function to call it 
  23684.  
  23685.       static void
  23686.       call_PrintUID()
  23687.       {
  23688.           dSP ;
  23689.  
  23690.           PUSHMARK(sp) ;
  23691.           perl_call_pv("PrintUID", G_DISCARD|G_NOARGS) ;
  23692.       }
  23693.  
  23694.  Simple, eh. 
  23695.  
  23696.  A few points to note about this example. 
  23697.  
  23698.    1. Ignore dSP and PUSHMARK(sp) for now. They will be discussed in the next 
  23699.       example. 
  23700.  
  23701.    2. We aren't passing any parameters to PrintUID so G_NOARGS can be 
  23702.       specified. 
  23703.  
  23704.    3. We aren't interested in anything returned from PrintUID, so G_DISCARD is 
  23705.       specified. Even if PrintUID was changed to actually return some value(s), 
  23706.       having specified G_DISCARD will mean that they will be wiped by the time 
  23707.       control returns from perl_call_pv. 
  23708.  
  23709.    4. As perl_call_pv is being used, the Perl subroutine is specified as a C 
  23710.       string. In this case the subroutine name has been 'hard-wired' into the 
  23711.       code. 
  23712.  
  23713.    5. Because we specified G_DISCARD, it is not necessary to check the value 
  23714.       returned from perl_call_pv. It will always be 0. 
  23715.  
  23716.  Passing Parameters 
  23717.  
  23718.  Now let's make a slightly more complex example. This time we want to call a 
  23719.  Perl subroutine, LeftString, which will take 2 parameters - a string ($s) and 
  23720.  an integer ($n).  The subroutine will simply print the first $n characters of 
  23721.  the string. 
  23722.  
  23723.  So the Perl subroutine would look like this 
  23724.  
  23725.       sub LeftString
  23726.       {
  23727.           my($s, $n) = @_ ;
  23728.           print substr($s, 0, $n), "\n" ;
  23729.       }
  23730.  
  23731.  The C function required to call LeftString would look like this. 
  23732.  
  23733.       static void
  23734.       call_LeftString(a, b)
  23735.       char * a ;
  23736.       int b ;
  23737.       {
  23738.           dSP ;
  23739.  
  23740.           PUSHMARK(sp) ;
  23741.           XPUSHs(sv_2mortal(newSVpv(a, 0)));
  23742.           XPUSHs(sv_2mortal(newSViv(b)));
  23743.           PUTBACK ;
  23744.  
  23745.           perl_call_pv("LeftString", G_DISCARD);
  23746.       }
  23747.  
  23748.  Here are a few notes on the C function call_LeftString. 
  23749.  
  23750.    1. Parameters are passed to the Perl subroutine using the Perl stack. This 
  23751.       is the purpose of the code beginning with the line dSP and ending with 
  23752.       the line PUTBACK. 
  23753.  
  23754.    2. If you are going to put something onto the Perl stack, you need to know 
  23755.       where to put it. This is the purpose of the macro dSP - it declares and 
  23756.       initializes a local copy of the Perl stack pointer. All the other macros 
  23757.       which will be used in this example require you to have used this macro. 
  23758.       The exception to this rule is if you are calling a Perl subroutine 
  23759.       directly from an XSUB function. In this case it is not necessary to 
  23760.       explicitly use the dSP macro - it will be declared for you automatically. 
  23761.  
  23762.    3. Any parameters to be pushed onto the stack should be bracketed by the 
  23763.       PUSHMARK and PUTBACK macros.  The purpose of these two macros, in this 
  23764.       context, is to automatically count the number of parameters you are 
  23765.       pushing. Then whenever Perl is creating the @_ array for the subroutine, 
  23766.       it knows how big to make it. The PUSHMARK macro tells Perl to make a 
  23767.       mental note of the current stack pointer. Even if you aren't passing any 
  23768.       parameters (like the example shown in the section No Parameters, Nothing 
  23769.       returned) you must still call the PUSHMARK macro before you can call any 
  23770.       of the perl_call_* functions - Perl still needs to know that there are no 
  23771.       parameters. The PUTBACK macro sets the global copy of the stack pointer 
  23772.       to be the same as our local copy. If we didn't do this perl_call_pv 
  23773.       wouldn't know where the two parameters we pushed were - remember that up 
  23774.       to now all the stack pointer manipulation we have done is with our local 
  23775.       copy, not the global copy. 
  23776.  
  23777.    4. The only flag specified this time is G_DISCARD. Since we are passing 2 
  23778.       parameters to the Perl subroutine this time, we have not specified 
  23779.       G_NOARGS. 
  23780.  
  23781.    5. Next, we come to XPUSHs. This is where the parameters actually get pushed 
  23782.       onto the stack. In this case we are pushing a string and an integer. See 
  23783.       the section perlguts/"XSUB'S and the Argument Stack" for details on how 
  23784.       the XPUSH macros work. 
  23785.  
  23786.    6. Finally, LeftString can now be called via the perl_call_pv function. 
  23787.  
  23788.  Returning a Scalar 
  23789.  
  23790.  Now for an example of dealing with the items returned from a Perl subroutine. 
  23791.  
  23792.  Here is a Perl subroutine, Adder,  which takes 2 integer parameters and simply 
  23793.  returns their sum. 
  23794.  
  23795.       sub Adder
  23796.       {
  23797.           my($a, $b) = @_ ;
  23798.           $a + $b ;
  23799.       }
  23800.  
  23801.  Since we are now concerned with the return value from Adder, the C function 
  23802.  required to call it is now a bit more complex. 
  23803.  
  23804.       static void
  23805.       call_Adder(a, b)
  23806.       int a ;
  23807.       int b ;
  23808.       {
  23809.           dSP ;
  23810.           int count ;
  23811.  
  23812.           ENTER ;
  23813.           SAVETMPS;
  23814.  
  23815.           PUSHMARK(sp) ;
  23816.           XPUSHs(sv_2mortal(newSViv(a)));
  23817.           XPUSHs(sv_2mortal(newSViv(b)));
  23818.           PUTBACK ;
  23819.  
  23820.           count = perl_call_pv("Adder", G_SCALAR);
  23821.  
  23822.           SPAGAIN ;
  23823.  
  23824.           if (count != 1)
  23825.               croak("Big trouble\n") ;
  23826.  
  23827.           printf ("The sum of %d and %d is %d\n", a, b, POPi) ;
  23828.  
  23829.           PUTBACK ;
  23830.           FREETMPS ;
  23831.           LEAVE ;
  23832.       }
  23833.  
  23834.  Points to note this time are 
  23835.  
  23836.    1. The only flag specified this time was G_SCALAR. That means the @_ array 
  23837.       will be created and that the value returned by Adder will still exist 
  23838.       after the call to perl_call_pv. 
  23839.  
  23840.    2. Because we are interested in what is returned from Adder we cannot 
  23841.       specify G_DISCARD. This means that we will have to tidy up the Perl stack 
  23842.       and dispose of any temporary values ourselves. This is the purpose of 
  23843.  
  23844.                 ENTER ;
  23845.                 SAVETMPS ;
  23846.  
  23847.       at the start of the function, and 
  23848.  
  23849.                 FREETMPS ;
  23850.                 LEAVE ;
  23851.  
  23852.       at the end. The ENTER/SAVETMPS pair creates a boundary for any 
  23853.       temporaries we create.  This means that the temporaries we get rid of 
  23854.       will be limited to those which were created after these calls. The 
  23855.       FREETMPS/LEAVE pair will get rid of any values returned by the Perl 
  23856.       subroutine, plus it will also dump the mortal SV's we have created. 
  23857.       Having ENTER/SAVETMPS at the beginning of the code makes sure that no 
  23858.       other mortals are destroyed. Think of these macros as working a bit like 
  23859.       using { and } in Perl to limit the scope of local variables. See the 
  23860.       section Using Perl to dispose of temporaries for details of an 
  23861.       alternative to using these macros. 
  23862.  
  23863.    3. The purpose of the macro SPAGAIN is to refresh the local copy of the 
  23864.       stack pointer. This is necessary because it is possible that the memory 
  23865.       allocated to the Perl stack has been re-allocated whilst in the 
  23866.       perl_call_pv call. If you are making use of the Perl stack pointer in 
  23867.       your code you must always refresh the your local copy using SPAGAIN 
  23868.       whenever you make use of the perl_call_* functions or any other Perl 
  23869.       internal function. 
  23870.  
  23871.    4. Although only a single value was expected to be returned from Adder, it 
  23872.       is still good practice to check the return code from perl_call_pv anyway. 
  23873.       Expecting a single value is not quite the same as knowing that there will 
  23874.       be one. If someone modified Adder to return a list and we didn't check 
  23875.       for that possibility and take appropriate action the Perl stack would end 
  23876.       up in an inconsistent state. That is something you really don't want to 
  23877.       ever happen. 
  23878.  
  23879.    5. The POPi macro is used here to pop the return value from the stack. In 
  23880.       this case we wanted an integer, so POPi was used. Here is the complete 
  23881.       list of POP macros available, along with the types they return. 
  23882.  
  23883.                 POPs        SV
  23884.                 POPp        pointer
  23885.                 POPn        double
  23886.                 POPi        integer
  23887.                 POPl        long
  23888.  
  23889.    6. The final PUTBACK is used to leave the Perl stack in a consistent state 
  23890.       before exiting the function.  This is necessary because when we popped 
  23891.       the return value from the stack with POPi it updated only our local copy 
  23892.       of the stack pointer.  Remember, PUTBACK sets the global stack pointer to 
  23893.       be the same as our local copy. 
  23894.  
  23895.  Returning a list of values 
  23896.  
  23897.  Now, let's extend the previous example to return both the sum of the 
  23898.  parameters and the difference. 
  23899.  
  23900.  Here is the Perl subroutine 
  23901.  
  23902.       sub AddSubtract
  23903.       {
  23904.          my($a, $b) = @_ ;
  23905.          ($a+$b, $a-$b) ;
  23906.       }
  23907.  
  23908.  and this is the C function 
  23909.  
  23910.       static void
  23911.       call_AddSubtract(a, b)
  23912.       int a ;
  23913.       int b ;
  23914.       {
  23915.           dSP ;
  23916.           int count ;
  23917.  
  23918.           ENTER ;
  23919.           SAVETMPS;
  23920.  
  23921.           PUSHMARK(sp) ;
  23922.           XPUSHs(sv_2mortal(newSViv(a)));
  23923.           XPUSHs(sv_2mortal(newSViv(b)));
  23924.           PUTBACK ;
  23925.  
  23926.           count = perl_call_pv("AddSubtract", G_ARRAY);
  23927.  
  23928.           SPAGAIN ;
  23929.  
  23930.           if (count != 2)
  23931.               croak("Big trouble\n") ;
  23932.  
  23933.           printf ("%d - %d = %d\n", a, b, POPi) ;
  23934.           printf ("%d + %d = %d\n", a, b, POPi) ;
  23935.  
  23936.           PUTBACK ;
  23937.           FREETMPS ;
  23938.           LEAVE ;
  23939.       }
  23940.  
  23941.  If call_AddSubtract is called like this 
  23942.  
  23943.       call_AddSubtract(7, 4) ;
  23944.  
  23945.  then here is the output 
  23946.  
  23947.       7 - 4 = 3
  23948.       7 + 4 = 11
  23949.  
  23950.  Notes 
  23951.  
  23952.    1. We wanted array context, so G_ARRAY was used. 
  23953.  
  23954.    2. Not surprisingly POPi is used twice this time because we were retrieving 
  23955.       2 values from the stack. The important thing to note is that when using 
  23956.       the POP* macros they come off the stack in reverse order. 
  23957.  
  23958.  Returning a list in a scalar context 
  23959.  
  23960.  Say the Perl subroutine in the previous section was called in a scalar 
  23961.  context, like this 
  23962.  
  23963.       static void
  23964.       call_AddSubScalar(a, b)
  23965.       int a ;
  23966.       int b ;
  23967.       {
  23968.           dSP ;
  23969.           int count ;
  23970.           int i ;
  23971.  
  23972.           ENTER ;
  23973.           SAVETMPS;
  23974.  
  23975.           PUSHMARK(sp) ;
  23976.           XPUSHs(sv_2mortal(newSViv(a)));
  23977.           XPUSHs(sv_2mortal(newSViv(b)));
  23978.           PUTBACK ;
  23979.  
  23980.           count = perl_call_pv("AddSubtract", G_SCALAR);
  23981.  
  23982.           SPAGAIN ;
  23983.  
  23984.           printf ("Items Returned = %d\n", count) ;
  23985.  
  23986.           for (i = 1 ; i <= count ; ++i)
  23987.               printf ("Value %d = %d\n", i, POPi) ;
  23988.  
  23989.           PUTBACK ;
  23990.           FREETMPS ;
  23991.           LEAVE ;
  23992.       }
  23993.  
  23994.  The other modification made is that call_AddSubScalar will print the number of 
  23995.  items returned from the Perl subroutine and their value (for simplicity it 
  23996.  assumes that they are integer).  So if call_AddSubScalar is called 
  23997.  
  23998.       call_AddSubScalar(7, 4) ;
  23999.  
  24000.  then the output will be 
  24001.  
  24002.       Items Returned = 1
  24003.       Value 1 = 3
  24004.  
  24005.  In this case the main point to note is that only the last item in the list 
  24006.  returned from the subroutine, Adder actually made it back to 
  24007.  call_AddSubScalar. 
  24008.  
  24009.  Returning Data from Perl via the parameter list 
  24010.  
  24011.  It is also possible to return values directly via the parameter list - whether 
  24012.  it is actually desirable to do it is another matter entirely. 
  24013.  
  24014.  The Perl subroutine, Inc, below takes 2 parameters and increments each 
  24015.  directly. 
  24016.  
  24017.       sub Inc
  24018.       {
  24019.           ++ $_[0] ;
  24020.           ++ $_[1] ;
  24021.       }
  24022.  
  24023.  and here is a C function to call it. 
  24024.  
  24025.       static void
  24026.       call_Inc(a, b)
  24027.       int a ;
  24028.       int b ;
  24029.       {
  24030.           dSP ;
  24031.           int count ;
  24032.           SV * sva ;
  24033.           SV * svb ;
  24034.  
  24035.           ENTER ;
  24036.           SAVETMPS;
  24037.  
  24038.           sva = sv_2mortal(newSViv(a)) ;
  24039.           svb = sv_2mortal(newSViv(b)) ;
  24040.  
  24041.           PUSHMARK(sp) ;
  24042.           XPUSHs(sva);
  24043.           XPUSHs(svb);
  24044.           PUTBACK ;
  24045.  
  24046.           count = perl_call_pv("Inc", G_DISCARD);
  24047.  
  24048.           if (count != 0)
  24049.               croak ("call_Inc: expected 0 values from 'Inc', got %d\n",
  24050.                      count) ;
  24051.  
  24052.           printf ("%d + 1 = %d\n", a, SvIV(sva)) ;
  24053.           printf ("%d + 1 = %d\n", b, SvIV(svb)) ;
  24054.  
  24055.           FREETMPS ;
  24056.           LEAVE ;
  24057.       }
  24058.  
  24059.  To be able to access the two parameters that were pushed onto the stack after 
  24060.  they return from perl_call_pv it is necessary to make a note of their 
  24061.  addresses - thus the two variables sva and svb. 
  24062.  
  24063.  The reason this is necessary is that the area of the Perl stack which held 
  24064.  them will very likely have been overwritten by something else by the time 
  24065.  control returns from perl_call_pv. 
  24066.  
  24067.  Using G_EVAL 
  24068.  
  24069.  Now an example using G_EVAL. Below is a Perl subroutine which computes the 
  24070.  difference of its 2 parameters. If this would result in a negative result, the 
  24071.  subroutine calls die. 
  24072.  
  24073.       sub Subtract
  24074.       {
  24075.           my ($a, $b) = @_ ;
  24076.  
  24077.           die "death can be fatal\n" if $a < $b ;
  24078.  
  24079.           $a - $b ;
  24080.       }
  24081.  
  24082.  and some C to call it 
  24083.  
  24084.       static void
  24085.       call_Subtract(a, b)
  24086.       int a ;
  24087.       int b ;
  24088.       {
  24089.           dSP ;
  24090.           int count ;
  24091.  
  24092.           ENTER ;
  24093.           SAVETMPS;
  24094.  
  24095.           PUSHMARK(sp) ;
  24096.           XPUSHs(sv_2mortal(newSViv(a)));
  24097.           XPUSHs(sv_2mortal(newSViv(b)));
  24098.           PUTBACK ;
  24099.  
  24100.           count = perl_call_pv("Subtract", G_EVAL|G_SCALAR);
  24101.  
  24102.           SPAGAIN ;
  24103.  
  24104.           /* Check the eval first */
  24105.           if (SvTRUE(GvSV(errgv)))
  24106.           {
  24107.               printf ("Uh oh - %s\n", SvPV(GvSV(errgv), na)) ;
  24108.               POPs ;
  24109.           }
  24110.           else
  24111.           {
  24112.               if (count != 1)
  24113.                  croak("call_Subtract: wanted 1 value from 'Subtract', got %d\n",
  24114.                           count) ;
  24115.  
  24116.               printf ("%d - %d = %d\n", a, b, POPi) ;
  24117.           }
  24118.  
  24119.           PUTBACK ;
  24120.           FREETMPS ;
  24121.           LEAVE ;
  24122.       }
  24123.  
  24124.  If call_Subtract is called thus 
  24125.  
  24126.       call_Subtract(4, 5)
  24127.  
  24128.  the following will be printed 
  24129.  
  24130.       Uh oh - death can be fatal
  24131.  
  24132.  Notes 
  24133.  
  24134.    1. We want to be able to catch the die so we have used the G_EVAL flag.  Not 
  24135.       specifying this flag would mean that the program would terminate 
  24136.       immediately at the die statement in the subroutine Subtract. 
  24137.  
  24138.    2. The code 
  24139.  
  24140.                 if (SvTRUE(GvSV(errgv)))
  24141.                 {
  24142.                     printf ("Uh oh - %s\n", SvPV(GvSV(errgv), na)) ;
  24143.                     POPs ;
  24144.                 }
  24145.  
  24146.       is the direct equivalent of this bit of Perl 
  24147.  
  24148.                 print "Uh oh - $@\n" if $@ ;
  24149.  
  24150.       errgv is a perl global of type GV * that points to the symbol table entry 
  24151.       containing the error.  GvSV(errgv) therefore refers to the C equivalent 
  24152.       of $@. 
  24153.  
  24154.    3. Note that the stack is popped using POPs in the block where 
  24155.       SvTRUE(GvSV(errgv)) is true.  This is necessary because whenever a 
  24156.       perl_call_* function invoked with G_EVAL|G_SCALAR returns an error, the 
  24157.       top of the stack holds the value undef. Since we want the program to 
  24158.       continue after detecting this error, it is essential that the stack is 
  24159.       tidied up by removing the undef. 
  24160.  
  24161.  Using G_KEEPERR 
  24162.  
  24163.  Consider this rather facetious example, where we have used an XS version of 
  24164.  the call_Subtract example above inside a destructor: 
  24165.  
  24166.       package Foo;
  24167.       sub new { bless {}, $_[0] }
  24168.       sub Subtract {
  24169.           my($a,$b) = @_;
  24170.           die "death can be fatal" if $a < $b ;
  24171.           $a - $b;
  24172.       }
  24173.       sub DESTROY { call_Subtract(5, 4); }
  24174.       sub foo { die "foo dies"; }
  24175.  
  24176.       package main;
  24177.       eval { Foo->new->foo };
  24178.       print "Saw: $@" if $@;             # should be, but isn't
  24179.  
  24180.  This example will fail to recognize that an error occurred inside the eval {}. 
  24181.  Here's why: the call_Subtract code got executed while perl was cleaning up 
  24182.  temporaries when exiting the eval block, and since call_Subtract is 
  24183.  implemented with perl_call_pv using the G_EVAL flag, it promptly reset $@. 
  24184.  This results in the failure of the outermost test for $@, and thereby the 
  24185.  failure of the error trap. 
  24186.  
  24187.  Appending the G_KEEPERR flag, so that the perl_call_pv call in call_Subtract 
  24188.  reads: 
  24189.  
  24190.           count = perl_call_pv("Subtract", G_EVAL|G_SCALAR|G_KEEPERR);
  24191.  
  24192.  will preserve the error and restore reliable error handling. 
  24193.  
  24194.  Using perl_call_sv 
  24195.  
  24196.  In all the previous examples I have 'hard-wired' the name of the Perl 
  24197.  subroutine to be called from C.  Most of the time though, it is more 
  24198.  convenient to be able to specify the name of the Perl subroutine from within 
  24199.  the Perl script. 
  24200.  
  24201.  Consider the Perl code below 
  24202.  
  24203.       sub fred
  24204.       {
  24205.           print "Hello there\n" ;
  24206.       }
  24207.  
  24208.       CallSubPV("fred") ;
  24209.  
  24210.  Here is a snippet of XSUB which defines CallSubPV. 
  24211.  
  24212.       void
  24213.       CallSubPV(name)
  24214.           char *  name
  24215.           CODE:
  24216.           PUSHMARK(sp) ;
  24217.           perl_call_pv(name, G_DISCARD|G_NOARGS) ;
  24218.  
  24219.  That is fine as far as it goes. The thing is, the Perl subroutine can be 
  24220.  specified only as a string.  For Perl 4 this was adequate, but Perl 5 allows 
  24221.  references to subroutines and anonymous subroutines. This is where 
  24222.  perl_call_sv is useful. 
  24223.  
  24224.  The code below for CallSubSV is identical to CallSubPV except that the name 
  24225.  parameter is now defined as an SV* and we use perl_call_sv instead of 
  24226.  perl_call_pv. 
  24227.  
  24228.       void
  24229.       CallSubSV(name)
  24230.           SV *    name
  24231.           CODE:
  24232.           PUSHMARK(sp) ;
  24233.           perl_call_sv(name, G_DISCARD|G_NOARGS) ;
  24234.  
  24235.  Since we are using an SV to call fred the following can all be used 
  24236.  
  24237.       CallSubSV("fred") ;
  24238.       CallSubSV(\&fred) ;
  24239.       $ref = \&fred ;
  24240.       CallSubSV($ref) ;
  24241.       CallSubSV( sub { print "Hello there\n" } ) ;
  24242.  
  24243.  As you can see, perl_call_sv gives you much greater flexibility in how you can 
  24244.  specify the Perl subroutine. 
  24245.  
  24246.  You should note that if it is necessary to store the SV (name in the example 
  24247.  above) which corresponds to the Perl subroutine so that it can be used later 
  24248.  in the program, it not enough to just store a copy of the pointer to the SV. 
  24249.  Say the code above had been like this 
  24250.  
  24251.       static SV * rememberSub ;
  24252.  
  24253.       void
  24254.       SaveSub1(name)
  24255.           SV *    name
  24256.           CODE:
  24257.           rememberSub = name ;
  24258.  
  24259.       void
  24260.       CallSavedSub1()
  24261.           CODE:
  24262.           PUSHMARK(sp) ;
  24263.           perl_call_sv(rememberSub, G_DISCARD|G_NOARGS) ;
  24264.  
  24265.  The reason this is wrong is that by the time you come to use the pointer 
  24266.  rememberSub in CallSavedSub1, it may or may not still refer to the Perl 
  24267.  subroutine that was recorded in SaveSub1.  This is particularly true for these 
  24268.  cases 
  24269.  
  24270.       SaveSub1(\&fred) ;
  24271.       CallSavedSub1() ;
  24272.  
  24273.       SaveSub1( sub { print "Hello there\n" } ) ;
  24274.       CallSavedSub1() ;
  24275.  
  24276.  By the time each of the SaveSub1 statements above have been executed, the 
  24277.  SV*'s which corresponded to the parameters will no longer exist. Expect an 
  24278.  error message from Perl of the form 
  24279.  
  24280.       Can't use an undefined value as a subroutine reference at ...
  24281.  
  24282.  for each of the CallSavedSub1 lines. 
  24283.  
  24284.  Similarly, with this code 
  24285.  
  24286.       $ref = \&fred ;
  24287.       SaveSub1($ref) ;
  24288.       $ref = 47 ;
  24289.       CallSavedSub1() ;
  24290.  
  24291.  you can expect one of these messages (which you actually get is dependant on 
  24292.  the version of Perl you are using) 
  24293.  
  24294.       Not a CODE reference at ...
  24295.       Undefined subroutine &main::47 called ...
  24296.  
  24297.  The variable $ref may have referred to the subroutine fred whenever the call 
  24298.  to SaveSub1 was made but by the time CallSavedSub1 gets called it now holds 
  24299.  the number 47. Since we saved only a pointer to the original SV in SaveSub1, 
  24300.  any changes to $ref will be tracked by the pointer rememberSub. This means 
  24301.  that whenever CallSavedSub1 gets called, it will attempt to execute the code 
  24302.  which is referenced by the SV* rememberSub.  In this case though, it now 
  24303.  refers to the integer 47, so expect Perl to complain loudly. 
  24304.  
  24305.  A similar but more subtle problem is illustrated with this code 
  24306.  
  24307.       $ref = \&fred ;
  24308.       SaveSub1($ref) ;
  24309.       $ref = \&joe ;
  24310.       CallSavedSub1() ;
  24311.  
  24312.  This time whenever CallSavedSub1 get called it will execute the Perl 
  24313.  subroutine joe (assuming it exists) rather than fred as was originally 
  24314.  requested in the call to SaveSub1. 
  24315.  
  24316.  To get around these problems it is necessary to take a full copy of the SV. 
  24317.  The code below shows SaveSub2 modified to do that 
  24318.  
  24319.       static SV * keepSub = (SV*)NULL ;
  24320.  
  24321.       void
  24322.       SaveSub2(name)
  24323.           SV *    name
  24324.           CODE:
  24325.           /* Take a copy of the callback */
  24326.           if (keepSub == (SV*)NULL)
  24327.               /* First time, so create a new SV */
  24328.               keepSub = newSVsv(name) ;
  24329.           else
  24330.               /* Been here before, so overwrite */
  24331.               SvSetSV(keepSub, name) ;
  24332.  
  24333.       void
  24334.       CallSavedSub2()
  24335.           CODE:
  24336.           PUSHMARK(sp) ;
  24337.           perl_call_sv(keepSub, G_DISCARD|G_NOARGS) ;
  24338.  
  24339.  In order to avoid creating a new SV every time SaveSub2 is called, the 
  24340.  function first checks to see if it has been called before.  If not, then space 
  24341.  for a new SV is allocated and the reference to the Perl subroutine, name is 
  24342.  copied to the variable keepSub in one operation using newSVsv.  Thereafter, 
  24343.  whenever SaveSub2 is called the existing SV, keepSub, is overwritten with the 
  24344.  new value using SvSetSV. 
  24345.  
  24346.  Using perl_call_argv 
  24347.  
  24348.  Here is a Perl subroutine which prints whatever parameters are passed to it. 
  24349.  
  24350.       sub PrintList
  24351.       {
  24352.           my(@list) = @_ ;
  24353.  
  24354.           foreach (@list) { print "$_\n" }
  24355.       }
  24356.  
  24357.  and here is an example of perl_call_argv which will call PrintList. 
  24358.  
  24359.       static char * words[] = {"alpha", "beta", "gamma", "delta", NULL} ;
  24360.  
  24361.       static void
  24362.       call_PrintList()
  24363.       {
  24364.           dSP ;
  24365.  
  24366.           perl_call_argv("PrintList", G_DISCARD, words) ;
  24367.       }
  24368.  
  24369.  Note that it is not necessary to call PUSHMARK in this instance. This is 
  24370.  because perl_call_argv will do it for you. 
  24371.  
  24372.  Using perl_call_method 
  24373.  
  24374.  Consider the following Perl code 
  24375.  
  24376.       {
  24377.           package Mine ;
  24378.  
  24379.           sub new
  24380.           {
  24381.               my($type) = shift ;
  24382.               bless [@_]
  24383.           }
  24384.  
  24385.           sub Display
  24386.           {
  24387.               my ($self, $index) = @_ ;
  24388.               print "$index: $$self[$index]\n" ;
  24389.           }
  24390.  
  24391.           sub PrintID
  24392.           {
  24393.               my($class) = @_ ;
  24394.               print "This is Class $class version 1.0\n" ;
  24395.           }
  24396.       }
  24397.  
  24398.  It just implements a very simple class to manage an array.  Apart from the 
  24399.  constructor, new, it declares methods, one static and one virtual. The static 
  24400.  method, PrintID, simply prints out the class name and a version number. The 
  24401.  virtual method, Display, prints out a single element of the array.  Here is an 
  24402.  all Perl example of using it. 
  24403.  
  24404.       $a = new Mine ('red', 'green', 'blue') ;
  24405.       $a->Display(1) ;
  24406.       PrintID Mine;
  24407.  
  24408.  will print 
  24409.  
  24410.       1: green
  24411.       This is Class Mine version 1.0
  24412.  
  24413.  Calling a Perl method from C is fairly straightforward. The following things 
  24414.  are required 
  24415.  
  24416.      a reference to the object for a virtual method or the name of the class 
  24417.       for a static method. 
  24418.  
  24419.      the name of the method. 
  24420.  
  24421.      any other parameters specific to the method. 
  24422.  
  24423.  Here is a simple XSUB which illustrates the mechanics of calling both the 
  24424.  PrintID and Display methods from C. 
  24425.  
  24426.       void
  24427.       call_Method(ref, method, index)
  24428.           SV *    ref
  24429.           char *  method
  24430.           int             index
  24431.           CODE:
  24432.           PUSHMARK(sp);
  24433.           XPUSHs(ref);
  24434.           XPUSHs(sv_2mortal(newSViv(index))) ;
  24435.           PUTBACK;
  24436.  
  24437.           perl_call_method(method, G_DISCARD) ;
  24438.  
  24439.       void
  24440.       call_PrintID(class, method)
  24441.           char *  class
  24442.           char *  method
  24443.           CODE:
  24444.           PUSHMARK(sp);
  24445.           XPUSHs(sv_2mortal(newSVpv(class, 0))) ;
  24446.           PUTBACK;
  24447.  
  24448.           perl_call_method(method, G_DISCARD) ;
  24449.  
  24450.  So the methods PrintID and Display can be invoked like this 
  24451.  
  24452.       $a = new Mine ('red', 'green', 'blue') ;
  24453.       call_Method($a, 'Display', 1) ;
  24454.       call_PrintID('Mine', 'PrintID') ;
  24455.  
  24456.  The only thing to note is that in both the static and virtual methods, the 
  24457.  method name is not passed via the stack - it is used as the first parameter to 
  24458.  perl_call_method. 
  24459.  
  24460.  Using GIMME 
  24461.  
  24462.  Here is a trivial XSUB which prints the context in which it is currently 
  24463.  executing. 
  24464.  
  24465.       void
  24466.       PrintContext()
  24467.           CODE:
  24468.           if (GIMME == G_SCALAR)
  24469.               printf ("Context is Scalar\n") ;
  24470.           else
  24471.               printf ("Context is Array\n") ;
  24472.  
  24473.  and here is some Perl to test it 
  24474.  
  24475.       $a = PrintContext ;
  24476.       @a = PrintContext ;
  24477.  
  24478.  The output from that will be 
  24479.  
  24480.       Context is Scalar
  24481.       Context is Array
  24482.  
  24483.  Using Perl to dispose of temporaries 
  24484.  
  24485.  In the examples given to date, any temporaries created in the callback (i.e. 
  24486.  parameters passed on the stack to the perl_call_* function or values returned 
  24487.  via the stack) have been freed by one of these methods 
  24488.  
  24489.      specifying the G_DISCARD flag with perl_call_*. 
  24490.  
  24491.      explicitly disposed of using the ENTER/SAVETMPS - FREETMPS/LEAVE pairing. 
  24492.  
  24493.  There is another method which can be used, namely letting Perl do it for you 
  24494.  automatically whenever it regains control after the callback has terminated. 
  24495.  This is done by simply not using the 
  24496.  
  24497.       ENTER ;
  24498.       SAVETMPS ;
  24499.       ...
  24500.       FREETMPS ;
  24501.       LEAVE ;
  24502.  
  24503.  sequence in the callback (and not, of course, specifying the G_DISCARD flag). 
  24504.  
  24505.  If you are going to use this method you have to be aware of a possible memory 
  24506.  leak which can arise under very specific circumstances.  To explain these 
  24507.  circumstances you need to know a bit about the flow of control between Perl 
  24508.  and the callback routine. 
  24509.  
  24510.  The examples given at the start of the document (an error handler and an event 
  24511.  driven program) are typical of the two main sorts of flow control that you are 
  24512.  likely to encounter with callbacks.  There is a very important distinction 
  24513.  between them, so pay attention. 
  24514.  
  24515.  In the first example, an error handler, the flow of control could be as 
  24516.  follows.  You have created an interface to an external library. Control can 
  24517.  reach the external library like this 
  24518.  
  24519.       perl --> XSUB --> external library
  24520.  
  24521.  Whilst control is in the library, an error condition occurs. You have 
  24522.  previously set up a Perl callback to handle this situation, so it will get 
  24523.  executed. Once the callback has finished, control will drop back to Perl 
  24524.  again.  Here is what the flow of control will be like in that situation 
  24525.  
  24526.       perl --> XSUB --> external library
  24527.                         ...
  24528.                         error occurs
  24529.                         ...
  24530.                         external library --> perl_call --> perl
  24531.                                                             |
  24532.       perl <-- XSUB <-- external library <-- perl_call <----+
  24533.  
  24534.  After processing of the error using perl_call_* is completed, control reverts 
  24535.  back to Perl more or less immediately. 
  24536.  
  24537.  In the diagram, the further right you go the more deeply nested the scope is. 
  24538.  It is only when control is back with perl on the extreme left of the diagram 
  24539.  that you will have dropped back to the enclosing scope and any temporaries you 
  24540.  have left hanging around will be freed. 
  24541.  
  24542.  In the second example, an event driven program, the flow of control will be 
  24543.  more like this 
  24544.  
  24545.       perl --> XSUB --> event handler
  24546.                         ...
  24547.                         event handler --> perl_call --> perl
  24548.                                                          |
  24549.                         event handler <-- perl_call --<--+
  24550.                         ...
  24551.                         event handler --> perl_call --> perl
  24552.                                                          |
  24553.                         event handler <-- perl_call --<--+
  24554.                         ...
  24555.                         event handler --> perl_call --> perl
  24556.                                                          |
  24557.                         event handler <-- perl_call --<--+
  24558.  
  24559.  In this case the flow of control can consist of only the repeated sequence 
  24560.  
  24561.       event handler --> perl_call --> perl
  24562.  
  24563.  for the practically the complete duration of the program.  This means that 
  24564.  control may never drop back to the surrounding scope in Perl at the extreme 
  24565.  left. 
  24566.  
  24567.  So what is the big problem? Well, if you are expecting Perl to tidy up those 
  24568.  temporaries for you, you might be in for a long wait.  For Perl to actually 
  24569.  dispose of your temporaries, control must drop back to the enclosing scope at 
  24570.  some stage.  In the event driven scenario that may never happen.  This means 
  24571.  that as time goes on, your program will create more and more temporaries, none 
  24572.  of which will ever be freed. As each of these temporaries consumes some memory 
  24573.  your program will eventually consume all the available memory in your system - 
  24574.  kapow! 
  24575.  
  24576.  So here is the bottom line - if you are sure that control will revert back to 
  24577.  the enclosing Perl scope fairly quickly after the end of your callback, then 
  24578.  it isn't absolutely necessary to explicitly dispose of any temporaries you may 
  24579.  have created. Mind you, if you are at all uncertain about what to do, it 
  24580.  doesn't do any harm to tidy up anyway. 
  24581.  
  24582.  Strategies for storing Callback Context Information 
  24583.  
  24584.  Potentially one of the trickiest problems to overcome when designing a 
  24585.  callback interface can be figuring out how to store the mapping between the C 
  24586.  callback function and the Perl equivalent. 
  24587.  
  24588.  To help understand why this can be a real problem first consider how a 
  24589.  callback is set up in an all C environment.  Typically a C API will provide a 
  24590.  function to register a callback.  This will expect a pointer to a function as 
  24591.  one of its parameters.  Below is a call to a hypothetical function 
  24592.  register_fatal which registers the C function to get called when a fatal error 
  24593.  occurs. 
  24594.  
  24595.       register_fatal(cb1) ;
  24596.  
  24597.  The single parameter cb1 is a pointer to a function, so you must have defined 
  24598.  cb1 in your code, say something like this 
  24599.  
  24600.       static void
  24601.       cb1()
  24602.       {
  24603.           printf ("Fatal Error\n") ;
  24604.           exit(1) ;
  24605.       }
  24606.  
  24607.  Now change that to call a Perl subroutine instead 
  24608.  
  24609.       static SV * callback = (SV*)NULL;
  24610.  
  24611.       static void
  24612.       cb1()
  24613.       {
  24614.           dSP ;
  24615.  
  24616.           PUSHMARK(sp) ;
  24617.  
  24618.           /* Call the Perl sub to process the callback */
  24619.           perl_call_sv(callback, G_DISCARD) ;
  24620.       }
  24621.  
  24622.       void
  24623.       register_fatal(fn)
  24624.           SV *    fn
  24625.           CODE:
  24626.           /* Remember the Perl sub */
  24627.           if (callback == (SV*)NULL)
  24628.               callback = newSVsv(fn) ;
  24629.           else
  24630.               SvSetSV(callback, fn) ;
  24631.  
  24632.           /* register the callback with the external library */
  24633.           register_fatal(cb1) ;
  24634.  
  24635.  where the Perl equivalent of register_fatal and the callback it registers, 
  24636.  pcb1, might look like this 
  24637.  
  24638.       # Register the sub pcb1
  24639.       register_fatal(\&pcb1) ;
  24640.  
  24641.       sub pcb1
  24642.       {
  24643.           die "I'm dying...\n" ;
  24644.       }
  24645.  
  24646.  The mapping between the C callback and the Perl equivalent is stored in the 
  24647.  global variable callback. 
  24648.  
  24649.  This will be adequate if you ever need to have only 1 callback registered at 
  24650.  any time. An example could be an error handler like the code sketched out 
  24651.  above. Remember though, repeated calls to register_fatal will replace the 
  24652.  previously registered callback function with the new one. 
  24653.  
  24654.  Say for example you want to interface to a library which allows asynchronous 
  24655.  file i/o.  In this case you may be able to register a callback whenever a read 
  24656.  operation has completed. To be of any use we want to be able to call separate 
  24657.  Perl subroutines for each file that is opened.  As it stands, the error 
  24658.  handler example above would not be adequate as it allows only a single 
  24659.  callback to be defined at any time. What we require is a means of storing the 
  24660.  mapping between the opened file and the Perl subroutine we want to be called 
  24661.  for that file. 
  24662.  
  24663.  Say the i/o library has a function asynch_read which associates a C function 
  24664.  ProcessRead with a file handle fh - this assumes that it has also provided 
  24665.  some routine to open the file and so obtain the file handle. 
  24666.  
  24667.       asynch_read(fh, ProcessRead)
  24668.  
  24669.  This may expect the C ProcessRead function of this form 
  24670.  
  24671.       void
  24672.       ProcessRead(fh, buffer)
  24673.       int fh ;
  24674.       char *      buffer ;
  24675.       {
  24676.            ...
  24677.       }
  24678.  
  24679.  To provide a Perl interface to this library we need to be able to map between 
  24680.  the fh parameter and the Perl subroutine we want called.  A hash is a 
  24681.  convenient mechanism for storing this mapping.  The code below shows a 
  24682.  possible implementation 
  24683.  
  24684.       static HV * Mapping = (HV*)NULL ;
  24685.  
  24686.       void
  24687.       asynch_read(fh, callback)
  24688.           int     fh
  24689.           SV *    callback
  24690.           CODE:
  24691.           /* If the hash doesn't already exist, create it */
  24692.           if (Mapping == (HV*)NULL)
  24693.               Mapping = newHV() ;
  24694.  
  24695.           /* Save the fh -> callback mapping */
  24696.           hv_store(Mapping, (char*)&fh, sizeof(fh), newSVsv(callback), 0) ;
  24697.  
  24698.           /* Register with the C Library */
  24699.           asynch_read(fh, asynch_read_if) ;
  24700.  
  24701.  and asynch_read_if could look like this 
  24702.  
  24703.       static void
  24704.       asynch_read_if(fh, buffer)
  24705.       int fh ;
  24706.       char *      buffer ;
  24707.       {
  24708.           dSP ;
  24709.           SV ** sv ;
  24710.  
  24711.           /* Get the callback associated with fh */
  24712.           sv =  hv_fetch(Mapping, (char*)&fh , sizeof(fh), FALSE) ;
  24713.           if (sv == (SV**)NULL)
  24714.               croak("Internal error...\n") ;
  24715.  
  24716.           PUSHMARK(sp) ;
  24717.           XPUSHs(sv_2mortal(newSViv(fh))) ;
  24718.           XPUSHs(sv_2mortal(newSVpv(buffer, 0))) ;
  24719.           PUTBACK ;
  24720.  
  24721.           /* Call the Perl sub */
  24722.           perl_call_sv(*sv, G_DISCARD) ;
  24723.       }
  24724.  
  24725.  For completeness, here is asynch_close.  This shows how to remove the entry 
  24726.  from the hash Mapping. 
  24727.  
  24728.       void
  24729.       asynch_close(fh)
  24730.           int     fh
  24731.           CODE:
  24732.           /* Remove the entry from the hash */
  24733.           (void) hv_delete(Mapping, (char*)&fh, sizeof(fh), G_DISCARD) ;
  24734.  
  24735.           /* Now call the real asynch_close */
  24736.           asynch_close(fh) ;
  24737.  
  24738.  So the Perl interface would look like this 
  24739.  
  24740.       sub callback1
  24741.       {
  24742.           my($handle, $buffer) = @_ ;
  24743.       }
  24744.  
  24745.       # Register the Perl callback
  24746.       asynch_read($fh, \&callback1) ;
  24747.  
  24748.       asynch_close($fh) ;
  24749.  
  24750.  The mapping between the C callback and Perl is stored in the global hash 
  24751.  Mapping this time. Using a hash has the distinct advantage that it allows an 
  24752.  unlimited number of callbacks to be registered. 
  24753.  
  24754.  What if the interface provided by the C callback doesn't contain a parameter 
  24755.  which allows the file handle to Perl subroutine mapping?  Say in the 
  24756.  asynchronous i/o package, the callback function gets passed only the buffer 
  24757.  parameter like this 
  24758.  
  24759.       void
  24760.       ProcessRead(buffer)
  24761.       char *      buffer ;
  24762.       {
  24763.           ...
  24764.       }
  24765.  
  24766.  Without the file handle there is no straightforward way to map from the C 
  24767.  callback to the Perl subroutine. 
  24768.  
  24769.  In this case a possible way around this problem is to pre-define a series of C 
  24770.  functions to act as the interface to Perl, thus 
  24771.  
  24772.       #define MAX_CB              3
  24773.       #define NULL_HANDLE -1
  24774.       typedef void (*FnMap)() ;
  24775.  
  24776.       struct MapStruct {
  24777.           FnMap    Function ;
  24778.           SV *     PerlSub ;
  24779.           int      Handle ;
  24780.         } ;
  24781.  
  24782.       static void  fn1() ;
  24783.       static void  fn2() ;
  24784.       static void  fn3() ;
  24785.  
  24786.       static struct MapStruct Map [MAX_CB] =
  24787.           {
  24788.               { fn1, NULL, NULL_HANDLE },
  24789.               { fn2, NULL, NULL_HANDLE },
  24790.               { fn3, NULL, NULL_HANDLE }
  24791.           } ;
  24792.  
  24793.       static void
  24794.       Pcb(index, buffer)
  24795.       int index ;
  24796.       char * buffer ;
  24797.       {
  24798.           dSP ;
  24799.  
  24800.           PUSHMARK(sp) ;
  24801.           XPUSHs(sv_2mortal(newSVpv(buffer, 0))) ;
  24802.           PUTBACK ;
  24803.  
  24804.           /* Call the Perl sub */
  24805.           perl_call_sv(Map[index].PerlSub, G_DISCARD) ;
  24806.       }
  24807.  
  24808.       static void
  24809.       fn1(buffer)
  24810.       char * buffer ;
  24811.       {
  24812.           Pcb(0, buffer) ;
  24813.       }
  24814.  
  24815.       static void
  24816.       fn2(buffer)
  24817.       char * buffer ;
  24818.       {
  24819.           Pcb(1, buffer) ;
  24820.       }
  24821.  
  24822.       static void
  24823.       fn3(buffer)
  24824.       char * buffer ;
  24825.       {
  24826.           Pcb(2, buffer) ;
  24827.       }
  24828.  
  24829.       void
  24830.       array_asynch_read(fh, callback)
  24831.           int             fh
  24832.           SV *    callback
  24833.           CODE:
  24834.           int index ;
  24835.           int null_index = MAX_CB ;
  24836.  
  24837.           /* Find the same handle or an empty entry */
  24838.           for (index = 0 ; index < MAX_CB ; ++index)
  24839.           {
  24840.               if (Map[index].Handle == fh)
  24841.                   break ;
  24842.  
  24843.               if (Map[index].Handle == NULL_HANDLE)
  24844.                   null_index = index ;
  24845.           }
  24846.  
  24847.           if (index == MAX_CB && null_index == MAX_CB)
  24848.               croak ("Too many callback functions registered\n") ;
  24849.  
  24850.           if (index == MAX_CB)
  24851.               index = null_index ;
  24852.  
  24853.           /* Save the file handle */
  24854.           Map[index].Handle = fh ;
  24855.  
  24856.           /* Remember the Perl sub */
  24857.           if (Map[index].PerlSub == (SV*)NULL)
  24858.               Map[index].PerlSub = newSVsv(callback) ;
  24859.           else
  24860.               SvSetSV(Map[index].PerlSub, callback) ;
  24861.  
  24862.           asynch_read(fh, Map[index].Function) ;
  24863.  
  24864.       void
  24865.       array_asynch_close(fh)
  24866.           int     fh
  24867.           CODE:
  24868.           int index ;
  24869.  
  24870.           /* Find the file handle */
  24871.           for (index = 0; index < MAX_CB ; ++ index)
  24872.               if (Map[index].Handle == fh)
  24873.                   break ;
  24874.  
  24875.           if (index == MAX_CB)
  24876.               croak ("could not close fh %d\n", fh) ;
  24877.  
  24878.           Map[index].Handle = NULL_HANDLE ;
  24879.           SvREFCNT_dec(Map[index].PerlSub) ;
  24880.           Map[index].PerlSub = (SV*)NULL ;
  24881.  
  24882.           asynch_close(fh) ;
  24883.  
  24884.  In this case the functions fn1, fn2 and fn3 are used to remember the Perl 
  24885.  subroutine to be called. Each of the functions holds a separate hard-wired 
  24886.  index which is used in the function Pcb to access the Map array and actually 
  24887.  call the Perl subroutine. 
  24888.  
  24889.  There are some obvious disadvantages with this technique. 
  24890.  
  24891.  Firstly, the code is considerably more complex than with the previous example. 
  24892.  
  24893.  Secondly, there is a hard-wired limit (in this case 3) to the number of 
  24894.  callbacks that can exist simultaneously. The only way to increase the limit is 
  24895.  by modifying the code to add more functions and then re-compiling.  None the 
  24896.  less, as long as the number of functions is chosen with some care, it is still 
  24897.  a workable solution and in some cases is the only one available. 
  24898.  
  24899.  To summarize, here are a number of possible methods for you to consider for 
  24900.  storing the mapping between C and the Perl callback 
  24901.  
  24902.    1. For a lot of situations, like interfacing to an error handler, this may 
  24903.       be a perfectly adequate solution. 
  24904.  
  24905.    2. If it is impossible to tell from the parameters passed back from the C 
  24906.       callback what the context is, then you may need to create a sequence of C 
  24907.       callback interface functions, and store pointers to each in an array. 
  24908.  
  24909.    3. A hash is an ideal mechanism to store the mapping between C and Perl. 
  24910.  
  24911.  Alternate Stack Manipulation 
  24912.  
  24913.  Although I have made use of only the POP* macros to access values returned 
  24914.  from Perl subroutines, it is also possible to bypass these macros and read the 
  24915.  stack using the ST macro (See perlxs for a full description of the ST macro). 
  24916.  
  24917.  Most of the time the POP* macros should be adequate, the main problem with 
  24918.  them is that they force you to process the returned values in sequence. This 
  24919.  may not be the most suitable way to process the values in some cases. What we 
  24920.  want is to be able to access the stack in a random order. The ST macro as used 
  24921.  when coding an XSUB is ideal for this purpose. 
  24922.  
  24923.  The code below is the example given in the section I<Returning a list of 
  24924.  values> recoded to use ST instead of POP*. 
  24925.  
  24926.       static void
  24927.       call_AddSubtract2(a, b)
  24928.       int a ;
  24929.       int b ;
  24930.       {
  24931.           dSP ;
  24932.           I32 ax ;
  24933.           int count ;
  24934.  
  24935.           ENTER ;
  24936.           SAVETMPS;
  24937.  
  24938.           PUSHMARK(sp) ;
  24939.           XPUSHs(sv_2mortal(newSViv(a)));
  24940.           XPUSHs(sv_2mortal(newSViv(b)));
  24941.           PUTBACK ;
  24942.  
  24943.           count = perl_call_pv("AddSubtract", G_ARRAY);
  24944.  
  24945.           SPAGAIN ;
  24946.           sp -= count ;
  24947.           ax = (sp - stack_base) + 1 ;
  24948.  
  24949.           if (count != 2)
  24950.               croak("Big trouble\n") ;
  24951.  
  24952.           printf ("%d + %d = %d\n", a, b, SvIV(ST(0))) ;
  24953.           printf ("%d - %d = %d\n", a, b, SvIV(ST(1))) ;
  24954.  
  24955.           PUTBACK ;
  24956.           FREETMPS ;
  24957.           LEAVE ;
  24958.       }
  24959.  
  24960.  Notes 
  24961.  
  24962.    1. Notice that it was necessary to define the variable ax.  This is because 
  24963.       the ST macro expects it to exist.  If we were in an XSUB it would not be 
  24964.       necessary to define ax as it is already defined for you. 
  24965.  
  24966.    2. The code 
  24967.  
  24968.                     SPAGAIN ;
  24969.                     sp -= count ;
  24970.                     ax = (sp - stack_base) + 1 ;
  24971.  
  24972.       sets the stack up so that we can use the ST macro. 
  24973.  
  24974.    3. Unlike the original coding of this example, the returned values are not 
  24975.       accessed in reverse order.  So ST(0) refers to the first value returned 
  24976.       by the Perl subroutine and ST(count-1) refers to the last. 
  24977.  
  24978.  SEE ALSO 
  24979.  
  24980.  perlxs, perlguts, perlembed 
  24981.  
  24982.  AUTHOR 
  24983.  
  24984.  Paul Marquess <pmarquess@bfsec.bt.co.uk> 
  24985.  
  24986.  Special thanks to the following people who assisted in the creation of the 
  24987.  document. 
  24988.  
  24989.  Jeff Okamoto, Tim Bunce, Nick Gianniotis, Steve Kelem, Gurusamy Sarathy and 
  24990.  Larry Wall. 
  24991.  
  24992.  DATE 
  24993.  
  24994.  Version 1.2, 16th Jan 1996 
  24995.  
  24996.  
  24997. ΓòÉΓòÉΓòÉ 35. Section - perlembed ΓòÉΓòÉΓòÉ
  24998.  
  24999. NAME 
  25000.  
  25001. perlembed - how to embed perl in your C program 
  25002.  
  25003. DESCRIPTION 
  25004.  
  25005. PREAMBLE 
  25006.  
  25007. Do you want to: 
  25008.  
  25009. Use C from Perl? 
  25010.  
  25011. Read perlcall and perlxs. 
  25012.  
  25013. Use a UNIX program from Perl? 
  25014.  
  25015. Read about backquotes and perlfunc/system and perlfunc/exec. 
  25016.  
  25017. Use Perl from Perl? 
  25018.  
  25019. Read about perlfunc/do and perlfunc/eval and perlmod/use and perlmod/require. 
  25020.  
  25021. Use C from C? 
  25022.  
  25023. Rethink your design. 
  25024.  
  25025. Use Perl from C? 
  25026.  
  25027. Read on... 
  25028.  
  25029. ROADMAP 
  25030.  
  25031. L<Compiling your C program> 
  25032.  
  25033. There's one example in each of the five sections: 
  25034.  
  25035. L<Adding a Perl interpreter to your C program> 
  25036.  
  25037. L<Calling a Perl subroutine from your C program> 
  25038.  
  25039. L<Evaluating a Perl statement from your C program> 
  25040.  
  25041. L<Performing Perl pattern matches and substitutions from your C program> 
  25042.  
  25043. L<Fiddling with the Perl stack from your C program> 
  25044.  
  25045. This documentation is UNIX specific. 
  25046.  
  25047. Compiling your C program 
  25048.  
  25049. Every C program that uses Perl must link in the perl library. 
  25050.  
  25051. What's that, you ask?  Perl is itself written in C; the perl library is the 
  25052. collection of compiled C programs that were used to create your perl executable 
  25053. (/usr/bin/perl or equivalent).  (Corollary: you can't use Perl from your C 
  25054. program unless Perl has been compiled on your machine, or installed 
  25055. properly--that's why you shouldn't blithely copy Perl executables from machine 
  25056. to machine without also copying the lib directory.) 
  25057.  
  25058. Your C program will--usually--allocate, "run", and deallocate a PerlInterpreter 
  25059. object, which is defined in the perl library. 
  25060.  
  25061. If your copy of Perl is recent enough to contain this documentation (5.002 or 
  25062. later), then the perl library (and EXTERN.h and perl.h, which you'll also need) 
  25063. will reside in a directory resembling this: 
  25064.  
  25065.     /usr/local/lib/perl5/your_architecture_here/CORE
  25066.  
  25067. or perhaps just 
  25068.  
  25069.     /usr/local/lib/perl5/CORE
  25070.  
  25071. or maybe something like 
  25072.  
  25073.     /usr/opt/perl5/CORE
  25074.  
  25075. Execute this statement for a hint about where to find CORE: 
  25076.  
  25077.     perl -e 'use Config; print $Config{archlib}'
  25078.  
  25079. Here's how you might compile the example in the next section, L<Adding a Perl 
  25080. interpreter to your C program>, on a DEC Alpha running the OSF operating 
  25081. system: 
  25082.  
  25083.     % cc -o interp interp.c -L/usr/local/lib/perl5/alpha-dec_osf/CORE
  25084.     -I/usr/local/lib/perl5/alpha-dec_osf/CORE -lperl -lm
  25085.  
  25086. You'll have to choose the appropriate compiler (cc, gcc, et al.)  and library 
  25087. directory (/usr/local/lib/...)  for your machine.  If your compiler complains 
  25088. that certain functions are undefined, or that it can't locate -lperl, then you 
  25089. need to change the path following the -L.  If it complains that it can't find 
  25090. EXTERN.h or perl.h, you need to change the path following the -I. 
  25091.  
  25092. You may have to add extra libraries as well.  Which ones? Perhaps those printed 
  25093. by 
  25094.  
  25095.    perl -e 'use Config; print $Config{libs}'
  25096.  
  25097. Adding a Perl interpreter to your C program 
  25098.  
  25099. In a sense, perl (the C program) is a good example of embedding Perl (the 
  25100. language), so I'll demonstrate embedding with miniperlmain.c, from the source 
  25101. distribution.  Here's a bastardized, non-portable version of miniperlmain.c 
  25102. containing the essentials of embedding: 
  25103.  
  25104.     #include <stdio.h>
  25105.     #include <EXTERN.h>               /* from the Perl distribution     */
  25106.     #include <perl.h>                 /* from the Perl distribution     */
  25107.  
  25108.     static PerlInterpreter *my_perl;  /***    The Perl interpreter    ***/
  25109.  
  25110.     int main(int argc, char **argv, char **env)
  25111.     {
  25112.         my_perl = perl_alloc();
  25113.         perl_construct(my_perl);
  25114.         perl_parse(my_perl, NULL, argc, argv, env);
  25115.         perl_run(my_perl);
  25116.         perl_destruct(my_perl);
  25117.         perl_free(my_perl);
  25118.     }
  25119.  
  25120. Now compile this program (I'll call it interp.c) into an executable: 
  25121.  
  25122.     % cc -o interp interp.c -L/usr/local/lib/perl5/alpha-dec_osf/CORE
  25123.     -I/usr/local/lib/perl5/alpha-dec_osf/CORE -lperl -lm
  25124.  
  25125. After a successful compilation, you'll be able to use interp just like perl 
  25126. itself: 
  25127.  
  25128.     % interp
  25129.     print "Pretty Good Perl \n";
  25130.     print "10890 - 9801 is ", 10890 - 9801;
  25131.     <CTRL-D>
  25132.     Pretty Good Perl
  25133.     10890 - 9801 is 1089
  25134.  
  25135. or 
  25136.  
  25137.     % interp -e 'printf("%x", 3735928559)'
  25138.     deadbeef
  25139.  
  25140. You can also read and execute Perl statements from a file while in the midst of 
  25141. your C program, by placing the filename in argv[1] before calling perl_run(). 
  25142.  
  25143. Calling a Perl subroutine from your C program 
  25144.  
  25145. To call individual Perl subroutines, you'll need to remove the call to 
  25146. perl_run() and replace it with a call to perl_call_argv(). 
  25147.  
  25148. That's shown below, in a program I'll call showtime.c. 
  25149.  
  25150.     #include <stdio.h>
  25151.     #include <EXTERN.h>
  25152.     #include <perl.h>
  25153.  
  25154.     static PerlInterpreter *my_perl;
  25155.  
  25156.     int main(int argc, char **argv, char **env)
  25157.     {
  25158.         my_perl = perl_alloc();
  25159.         perl_construct(my_perl);
  25160.  
  25161.         perl_parse(my_perl, NULL, argc, argv, env);
  25162.  
  25163.                                      /*** This replaces perl_run() ***/
  25164.         perl_call_argv("showtime", G_DISCARD | G_NOARGS, argv);
  25165.         perl_destruct(my_perl);
  25166.         perl_free(my_perl);
  25167.     }
  25168.  
  25169. where showtime is a Perl subroutine that takes no arguments (that's the 
  25170. G_NOARGS) and for which I'll ignore the return value (that's the G_DISCARD). 
  25171. Those flags, and others, are discussed in perlcall. 
  25172.  
  25173. I'll define the showtime subroutine in a file called showtime.pl: 
  25174.  
  25175.     print "I shan't be printed.";
  25176.  
  25177.     sub showtime {
  25178.         print time;
  25179.     }
  25180.  
  25181. Simple enough.  Now compile and run: 
  25182.  
  25183.     % cc -o showtime showtime.c -L/usr/local/lib/perl5/alpha-dec_osf/CORE
  25184.     -I/usr/local/lib/perl5/alpha-dec_osf/CORE -lperl -lm
  25185.  
  25186.     % showtime showtime.pl
  25187.     818284590
  25188.  
  25189. yielding the number of seconds that elapsed between January 1, 1970 (the 
  25190. beginning of the UNIX epoch), and the moment I began writing this sentence. 
  25191.  
  25192. If you want to pass some arguments to the Perl subroutine, or you want to 
  25193. access the return value, you'll need to manipulate the Perl stack, demonstrated 
  25194. in the last section of this document: L<Fiddling with the Perl stack from your 
  25195. C program> 
  25196.  
  25197. Evaluating a Perl statement from your C program 
  25198.  
  25199. NOTE: This section, and the next, employ some very brittle techniques for 
  25200. evaluting strings of Perl code.  Perl 5.002 contains some nifty features that 
  25201. enable A Better Way (such as with perlguts/perl_eval_sv). Look for updates to 
  25202. this document soon. 
  25203.  
  25204. One way to evaluate a Perl string is to define a function (we'll call ours 
  25205. perl_eval()) that wraps around Perl's perlfunc/eval. 
  25206.  
  25207. Arguably, this is the only routine you'll ever need to execute snippets of Perl 
  25208. code from within your C program.  Your string can be as long as you wish; it 
  25209. can contain multiple statements; it can use perlmod/require or perlfunc/do to 
  25210. include external Perl files. 
  25211.  
  25212. Our perl_eval() lets us evaluate individual Perl strings, and then extract 
  25213. variables for coercion into C types.  The following program, string.c, executes 
  25214. three Perl strings, extracting an int from the first, a float from the second, 
  25215. and a char * from the third. 
  25216.  
  25217.    #include <stdio.h>
  25218.    #include <EXTERN.h>
  25219.    #include <perl.h>
  25220.  
  25221.    static PerlInterpreter *my_perl;
  25222.  
  25223.    int perl_eval(char *string)
  25224.    {
  25225.      char *argv[2];
  25226.      argv[0] = string;
  25227.      argv[1] = NULL;
  25228.      perl_call_argv("_eval_", 0, argv);
  25229.    }
  25230.  
  25231.    main (int argc, char **argv, char **env)
  25232.    {
  25233.      char *embedding[] = { "", "-e", "sub _eval_ { eval $_[0] }" };
  25234.      STRLEN length;
  25235.  
  25236.      my_perl = perl_alloc();
  25237.      perl_construct( my_perl );
  25238.  
  25239.      perl_parse(my_perl, NULL, 3, embedding, env);
  25240.  
  25241.                                        /** Treat $a as an integer **/
  25242.      perl_eval("$a = 3; $a **= 2");
  25243.      printf("a = %d\n", SvIV(perl_get_sv("a", FALSE)));
  25244.  
  25245.                                        /** Treat $a as a float **/
  25246.      perl_eval("$a = 3.14; $a **= 2");
  25247.      printf("a = %f\n", SvNV(perl_get_sv("a", FALSE)));
  25248.  
  25249.                                        /** Treat $a as a string **/
  25250.      perl_eval("$a = 'rekcaH lreP rehtonA tsuJ'; $a = reverse($a); ");
  25251.      printf("a = %s\n", SvPV(perl_get_sv("a", FALSE), length));
  25252.  
  25253.      perl_destruct(my_perl);
  25254.      perl_free(my_perl);
  25255.    }
  25256.  
  25257. All of those strange functions with sv in their names help convert Perl scalars 
  25258. to C types.  They're described in perlguts. 
  25259.  
  25260. If you compile and run string.c, you'll see the results of using SvIV() to 
  25261. create an int, SvNV() to create a float, and SvPV() to create a string: 
  25262.  
  25263.    a = 9
  25264.    a = 9.859600
  25265.    a = Just Another Perl Hacker
  25266.  
  25267. Performing Perl pattern matches and substitutions from your C program 
  25268.  
  25269. Our perl_eval() lets us evaluate strings of Perl code, so we can define some 
  25270. functions that use it to "specialize" in matches and substitutions: match(), 
  25271. substitute(), and matches(). 
  25272.  
  25273.    char match(char *string, char *pattern);
  25274.  
  25275. Given a string and a pattern (e.g. "m/clasp/" or "/\b\w*\b/", which in your 
  25276. program might be represented as "/\\b\\w*\\b/"), returns 1 if the string 
  25277. matches the pattern and 0 otherwise. 
  25278.  
  25279.    int substitute(char *string[], char *pattern);
  25280.  
  25281. Given a pointer to a string and an "=~" operation (e.g. "s/bob/robert/g" or 
  25282. "tr[A-Z][a-z]"), modifies the string according to the operation, returning the 
  25283. number of substitutions made. 
  25284.  
  25285.    int matches(char *string, char *pattern, char **matches[]);
  25286.  
  25287. Given a string, a pattern, and a pointer to an empty array of strings, 
  25288. evaluates $string =~ $pattern in an array context, and fills in matches with 
  25289. the array elements (allocating memory as it does so), returning the number of 
  25290. matches found. 
  25291.  
  25292. Here's a sample program, match.c, that uses all three: 
  25293.  
  25294.    #include <stdio.h>
  25295.    #include <EXTERN.h>
  25296.    #include <perl.h>
  25297.  
  25298.    static PerlInterpreter *my_perl;
  25299.  
  25300.    int eval(char *string)
  25301.    {
  25302.      char *argv[2];
  25303.      argv[0] = string;
  25304.      argv[1] = NULL;
  25305.      perl_call_argv("_eval_", 0, argv);
  25306.    }
  25307.  
  25308.    /** match(string, pattern)
  25309.     **
  25310.     ** Used for matches in a scalar context.
  25311.     **
  25312.     ** Returns 1 if the match was successful; 0 otherwise.
  25313.     **/
  25314.    char match(char *string, char *pattern)
  25315.    {
  25316.      char *command;
  25317.      command = malloc(sizeof(char) * strlen(string) + strlen(pattern) + 37);
  25318.      sprintf(command, "$string = '%s'; $return = $string =~ %s",
  25319.         string, pattern);
  25320.      perl_eval(command);
  25321.      free(command);
  25322.      return SvIV(perl_get_sv("return", FALSE));
  25323.    }
  25324.  
  25325.    /** substitute(string, pattern)
  25326.     **
  25327.     ** Used for =~ operations that modify their left-hand side (s/// and tr///)
  25328.     **
  25329.     ** Returns the number of successful matches, and
  25330.     ** modifies the input string if there were any.
  25331.     **/
  25332.    int substitute(char *string[], char *pattern)
  25333.    {
  25334.      char *command;
  25335.      STRLEN length;
  25336.      command = malloc(sizeof(char) * strlen(*string) + strlen(pattern) + 35);
  25337.      sprintf(command, "$string = '%s'; $ret = ($string =~ %s)",
  25338.         *string, pattern);
  25339.      perl_eval(command);
  25340.      free(command);
  25341.      *string = SvPV(perl_get_sv("string", FALSE), length);
  25342.      return SvIV(perl_get_sv("ret", FALSE));
  25343.    }
  25344.  
  25345.    /** matches(string, pattern, matches)
  25346.     **
  25347.     ** Used for matches in an array context.
  25348.     **
  25349.     ** Returns the number of matches,
  25350.     ** and fills in **matches with the matching substrings (allocates memory!)
  25351.     **/
  25352.    int matches(char *string, char *pattern, char **matches[])
  25353.    {
  25354.      char *command;
  25355.      SV *current_match;
  25356.      AV *array;
  25357.      I32 num_matches;
  25358.      STRLEN length;
  25359.      int i;
  25360.  
  25361.      command = malloc(sizeof(char) * strlen(string) + strlen(pattern) + 38);
  25362.      sprintf(command, "$string = '%s'; @array = ($string =~ %s)",
  25363.         string, pattern);
  25364.      perl_eval(command);
  25365.      free(command);
  25366.      array = perl_get_av("array", FALSE);
  25367.      num_matches = av_len(array) + 1; /** assume $[ is 0 **/
  25368.      *matches = (char **) malloc(sizeof(char *) * num_matches);
  25369.      for (i = 0; i <= num_matches; i++) {
  25370.        current_match = av_shift(array);
  25371.        (*matches)[i] = SvPV(current_match, length);
  25372.      }
  25373.      return num_matches;
  25374.    }
  25375.  
  25376.    main (int argc, char **argv, char **env)
  25377.    {
  25378.      char *embedding[] = { "", "-e", "sub _eval_ { eval $_[0] }" };
  25379.      char *text, **matches;
  25380.      int num_matches, i;
  25381.      int j;
  25382.  
  25383.      my_perl = perl_alloc();
  25384.      perl_construct( my_perl );
  25385.  
  25386.      perl_parse(my_perl, NULL, 3, embedding, env);
  25387.  
  25388.      text = (char *) malloc(sizeof(char) * 486); /** A long string follows! **/
  25389. );
  25390.  
  25391.      if (perl_match(text, "m/quarter/")) /** Does text contain 'quarter'? **/
  25392.        printf("perl_match: Text contains the word 'quarter'.\n\n");
  25393.      else
  25394.        printf("perl_match: Text doesn't contain the word 'quarter'.\n\n");
  25395.  
  25396.      if (perl_match(text, "m/eighth/")) /** Does text contain 'eighth'? **/
  25397.        printf("perl_match: Text contains the word 'eighth'.\n\n");
  25398.      else
  25399.        printf("perl_match: Text doesn't contain the word 'eighth'.\n\n");
  25400.  
  25401.                                        /** Match all occurrences of /wi../ **/
  25402.      num_matches = perl_matches(text, "m/(wi..)/g", &matches);
  25403.  
  25404.      printf("perl_matches: m/(wi..)/g found %d matches...\n", num_matches);
  25405.      for (i = 0; i < num_matches; i++)
  25406.        printf("match: %s\n", matches[i]);
  25407.      printf("\n");
  25408.      for (i = 0; i < num_matches; i++) {
  25409.        free(matches[i]);
  25410.      }
  25411.      free(matches);
  25412.  
  25413.                                        /** Remove all vowels from text **/
  25414.      num_matches = perl_substitute(&text, "s/[aeiou]//gi");
  25415.      if (num_matches) {
  25416.        printf("perl_substitute: s/[aeiou]//gi...%d substitutions made.\n",
  25417.         num_matches);
  25418.        printf("Now text is: %s\n\n", text);
  25419.      }
  25420.  
  25421.                                        /** Attempt a substitution
  25422.      if (!perl_substitute(&text, "s/Perl/C/")) {
  25423.        printf("perl_substitute: s/Perl/C...No substitution made.\n\n");
  25424.      }
  25425.  
  25426.      free(text);
  25427.  
  25428.      perl_destruct(my_perl);
  25429.      perl_free(my_perl);
  25430.    }
  25431.  
  25432. which produces the output 
  25433.  
  25434.    perl_match: Text contains the word 'quarter'.
  25435.  
  25436.    perl_match: Text doesn't contain the word 'eighth'.
  25437.  
  25438.    perl_matches: m/(wi..)/g found 2 matches...
  25439.    match: will
  25440.    match: with
  25441.  
  25442.    perl_substitute: s/[aeiou]//gi...139 substitutions made.
  25443.  h mght lck nt th crrct mnt.  Th by gvs hm bck tw f hs wn pnns nd thn th bg shny qrtr tht s hs prz. -RCHH
  25444.  
  25445.    perl_substitute: s/Perl/C...No substitution made.
  25446.  
  25447. Fiddling with the Perl stack from your C program 
  25448.  
  25449. When trying to explain stacks, most computer science textbooks mumble something 
  25450. about spring-loaded columns of cafeteria plates: the last thing you pushed on 
  25451. the stack is the first thing you pop off.  That'll do for our purposes: your C 
  25452. program will push some arguments onto "the Perl stack", shut its eyes while 
  25453. some magic happens, and then pop the results--the return value of your Perl 
  25454. subroutine--off the stack. 
  25455.  
  25456.  
  25457. First you'll need to know how to convert between C types and Perl types, with 
  25458. newSViv() and sv_setnv() and newAV() and all their friends.  They're described 
  25459. in perlguts. 
  25460.  
  25461. Then you'll need to know how to manipulate the Perl stack.  That's described in 
  25462. perlcall. 
  25463.  
  25464. Once you've understood those, embedding Perl in C is easy. 
  25465.  
  25466. Since C has no built-in function for integer exponentiation, let's make Perl's 
  25467. ** operator available to it (this is less useful than it sounds, since Perl 
  25468. implements ** with C's pow() function).  First I'll create a stub 
  25469. exponentiation function in power.pl: 
  25470.  
  25471.     sub expo {
  25472.         my ($a, $b) = @_;
  25473.         return $a ** $b;
  25474.     }
  25475.  
  25476. Now I'll create a C program, power.c, with a function PerlPower() that contains 
  25477. all the perlguts necessary to push the two arguments into expo() and to pop the 
  25478. return value out.  Take a deep breath... 
  25479.  
  25480.     #include <stdio.h>
  25481.     #include <EXTERN.h>
  25482.     #include <perl.h>
  25483.  
  25484.     static PerlInterpreter *my_perl;
  25485.  
  25486.     static void
  25487.     PerlPower(int a, int b)
  25488.     {
  25489.       dSP;                            /* initialize stack pointer      */
  25490.       ENTER;                          /* everything created after here */
  25491.       SAVETMPS;                       /* ...is a temporary variable.   */
  25492.       PUSHMARK(sp);                   /* remember the stack pointer    */
  25493.       XPUSHs(sv_2mortal(newSViv(a))); /* push the base onto the stack  */
  25494.       XPUSHs(sv_2mortal(newSViv(b))); /* push the exponent onto stack  */
  25495.       PUTBACK;                      /* make local stack pointer global */
  25496.       perl_call_pv("expo", G_SCALAR); /* call the function             */
  25497.       SPAGAIN;                        /* refresh stack pointer         */
  25498.                                     /* pop the return value from stack */
  25499.       printf ("%d to the %dth power is %d.\n", a, b, POPi);
  25500.       PUTBACK;
  25501.       FREETMPS;                       /* free that return value        */
  25502.       LEAVE;                       /* ...and the XPUSHed "mortal" args.*/
  25503.     }
  25504.  
  25505.     int main (int argc, char **argv, char **env)
  25506.     {
  25507.       char *my_argv[2];
  25508.  
  25509.       my_perl = perl_alloc();
  25510.       perl_construct( my_perl );
  25511.  
  25512.       my_argv[1] = (char *) malloc(10);
  25513.       sprintf(my_argv[1], "power.pl");
  25514.  
  25515.       perl_parse(my_perl, NULL, argc, my_argv, env);
  25516.  
  25517.       PerlPower(3, 4);                      /*** Compute 3 ** 4 ***/
  25518.  
  25519.       perl_destruct(my_perl);
  25520.       perl_free(my_perl);
  25521.     }
  25522.  
  25523. Compile and run: 
  25524.  
  25525.     % cc -o power power.c -L/usr/local/lib/perl5/alpha-dec_osf/CORE
  25526.     -I/usr/local/lib/perl5/alpha-dec_osf/CORE -lperl -lm
  25527.  
  25528.     % power
  25529.     3 to the 4th power is 81.
  25530.  
  25531. MORAL 
  25532.  
  25533. You can sometimes write faster code in C, but you can always write code faster 
  25534. in Perl.  Since you can use each from the other, combine them as you wish. 
  25535.  
  25536. AUTHOR 
  25537.  
  25538. Jon Orwant <orwant@media.mit.edu>, with contributions from Tim Bunce, Tom 
  25539. Christiansen, Dov Grobgeld, and Ilya Zakharevich. 
  25540.  
  25541. December 18, 1995 
  25542.  
  25543. Some of this material is excerpted from my book: Perl 5 Interactive, Waite 
  25544. Group Press, 1996 (ISBN 1-57169-064-6) and appears courtesy of Waite Group 
  25545. Press. 
  25546.  
  25547.  
  25548. ΓòÉΓòÉΓòÉ 36. Section - perlpod ΓòÉΓòÉΓòÉ
  25549.  
  25550. NAME 
  25551.  
  25552. perlpod - plain old documentation 
  25553.  
  25554. DESCRIPTION 
  25555.  
  25556. A pod-to-whatever translator reads a pod file paragraph by paragraph, and 
  25557. translates it to the appropriate output format.  There are three kinds of 
  25558. paragraphs: 
  25559.  
  25560.      A verbatim paragraph, distinguished by being indented (that is, it starts 
  25561.       with space or tab).  It should be reproduced exactly, with tabs assumed 
  25562.       to be on 8-column boundaries.  There are no special formatting escapes, 
  25563.       so you can't italicize or anything like that.  A \ means \, and nothing 
  25564.       else. 
  25565.  
  25566.      A command.  All command paragraphs start with "=", followed by an 
  25567.       identifier, followed by arbitrary text that the command can use however 
  25568.       it pleases.  Currently recognized commands are 
  25569.  
  25570.                 =head1 heading
  25571.                 =head2 heading
  25572.                 =item text
  25573.                 =over N
  25574.                 =back
  25575.                 =cut
  25576.                 =pod
  25577.  
  25578.       The "=pod" directive does nothing beyond telling the compiler to lay off 
  25579.       of through the next "=cut".  It's useful for adding another paragraph to 
  25580.       the doc if you're mixing up code and pod a lot. Head1 and head2 produce 
  25581.       first and second level headings, with the text on the same paragraph as 
  25582.       "=headn" forming the heading description. Item, over, and back require a 
  25583.       little more explanation: Over starts a section specifically for the 
  25584.       generation of a list using =item commands. At the end of your list, use 
  25585.       =back to end it. You will probably want to give "4" as the number to 
  25586.       =over, as some formatters will use this for indention. This should 
  25587.       probably be a default. Note also that there are some basic rules to using 
  25588.       =item: don't use them outside of an =over/=back block, use at least one 
  25589.       inside an =over/=back block, you don't _have_ to include the =back if the 
  25590.       list just runs off the document, and perhaps most importantly, keep the 
  25591.       items consistent: either use "=item *" for all of them, to produce 
  25592.       bullets, or use "=item 1.", "=item 2.", etc., to produce numbered lists, 
  25593.       or use "=item foo", "=item bar", etc., i.e., things that looks nothing 
  25594.       like bullets or numbers. If you start with bullets or numbers, stick with 
  25595.       them, as many formatters you the first =item type to decide how to format 
  25596.       the list. And don't forget, when using any command, that that command 
  25597.       lasts up until the end of the paragraph, not the line. Hence in the 
  25598.       examples below, you can see the blank lines after each command to end 
  25599.       it's paragraph. Some examples of lists include: 
  25600.  
  25601.              =over 4
  25602.  
  25603.              =item *
  25604.  
  25605.              First item
  25606.  
  25607.              =item *
  25608.  
  25609.              Second item
  25610.  
  25611.              =back
  25612.  
  25613.              =over 4
  25614.  
  25615.              =item Foo()
  25616.  
  25617.              Description of Foo function
  25618.  
  25619.              =item Bar()
  25620.  
  25621.              Description of Bar function
  25622.  
  25623.              =back
  25624.  
  25625.      An ordinary block of text.  It will be filled, and maybe even justified. 
  25626.       Certain interior sequences are recognized both here and in commands: 
  25627.  
  25628.                 I<text>     italicize text, used for emphasis or variables
  25629.                 B<text>     embolden text, used for switches and programs
  25630.                 S<text>     text contains non-breaking spaces
  25631.                 C<code>     literal code
  25632.                 L<name>     A link (cross reference) to name
  25633.                                 L<name>             manpage
  25634.                                 L<name/ident>       item in manpage
  25635.                                 L<name/"sec">       section in other manpage
  25636.                                 L<"sec">            section in this manpage
  25637.                                                     (the quotes are optional)
  25638.                                 L</"sec">           ditto
  25639.                 F<file>     Used for filenames
  25640.                 X<index>    An index entry
  25641.                 Z<>         A zero-width character
  25642.  
  25643.       That's it.  The intent is simplicity, not power.  I wanted paragraphs to 
  25644.       look like paragraphs (block format), so that they stand out visually, and 
  25645.       so that I could run them through fmt easily to reformat them (that's F7 
  25646.       in my version of vi).  I wanted the translator (and not me) to worry 
  25647.       about whether " or ' is a left quote or a right quote within filled text, 
  25648.       and I wanted it to leave the quotes alone dammit in verbatim mode, so I 
  25649.       could slurp in a working program, shift it over 4 spaces, and have it 
  25650.       print out, er, verbatim.  And presumably in a constant width font. In 
  25651.       particular, you can leave things like this verbatim in your text: 
  25652.  
  25653.                 Perl
  25654.                 FILEHANDLE
  25655.                 $variable
  25656.                 function()
  25657.                 manpage(3r)
  25658.  
  25659.       Doubtless a few other commands or sequences will need to be added along 
  25660.       the way, but I've gotten along surprisingly well with just these. Note 
  25661.       that I'm not at all claiming this to be sufficient for producing a book. 
  25662.       I'm just trying to make an idiot-proof common source for nroff, TeX, and 
  25663.       other markup languages, as used for online documentation. Translators 
  25664.       exist for pod2man  (that's for nroff(1) and troff(1)), pod2html, 
  25665.       pod2latex, and pod2fm. 
  25666.  
  25667.       Embedding Pods in Perl Modules 
  25668.  
  25669.       You can embed pod documentation in your Perl scripts.  Start your 
  25670.       documentation with a =head1 command at the beg, and end it with an =cut 
  25671.       command.  Perl will ignore the pod text.  See any of the supplied library 
  25672.       modules for examples.  If you're going to put your pods at the end of the 
  25673.       file, and you're using an __END__ or __DATA__ cut mark, make sure to put 
  25674.       a blank line there before the first pod directive. 
  25675.  
  25676.                 __END__
  25677.  
  25678.                 =head1 NAME
  25679.  
  25680.                 modern - I am a modern module
  25681.  
  25682.       If you had not had that blank line there, then the translators wouldn't 
  25683.       have seen it. 
  25684.  
  25685.       SEE ALSO 
  25686.  
  25687.       L<pod2man> and perlsyn/"PODs: Embedded Documentation" 
  25688.  
  25689.       AUTHOR 
  25690.  
  25691.       Larry Wall 
  25692.  
  25693.  
  25694. ΓòÉΓòÉΓòÉ 37. Section - perlbook ΓòÉΓòÉΓòÉ
  25695.  
  25696. NAME 
  25697.  
  25698. perlbook - Perl book information 
  25699.  
  25700. DESCRIPTION 
  25701.  
  25702. You can order Perl books from O'Reilly & Associates, 1-800-998-9938. 
  25703. Local/overseas is +1 707 829 0515.  If you can locate an O'Reilly order form, 
  25704. you can also fax to +1 707 829 0104.  Programming Perl is a reference work that 
  25705. covers nearly all of Perl (version 4, alas), while Learning Perl is a tutorial 
  25706. that covers the most frequently used subset of the language. 
  25707.  
  25708.     Programming Perl (the Camel Book):
  25709.         ISBN 0-937175-64-1      (English)
  25710.         ISBN 4-89052-384-7      (Japanese)
  25711.  
  25712.     Learning Perl (the Llama Book):
  25713.         ISBN 1-56592-042-2      (English)
  25714.         ISBN 4-89502-678-1      (Japanese)
  25715.         ISBN 2-84177-005-2      (French)
  25716.         ISBN 3-930673-08-8      (German)
  25717.  
  25718.  
  25719. ΓòÉΓòÉΓòÉ 38. Appendix - pod2ipf ΓòÉΓòÉΓòÉ
  25720.  
  25721. # $Id: pod2ipf.pl, v 0517 Wed Aug  7 09:24:34 1996 TullyS $
  25722. #
  25723. # pod2ipf - convert pod format to compilable OS/2 IPF format
  25724. # Version 1.413
  25725. # usage: pod2ipf
  25726. #
  25727. # This has a built-in list of the podfiles, to control the order
  25728. # since HPFS sorts everything into alpha-order and that's not
  25729. # what we want...
  25730. #
  25731. # Tully Steward,  71231.1173@compuserve.com
  25732. #
  25733. # Please send patches/fixes/features to me
  25734. #
  25735. #
  25736. *RS = */;
  25737. *ERRNO = *!;
  25738.  
  25739. ################################################################################
  25740. # Invoke with various levels of debugging possible
  25741. ################################################################################
  25742. while ($ARGV[0] =~ /^-d(.*)/) {
  25743.     shift;
  25744.     $Debug{ lc($1 || shift) }++;
  25745. }
  25746.  
  25747. ################################################################################
  25748. # ck for podnames on command line, usually just let it use the list def'd below.
  25749. ################################################################################
  25750. while ($ARGV[0]) {
  25751.     push(@Pods,shift);
  25752. }
  25753.  
  25754. $dir = ".";             # location of pods
  25755.  
  25756. ################################################################################
  25757. # look in these pods for things not found within the current pod
  25758. # be careful tho, namespace collisions cause stupid links
  25759. ################################################################################
  25760.  
  25761. @inclusions = qw[
  25762.      perlfunc perlvar perlrun perlop
  25763. ];
  25764.  
  25765. ################################################################################
  25766. # END CONFIGURE
  25767. ################################################################################
  25768.  
  25769.  $A = {};  # The beginning of all things
  25770.  $rescount = 0;
  25771.  
  25772. @Pods = ( 'perl.pod'
  25773. #         , 'perltoc.pod'
  25774.         , 'perldata.pod'
  25775.         , 'perlsyn.pod'
  25776.         , 'perlop.pod'
  25777.         , 'perlre.pod'
  25778.         , 'perlrun.pod'
  25779.         , 'perlfunc.pod'
  25780.         , 'perlvar.pod'
  25781.         , 'perlsub.pod'
  25782.         , 'perlmod.pod'
  25783.         , 'perlref.pod'
  25784.         , 'perldsc.pod'
  25785.         , 'perllol.pod'
  25786.         , 'perlobj.pod'
  25787.         , 'perltie.pod'
  25788.         , 'perlbot.pod'
  25789.         , 'perldebug.pod'
  25790.         , 'perldiag.pod'
  25791.         , 'perlform.pod'
  25792.         , 'perlipc.pod'
  25793.         , 'perlsec.pod'
  25794.         , 'perltrap.pod'
  25795.         , 'perlstyle.pod'
  25796.         , 'perlxs.pod'
  25797.         , 'perlxstut.pod'
  25798.         , 'perlguts.pod'
  25799.         , 'perlcall.pod'
  25800.         , 'perlembed.pod'
  25801.         , 'perlpod.pod'
  25802. #         , 'perlovl.pod'
  25803.         , 'perlbook.pod'
  25804.         );
  25805.  
  25806.   unless (@Pods)
  25807.   {
  25808.     opendir(DIR,$dir)  or  die "Can't opendir $dir: $ERRNO";
  25809.     @Pods = grep(/\.pod$/,readdir(DIR));
  25810.     closedir(DIR) or die "Can't closedir $dir: $ERRNO";
  25811.   }
  25812.   @Pods or die "aak, expected pods";
  25813.  
  25814.   $perlinf0 = 'perlinf.ipf';     # main file with most IPF statements.
  25815.   $perlinf1 = 'perlinf1.ipf';    # sub file for categorical function list
  25816.   $perlinf2 = 'perlinf2.ipf';    # sub file for alphabetical function list
  25817.   $perlinf3 = 'perlinf3.ipf';    # sub file with IPF for Perl Diag Messages.
  25818.   $perlinf4 = 'perlinf4.ipf';    # sub file with IPF for Perl Predefined var info.
  25819.   $perlinf5 = 'perlinf5.ipf';    # sub file with IPF for Perl Guts info.
  25820.  
  25821.    open(PERLINF,">$perlinf0") || die "can't create $perlinf0: $ERRNO";
  25822.   #  print PERLINF ":userdoc.\n";
  25823.   #  print PERLINF ":docprof toc=123.\n";
  25824.   #  print PERLINF ":title.Perl 5.02B Reference Manual\n\n";
  25825.  
  25826.   $lt_error  = 0;
  25827.   $lt_head1  = 1;
  25828.   $lt_head2  = 2;
  25829.   $lt_item   = 3;
  25830.   $lt_over   = 4;
  25831.   $lt_back   = 5;
  25832.   $lt_cut    = 6;
  25833.   $lt_niline = 10;
  25834.   $lt_iline  = 11;
  25835.   $lt_bline  = 12;
  25836.  
  25837.   $st_init      = 0;
  25838.   $st_para      = 1;
  25839.   $st_list      = 2;
  25840.   $st_xmp       = 3;
  25841.   $st_beg_list  = 4;
  25842.   $st_list_ul   = 5;
  25843.   $st_list_ol   = 6;
  25844.   $st_list_dl   = 7;
  25845.   $st_item_list = 8;
  25846.   $st_list_xmp  = 9;
  25847.  
  25848.   print STDERR "Sucking pods...\n";
  25849.   $rescount = 0;
  25850.   foreach $podfh ( @Pods )
  25851.   {
  25852.     ($pod = $podfh) =~ s/\.pod$//;
  25853.       Debug("files", "opening 2 $podfh" );
  25854.     print "Absorbing pod: $podfh\n";
  25855.       open($podfh,"<".$podfh)  || die "can't open $podfh: $ERRNO";
  25856.       @all = <$podfh>;
  25857.       close($podfh);
  25858.  
  25859.     if ( $pod eq 'perlfunc')
  25860.     {
  25861.       &process_func_pod($pod,\@all);
  25862.     }
  25863.     elsif ( $pod eq 'perldiag')
  25864.     {
  25865.       &process_diag_pod($pod,\@all);
  25866.     }
  25867.     elsif ( $pod eq 'perlvar')
  25868.     {
  25869.       &process_var_pod($pod,\@all);
  25870.     }
  25871.     elsif ( $pod eq 'perlguts')
  25872.     {
  25873.       &process_guts_pod($pod,\@all);
  25874.     }
  25875.     else
  25876.     {
  25877.       &process_norm_pod($pod,\@all);
  25878.     }
  25879.   }
  25880.  
  25881. #  print PERLINF ":euserdoc.\n";
  25882.  
  25883.   print "Absorbing pod2ipf\n";
  25884.   open(POD2IPF,"<POD2IPF.PL")  || die "can't open POD2IPF.PL: $ERRNO";
  25885.   @all = <POD2IPF>;
  25886.   close(POD2IPF);
  25887.  
  25888.   print PERLINF ":h1 id='pod2ipf'.Appendix - pod2ipf\n\n";
  25889.   print PERLINF ":xmp.\n";
  25890.   for ($i = 0; $i <= $#all; $i++)
  25891.   {
  25892.     $temp = $all[$i];
  25893.  
  25894.     $temp =~ s/&/&./g;
  25895.     $temp =~ s/:/&colon./g;
  25896.     $temp =~ s/%/&percent./g;
  25897.  
  25898.     print PERLINF "$temp";
  25899.  
  25900.   }
  25901.   print PERLINF ":exmp.\n";
  25902.  
  25903.   $all[0] =~ /v ([0-9]+) /;
  25904.   $rev = $1;
  25905.  
  25906.   $version = 'Version 1.XXX, OS/2 Warp Perl Manual Page Information, to accompany Perl 5.02B.';
  25907.   $version =~ s/XXX/$rev/;
  25908.  
  25909.   $timenow = localtime;
  25910.   $timenow =~ s/:/&colon./g;
  25911.  
  25912.   open(PERLREV,">PERLREVISION.IPF") || die "can't create PERLREVISION.IPF: $ERRNO";
  25913.   print PERLREV ":h1 id='VersionInfo'.Version Information\n\n";
  25914.   print PERLREV ":p.$version\n\n";
  25915.   print PERLREV ":p.Compiled&colon. $timenow\n\n";
  25916.   close(PERLREV);
  25917.  
  25918.   exit;
  25919.  
  25920. sub process_norm_pod
  25921. {
  25922.   my($pod,$all) = @_;
  25923.   my($state,$prevstate,$depth) = ($st_init,$st_init,0);
  25924.  
  25925.   print PERLINF ":h1 id='$pod'.Section - $pod\n\n";
  25926.   print PERLINF ":i1 id=$pod.$pod section\n\n";
  25927.  
  25928.   for ($i = 0; $i <= $#all; $i++)
  25929.   {
  25930.     ($type, $text) = &process_line(\$all[$i]);
  25931.     &remove_specials(\$text,( $type != $lt_iline ));
  25932.  
  25933.     TOP:
  25934.     {
  25935.       if ( $state == $st_init )
  25936.       {
  25937.         if ( $type == $lt_head1 )
  25938.         {
  25939.           print PERLINF ":p.:hp7.$text:ehp7.\n";
  25940.         }
  25941.         elsif ( $type == $lt_head2 )
  25942.         {
  25943.           print PERLINF ":p.:hp2.$text:ehp2.\n";
  25944.         }
  25945.         elsif ( $type == $lt_item )
  25946.         {
  25947.           # An item here isn't really part of a list...
  25948.           print PERLINF ":p.$text\n\n";
  25949.         }
  25950.         elsif ( $type == $lt_over )
  25951.         {
  25952.           $depth += 1;
  25953.           $state = $st_beg_list;
  25954.         }
  25955.         elsif ( $type == $lt_back )
  25956.         {
  25957.           if ($Debug{"misc"})
  25958.           {
  25959.             warn("unrecognized header: $cmd");
  25960.           }
  25961.         }
  25962.         elsif ( $type == $lt_niline )
  25963.         {
  25964.           print PERLINF ":p.$text\n";
  25965.           $state = $st_para;
  25966.         }
  25967.         elsif ( $type == $lt_iline )
  25968.         {
  25969.           print PERLINF ":xmp.\n";
  25970.           print PERLINF "$text\n";
  25971.           $state = $st_xmp;
  25972.         }
  25973.       }
  25974.       elsif($state == $st_list)
  25975.       {
  25976.         if ( $type == $lt_niline )
  25977.         {
  25978.           print PERLINF "$text\n";
  25979.         }
  25980.         elsif ( $type == $lt_iline )
  25981.         {
  25982.         }
  25983.         elsif ( $type == $lt_bline )
  25984.         {
  25985.         }
  25986.         else
  25987.         {
  25988.           $state = $st_init;
  25989.           redo TOP;
  25990.         }
  25991.       }
  25992.       elsif($state == $st_para)
  25993.       {
  25994.         if ( $type == $lt_niline )
  25995.         {
  25996.           print PERLINF "$text\n";
  25997.         }
  25998.         else
  25999.         {
  26000.           $state = $st_init;
  26001.           redo TOP;
  26002.         }
  26003.       }
  26004.       elsif($state == $st_xmp)
  26005.       {
  26006.         if ( $type == $lt_iline )
  26007.         {
  26008.           print PERLINF "$text\n";
  26009.         }
  26010.         else
  26011.         {
  26012.           print PERLINF ":exmp.\n";
  26013.           $state = $st_init;
  26014.           redo TOP;
  26015.         }
  26016.       }
  26017.       elsif($state == $st_beg_list)
  26018.       {
  26019.         if ( $type == $lt_niline )
  26020.         {
  26021.         }
  26022.         elsif ( $type == $lt_iline )
  26023.         {
  26024.         }
  26025.         elsif ( $type == $lt_bline )
  26026.         {
  26027.         }
  26028.         elsif ( $type == $lt_item )
  26029.         {
  26030.           if ( $text =~ /^\d+/ )
  26031.           {
  26032.             print PERLINF ":ol.\n";
  26033.             print PERLINF ":li.\n";
  26034.             $state = $st_list_ol;
  26035.           }
  26036.           elsif ( $text =~ /^\*\s*$/ )
  26037.           {
  26038.             print PERLINF ":ul.\n";
  26039.             print PERLINF ":li.\n";
  26040.             $state = $st_list_ul;
  26041.           }
  26042.           else
  26043.           {
  26044.             print PERLINF ":p.:hp2.$text:ehp2.\n";
  26045.             print PERLINF ":p.\n";
  26046.             $state = $st_list_dl;
  26047.           }
  26048.         }
  26049.       }
  26050.       elsif($state == $st_list_ul)
  26051.       {
  26052.         if ( $type == $lt_niline )
  26053.         {
  26054.           print PERLINF "$text\n";
  26055.         }
  26056.         elsif ( $type == $lt_iline )
  26057.         {
  26058.           print PERLINF ":xmp.\n";
  26059.           print PERLINF "$text\n";
  26060.           $prevstate = $state;
  26061.           $state = $st_list_xmp;
  26062.         }
  26063.         elsif ( $type == $lt_bline )
  26064.         {
  26065.         }
  26066.         elsif ( $type == $lt_item )
  26067.         {
  26068.           print PERLINF ":li.\n";
  26069.         }
  26070.         elsif ( $type == $lt_back )
  26071.         {
  26072.           print PERLINF ":eul.\n";
  26073.           $depth -= 1;
  26074.           $state = $st_init;
  26075.         }
  26076.         else
  26077.         {
  26078.           $state = $st_init;
  26079.           redo TOP;
  26080.         }
  26081.       }
  26082.       elsif($state == $st_list_ol)
  26083.       {
  26084.         if ( $type == $lt_niline )
  26085.         {
  26086.           print PERLINF "$text\n";
  26087.         }
  26088.         elsif ( $type == $lt_iline )
  26089.         {
  26090.           print PERLINF ":xmp.\n";
  26091.           print PERLINF "$text\n";
  26092.           $prevstate = $state;
  26093.           $state = $st_list_xmp;
  26094.         }
  26095.         elsif ( $type == $lt_bline )
  26096.         {
  26097.         }
  26098.         elsif ( $type == $lt_item )
  26099.         {
  26100.           print PERLINF ":li.\n";
  26101.         }
  26102.         elsif ( $type == $lt_back )
  26103.         {
  26104.           print PERLINF ":eol.\n";
  26105.           $depth -= 1;
  26106.           $state = $st_init;
  26107.         }
  26108.         else
  26109.         {
  26110.           $state = $st_init;
  26111.           redo TOP;
  26112.         }
  26113.       }
  26114.       elsif($state == $st_list_dl)
  26115.       {
  26116.         if ( $type == $lt_niline )
  26117.         {
  26118.           print PERLINF "$text\n";
  26119.         }
  26120.         elsif ( $type == $lt_iline )
  26121.         {
  26122.           print PERLINF ":xmp.\n";
  26123.           print PERLINF "$text\n";
  26124.           $prevstate = $state;
  26125.           $state = $st_list_xmp;
  26126.         }
  26127.         elsif ( $type == $lt_bline )
  26128.         {
  26129.         }
  26130.         elsif ( $type == $lt_item )
  26131.         {
  26132.           print PERLINF ":p.:hp2.$text:ehp2.\n";
  26133.           print PERLINF ":p.\n";
  26134.         }
  26135.         elsif ( $type == $lt_back )
  26136.         {
  26137.           $depth -= 1;
  26138.           $state = $st_init;
  26139.         }
  26140.         else
  26141.         {
  26142.           $state = $st_init;
  26143.           redo TOP;
  26144.         }
  26145.       }
  26146.       elsif($state == $st_list_xmp)
  26147.       {
  26148.         if ( $type == $lt_iline )
  26149.         {
  26150.           print PERLINF "$text\n";
  26151.         }
  26152.         else
  26153.         {
  26154.           print PERLINF ":exmp.\n";
  26155.           print PERLINF ":p.\n";
  26156.           $state = $prevstate;
  26157.           redo TOP;
  26158.         }
  26159.       }
  26160.     }
  26161.   }
  26162.  
  26163.   # At end of file, terminate any blocks...
  26164.   if ( $state == $st_xmp )
  26165.   {
  26166.     print PERLINF ":exmp.\n";
  26167.   }
  26168. }
  26169.  
  26170. sub process_line
  26171. {
  26172.   my($line) = @_;
  26173.  
  26174.   if (${$line} =~ /^=(\w+)\s*(.*)\n?$/)
  26175.   {
  26176.     # handle command...
  26177.     ($cmd, $text) = ($1,$2);
  26178.  
  26179.     if ($cmd =~ /^head([12])/)
  26180.     {
  26181.       if ($1 == 1)
  26182.       {
  26183.         return ($lt_head1,$text);
  26184.       }
  26185.       else
  26186.       {
  26187.         return ($lt_head2,$text);
  26188.       }
  26189.     }
  26190.     elsif ($cmd =~ /^item/)
  26191.     {
  26192.       return ($lt_item,$text);
  26193.     }
  26194.     elsif ($cmd =~ /^over/)
  26195.     {
  26196.       return ($lt_over,$text);
  26197.     }
  26198.     elsif ($cmd =~ /^back/)
  26199.     {
  26200.       return ($lt_back,'');
  26201.     }
  26202.     elsif ($cmd =~ /^cut/)
  26203.     {
  26204.       return ($lt_cut,'');
  26205.     }
  26206.     elsif ($Debug{"misc"})
  26207.     {
  26208.       warn("unrecognized header: $cmd");
  26209.     }
  26210.     return ($lt_error);
  26211.   }
  26212.   elsif(${$line} =~ /^([^\n\t ][^\n]+)\n?$/)
  26213.   {
  26214.     # handle non-indented line...
  26215.     return ($lt_niline,$1);
  26216.   }
  26217.   elsif(${$line} =~ /^(\s+[^\n]+)\n?$/)
  26218.   {
  26219.     # handle indented line...
  26220.     return ($lt_iline,$1);
  26221.   }
  26222.   else
  26223.   {
  26224.     # handle blank line...
  26225.     return ($lt_bline,'');
  26226.   }
  26227. }
  26228.  
  26229. sub remove_specials
  26230. {
  26231.   my($line,$switch) = @_;
  26232.  
  26233. # Do these first since they will change the final line length...
  26234.  
  26235.   if ( $switch != 0 )
  26236.   {
  26237.     ${$line} =~ s/[E]<gt>/\>/g;
  26238.     ${$line} =~ s/[E]<lt>/\</g;
  26239.     ${$line} =~ s/[C]<(.*?)>/$1/g;
  26240.     ${$line} =~ s/[S]<(.*?)>/$1/g;
  26241.   }
  26242.  
  26243. # Detab this version of the line now...
  26244.  
  26245.   if ( ${$line} =~ /\t/ )
  26246.   {
  26247. #     ${$line} =~ s/\t/    /g;
  26248.  
  26249.     while( ($tabpos = index(${$line}, "\t" )) != -1 )
  26250.     {
  26251.       $tabwidth = (8 - ($tabpos % 8));
  26252.  
  26253.       $spaces = '';
  26254.       while ( $tabwidth > 0 )
  26255.       {
  26256.         $spaces = $spaces.' ';
  26257.         $tabwidth -= 1;
  26258.       }
  26259.  
  26260.       ${$line} =~ s/\t/$spaces/;
  26261.     }
  26262.   }
  26263.  
  26264. # And translate the codes that screw up the IPFC, but that it will take
  26265. # right back out (so the length won't change)...
  26266.  
  26267.   ${$line} =~ s/&/&./g;
  26268.   ${$line} =~ s/:/&colon./g;
  26269.   ${$line} =~ s/%/&percent./g;
  26270.  
  26271. # and hilite or italicize ...
  26272.  
  26273.   if ( $switch != 0 )
  26274.   {
  26275.     ${$line} =~ s/[IF]<(.*?)>/:hp1.$1:ehp1./g;
  26276.     ${$line} =~ s/[B]<(.*?)>/:hp2.$1:ehp2./g;
  26277.   }
  26278.  
  26279. # and insert any link info ...
  26280.  
  26281.     $mask1 = "[L]<(perl[^>]*)>";
  26282.     $mask2 = "(perl.*?)(/.*)";
  26283.  
  26284.     while ( ${$line} =~ m|$mask1|g )
  26285.     {
  26286.       $maskitem = $1;
  26287.       $linkitem = $1;
  26288.       $linkitem =~ s|$mask2|$1|;
  26289.       $restitem = $2;
  26290.       ${$line} =~ s|$mask1|:link reftype=hd refid='$linkitem'.$linkitem:elink.$restitem|;
  26291.     }
  26292.  
  26293. }
  26294.  
  26295. sub Debug {
  26296.     my $level = shift;
  26297.     print STDERR @_,"\n" if $Debug{$level};
  26298. }
  26299.  
  26300. sub process_func_pod
  26301. {
  26302.   my($pod,$all) = @_;
  26303.   my($state,$part) = ($st_init,0);
  26304.  
  26305.   print PERLINF ":h1 id='$pod'.Section - $pod\n\n";
  26306.   print PERLINF ":i1 id=$pod.$pod section\n\n";
  26307.   open(PERLINF1,">$perlinf1") || die "can't create $perlinf1: $ERRNO";
  26308.   open(PERLINF2,">$perlinf2") || die "can't create $perlinf2: $ERRNO";
  26309.  
  26310.   for ($i = 0; $i <= $#all; $i++)
  26311.   {
  26312.     ($type, $text) = &process_line(\$all[$i]);
  26313.  
  26314.     &remove_specials(\$text,( $type != $lt_iline ));
  26315.  
  26316.     if ( $part == 0 )
  26317.     {
  26318.       TOP:
  26319.       {
  26320.         if ( $state == $st_init )
  26321.         {
  26322.           if ( $type == $lt_head1 )
  26323.           {
  26324.             print PERLINF ":p.:hp7.$text:ehp7.\n";
  26325.           }
  26326.           elsif ( $type == $lt_head2 )
  26327.           {
  26328.             if ( $text =~ /^Perl Functions/ )
  26329.             {
  26330.               # Go do the category function list as individual
  26331.               # IPF sections, instead of the way they had it...
  26332.               print PERLINF1 ":h1 id='PerlCategoryList'.Categorical Listing of Perl Functions\n\n";
  26333.               print PERLINF1 ":i2 refid=$pod.Categorical Listing of Perl Functions\n\n";
  26334.               print PERLINF1 ":p.:hp7.Categorical Listing of Perl Functions:ehp7.\n";
  26335.               $part = 1;
  26336.               $state = $st_init;
  26337.             }
  26338.             else
  26339.             {
  26340.               print PERLINF ":p.:hp7.$text:ehp7.\n";
  26341.             }
  26342.           }
  26343.           elsif ( $type == $lt_item )
  26344.           {
  26345.             print PERLINF ":p.:hp2.$text:ehp2.\n";
  26346.           }
  26347.           elsif ( $type == $lt_niline )
  26348.           {
  26349.             $state = $st_para;
  26350.             print PERLINF ":p.$text\n";
  26351.           }
  26352.           elsif ( $type == $lt_iline )
  26353.           {
  26354.             $state = $st_xmp;
  26355.             print PERLINF ":xmp.\n";
  26356.             print PERLINF "$text\n";
  26357.           }
  26358.           elsif ( $type == $lt_bline )
  26359.           {
  26360.           }
  26361.         }
  26362.         elsif($state == $st_para)
  26363.         {
  26364.           if ( $type == $lt_niline )
  26365.           {
  26366.             print PERLINF "$text\n";
  26367.           }
  26368.           else
  26369.           {
  26370.             $state = $st_init;
  26371.             redo TOP;
  26372.           }
  26373.         }
  26374.         elsif($state == $st_xmp)
  26375.         {
  26376.           if ( $type == $lt_iline )
  26377.           {
  26378.             print PERLINF "$text\n";
  26379.           }
  26380.           elsif ( $type == $lt_bline )
  26381.           {
  26382.           }
  26383.           else
  26384.           {
  26385.             print PERLINF ":exmp.\n";
  26386.             $state = $st_init;
  26387.             redo TOP;
  26388.           }
  26389.         }
  26390.       }
  26391.     }
  26392.     elsif ( $part == 1 )
  26393.     {
  26394.      # Process the categorical function list, by
  26395.      #
  26396.      TOP:
  26397.       {
  26398.         if ( $state == $st_init )
  26399.         {
  26400.           if ( $type == $lt_head1 )
  26401.           {
  26402.             print PERLINF1 ":p.:hp7.$text:ehp7.\n";
  26403.           }
  26404.           elsif ( $type == $lt_head2 )
  26405.           {
  26406.             if ( $text =~ /^Alphabetical/ )
  26407.             {
  26408.               close(PERLINF1);
  26409.               # Go do the alpha function list as individual
  26410.               # IPF sections, instead of the way they had it...
  26411.               print PERLINF ":p.:link reftype=hd refid='PerlCategoryList'.Categorical Listing of Perl Functions:elink.\n";
  26412.               print PERLINF ":p.:link reftype=hd refid='PerlFuncList'.Alphabetical Listing of Perl Functions:elink.\n";
  26413.               print PERLINF ".im $perlinf1\n";
  26414.               print PERLINF ":h1 id='PerlFuncList'.Alphabetical Listing of Perl Functions\n\n";
  26415.               print PERLINF ":i2 refid=$pod.Alphabetical Listing of Perl Functions\n\n";
  26416.               print PERLINF ":p.:hp7.Alphabetical Listing of Perl Functions:ehp7.\n";
  26417.               print PERLINF ":sl compact.\n";
  26418.               $part = 2;
  26419.               $state = $st_init;
  26420.             }
  26421.             else
  26422.             {
  26423.               print PERLINF1 ":p.:hp7.$text:ehp7.\n";
  26424.             }
  26425.           }
  26426.           elsif ( $type == $lt_item )
  26427.           {
  26428.             print PERLINF1 ":p.:hp2.$text:ehp2.\n";
  26429.           }
  26430.           elsif ( $type == $lt_niline )
  26431.           {
  26432.             $state = $st_para;
  26433.             print PERLINF1 ":p.$text\n";
  26434.           }
  26435.           elsif ( $type == $lt_iline )
  26436.           {
  26437.             $state = $st_xmp;
  26438.             print PERLINF1 ":xmp.\n";
  26439.             print PERLINF1 "$text\n";
  26440.           }
  26441.           elsif ( $type == $lt_bline )
  26442.           {
  26443.           }
  26444.         }
  26445.         elsif($state == $st_para)
  26446.         {
  26447.           if ( $type == $lt_niline )
  26448.           {
  26449.             print PERLINF1 "$text\n";
  26450.           }
  26451.           else
  26452.           {
  26453.             $state = $st_init;
  26454.             redo TOP;
  26455.           }
  26456.         }
  26457.         elsif($state == $st_xmp)
  26458.         {
  26459.           if ( $type == $lt_iline )
  26460.           {
  26461.             print PERLINF1 "$text\n";
  26462.           }
  26463.           elsif ( $type == $lt_bline )
  26464.           {
  26465.           }
  26466.           else
  26467.           {
  26468.             print PERLINF1 ":exmp.\n";
  26469.             $state = $st_init;
  26470.             redo TOP;
  26471.           }
  26472.         }
  26473.       }
  26474.     }
  26475.     elsif ( $part == 2 )
  26476.     {
  26477.       # Process the alphabetical function list, by
  26478.       #
  26479.       TOP:
  26480.       {
  26481.         if ( $state == $st_init )
  26482.         {
  26483.           if ( $type == $lt_item )
  26484.           {
  26485.             $rescount += 1;
  26486.             print PERLINF2 ":h2 res=$rescount.$text\n\n";
  26487.             print PERLINF2 ":p.:hp2.$text:ehp2.\n";
  26488.             print PERLINF ":li.:link reftype=hd res=$rescount.$text:elink.\n";
  26489.             @temp = split(' ',$text);
  26490.             $funclink{$temp[0]} = $rescount;
  26491.             $state = $st_item_list;
  26492.           }
  26493.           elsif ( $type == $lt_niline )
  26494.           {
  26495.             $state = $st_para;
  26496.             print PERLINF2 ":p.$text\n";
  26497.           }
  26498.           elsif ( $type == $lt_iline )
  26499.           {
  26500.             $state = $st_xmp;
  26501.             print PERLINF2 ":xmp.\n";
  26502.             print PERLINF2 "$text\n";
  26503.           }
  26504.         }
  26505.         elsif($state == $st_item_list)
  26506.         {
  26507.           if ( $type == $lt_item )
  26508.           {
  26509.             print PERLINF2 ":p.:hp2.$text:ehp2.\n";
  26510.             print PERLINF ":li.:link reftype=hd res=$rescount.$text:elink.\n";
  26511.             @temp = split(' ',$text);
  26512.             $funclink{$temp[0]} = $rescount;
  26513.           }
  26514.           elsif ( $type == $lt_niline )
  26515.           {
  26516.             $state = $st_para;
  26517.             print PERLINF2 ":p.$text\n";
  26518.           }
  26519.           elsif ( $type == $lt_iline )
  26520.           {
  26521.             $state = $st_xmp;
  26522.             print PERLINF2 ":xmp.\n";
  26523.             print PERLINF2 "$text\n";
  26524.           }
  26525.         }
  26526.         elsif($state == $st_para)
  26527.         {
  26528.           if ( $type == $lt_niline )
  26529.           {
  26530.             print PERLINF2 "$text\n";
  26531.           }
  26532.           else
  26533.           {
  26534.             $state = $st_init;
  26535.             redo TOP;
  26536.           }
  26537.         }
  26538.         elsif($state == $st_xmp)
  26539.         {
  26540.           if ( $type == $lt_iline )
  26541.           {
  26542.             print PERLINF2 "$text\n";
  26543.           }
  26544.           elsif ( $type == $lt_bline )
  26545.           {
  26546.           }
  26547.           else
  26548.           {
  26549.             print PERLINF2 ":exmp.\n";
  26550.             $state = $st_init;
  26551.             redo TOP;
  26552.           }
  26553.         }
  26554.       }
  26555.     }
  26556.   }
  26557.  
  26558.   close(PERLINF2);
  26559.  
  26560.   # Now we'll set all the category links by reading in the category
  26561.   # sub file and translating using the index we built...
  26562.  
  26563.   $temp = $/;
  26564.   undef $/;
  26565.   open(PERLINF1,"<$perlinf1") || die "can't read $perlinf1: $ERRNO";
  26566.   $filecontents = <PERLINF1>;
  26567.   close(PERLINF1);
  26568.   $/ = $temp;
  26569.  
  26570.   foreach $functype (keys(%funclink))
  26571.   {
  26572.     $temp = $funclink{$functype};
  26573. #    @func = split(' ',$functype);
  26574.  
  26575.     $filecontents =~ s|([^\w:])$functype([^\w ])|$1:link reftype=hd res=$temp.$functype:elink.$2|g;
  26576.  
  26577. #    print PERLINF ".* $functype $temp $func[0]\n";
  26578. #    print PERLINF ".* $functype $temp $func[0]\n";
  26579.   }
  26580.  
  26581.   open(PERLINF1,">$perlinf1") || die "can't create $perlinf1: $ERRNO";
  26582.   print PERLINF1 $filecontents;
  26583.   close(PERLINF1);
  26584. #  exit 99;
  26585.  
  26586.   print PERLINF ":esl.\n";
  26587.   print PERLINF ".im $perlinf2\n";
  26588. }
  26589.  
  26590. sub process_diag_pod
  26591. {
  26592.   my($pod,$all) = @_;
  26593.   my($state,$part) = ($st_init,0);
  26594.  
  26595.   print PERLINF ":h1 id='$pod'.Section - $pod\n\n";
  26596.   print PERLINF ":i1 id=$pod.$pod section\n\n";
  26597.   open(PERLINF3,">$perlinf3") || die "can't create $perlinf3: $ERRNO";
  26598.  
  26599.   for ($i = 0; $i <= $#all; $i++)
  26600.   {
  26601.     ($type, $text) = &process_line(\$all[$i]);
  26602.  
  26603.     &remove_specials(\$text,( $type != $lt_iline ));
  26604.  
  26605.     if ( $part == 0 )
  26606.     {
  26607.       TOP:
  26608.       {
  26609.         if ( $state == $st_init )
  26610.         {
  26611.           if ( $type == $lt_head1 )
  26612.           {
  26613.             print PERLINF ":p.:hp7.$text:ehp7.\n";
  26614.           }
  26615.           elsif ( $type == $lt_over )
  26616.           {
  26617.             # Go do the message list as individual
  26618.             # IPF sections, instead of the way they had it...
  26619.             print PERLINF ":p.:link reftype=hd refid='PerlMessageList'.Listing of Perl Diagnostic Messages:elink.\n";
  26620.             print PERLINF ":h1 id='PerlMessageList'.Listing of Perl Diagnostic Messages\n\n";
  26621.             print PERLINF ":i2 refid=$pod.Listing of Perl Diagnostic Messages\n\n";
  26622.             print PERLINF ":p.:hp7.Listing of Perl Diagnostic Messages:ehp7.\n";
  26623.             print PERLINF ":sl compact.\n";
  26624.             $part = 1;
  26625.             $state = $st_init;
  26626.           }
  26627.           elsif ( $type == $lt_niline )
  26628.           {
  26629.             $state = $st_para;
  26630.             print PERLINF ":p.$text\n";
  26631.           }
  26632.           elsif ( $type == $lt_iline )
  26633.           {
  26634.             $state = $st_xmp;
  26635.             print PERLINF ":xmp.\n";
  26636.             print PERLINF "$text\n";
  26637.           }
  26638.           elsif ( $type == $lt_bline )
  26639.           {
  26640.           }
  26641.         }
  26642.         elsif($state == $st_para)
  26643.         {
  26644.           if ( $type == $lt_niline )
  26645.           {
  26646.             print PERLINF "$text\n";
  26647.           }
  26648.           else
  26649.           {
  26650.             $state = $st_init;
  26651.             redo TOP;
  26652.           }
  26653.         }
  26654.         elsif($state == $st_xmp)
  26655.         {
  26656.           if ( $type == $lt_iline )
  26657.           {
  26658.             print PERLINF "$text\n";
  26659.           }
  26660.           elsif ( $type == $lt_bline )
  26661.           {
  26662.           }
  26663.           else
  26664.           {
  26665.             print PERLINF ":exmp.\n";
  26666.             $state = $st_init;
  26667.             redo TOP;
  26668.           }
  26669.         }
  26670.       }
  26671.     }
  26672.     else
  26673.     {
  26674.       # Process the diag message list, by
  26675.       #
  26676.       TOP:
  26677.       {
  26678.         if ( $state == $st_init )
  26679.         {
  26680.           if ( $type == $lt_item )
  26681.           {
  26682.             $rescount += 1;
  26683.             print PERLINF3 ":h2 res=$rescount.$text\n\n";
  26684.             print PERLINF3 ":p.:hp2.$text:ehp2.\n";
  26685.             print PERLINF ":li.:link reftype=hd res=$rescount.$text:elink.\n";
  26686.           }
  26687.           elsif ( $type == $lt_niline )
  26688.           {
  26689.             print PERLINF3 ":p.$text\n";
  26690.             $state = $st_para;
  26691.           }
  26692.           elsif ( $type == $lt_iline )
  26693.           {
  26694.             print PERLINF3 ":xmp.\n";
  26695.             print PERLINF3 "$text\n";
  26696.             $state = $st_xmp;
  26697.           }
  26698.         }
  26699.         elsif($state == $st_para)
  26700.         {
  26701.           if ( $type == $lt_niline )
  26702.           {
  26703.             print PERLINF3 "$text\n";
  26704.           }
  26705.           else
  26706.           {
  26707.             $state = $st_init;
  26708.             redo TOP;
  26709.           }
  26710.         }
  26711.         elsif($state == $st_xmp)
  26712.         {
  26713.           if ( $type == $lt_iline )
  26714.           {
  26715.             print PERLINF3 "$text\n";
  26716.           }
  26717.           elsif ( $type == $lt_bline )
  26718.           {
  26719.           }
  26720.           else
  26721.           {
  26722.             print PERLINF3 ":exmp.\n";
  26723.             $state = $st_init;
  26724.             redo TOP;
  26725.           }
  26726.         }
  26727.       }
  26728.     }
  26729.   }
  26730.  
  26731.   close(PERLINF3);
  26732.   print PERLINF ":esl.\n";
  26733.   print PERLINF ".im $perlinf3\n";
  26734. }
  26735.  
  26736. sub process_var_pod
  26737. {
  26738.   my($pod,$all) = @_;
  26739.   my($state,$part) = ($st_init,0);
  26740.  
  26741.   print PERLINF ":h1 id='$pod'.Section - $pod\n\n";
  26742.   print PERLINF ":i1 id=$pod.$pod section\n\n";
  26743.   open(PERLINF4,">$perlinf4") || die "can't create $perlinf4: $ERRNO";
  26744.  
  26745.   for ($i = 0; $i <= $#all; $i++)
  26746.   {
  26747.     ($type, $text) = &process_line(\$all[$i]);
  26748.  
  26749.     &remove_specials(\$text,( $type != $lt_iline ));
  26750.  
  26751.     if ( $part == 0 )
  26752.     {
  26753.       TOP:
  26754.       {
  26755.         if ( $state == $st_init )
  26756.         {
  26757.           if ( $type == $lt_head1 )
  26758.           {
  26759.             print PERLINF ":p.:hp7.$text:ehp7.\n";
  26760.           }
  26761.           elsif ( $type == $lt_head2 )
  26762.           {
  26763.             print PERLINF ":p.:hp7.$text:ehp7.\n";
  26764.           }
  26765.           elsif ( $type == $lt_over )
  26766.           {
  26767.             # Go do the predefined variable list as individual
  26768.             # IPF sections, instead of the way they had it...
  26769.             print PERLINF ":p.:link reftype=hd refid='PerlVarList'.Listing of Perl Predefined Variables:elink.\n";
  26770.             print PERLINF ":h1 id='PerlVarList'.Listing of Perl Predefined Variables\n\n";
  26771.             print PERLINF ":i2 refid=$pod.Listing of Perl Predefined Variables\n\n";
  26772.             print PERLINF ":p.:hp7.Listing of Perl Predefined Variables:ehp7.\n";
  26773.             print PERLINF ":sl compact.\n";
  26774.             $part = 1;
  26775.             $state = $st_init;
  26776.           }
  26777.           elsif ( $type == $lt_item )
  26778.           {
  26779.             print PERLINF ":p.:hp2.$text:ehp2.\n";
  26780.           }
  26781.           elsif ( $type == $lt_niline )
  26782.           {
  26783.             $state = $st_para;
  26784.             print PERLINF ":p.$text\n";
  26785.           }
  26786.           elsif ( $type == $lt_iline )
  26787.           {
  26788.             $state = $st_xmp;
  26789.             print PERLINF ":xmp.\n";
  26790.             print PERLINF "$text\n";
  26791.           }
  26792.           elsif ( $type == $lt_bline )
  26793.           {
  26794.           }
  26795.         }
  26796.         elsif($state == $st_para)
  26797.         {
  26798.           if ( $type == $lt_niline )
  26799.           {
  26800.             print PERLINF "$text\n";
  26801.           }
  26802.           else
  26803.           {
  26804.             $state = $st_init;
  26805.             redo TOP;
  26806.           }
  26807.         }
  26808.         elsif($state == $st_xmp)
  26809.         {
  26810.           if ( $type == $lt_iline )
  26811.           {
  26812.             print PERLINF "$text\n";
  26813.           }
  26814.           elsif ( $type == $lt_bline )
  26815.           {
  26816.           }
  26817.           else
  26818.           {
  26819.             print PERLINF ":exmp.\n";
  26820.             $state = $st_init;
  26821.             redo TOP;
  26822.           }
  26823.         }
  26824.       }
  26825.     }
  26826.     else
  26827.     {
  26828.       # Process the predefined variable list list, by
  26829.       #
  26830.       TOP:
  26831.       {
  26832.         if ( $state == $st_init )
  26833.         {
  26834.           if ( $type == $lt_item )
  26835.           {
  26836.             $rescount += 1;
  26837.             print PERLINF4 ":h2 res=$rescount.$text\n\n";
  26838.             print PERLINF4 ":p.:hp2.$text:ehp2.\n";
  26839.             print PERLINF ":li.:link reftype=hd res=$rescount.$text:elink.\n";
  26840.             $state = $st_item_list;
  26841.           }
  26842.           elsif ( $type == $lt_niline )
  26843.           {
  26844.             $state = $st_para;
  26845.             print PERLINF4 ":p.$text\n";
  26846.           }
  26847.           elsif ( $type == $lt_iline )
  26848.           {
  26849.             $state = $st_xmp;
  26850.             print PERLINF4 ":xmp.\n";
  26851.             print PERLINF4 "$text\n";
  26852.           }
  26853.           elsif ( $type == $lt_over )
  26854.           {
  26855.             print PERLINF4 ":ul.\n";
  26856.             $state = $st_list_ul;
  26857.           }
  26858.         }
  26859.         elsif($state == $st_item_list)
  26860.         {
  26861.           if ( $type == $lt_item )
  26862.           {
  26863.             print PERLINF4 ":p.:hp2.$text:ehp2.\n";
  26864.             print PERLINF ":li.:link reftype=hd res=$rescount.$text:elink.\n";
  26865.           }
  26866.           elsif ( $type == $lt_niline )
  26867.           {
  26868.             $state = $st_para;
  26869.             print PERLINF4 ":p.$text\n";
  26870.           }
  26871.           elsif ( $type == $lt_iline )
  26872.           {
  26873.             $state = $st_xmp;
  26874.             print PERLINF4 ":xmp.\n";
  26875.             print PERLINF4 "$text\n";
  26876.           }
  26877.         }
  26878.         elsif($state == $st_para)
  26879.         {
  26880.           if ( $type == $lt_niline )
  26881.           {
  26882.             print PERLINF4 "$text\n";
  26883.           }
  26884.           else
  26885.           {
  26886.             $state = $st_init;
  26887.             redo TOP;
  26888.           }
  26889.         }
  26890.         elsif($state == $st_xmp)
  26891.         {
  26892.           if ( $type == $lt_iline )
  26893.           {
  26894.             print PERLINF4 "$text\n";
  26895.           }
  26896.           elsif ( $type == $lt_bline )
  26897.           {
  26898.           }
  26899.           else
  26900.           {
  26901.             print PERLINF4 ":exmp.\n";
  26902.             $state = $st_init;
  26903.             redo TOP;
  26904.           }
  26905.         }
  26906.         elsif($state == $st_list_ul)
  26907.         {
  26908.           if ( $type == $lt_niline )
  26909.           {
  26910.             print PERLINF4 "$text\n";
  26911.           }
  26912.           elsif ( $type == $lt_bline )
  26913.           {
  26914.           }
  26915.           elsif ( $type == $lt_item )
  26916.           {
  26917.             print PERLINF4 ":li.\n";
  26918.           }
  26919.           elsif ( $type == $lt_back )
  26920.           {
  26921.             print PERLINF4 ":eul.\n";
  26922.             $state = $st_init;
  26923.           }
  26924.           else
  26925.           {
  26926.             $state = $st_init;
  26927.             redo TOP;
  26928.           }
  26929.         }
  26930.       }
  26931.     }
  26932.   }
  26933.  
  26934.   close(PERLINF4);
  26935.   print PERLINF ":esl.\n";
  26936.   print PERLINF ".im $perlinf4\n";
  26937. }
  26938.  
  26939. sub process_guts_pod
  26940. {
  26941.   my($pod,$all) = @_;
  26942.   my($state,$part) = ($st_init,0);
  26943.  
  26944.   print PERLINF ":h1 id='$pod'.Section - $pod\n\n";
  26945.   print PERLINF ":i1 id=$pod.$pod section\n\n";
  26946.   open(PERLINF5,">$perlinf5") || die "can't create $perlinf5: $ERRNO";
  26947.  
  26948.   for ($i = 0; $i <= $#all; $i++)
  26949.   {
  26950.     ($type, $text) = &process_line(\$all[$i]);
  26951.  
  26952.     &remove_specials(\$text,( $type != $lt_iline ));
  26953.  
  26954.     if ( $part == 0 )
  26955.     {
  26956.       TOP:
  26957.       {
  26958.         if ( $state == $st_init )
  26959.         {
  26960.           if ( $type == $lt_head1 )
  26961.           {
  26962.             print PERLINF ":p.:hp7.$text:ehp7.\n";
  26963.           }
  26964.           elsif ( $type == $lt_head2 )
  26965.           {
  26966.             print PERLINF ":p.:hp7.$text:ehp7.\n";
  26967.           }
  26968.           elsif ( $type == $lt_over )
  26969.           {
  26970.             # Go do the API LISTING as individual
  26971.             # IPF sections, instead of the way they had it...
  26972.             print PERLINF ":p.:link reftype=hd refid='PerlAPIList'.Listing of Perl Internal API:elink.\n";
  26973.             print PERLINF ":h1 id='PerlAPIList'.Listing of Perl Internal API\n\n";
  26974.             print PERLINF ":i2 refid=$pod.Listing of Perl Internal API\n\n";
  26975.             print PERLINF ":p.:hp7.Listing of Perl Internal API:ehp7.\n";
  26976.             print PERLINF ":sl compact.\n";
  26977.             $part = 1;
  26978.             $state = $st_init;
  26979.           }
  26980.           elsif ( $type == $lt_item )
  26981.           {
  26982.             print PERLINF ":p.:hp2.$text:ehp2.\n";
  26983.           }
  26984.           elsif ( $type == $lt_niline )
  26985.           {
  26986.             $state = $st_para;
  26987.             print PERLINF ":p.$text\n";
  26988.           }
  26989.           elsif ( $type == $lt_iline )
  26990.           {
  26991.             $state = $st_xmp;
  26992.             print PERLINF ":xmp.\n";
  26993.             print PERLINF "$text\n";
  26994.           }
  26995.           elsif ( $type == $lt_bline )
  26996.           {
  26997.           }
  26998.         }
  26999.         elsif($state == $st_para)
  27000.         {
  27001.           if ( $type == $lt_niline )
  27002.           {
  27003.             print PERLINF "$text\n";
  27004.           }
  27005.           else
  27006.           {
  27007.             $state = $st_init;
  27008.             redo TOP;
  27009.           }
  27010.         }
  27011.         elsif($state == $st_xmp)
  27012.         {
  27013.           if ( $type == $lt_iline )
  27014.           {
  27015.             print PERLINF "$text\n";
  27016.           }
  27017.           elsif ( $type == $lt_bline )
  27018.           {
  27019.           }
  27020.           else
  27021.           {
  27022.             print PERLINF ":exmp.\n";
  27023.             $state = $st_init;
  27024.             redo TOP;
  27025.           }
  27026.         }
  27027.       }
  27028.     }
  27029.     else
  27030.     {
  27031.       # Process the API LISTING, by
  27032.       #
  27033.       TOP:
  27034.       {
  27035.         if ( $state == $st_init )
  27036.         {
  27037.           if ( $type == $lt_item )
  27038.           {
  27039.             $rescount += 1;
  27040.             print PERLINF5 ":h2 res=$rescount.$text\n\n";
  27041.             print PERLINF5 ":p.:hp2.$text:ehp2.\n";
  27042.             print PERLINF ":li.:link reftype=hd res=$rescount.$text:elink.\n";
  27043.             $state = $st_item_list;
  27044.           }
  27045.           elsif ( $type == $lt_niline )
  27046.           {
  27047.             $state = $st_para;
  27048.             print PERLINF5 ":p.$text\n";
  27049.           }
  27050.           elsif ( $type == $lt_iline )
  27051.           {
  27052.             $state = $st_xmp;
  27053.             print PERLINF5 ":xmp.\n";
  27054.             print PERLINF5 "$text\n";
  27055.           }
  27056.           elsif ( $type == $lt_over )
  27057.           {
  27058.             print PERLINF5 ":ul.\n";
  27059.             $state = $st_list_ul;
  27060.           }
  27061.         }
  27062.         elsif($state == $st_item_list)
  27063.         {
  27064.           if ( $type == $lt_item )
  27065.           {
  27066.             print PERLINF5 ":p.:hp2.$text:ehp2.\n";
  27067.             print PERLINF ":li.:link reftype=hd res=$rescount.$text:elink.\n";
  27068.           }
  27069.           elsif ( $type == $lt_niline )
  27070.           {
  27071.             $state = $st_para;
  27072.             print PERLINF5 ":p.$text\n";
  27073.           }
  27074.           elsif ( $type == $lt_iline )
  27075.           {
  27076.             $state = $st_xmp;
  27077.             print PERLINF5 ":xmp.\n";
  27078.             print PERLINF5 "$text\n";
  27079.           }
  27080.         }
  27081.         elsif($state == $st_para)
  27082.         {
  27083.           if ( $type == $lt_niline )
  27084.           {
  27085.             print PERLINF5 "$text\n";
  27086.           }
  27087.           else
  27088.           {
  27089.             $state = $st_init;
  27090.             redo TOP;
  27091.           }
  27092.         }
  27093.         elsif($state == $st_xmp)
  27094.         {
  27095.           if ( $type == $lt_iline )
  27096.           {
  27097.             print PERLINF5 "$text\n";
  27098.           }
  27099.           elsif ( $type == $lt_bline )
  27100.           {
  27101.           }
  27102.           else
  27103.           {
  27104.             print PERLINF5 ":exmp.\n";
  27105.             $state = $st_init;
  27106.             redo TOP;
  27107.           }
  27108.         }
  27109.         elsif($state == $st_list_ul)
  27110.         {
  27111.           if ( $type == $lt_niline )
  27112.           {
  27113.             print PERLINF5 "$text\n";
  27114.           }
  27115.           elsif ( $type == $lt_bline )
  27116.           {
  27117.           }
  27118.           elsif ( $type == $lt_item )
  27119.           {
  27120.             print PERLINF5 ":li.\n";
  27121.           }
  27122.           elsif ( $type == $lt_back )
  27123.           {
  27124.             print PERLINF5 ":eul.\n";
  27125.             $state = $st_init;
  27126.           }
  27127.           else
  27128.           {
  27129.             $state = $st_init;
  27130.             redo TOP;
  27131.           }
  27132.         }
  27133.       }
  27134.     }
  27135.   }
  27136.  
  27137.   close(PERLINF5);
  27138.   print PERLINF ":esl.\n";
  27139.   print PERLINF ".im $perlinf5\n";
  27140. }
  27141.