home *** CD-ROM | disk | FTP | other *** search
/ PC Online 1996 December / PCO1296.ISO / filesbbs / content / perl-faq.txt < prev    next >
Encoding:
Text File  |  1996-10-17  |  201.4 KB  |  5,154 lines

  1.  
  2. Article: 62264 in news.answers
  3. Path: Dortmund.Germany.EU.net!nntp.gmd.de!news.ruhr-uni-bochum.de!news.dfn.de!hookup!gatech!newsfeed.internetmci.com!news.dacom.co.kr!usenet.seri.re.kr!news.cais.net!news1.radix.net!news1.radix.net!spp
  4. From: spp@psa.pencom.com
  5. Newsgroups: comp.lang.perl.announce,comp.lang.perl.misc,comp.answers,news.answers
  6. Subject: comp.lang.perl.* FAQ 0/5 - Introduction
  7. Followup-To: poster
  8. Date: 27 Jan 1996 01:21:04 GMT
  9. Organization: Pencom Systems Administration
  10. Lines: 223
  11. Approved: news-answers-request@MIT.EDU
  12. Distribution: world
  13. Message-ID: <SPP.96Jan26202104@syrinx.hideout.com>
  14. NNTP-Posting-Host: dialin23.annex1.radix.net
  15. Xref: Dortmund.Germany.EU.net comp.lang.perl.announce:240 comp.lang.perl.misc:18664 comp.answers:16588 news.answers:62264
  16.  
  17.  
  18. Archive-name: perl-faq/part0
  19. Version: $Id: perl-intro,v 2.8 1995/05/15 15:43:59 spp Exp spp $
  20. Posting-Frequency: bi-weekly
  21. Last Edited: Thu Jan 11 00:52:58 1996 by spp (Stephen P Potter) on syrinx.psa.com
  22.  
  23. Hear ye, hear ye.  This most honourable session on Perl Frequently Asked
  24. Questions is hereby called to order.  Please stand and show your respect
  25. for those that have gone before us.  Let us honour Larry Wall*, the father
  26. of Perl who unselfishly spends vast amounts of time reviewing this document
  27. for veracity and accuracy.  Let us also honour Tom Christiansen* without
  28. whom this document would not exist.  Finally, let us collectively honour
  29. the members of comp.lang.perl.misc who have offered much advice and
  30. corrections to this list.
  31.  
  32. This article details the contents of the most Frequently Asked Questions in
  33. comp.lang.perl.misc, a Usenet newsgroup devoted to the Perl programming
  34. language.  There are five pieces following this, the general information
  35. questions in part1, part2 and part3 and the programming ones in part4 and
  36. part5. 
  37.  
  38. If this is your first exposure to Perl, please read this document and the 
  39. perl(1) man page before asking questions in comp.lang.perl.misc.  If you're
  40. using v4 perl, that page contains all you need to know (or at least enough
  41. to get started).  If you're using v5 perl, that page will show you where to
  42. look for specific information.  When we refer to perlmod(1), it means the 
  43. "perlmod" man page in section "1" of the manual, just as Foo(3pm), that
  44. means it's the "Foo" man page in section "3pm" (perl modules) of the
  45. library.  The perl install does NOT automatically install the module man
  46. pages for you, however.
  47.  
  48. Hopefully the questions herein are asked enough that considerable net
  49. bandwidth can be saved by looking here before asking.  Also, hopefully
  50. there is enough information contained here that someone who has never
  51. heard of Perl can read this and at least have some sort of idea as to what
  52. Perl is.
  53.  
  54. Some questions in this group aren't really about Perl, but rather about
  55. system-specific issues.  You might also consult the Most Frequently Asked
  56. Questions list in comp.unix.questions for answers to this type of question.
  57.  
  58. The current version of perl is 5.001, perl 5.000 emerged into the world on
  59. 16 October, 1994.  The previous non-beta version was 4.036 (version 4,
  60. patchlevel 36).  Many of these questions were written for perl4, however a
  61. lot of perl5 information has also been added.  Perl5 only features will be
  62. clearly marked as such, so as not to cause confusion for those still using
  63. perl4.  You should upgrade to perl5 as soon as possible though (see below).
  64.  
  65. This list was initially written, and still hacked upon, by Tom
  66. Christiansen*.  However, due to his erratic schedule, it is currently
  67. maintained by Stephen P Potter*.  First person singular pronouns, when not
  68. in quoted postings, generally are Tom talking.  
  69.  
  70. This document, and all its parts, are Copyright (c) 1994/1995, Stephen P
  71. Potter and Tom Christiansen, perlfaq@perl.com.  All rights reservered.
  72. Permisson to distribute this collection, in part or full, via electronic
  73. means (emailed, posted or archived) or printed copy are granted providing
  74. that no charges are involved, reasonable attempt is made to use the most
  75. current version, and all credits and copyright notices are retained.
  76. Requests for other distribution rights, including incorporation in
  77. commercial products, such as books, magazine articles, or CD-ROMs should be
  78. made to perlfaq@perl.com.
  79.  
  80. This FAQ is archived on ftp.cis.ufl.edu [128.227.100.198] in the file
  81. pub/perl/doc/FAQ, as well as on rtfm.mit.edu [18.181.0.24] in
  82. /pub/usenet/comp.lang.perl.*.  If you have any suggested additions or
  83. corrections to this article, please send them to <perlfaq@perl.com>. 
  84.  
  85.  
  86. Part 1 - General Information and Availability
  87. 1.1) What is Perl?
  88. 1.2) What are perl4 and perl5, are there any differences?
  89. 1.3) What features does perl5 provide over perl4?
  90. 1.4) Where can I get docs on perl5?
  91. 1.5) Will perl5 break my perl4 scripts?
  92. 1.6) When will Perl stabilize?
  93. 1.7) What's the difference between "perl" and "Perl"?
  94. 1.8) Is it a perl program or a perl script?
  95. 1.9) Is perl difficult to learn?
  96. 1.10) Should I program everything in perl?
  97. 1.11) How does perl compare with other scripting languages, like Tcl,
  98.         Python or REXX? 
  99. 1.12) Where can I get Perl over the Internet (FTP)?
  100. 1.13) How can I get Perl via email?
  101. 1.14) How can I get Perl via UUCP?
  102. 1.15) Are there other ways of getting perl?
  103. 1.16) Has perl been ported to machine FOO?
  104. 1.17) How do I get perl to compile on Solaris?
  105. 1.18) How do I get perl to compile on a NeXT?
  106. 1.19) What extensions are available for Perl and where can I get them?
  107. 1.20) What is dbperl and where can I get it?
  108. 1.21) Which DBM should I use?
  109. 1.22) Is there an SNMP aware perl?
  110. 1.23) Is there an ISO or ANSI certified version of Perl?
  111.  
  112.  
  113. Part 2 - Informational Sources
  114. 2.1) Is there a USENET group for perl?
  115. 2.2) Have any books or magazine articles been published about perl?
  116. 2.3) When will the Camel and Llama books be updated?
  117. 2.4) What FTP resources are available?
  118. 2.5) What WWW/gopher resources are available?
  119. 2.6) Can people who don't have access to USENET get comp.lang.perl.misc?
  120. 2.7) Are archives of comp.lang.perl.* available?
  121. 2.8) Is there a WAIS server for comp.lang.perl.*?
  122. 2.9) What other sources of information about Perl or training are available?
  123. 2.10) Where can I get training classes on Perl?
  124. 2.11) What companies ship or use perl?
  125. 2.12) Is there commercial, third-party support for perl?
  126. 2.13) What is a JAPH?  What does "Will hack perl for ..." mean?
  127. 2.14) Where can I get a collection of Larry Wall witticisms?
  128. 2.15) What are the known bugs?
  129. 2.16) Where should I post bugs?
  130. 2.17) Where should I post source code?
  131. 2.18) Where can I learn about object-orienting Perl programming?
  132. 2.19) Where can I learn about linking C with Perl? [h2xs, xsubpp]
  133. 2.20) What is perl.com?
  134. 2.21) What do the asterisks (*) throughout the FAQ stand for?
  135.  
  136.  
  137. Part 3 - Programming Aids
  138. 3.1) How do I use perl interactively?
  139. 3.2) Is there a perl profiler?
  140. 3.3) Is there a yacc for perl?
  141. 3.4) Is there a pretty printer (similar to indent(1)) for perl?
  142. 3.5) How can I convert my perl scripts directly to C or compile them into
  143.      binary form?
  144. 3.6) Where can I get a perl mode for emacs?
  145. 3.7) Is there a perl shell?
  146. 3.8) How can I use curses with perl?
  147. 3.9) How can I use X or Tk with perl?
  148. 3.10) Can I dynamically load C user routines?
  149. 3.11) What is undump and where can I get it?
  150. 3.12) How can I get '#!perl' to work under MS-DOS?
  151. 3.13) Can I write useful perl programs on the command line?
  152. 3.14) What's a "closure"?
  153.  
  154.  
  155. Part 4 - General Programming, Regular Expressions (Regexp) and I/O
  156. 4.1) What are all these $@%*<> signs and how do I know when to use them?
  157. 4.2) Why do Perl operators have different precedence than C operators?
  158. 4.3) What's the difference between dynamic and static (lexical) scoping?
  159. 4.4) What's the difference between deep and shallow binding?
  160. 4.5) How can I manipulate fixed-record-length files?
  161. 4.6) How can I make a file handle local to a subroutine?
  162. 4.7) How can I sleep or alarm for under a second?
  163. 4.8) How can I do an atexit() or setjmp()/longjmp()? (Exception handling) 
  164. 4.9) How can I catch signals?
  165. 4.10) Why isn't my octal data interpretted correctly?
  166. 4.11) How can I compare two date strings?
  167. 4.12) How can I find the Julian Day?
  168. 4.13) Does perl have a round function?  What about ceil() and floor()?
  169. 4.14) What's the fastest way to code up a given task in perl?
  170. 4.15) Do I always/never have to quote my strings or use semicolons?
  171. 4.16) What is variable suicide and how can I prevent it?
  172. 4.17) What does "Malformed command links" mean?
  173. 4.18) How can I set up a footer format to be used with write()?
  174. 4.19) Why does my program keep growing in size?
  175. 4.20) Can I do RPC?
  176. 4.21) Why doesn't my sockets program work under System V (Solaris)?  What
  177.         does the error message "Protocol not supported" mean?
  178. 4.22) How can I quote a variable to use in a regexp?
  179. 4.23) How can I change the first N letters of a string?
  180. 4.24) How can I count the number of occurrences of a substring within a
  181.         string?
  182. 4.25) Can I use Perl regular expressions to match balanced text?
  183. 4.26) What does it mean that regexps are greedy?  How can I get around it?
  184. 4.27) How do I use a regular expression to strip C style comments from a
  185.         file?
  186. 4.28) How can I split a [character] delimited string except when inside
  187.         [character]?
  188. 4.29) Why doesn't "local($foo) = <FILE>;" work right?
  189. 4.30) How can I detect keyboard input without reading it? 
  190. 4.31) How can I read a single character from the keyboard under UNIX and DOS?
  191. 4.32) How can I get input from the keyboard without it echoing to the
  192.         screen?
  193. 4.33) Is there any easy way to strip blank space from the beginning/end of
  194.         a string?
  195. 4.34) How can I output my numbers with commas added?
  196. 4.35) How do I expand tags in a string?
  197. 4.36) What's wrong with grep in a void context?
  198.  
  199.  
  200. Part 5 - Arrays and Shell and External Program Interactions
  201. 5.1) What is the difference between $array[1] and @array[1]?
  202. 5.2) How can I make an array of arrays or other recursive data types?
  203. 5.3) How can I make an array of structures containing various data types?
  204. 5.4) How can I extract just the unique elements of an array?
  205. 5.5) How can I tell whether an array contains a certain element?
  206. 5.6) How can I sort an associative array by value instead of by key?
  207. 5.7) How can I know how many entries are in an associative array?
  208. 5.8) What's the difference between "delete" and "undef" with %arrays?
  209. 5.9) Why don't backticks work as they do in shells?
  210. 5.10) Why does my converted awk/sed/sh script run more slowly in perl?
  211. 5.11) How can I call my system's unique C functions from perl?
  212. 5.12) Where do I get the include files to do ioctl() or syscall()?  [h2ph]
  213. 5.13) Why do setuid perl scripts complain about kernel problems?
  214. 5.14) How can I open a pipe both to and from a command?
  215. 5.15) How can I capture STDERR from an external command?
  216. 5.16) Why doesn't open() return an error when a pipe open fails?
  217. 5.17) Why can't my script read from STDIN after I gave it ^D (EOF)?
  218. 5.18) How can I translate tildes (~) in a filename?
  219. 5.19) How can I convert my shell script to perl?
  220. 5.20) Can I use perl to run a telnet or ftp session?
  221. 5.21) Why do I sometimes get an "Argument list to long" when I use <*>?
  222. 5.22) How do I do a "tail -f" in perl?
  223. 5.23) Is there a way to hide perl's command line from programs such as "ps"?
  224. 5.24) I {changed directory, modified my environment} in a perl script.  How
  225.       come the change disappeared when I exited the script?  How do I get
  226.       my changes to be visible?
  227. 5.25) How can I pass a filehandle to a function, or make a list of
  228.       filehandles? 
  229. 5.26) How can I open a file with a leading ">" or trailing blanks?
  230. 5.27) How can I tell if a variable is tainted?
  231. --
  232. Stephen P Potter        Pencom Systems Administration              Beaching It 
  233. spp@psa.pencom.com    Pager: 1-800-759-8888, 547-9561     Work: 703-860-2222
  234.   Cthulhu for President in '96: When You're Tired of the Lesser of Two Evils
  235. --
  236. Stephen P Potter        Pencom Systems Administration              Beaching It 
  237. spp@psa.pencom.com    Pager: 1-800-759-8888, 547-9561     Work: 703-860-2222
  238. "I don't care whether people actually like Perl, just so long as they *think*
  239.     they like it...  ;-)"    -Larry Wall
  240.  
  241. Article: 62271 in news.answers
  242. Path: Dortmund.Germany.EU.net!Germany.EU.net!wizard.pn.com!satisfied.apocalypse.org!news2.near.net!cocoa.brown.edu!ride.ri.net!news3.near.net!paperboy.wellfleet.com!news-feed-1.peachnet.edu!gatech!newsfeed.internetmci.com!in2.uu.net!news1.radix.net!news1.radix.net!spp
  243. From: spp@psa.pencom.com
  244. Newsgroups: comp.lang.perl.announce,comp.lang.perl.misc,comp.answers,news.answers
  245. Subject: comp.lang.perl.* FAQ 1/5 - Availability
  246. Followup-To: poster
  247. Date: 27 Jan 1996 01:21:47 GMT
  248. Organization: Pencom Systems Incorporated
  249. Lines: 958
  250. Approved: news-answers-request@MIT.EDU
  251. Distribution: world
  252. Message-ID: <SPP.96Jan26202147@syrinx.hideout.com>
  253. NNTP-Posting-Host: dialin23.annex1.radix.net
  254. Xref: Dortmund.Germany.EU.net comp.lang.perl.announce:241 comp.lang.perl.misc:18666 comp.answers:16592 news.answers:62271
  255.  
  256.  
  257. Archive-name: perl-faq/part1
  258. Version: $Id: part1,v 2.9 1995/05/15 15:44:17 spp Exp spp $
  259. Posting-Frequency: bi-weekly
  260. Last Edited: Thu Jan 11 00:53:46 1996 by spp (Stephen P Potter) on syrinx.psa.com
  261.  
  262. This posting contains answers to general information and availability
  263. questions.  The following questions are answered in this posting: 
  264.  
  265.  
  266. 1.1) What is Perl?
  267.     
  268.     Perl is a compiled scripting language written by Larry Wall*.
  269.  
  270.     Here's the beginning of the description from the perl(1) man page:
  271.  
  272.     Perl is an interpreted language optimized for scanning arbi-
  273.     trary  text  files,  extracting  information from those text
  274.     files, and printing reports based on that information.  It's
  275.     also  a good language for many system management tasks.  The
  276.     language is intended to be practical  (easy  to  use,  effi-
  277.     cient,  complete)  rather  than  beautiful  (tiny,  elegant,
  278.     minimal).  It combines (in  the  author's  opinion,  anyway)
  279.     some  of the best features of C, sed, awk, and sh, so people
  280.     familiar with those languages should have little  difficulty
  281.     with  it.  (Language historians will also note some vestiges
  282.     of csh, Pascal,  and  even  BASIC-PLUS.)  Expression  syntax
  283.     corresponds  quite  closely  to C expression syntax.  Unlike
  284.         most Unix utilities, perl does  not  arbitrarily  limit  the
  285.     size  of your data--if you've got the memory, perl can slurp
  286.         in your whole file as a  single  string.   Recursion  is  of
  287.     unlimited  depth.   And  the hash tables used by associative
  288.         arrays grow as necessary to  prevent  degraded  performance.
  289.     Perl  uses sophisticated pattern matching techniques to scan
  290.         large amounts of data very quickly.  Although optimized  for
  291.     scanning  text, perl can also deal with binary data, and can
  292.         make dbm files look like associative arrays  (where  dbm  is
  293.     available).   Setuid  perl scripts are safer than C programs
  294.         through a dataflow tracing  mechanism  which  prevents  many
  295.     stupid  security  holes.   If  you have a problem that would
  296.         ordinarily use sed or awk or sh, but it exceeds their  capa-
  297.     bilities  or must run a little faster, and you don't want to
  298.         write the silly thing in C, then perl may be for you.  There
  299.     are  also  translators to turn your sed and awk scripts into
  300.         perl scripts.  OK, enough hype.
  301.  
  302.  
  303. 1.2) What are perl4 and perl5, are there any differences?
  304.  
  305.     Perl4 and perl5 are different versions of the language.  Perl4 was the
  306.     previous release, and perl5 is "Perl: The Next Generation."
  307.     Perl5 is, essentially, a complete rewrite of the perl source code
  308.     from the ground up.  It has been modularized, object oriented, 
  309.     tweaked, trimmed, and optimized until it almost doesn't look like
  310.     the old code.  However, the interface is mostly the same, and
  311.     compatibility with previous releases is very high.
  312.  
  313.  
  314. 1.3) What features does perl5 provide over perl4?
  315.  
  316.     If you get the newest source (from any of the main FTP sites), you will
  317.     find a directory full of man pages (possibly to be installed as section
  318.     1p and 3pm) that discuss the differences, new features, old
  319.     incompatibilies and much more.  Here, however, are some highlights as
  320.     to the new features and old incompatibilities.
  321.  
  322.     * Enhanced Usability:  Perl code can now be written in a much more
  323.     legible style.  Regular expressions have been enhanced to allow
  324.     minimal matches, conditionals, and much more.  Cryptic variable
  325.     names (although still supported) have been aliased to new
  326.         nmemonics, using the "English" module, allowing old scripts to run
  327.         and new scripts to be readable.  Error messages and optional
  328.         warnings are more informative and will catch many common mistakes.
  329.         See the perldiag(1) man page, which contains pithy prose from Larry
  330.         Wall* on each and every possible muttering perl might spout at you.
  331.     * Simplified Grammar:  The new yacc grammar is one half the size of
  332.     the old one.  Many of the arbitrary grammar rules have been
  333.     regularized.  The number of reserved words has been cut by 2/3.
  334.     * Lexical Scoping:  Perl variables may now be declared within a
  335.     lexical scope, similar to C's "auto" variables.  This is a
  336.     great improvement on efficiency and contributes to better
  337.     privacy.  See the my() entry in perlfunc(1).
  338.     * Arbitrarily nested data structures:  Full fledged multidimensional
  339.     arrays.  Any scalar value, including an array element, may now
  340.     contain a reference to any other variable or subroutine.
  341.     Easily created anonymous variables and subroutines.  See
  342.         perlref(1).
  343.     * Modularity and Reusability:  The Perl library is now defined in
  344.     terms of modules which can be easily shared among various
  345.     packages.  Packages can import any or all of a module's
  346.     published interface.  See perlmod(1), perlsub(1), and
  347.         Exporter(3pm). 
  348.     * Object-oriented programming:  A package can function as a class.
  349.     Dynamic multiple inheritance and virtual methods are supported
  350.     in a straight-forward manner with little new syntax.  Filehandles
  351.     are now treated as objects.  See perlobj(1), perlmod(1), and
  352.         FileHandle(3pm). 
  353.     * Embeddable and Extensible:  Perl can be easily embedded in C/C++
  354.     applications, and can either call or be called by your routines
  355.         through a documented interface.  The XS preprocessor is provided to
  356.         make it easy to glue your C/C++ routines into Perl.  Dynamic
  357.         loading of modules is supported.  See perlapi(1), perlcall(1), and
  358.         DynaLoader(3pm). 
  359.     * POSIX compliant:  A major new module is the POSIX module, which
  360.     provides access to all available POSIX routines and definitions.
  361.         Seee POSIX(3pm).
  362.     * Package constructors and destructors:  The new BEGIN and END blocks
  363.         provide means to capture control as a package is being compiled and
  364.         after the program exits.  As a degenerate case, they work just like
  365.         awk's BEGIN and END when you use the -p or -n switches.  See
  366.         perlmod(1). 
  367.     * Multiple simultaneous DBM implementations:  A perl program now has
  368.         access to DBM, NDBM, SDBM, GDBM and Berkeley DB files in the same
  369.         script.  The dbmopen interface has been generalized to allow any
  370.         variable to be tied to an object class which defines its access
  371.         methods.  tie/untie now preferable to dbmopen/dbmclose.  See the
  372.         tie() entry in perlfunc(1) and the DB_File(3pm) man pages.
  373.     * Subroutine definitions may now be autoloaded:  The AUTOLOAD mechanism
  374.         allows any arbitrary semantics to undefined subroutine calls.  See
  375.         the section on Autoloading in the perlsub(1) manpage.
  376.     * Regular Expression Enhancements:  Qualifiers may be followed by a "?"
  377.     to signify that they should be non-greedy.  A "?" directly after
  378.     an opening paren indicates non backreference grouping and the next
  379.     character determines the purpose of the match (?:a|b|c) will match
  380.     any of a b or c without producing a backreference, (?=stuff) does
  381.     a non-eating look ahead to assure that the next thing is stuff, 
  382.     (?!nonsense) looks ahead to assure that the next thing must not
  383.     be "nonsense".  Embedded whitespace and comments for readability.  
  384.     A consistent extensibility mechanism has been added that is 
  385.     upwardly compatible with all old regexps.  Variables may now be 
  386.     interpolated literally into a pattern with \Q or the quotemeta 
  387.     function, which works like \U but backwhacks non-alphanumerics.  
  388.     New m and s "flags" for pattern matching force multi- or 
  389.     single-line matching.  The "s" makes "." match "\n".  \A and
  390.     \Z anchor matches to the beginning and end of a string and ignore
  391.     multiline semantics.  \G matches where the previous m//g or s///g
  392.     left off.
  393.     * The -w (warnings) switch is much more informative.
  394.     * References and Objects (see t/op/ref.t) for examples.
  395.     * => is a synonym for comma and helps group paired arguments, such
  396.     as initializers for associative arrays and named arguments to
  397.     subroutines.
  398.     * All functions, even predeclared subroutines, are treated as list
  399.         operators or unary operators.  Parens are optional. 
  400.     * Flattened interpreter:  Compare perl4's eval.c with perl5's pp.c.
  401.     Compare perl4's 900 line interpreter look with perl5's one line.
  402.     * eval is now treated like a subroutine call, meaning (among other
  403.     things) you can return from it.
  404.     * format value lists may be spread over multiple lines with a do {}
  405.     block.
  406.     * flags on the #! line are interpreted even if the script wasn't
  407.     invoked directly.
  408.     * ?: is now an lvalue.
  409.     * list context now propogates to the right side of && and ||, and
  410.     as the 2nd and 3rd arguments of ?:
  411.     * preferred package delimiter now :: rather than '.
  412.     * new "and" and "or" operators, like && and || but with a lower
  413.     precedence than comma, so they work better with list operators.
  414.     * New functions abs(), chr(), uc(), ucfirst(), lc(), and lcfirst()
  415.     * require(number) checks to see that the version is at least that
  416.     version
  417.     * qw//, which is equivalent to split(' ', q//)
  418.     * assignment of a reference to a glob replaces the single element
  419.     of the glob corresponding to the reference type:
  420.         *foo = \$bar, * foo = \&bletch;
  421.     * filehandle methods are supported:
  422.     output_autoflush STDOUT 1;
  423.     * Autoload stubs can now call the replacement subroutine with
  424.     goto &realsub.
  425.     * Subroutines can be defined lazily in any package by declaring
  426.     an AUTOLOAD routine, which will be called if a non-existent
  427.     subroutine is called in that package.
  428.     * "use" and "no" subsume many features.  "use Module LIST" is
  429.     short for "BEGIN { require Module; import Module LIST }"
  430.     "no" is identical, except that it calls "unimport" instead.
  431.     "use integer" and variations of "use strict [vars,refs,subs]"
  432.     were implemented through new modules.
  433.  
  434. (Thanks to Tom Christiansen* for this section)
  435.  
  436.  
  437. 1.4) Where can I get docs on perl5?
  438.   
  439.     The complete perl documentation is available with the Perl
  440.     distribution, or can be accessed from the following sites.
  441.     Note that the PerlDoc ps file is 240 pages long!! 
  442.   
  443.     Marked Up (HTML) format:
  444.         http://www.metronet.com/0/perlinfo/perl5/manual/perl.html
  445.         http://web.nexor.co.uk/perl/perl.html                    (Europe)
  446.  
  447.     PostScript:
  448.     ftp://ftp.cis.ufl.edu/pub/perl/doc/PerlDoc.ps.gz
  449.         ftp://ftp.uu.net/languages/perl/PerlDoc.ps.gz
  450.         ftp://www.metronet.com/pub/perl/perl5/manual/PerlDoc.ps.gz
  451.         ftp://ftp.zrz.tu-berlin.de/pub/unix/perl/PerlDoc.ps.gz  (Europe)
  452.         ftp://ftp.cs.ruu.nl/pub/PERL/perl5.0/doc/PerlDoc.ps.gz  (Europe)
  453.         ftp://sungear.mame.mu.oz.au/pub/perl/doc/PerlDoc.ps.gz  (Oz)
  454.         unable to access as of 7/15/95
  455.  
  456.     TeXinfo (Emacs) Format:
  457.         ftp://www.metronet.com/pub/perl/perl5/manual/perl5-info.tar.gz
  458.  
  459.  
  460. 1.5) Will perl5 break my perl4 scripts?
  461.   
  462.     In general, no.  However, certain bad old practices have become highly
  463.     frowned upon.  The following are the most important of the known
  464.     incompatibilities between perl4 and perl5.  See perltrap(1) for more 
  465.     details.
  466.   
  467.     * "@" ***ALWAYS*** interpolates in double quoted strings.  Non-array
  468.     "@"s must be escaped: 
  469.         Mail("foo@bar.com") needs to be
  470.         Mail("foo\@bar.com"); 
  471.     The compiler catches this.
  472.     * "open FILE || die" needs to be "open(FILE) || die".  The compiler
  473.       forgives you for this, but won't stop complaining until you fix it.
  474.     * Barewords are no longer (necessarily) strings: they will actually
  475.       call the function (if it existed when that code was compiled)
  476.       instead of returning a string of that value.  Check your 
  477.       signal handlers.  The 'use strict subs' pragma (see strict(3pm))
  478.       will help you with this.
  479.     * "shift @x + 20" needs to be "shift(@x) + 20" because of precedence,
  480.       and likewise "$y = scalar keys %foo + 30" needs to be instead 
  481.       "$y = scalar keys(%foo) + 30".
  482.     * The internal symbol table is called %{PACKAGE::} for any given 
  483.       package.  It used to be %{_PACKAGE}.
  484.     * You may no longer (attempt to) write to read-only variables, like $1,
  485.       or assign to a substr() past the end of a string.
  486.     * Various deprecated practices elicit warning messages.
  487.     * The package delimiter has been changed from ' to ::.  Use of ' is
  488.       deprecated, but still works.  Use of :: may break scripts if you
  489.       aren't careful (especially if you are working with colon delimited
  490.       data files, like /etc/passwd)
  491.  
  492.  
  493. 1.6) When will Perl stabilize?
  494.   
  495. When asked at what point the Perl code would be frozen, Larry answered:
  496.   
  497.     Part of the redesign of Perl is to *allow* us to more or less freeze
  498.     the language itself.  It won't totally freeze, of course, but I think
  499.     the rate of change of the core of the language is asymptotically
  500.     approaching 0.  In fact, as time goes on, now that we have an official
  501.     extension mechanism, some of the things that are currently in the core
  502.     of the language may move out (transparently) as extensions.  This has
  503.     already happened to dbmopen().
  504.   
  505.     I've also been continuously reminding myself of what Henry Spencer
  506.     calls "second system syndrome", in which everything under the sun gets
  507.     added, resulting in a colossal kludge, like OS 360.  You'll find that
  508.     the new features in Perl 5 are all pretty minimalistic.  The
  509.     object-oriented features in particular added only one new piece of
  510.     syntax, a C++-style method call.
  511.   
  512.     : The whole idea behind
  513.     : Perl is to be a fast text-processing, system-maintenance, zero-startup
  514.     : time language. If it gets to be so large and complicated that it isn't
  515.     : fast-running and easy to use, it won't be to anyone's benefit.
  516.   
  517.     My motto from the start has been, "If it ain't broke, don't fix it."
  518.     I've been trying very hard not to remove those features from Perl that
  519.     make it what it is.  At the same time, a lot of streamlining has gone
  520.     into the syntax.  The new yacc file is about half the size of the old
  521.     one, and the number of official reserved words has been cut by 2/3.
  522.     All built-in functions have been unified (dualified?) as either list
  523.     operators or unary operators.
  524.   
  525.     : I really like a lot of the features in Perl, but in order for Perl to
  526.     : be useful on a long term basis, those features have to stay put. I
  527.     : bought the Camel book less than a year ago and it sounds like within
  528.     : another year it will be obsolete.
  529.   
  530.     The parts of Perl that the Camel book covers have not changed all that
  531.     much.  Most old scripts still run.  Many scripts from Perl version 1.0
  532.     still run.  We'll certainly be revising the Camel, but the new man
  533.     pages are split up such that it's pretty easy to ferret out the new
  534.     info when you want it.
  535.   
  536.     We did break a few misfeatures in going to Perl 5.  It seemed like the
  537.     first and last chance to do so.  There's a list of the
  538.     incompatibilities in the documentation. 
  539.   
  540.     : Not only is it a lot of work to recompile Perl
  541.     : on 20+ machines periodically, but it's hard to write scripts that are 
  542.     : useful in the long term if the guts of the language keep changing.
  543.     : (And if I keep having to buy new books. I keep hearing about new
  544.     : features of Perl 5 that aren't documented in any of the perl 5
  545.     : documentation that *I* can find.)
  546.   
  547.     I think you'll find a lot of folks who think that 4.036 has been a
  548.     pretty stable platform.
  549.   
  550.     Perl 5 is a special case.  I've been working on it for years.  (This is
  551.     part of the reason 4.036 has been so stable!)  There are many changes,
  552.     most of them for the better, I hope.  I don't expect the transition to
  553.     be without pain.  But that's why I stuck numbered versions out in your
  554.     bin directory, so that you can upgrade piecemeal if you like.  And
  555.     that's why I made the -w switch warn about many of the incompatibilities.
  556.   
  557.     And overriding all that, I've tried to keep it so that you don't have
  558.     to know much about the new stuff to use the old stuff.  You can upgrade
  559.     your *knowledge* piecemeal too.
  560.   
  561.     The extension mechanism is designed to take over most of the
  562.     evolutionary role from now on.  And it's set up so that, if you don't
  563.     have a particular extension, you know it right up at the front. 
  564.   
  565.     : Are there any plans to write a Perl compiler? While interpreted Perl
  566.     : is great for many applications, it would also be cool to be able to
  567.     : precompile many scripts. (Yes, I know you can undump things, but
  568.     : undump isn't provided with Perl and I haven't found a copy.) The
  569.     : creation of a perl library and dynamically-loadable modules seems
  570.     : like a step in that direction.  
  571.   
  572.     Yes, part of the design of Perl 5 was to make it *possible* to write a 
  573.     compiler for it.  It could even be done as an extension module, I
  574.     suppose.  Anyone looking for a master's thesis topic?
  575.   
  576.     In summary, almost every concern that you might think of has already
  577.     been (at least) thought about.  In a perfect world, every concern
  578.     could be addressed perfectly.  But in this world we just have to slog
  579.     through.
  580.   
  581.  
  582. 1.7) What's the difference between "perl" and "Perl"?
  583.  
  584.     32!  [ ord('p') - ord('P') ]  (Shouldn't that be 42, the Answer to the
  585.         Great Question of Life, the Universe, and Everything?  ;) 
  586.  
  587.     Larry now uses "Perl" to signify the language proper and "perl" the
  588.     implementation of it, i.e. the current interpreter.  Hence Tom's
  589.     quip that "Nothing but perl can parse Perl."
  590.  
  591.     On the other hand, the aesthetic value of casewise parallelism in
  592.     "awk", "sed", and "perl" as much require the lower-case version as "C",
  593.     "Pascal", and "Perl" require the upper-case version.  It's also easier
  594.     to type "Perl" in typeset print than to be constantly switching in
  595.     Courier. :-) 
  596.     
  597.     In other words, it doesn't matter much, especially if all you're doing
  598.     is hearing someone talk about the language; case is hard to distinguish
  599.     aurally. 
  600.  
  601.  
  602. 1.8) Is it a perl program or a perl script?
  603.  
  604.     It depends on whether you are talking about the perl binary or
  605.     something that you wrote using perl.  And, actually, even this isn't
  606.     necessarily true.
  607.  
  608.     "Standard" UNIX terminology is (roughly) this:  programs are compiled
  609.     into machine code once and run multiple times, scripts are translated
  610.     (by a program) each time they are used.  However, some say that a
  611.     program is anything written which is executed on a computer system.
  612.     Larry considers it a program if it is set in stone and you can't change
  613.     it, whereas if you can go in and hack at it, it's a script.  Of course,
  614.     if you have the source code, that makes just about anything a
  615.     script.  ;)
  616.  
  617.     In general, it probably doesn't really matter.  The terms are used
  618.     interchangeably.  If you particularly like one or the other, use it.  If
  619.     you want to call yourself a perl programmer, call them programs.  If
  620.     you want to call yourself a perl scripter, call them scripts.  Randal*
  621.     and I (at least) will call them hacks.  (See question 2.10 ;)
  622.  
  623.     Larry says that a script is what you give an actor, but a program is
  624.     what you give an audience.
  625.  
  626.  
  627. 1.9) Is perl difficult to learn?
  628.     
  629.     Not at all.  Many people find Perl extremely easy to learn.  There are
  630.     at least three main reasons for this.
  631.  
  632.     The first reason is that most of Perl has been derived from standard
  633.     utilities, tools, and languages that you are (probably) already
  634.     familiar with.  If you have any knowledge of the C programming language
  635.     and standard C library, the Unix Shell, sed and awk, Perl should be
  636.     simple and fun for you to learn.
  637.  
  638.     The second reason that Perl is easy to learn is that you only have to
  639.     know a very small subset of Perl to be able to get useful results.  In
  640.     fact, once you can master
  641.  
  642.         #!/usr/local/bin/perl
  643.      print "Hello, world\n";
  644.  
  645.     you can start writing Perl scripts.  In fact, you will probably never
  646.     have to (or be able to) know everything about Perl.  As you feel the
  647.     need or desire to use more sophisticated features (such as C structures
  648.     or networking), you can learn these as you go.  The learning curve for
  649.     Perl is not a steep one, especially if you have the headstart of having 
  650.     a background in UNIX.  Rather, its learning curve is gentle and
  651.     gradual, but it *is* admittedly rather long. 
  652.  
  653.     The third reason is that you can get immediate results from your
  654.     scripts.  Unlike a normal compiled language (like C or Pascal, for
  655.     example), you don't have to continually recompile your program every
  656.     time you change one little thing.  Perl allows you to experiment and
  657.     test/debug quickly and easily.  This ease of experimentation flattens
  658.     the learning curve even more.
  659.  
  660.     If you don't know C or UNIX at all, it'll be a steeper learning curve,
  661.     but what you then learn from Perl will carry over into other areas,
  662.     like using the C library, UNIX system calls, regular expressions, and 
  663.     associative arrays, just to name a few.  To know Perl is to know UNIX,
  664.     and vice versa. 
  665.  
  666.  
  667. 1.10) Should I program everything in Perl?
  668.  
  669.     Most definitely.  In fact, you should delete the binaries for sed, awk,
  670.     cc, gcc, grep, rm, ls, cat... well, just delete your /bin directory.
  671.  
  672.     But seriously, of course you shouldn't.  As with any job, you should
  673.     use the appropriate tool for the task at hand.  Just because a hammer 
  674.     will put screws into a piece of board, you probably don't want to do
  675.     that.
  676.  
  677.     While it's true that the answer to the question "Can I do (some
  678.     arbitrary task) in Perl?" is almost always "yes", that doesn't mean
  679.     this is necessarily a good thing to do.  For many people, Perl serves
  680.     as a great replacement for shell programming.  For a few people, it
  681.     also serves as a replacement for most of what they'd do in C.  But for
  682.     some things, Perl just isn't the optimal choice.
  683.  
  684.  
  685. 1.11) How does Perl compare with other scripting languages, like Tcl, Python
  686.      or REXX?
  687.  
  688.     REXX is an interpreted programming language first seen on IBM systems.
  689.     Python is an interpreted programming language by Guido van Rossum*.
  690.     TCL is John Ousterhout*'s embeddable command language, designed just
  691.     for embedded command extensions, but lately used for larger
  692.     applications.  TCL's most intriguing feature for many people is the
  693.     tcl/tk toolset that allows for interpreted X-based tools.  Others use
  694.     it for its "expect" extension.
  695.  
  696.     To avoid any flamage, if you really want to know the answer to this
  697.     question, probably the best thing to do is try to write equivalent
  698.     code to do a set of tasks.  All three have their own newsgroups in
  699.     which you can learn about (but hopefully not argue about) these
  700.     languages.
  701.  
  702.     To find out more about these or other languages, you might also check
  703.     out David Muir Sharnoff*'s posting "Catalog of Compilers, Interpreters,
  704.     and Other Language Tools" which he posts to comp.lang.misc,
  705.     comp.sources.d, comp.archives.admin, and news.answers newsgroups.  It's
  706.     a comprehensive treatment of many different languages.  (Caveat lector:
  707.     he considers Perl's syntax "unappealing".)
  708.  
  709.  
  710. 1.12) How can I get Perl over the Internet?
  711.  
  712.     Perl is available from any comp.sources.misc archive.  You can use an
  713.     archie server (see the alt.sources FAQ in news.answers) to find these
  714.     if you want.
  715.  
  716.       Version 4:
  717.     Volume    Issues    Patchlevel and Notes
  718.     ------    ------    ------------------------------------------------
  719.       18    19-54    Patchlevel 3, Initial posting.
  720.       20    56-62    Patches 4-10    
  721.  
  722.       Version 5:
  723.         Volume    Issues    Patchlevel and Notes
  724.         ------    ------    -----------------------------------------------
  725.           45    64-128    Initial Posting, patchlevel 0.
  726.  
  727.     Since 1993, a number of archives have sprung up specifically for Perl
  728.     and Perl related items.  Larry maintains the official distribution
  729.     site (for both perl4.036 and perl5) at netlabs.  Probably the largest
  730.     archive is at the University of Florida.  In order of probability these
  731.     sites will have the sources.
  732.  
  733.     Site    Directory and notes                        IP                
  734.     ---------------------------------------------         -------        
  735.     North America:
  736.     ftp://ftp.netlabs.com/pub/outgoing/perl5.0/         192.94.48.152
  737.     ftp://ftp.cis.ufl.edu/pub/perl/src/5.0/                128.227.100.198
  738.         ftp://prep.ai.mit.edu/pub/gnu/                        18.71.0.38
  739.         not current as of 7/15/95
  740.         ftp://ftp.uu.net/languages/perl/                    192.48.96.9
  741.         not current as of 7/15/95
  742.         ftp://ftp.khoros.unm.edu/pub/perl/                  198.59.155.28
  743.         not current as of 7/15/95
  744.         ftp://ftp.cbi.tamucc.edu/pub/duff/Perl/                165.95.1.3
  745.     ftp://ftp.metronet.com/pub/perl/sources/            192.245.137.1
  746.         ftp://genetics.upenn.edu/perl5/                        128.91.200.37
  747.  
  748.     Europe:
  749.         ftp://ftp.cs.ruu.nl/pub/PERL/perl5.0/src/        131.211.80.17
  750.         ftp://ftp.funet.fi/pub/languages/perl/ports/perl5/  128.214.248.6
  751.         ftp://ftp.zrz.tu-berlin.de/pub/unix/perl/           130.149.4.40
  752.         ftp://src.doc.ic.ac.uk/packages/perl5/                146.169.17.5
  753.   
  754.     Australia:
  755.         ftp://sungear.mame.mu.oz.au/pub/perl/src/5.0/        128.250.209.2
  756.  
  757.     South America (mirror of ftp://prep.ai.mit.edu/pub/gnu):
  758.         ftp://ftp.inf.utfsm.cl/pub/gnu/                        146.83.198.3
  759.  
  760.     If there is a site in Asia or Japan, please tell us about it.  Thanks! 
  761.  
  762.     You can also retrieve perl via non-ftp methods:
  763.   
  764.         http://src.doc.ic.ac.uk/packages/perl5/                146.169.17.5
  765.         gopher://src.doc.ic.ac.uk/0/packages/perl5/         146.169.17.5
  766.  
  767.  
  768. 1.13) How can I get Perl via Email?
  769.  
  770.     The following is a list of known ftpmail sites.  Please attempt to use
  771.     the site closest to you with the ftp archive closest to it.  Many of
  772.     these sites already have perl on them.  For information on how to use
  773.     one of these sites, send email containing the word "help" to the
  774.     address.
  775.  
  776.     United States:
  777.         Massachusetts:    ftpmail@decwrl.dec.com
  778.         New Jersey:        bitftp@pucc.princeton.edu
  779.         North Carolina:    ftpmail@sunsite.unc.edu
  780.  
  781.     Europe/UK:
  782.         Germany:        ftpmail@ftp.uni-stuttgart.de
  783.                 bitftp@vx.gmd.de
  784.         UK:            ftpmail@doc.ic.ac.uk
  785.  
  786.     Australia:        ftpmail@cs.uow.edu.au
  787.  
  788.     Henk P Penning* suggests that if you are in Europe you should try the
  789.     following (if you are in Germany or the UK, you should probably use one
  790.     of the servers listed above): 
  791.  
  792.         Email: Send a message to 'mail-server@cs.ruu.nl' containing:
  793.      begin
  794.      path your_email_address
  795.      send help
  796.      send PERL/perl5.0/INDEX
  797.      end
  798.     The path-line may be omitted if your message contains a normal
  799.     From:-line.  You will receive a help-file and an index of the
  800.     directory that contains the Perl stuff.
  801.  
  802.     If all else fails, mail to Larry usually suffices.
  803.  
  804.  
  805. 1.14) How can I get Perl via UUCP?
  806.  
  807.     There currently is no way of getting Perl via UUCP.  If anyone knows of
  808.     a way, please contact me.  The OSU site has discontinued the service.
  809.  
  810.  
  811. 1.15) Are there other ways of getting perl?
  812.  
  813.     Another possibility is to use UUNET, although they charge you for it.
  814.     You have been duly warned.  Here's the advertisement: 
  815.  
  816.            Anonymous Access to UUNET's Source Archives
  817.  
  818.                  1-900-GOT-SRCS
  819.  
  820.     UUNET now provides access to its extensive collection of UNIX
  821.     related sources to non- subscribers.  By  calling  1-900-468-7727
  822.     and  using the login "uucp" with no password, anyone may uucp any
  823.     of UUNET's on line source collection.  Callers will be charged 40
  824.     cents  per  minute.   The charges will appear on their next tele-
  825.     phone bill.
  826.  
  827.      The file uunet!/info/help contains instructions.   The  file
  828.     uunet!/index//ls-lR.Z  contains  a  complete  list  of  the files 
  829.     available  and is  updated daily.   Files ending  in Z need to be 
  830.     uncompressed before being used.  The file uunet!~/compress.tar is
  831.     a tar archive containing the C sources for the uncompress program. 
  832.  
  833.      This service provides a  cost  effective  way  of  obtaining
  834.     current  releases  of sources without having to maintain accounts
  835.     with UUNET or some other service.  All modems  connected  to  the
  836.     900  number  are  Telebit T2500 modems.  These modems support all
  837.     standard modem speeds including PEP, V.32 (9600), V.22bis (2400),
  838.     Bell  212a  (1200), and Bell 103 (300).  Using PEP or V.32, a 1.5
  839.     megabyte file such as the GNU C compiler would cost $10  in  con-
  840.     nect  charges.   The  entire  55  megabyte X Window system V11 R4
  841.     would cost only $370 in connect time.  These costs are less  than
  842.     the  official  tape  distribution fees and they are available now
  843.     via modem.
  844.  
  845.               UUNET Communications Services
  846.            3110 Fairview Park Drive, Suite 570
  847.              Falls Church, VA 22042
  848.              +1 703 876 5050 (voice)
  849.               +1 703 876 5059 (fax)
  850.                 info@uunet.uu.net
  851.  
  852.  
  853. 1.16) Has perl been ported to machine FOO?
  854.  
  855.     Perl runs on virtually all Unix machines simply by following the hints
  856.     file and instructions in the Configure script.  This auto-configuration
  857.     script allows Perl to compile on a wide variety of platforms by
  858.     modifying the machine specific parts of the code.  For most Unix
  859.     systems, or VMS systems for v5 perl, no porting is required.  Try to
  860.     compile Perl on your machine.  If you have problems, examine the README
  861.     file carefully.  If all else fails, send a message to comp.lang.perl
  862.     and crosspost to comp.sys.[whatever], there's probably someone out
  863.     there that has already solved your problem and will be able to help you
  864.     out. 
  865.  
  866.     Perl4.036 has been ported to many non-Unix systems, although currently
  867.     there are only a few (beta) v5 ports.  All of the following are
  868.     mirrored at ftp://ftp.cis.ufl.edu:/pub/perl/src/.  The following are
  869.     the (known) official distribution points.  Please contact the porters 
  870.     directly (when possible) in case of questions on these ports.
  871.  
  872.     * MS-DOS binaries and source are available at  [130.179.8.47]
  873.           ftp://ftp.ee.umanitoba.ca/pub/msdos/perl/perl4
  874.       There are currently half a dozen different ports for MS-DOS.
  875.       BigPerl4 (v4) is perl4.036 compiled with the Watcom C/C++^32
  876.       compiler (32-bit, flat-memory model C compiler) with the
  877.       following features:
  878.         * Up to 32MB of memory can be used.
  879.         * Supports virtual memory.
  880.         * Works under Windows 3.1 
  881.         * The perl debugger can be used.
  882.         * Contains Berkeley DB support.  GDBM is no longer supported.
  883.  
  884.       Note that the latest version of BigPerl4 can also be found at
  885.       any SimTel mirror site (ftp.ee.umanitoba.ca does not
  886.       necessarily have the latest version), such as:
  887.  
  888.         ftp://oak.oakland.edu/SimTel/msdos/perl/
  889.  
  890.           A beta-test version of bigperl based on Perl 5.000 can be
  891.           obtained from the following sites:
  892.  
  893.             ftp://ftp.einet.net/pub/perl5
  894.             ftp://ftp.khoros.unm.edu/pub/perl/msdos
  895.             ftp://ftp.ee.umanitoba.ca/pub/msdos/perl/perl5
  896.  
  897.           This beta bigperl also contains ported versions of a2p and s2p.
  898.  
  899.     * Windows/NT binaries are available from
  900.           ftp://ftp.intergraph.com/pub/win32/perl, or at any of the major
  901.           NT archives.  They are compiled for NT 3.5, but appears to work
  902.           under Win95 also.  It is visible to the NT Registry.  Dean
  903.           Troyer* is working on extending the visibility to SAM and the
  904.           Event Log.  His current work-in-progress is available from
  905.           ftp://pmip.dist.maricopa.edu/pub/nt.
  906.  
  907.     * Macintosh binaries and source are available from [130.59.1.40]
  908.           ftp://nic.switch.ch/software/mac/perl.
  909.       Version 4.1.3 is perl4.036 compiled with the MPW C compiler
  910.         * Mac_Perl_413_src.sit.bin        Sources
  911.         * Mac_Perl_413_tool.sit.bin        MPW Tool
  912.         * Mac_Perl_413_appl.sit.bin        Standalone Application
  913.       There is a mailing list for discussing Macintosh Perl.  Contact
  914.       "mpw-perl-request@iis.ee.ethz.ch".
  915.  
  916.       Timothy Murphy* also ported a version of perl to the Macintosh
  917.       using Think C.  It has probably been abandoned in favour of the
  918.       MPW port, but is still available at [134.266.81.10]
  919.           ftp://ftp.maths.tcd.ie/pub/Mac/perl-4.035/.
  920.  
  921.           Matthias Ulrich Neeracher* is working on a perl5 port to the
  922.           Macintosh.  A PowerPC version is available at 
  923.           ftp://err.ethz.ch/pub/neeri/MacPerlBeta.
  924.  
  925.     * OS/2 sources are also available at
  926.           ftp://ftp.cis.ufl.edu/pub/perl/src/4.0/os2.  This appears to have
  927.           been abandoned and added to the official distribution.  See the
  928.           directory os2 in the perl5 sources.
  929.  
  930.     * VMS systems should be able to build directly from the standard
  931.       distribution.
  932.  
  933.         * Amiga sources are not available from ftp.cis.ufl.edu, but can
  934.           be found at any Aminet archive, notably:
  935.             * ftp://ftp.wustl.edu/pub/aminet/dev/lang/
  936.             * ftp://ftp.uni-erlangen.de/pub/aminet/dev/lang/
  937.             * ftp://ftp.doc.ic.ac.uk/pub/aminet/dev/lang/
  938.             * ftp://ftp.funet.fi/pub/languages/perl/ports/perl4/amiga
  939.  
  940. 1.17) How do I get Perl to compile on Solaris?
  941.  
  942.     The following directions are for perl, version 4.  Perl, version 5,
  943.     should compile more easily.  If not, send mail to The Perl Porters
  944.     Mailing List (perl5-porters@nicoh.com)
  945.  
  946.     John Lees* reports:
  947.  
  948.         I have built perl on Solaris 2.1, 2.2 beta, and 2.2 FCS. Take
  949.     /usr/ucb out of your path and do not use any BSD/UCB libraries.
  950.     Only -lsocket, -lnsl, and -lm are needed. You can use the hint for
  951.     Solaris 2.0, but the one for 2.1 is wrong. Do not use vfork. Do not
  952.     use -I/usr/ucbinclude.  The result works fine for me, but of couse
  953.     does not support a couple of BSDism's.
  954.  
  955.     Casper H.S. Dik* reports
  956.  
  957.         You must remove all the references to /usr/ucblib AND
  958.         /usr/ucbinclude.  And ignore the Solaris_2.1 hints. They are wrong.
  959.         The undefining of vfork() probably has to do with the confusion it 
  960.         gives to the compilers.  If you use cc, you mustn't compile
  961.     util.c/tutil.c  with -O.  I only used the following libs: -lsocket 
  962.     -lnsl -lm (there is a problem with -lmalloc)
  963.  
  964.     Michael D'Errico* reports:
  965.  
  966.         If you are using Solaris 2.x, the signal handling is broken.  If
  967.     you set up a signal handler such as 'ripper' it will be forgotten
  968.     after the first time the signal is caught.  To fix this, you need
  969.     to recompile Perl.  Just add '#define signal(x,y) sigset((x),(y))'
  970.     after the '#include <signal.h>' directive in each file that it
  971.     occurs, then make it again. 
  972.  
  973.  
  974. 1.18) How do I get Perl to compile on a Next?
  975.  
  976.     According to Andreas Koenig*, under NeXTstep 3.2, both perl4.036 and
  977.     perl5.000 compile with the supplied hints file. 
  978.  
  979.     However, Bill Eldridge* provides this message to help get perl4.036 on
  980.     NeXTstep 3.0 to work: 
  981.  
  982.         To get perl to compile on NeXTs, you need to combine the ANSI
  983.         and BSD headers:
  984.  
  985.         cd /usr/include
  986.         mkdir ansibsd
  987.         cd ansibsd
  988.         ln -s ../ansi
  989.         ln -s ../bsd
  990.  
  991.         Then, follow the configuration instructions for NeXTs, *replacing*
  992.         all mention of -I/usr/include/ansi or -I/usr/include/bsd with
  993.         -I/usr/include/ansibsd.
  994.  
  995.  
  996. 1.19) What extensions are available from Perl and where can I get them?
  997.   
  998.     Some of the more popular extensions include those for windowing,
  999.     graphics, or data base work.  Most of the major sites contain an
  1000.     archive of the extensions, usually in the ext directory.  Since the
  1001.     list of available extensions changes so often, I have opted to list
  1002.     only the sites and directories, not the individual extensions, please
  1003.     check the closest archive for more information
  1004.   
  1005.       ftp://ftp.cis.ufl.edu/pub/perl/ext
  1006.         (also linked at ftp://ftp.cis.ufl.edu/pub/perl/src/5.0/ext)
  1007.       ftp://ftp.khoros.unm.edu/pub/perl/extensions/
  1008.       ftp://ftp.metronet.com/pub/perlinfo/perl5/
  1009.       ftp://ftp.cs.ruu.nl/pub/PERL/perl5.0/ext
  1010.       ftp://black.ox.ac.uk/src/ALPHA/
  1011.  
  1012.  
  1013. 1.20) What is dbperl and where can I get it?
  1014.  
  1015.     Many database-oriented extensions to Perl have been written.
  1016.     Basically, these use the usub mechanism (see the usub/ subdirectory) in
  1017.     the source distribution) to link in a database library, allowing
  1018.     embedded calls to Informix, Ingres, Interbase, Oracle and Sybase.
  1019.  
  1020.     Here are the authors of the various extensions:
  1021.  
  1022.     What            Target DB       Who
  1023.     --------        -----------     ----------------------------------------
  1024.     ?Infoperl       Informix        Kurt Andersen (kurt@hpsdid.sdd.hp.com)
  1025.     Ingperl        Ingres        Tim Bunce (timbo@ig.co.uk) and Ted Lemon
  1026.     Interperl       Interbase       Buzz Moschetti (buzz@bear.com)
  1027.     Isqlperl        Informix        William Hails, bill@tardis.co.uk
  1028.     Oraperl         Oracle          Kevin Stock (kstock@Auspex.com)
  1029.     Pgperl        Postgres        Igor Metz (metz@iam.unibe.ch)
  1030.     *Sqlperl        Ingres          Ted Lemon (mellon@ncd.com)
  1031.     Sybperl         Sybase          Michael Peppler (mpeppler@itf.ch)
  1032.     Uniperl        Unify 5.0        Rick Wargo (rickers@coe.drexel.edu)
  1033.  
  1034.     ? Does this one still exist?
  1035.     * Sqlperl appears to have been subsumed by Ingperl
  1036.  
  1037.     Buzz Moschetti* has organized a project to create a higher level
  1038.     interface to allow you to write your queries in a database-independent
  1039.     fashion.  If this type of project interests you, send mail to
  1040.     <perldb-interest-request@vix.com> and asked to be placed on the 
  1041.     "perldb-interest" mailing lists.
  1042.  
  1043.     Here's a bit of advertising from Buzz:
  1044.  
  1045.     Perl is an interpreted language with powerful string, scalar, and
  1046.     array processing features developed by Larry Wall that "nicely
  1047.     bridges the functionality gap between sh(1) and C."  Since
  1048.     relational DB operations are typically textually oriented, perl is
  1049.     particularly well-suited to manage the data flows.  The C source
  1050.     code, which is available free of charge and runs on many platforms,
  1051.     contains a user-defined function entry point that permits a
  1052.     developer to extend the basic function set of the language.  The
  1053.     DBperl Group seeks to exploit this capability by creating a
  1054.     standardized set of perl function extensions (e.g. db_fetch(),
  1055.     db_attach()) based on the SQL model for manipulating a relational
  1056.         DB, thus providing a portable perl interface to a variety of
  1057.         popular RDMS engines including Sybase, Oracle, Ingres, Informix,
  1058.         and Interbase.  In theory, any DB engine that implements a dynamic
  1059.         SQL interpreter in its HLI can be bolted onto the perl front end
  1060.         with predicatable results, although at this time backends exist
  1061.         only for the aforementioned five DB engines. 
  1062.  
  1063.     The official archive for DBperl extensions is ftp.demon.co.uk:
  1064.     /pub/perl/db.  It's the home of the evolving DBperl API Specification.
  1065.     Here's an extract from the updated README there:
  1066.  
  1067.     DBI/        The home of the DBI archive. To join the DBI mailing list
  1068.                 send your request to perldb-interest-REQUEST@vix.com
  1069.  
  1070.     DBD/        Database Drivers for the DBI ...
  1071.      
  1072.     Oracle/      By Tim Bunce (not yet ready!) 
  1073.     Ingres/      By Tim Bunce (not yet started!) 
  1074.  
  1075.     mod/           Other Perl 5 Modules and Extensions ...
  1076.  
  1077.     Sybperl/    By Michael Peppler, mpeppler@itf.ch
  1078.  
  1079.  
  1080.     perl4/         Perl 4 extensions (using the usub C interface)
  1081.  
  1082.        oraperl/   ORACLE 6 & 7  By Kevin Stock, kstock@auspex.com 
  1083.        sybperl/   SYBASE 4      By Michael Peppler, mpeppler@itf.ch
  1084.        ingperl/   INGRES        By Tim Bunce timbo@ig.co.uk and Ted Lemon
  1085.        isqlperl/  INFORMIX      By William Hails, bill@tardis.co.uk
  1086.        interperl/ INTERBASE     By Buzz Moschetti, buzz@bear.com
  1087.        oraperl/   ORACLE 6 & 7  By Kevin Stock (sadly no longer on the net)
  1088.        sybperl/   SYBASE 4      By Michael Peppler, mpeppler@itf.ch
  1089.        ingperl/   INGRES        By Tim Bunce timbo@ig.co.uk and Ted Lemon
  1090.        isqlperl/  INFORMIX      By William Hails, bill@tardis.co.uk
  1091.        interperl/ INTERBASE     By Buzz Moschetti, buzz@bear.com
  1092.        uniperl/   UNIFY 5.0     By Rick Wargo, rickers@coe.drexel.edu
  1093.        pgperl/    POSTGRES      By Igor Metz, metz@iam.unibe.ch
  1094.  
  1095.        btreeperl/ NDBM perl extensions.   By John Conover, john@johncon.com
  1096.        ctreeperl/ C-Tree perl extensions. By John Conover, john@johncon.com
  1097.        duaperl/   X.500 Directory User Agent. By Eric Douglas.
  1098.   
  1099.     scripts/       Perl and shell scripts
  1100.   
  1101.        rdb/       RDB is a perl RDBMS for ASCII files. By Walt Hobbs,
  1102.                     hobbs@rand.org 
  1103.        shql/      SHQL is an interactive SQL database engine.  Written as a
  1104.                     shell script, SHQL interprets SQL commands and
  1105.                     manipulates flat files based on those commands. By
  1106.                     Bruce Momjian, root@candle.uucp 
  1107.        xbase/     Perl scripts for accessing xBase style files (dBase III) 
  1108.  
  1109.  
  1110.    refinfo/       Reference information
  1111.       
  1112.        sqlsyntax/ Yacc and lex syntax and C source code for SQL1 and SQL2
  1113.             from ftp.uu.net:/pub/uunet/published/oreilly/nutshell/yacclex, 
  1114.             and a draft SQL3 syntax from Jeff Fried <jfried@informix.com>+      
  1115.        formats/   Details of file formats such as Lotus 1-2-3 .WK1
  1116.  
  1117.     There are also a number of non SQL database interfaces for perl
  1118.     available from ftp.demon.co.uk.  These include:
  1119.  
  1120.     Directory    Target System    Authors and notes
  1121.     ---------    -------------    -------------------------------------------
  1122.     btreeperl    NDBM extension    John Conover (john@johncon.com)
  1123.     ctreeperl    CTree extension John Conover (john@johncon.com)
  1124.     duaperl    X.500 DUA    Eric Douglas
  1125.     rdb        RDBMS        Walt Hobbs (hobbs@rand.org)
  1126.     shql    SQL Engine    Bruce Momjian (root@candle.uucp)
  1127.  
  1128.  
  1129. 1.21) Which DBM should I use?
  1130.  
  1131.     As shipped, Perl (version 5) comes with interfaces for several DBM
  1132.     packages (SDBM, old DBM, NDBM, GDBM, Berkeley DBM) that are not supplied  
  1133.     but either come with your system are readily accessible via FTP.  SDBM
  1134.     is guaranteed to be there.  For a comparison, see AnyDBM_File(3pm)
  1135.     and DB_File(3pm).
  1136.  
  1137.     
  1138. 1.22) Is there an SNMP aware Perl?
  1139.  
  1140.     snmperl was written by Guy Streeter (streeter@ingr.com), and was
  1141.     posted in late February 1993 to comp.protocols.snmp.  It can be found
  1142.     archived at one of two (known) places:
  1143.  
  1144.     Host liasun3.epfl.ch
  1145.  
  1146.     Location: /pub/net/snmp
  1147.            FILE -rw-rw-r--       3407  Aug 11 1992  snmperl.README
  1148.            FILE -rw-r--r--      17678  Aug 11 1992  snmperl.tar.Z
  1149.  
  1150.     Host ftp.cis.ufl.edu
  1151.     Location: /pub/perl/scripts/snmp
  1152.  
  1153.     Here is the gist of the README:
  1154.  
  1155.     This directory contains the source code to add callable C subroutines
  1156.     to perl.  The subroutines implement the SNMP functions "get",
  1157.     "getnext", and "set".  They use the freely-distributable SNMP package
  1158.     (version 1.1b) from CMU.
  1159.  
  1160.     USE:
  1161.       There are four subroutines defined in the callable interface:
  1162.     snmp_get, snmp_next, snmp_set, and snmp_error.
  1163.  
  1164.       snmp_get and snmp_next implement the GET and GETNEXT operations,
  1165.     respectively.  The first two calling arguments are the hostname and
  1166.     Community string.  The IP address of the host, as a dotted-quad ASCII
  1167.     string, may be used as the hostname.  The rest of the calling
  1168.     arguments are a list of variables.  See the CMU package documentation
  1169.     for how variables may be specified.
  1170.       snmp_set also takes hostname and Community string as arguments.  The
  1171.     remaining arguments are a list of triples consisting of variable name,
  1172.     variable type, and value.  The variable type is a string, such as
  1173.     "INTEGER" or "IpAddress".
  1174.       snmp_get, snmp_next, and snmp_set return a list containing
  1175.     alternating variables and values.  snmp_get and snmp_next will simply
  1176.     omit non-existent variables on return.  snmp_set will fail completely
  1177.     if one of the specified variables does not exist (or is read-only).
  1178.       snmp_error will return a text string containing some error
  1179.     information about the most recent snmp_get|next|set call, if it had an
  1180.     error.
  1181.  
  1182.     OTHER NOTES:
  1183.       I didn't find all the places where the CMU library writes to stderr
  1184.     or calls exit() directly.
  1185.       The changes I made to mib.c involve the formatting of variable values
  1186.     for return to the caller.  I took out the descriptive prefix so the
  1187.     string contains only the value.
  1188.       Enumerated types are returned as a string containing the symbolic
  1189.     representation followed in parentheses by the numeric.
  1190.  
  1191.     DISTRIBUTION and OWNERSHIP
  1192.       perl and the CMU SNMP package have their own statements.  Read them.
  1193.     The work I've done is free and clear.  Just don't say you wrote it if
  1194.     you didn't, and don't say I wrote it if you change it.
  1195.  
  1196.     Guy Streeter
  1197.     streeter@ingr.com
  1198.     April 1, 1992 (not a joke!)
  1199.  
  1200.  
  1201. 1.23) Is there an ISO or ANSI certified version of Perl?
  1202.  
  1203.     No.  Larry thinks it likely that he'll be certified before perl is.
  1204.  
  1205. --
  1206. Stephen P Potter        Pencom Systems Administration              Beaching It 
  1207. spp@psa.pencom.com    Pager: 1-800-759-8888, 547-9561     Work: 703-860-2222
  1208.   Cthulhu for President in '96: When You're Tired of the Lesser of Two Evils
  1209. --
  1210. Stephen P Potter        Pencom Systems Administration              Beaching It 
  1211. spp@psa.pencom.com    Pager: 1-800-759-8888, 547-9561     Work: 703-860-2222
  1212. "I don't care whether people actually like Perl, just so long as they *think*
  1213.     they like it...  ;-)"    -Larry Wall
  1214.  
  1215. Article: 62274 in news.answers
  1216. Path: Dortmund.Germany.EU.net!Germany.EU.net!wizard.pn.com!satisfied.apocalypse.org!news2.near.net!cocoa.brown.edu!ride.ri.net!news3.near.net!paperboy.wellfleet.com!news-feed-1.peachnet.edu!gatech!newsfeed.internetmci.com!in2.uu.net!news1.radix.net!news1.radix.net!spp
  1217. From: spp@psa.pencom.com
  1218. Newsgroups: comp.lang.perl.announce,comp.lang.perl.misc,comp.answers,news.answers
  1219. Subject: comp.lang.perl.* FAQ 2/5 - Information Sources
  1220. Followup-To: poster
  1221. Date: 27 Jan 1996 01:22:29 GMT
  1222. Organization: Pencom Systems Administration
  1223. Lines: 637
  1224. Approved: news-answers-request@MIT.EDU
  1225. Distribution: world
  1226. Message-ID: <SPP.96Jan26202229@syrinx.hideout.com>
  1227. NNTP-Posting-Host: dialin23.annex1.radix.net
  1228. Xref: Dortmund.Germany.EU.net comp.lang.perl.announce:242 comp.lang.perl.misc:18677 comp.answers:16593 news.answers:62274
  1229.  
  1230.  
  1231. Archive-name: perl-faq/part2
  1232. Version: $Id: part2,v 2.9 1995/05/15 15:44:29 spp Exp spp $
  1233. Posting-Frequency: bi-weekly
  1234. Last Edited: Thu Jan 11 00:54:41 1996 by spp (Stephen P Potter) on syrinx.psa.com
  1235.  
  1236. This posting contains answers to general information questions, mostly of 
  1237. about information sources.
  1238.  
  1239. 2.1) Is there a USENET group for Perl?
  1240.  
  1241.     Yes there is: comp.lang.perl.misc.  This group, which currently can get
  1242.     up to 150 messages per day, contains all kinds of discussions about
  1243.     Perl; everything from bug reports to new features to the history to
  1244.     humour and trivia.  This is the best source of information about
  1245.     anything Perl related, especially what's new with Perl5.  Because of
  1246.     its vast array of topics, it functions as both a comp.lang.* style
  1247.     newsgroup (providing technical information) and also as a rec.* style
  1248.     newsgroup, kind of a support group for Perl addicts (PerlAnon?).  There
  1249.     is also the group comp.lang.perl.announce, a place specifically for
  1250.     announcements related to perl (new releases, the FAQ, new modules,
  1251.     etc).
  1252.  
  1253.     Larry is a frequent poster to this group as well as most (all?) of the
  1254.     seasoned Perl programmers.  Questions will be answered by some of the
  1255.     most knowledgable Perl Hackers, often within minutes of a question
  1256.     being posted (give or take distribution times).
  1257.  
  1258.  
  1259. 2.2) Have any books or magazine articles been published about Perl?
  1260.  
  1261.     There are a number of books either available or planned.  Mostly
  1262.     chronologically, they are:
  1263.  
  1264.          Programming Perl (the Camel Book):
  1265.          Author: Larry Wall and Randal Schwartz
  1266.          Publisher: O'Reilly and Associates
  1267.              ISBN 0-937175-64-1  (English)
  1268.              ISBN 4-89052-384-7  (Japanese)
  1269.          ISBN 3-446-17257-2     (German)  (Programmieren in Perl)
  1270.             (translator: Hanser Verlag)
  1271.  
  1272.     This is probably the most well known and most useful book for 4.036 and
  1273.     earlier.  This part of O'Reilly's hugely successful "Nutshell Handbook"
  1274.     series.  Besides serving as a reference guide for Perl, it also contains
  1275.     tutorial material and is a great source of examples and cookbook
  1276.     procedures, as well as wit and wisdom, tricks and traps, pranks and
  1277.     pitfalls.  The code examples contained therein are available from
  1278.     ftp://ftp.ora.com/pub/examples/nutshell/programming_perl/perl.tar.Z or
  1279.     ftp://ftp.cis.ufl.edu/pub/perl/ora/programming_perl.  Corrections and
  1280.     additions to the book can be found in the Perl4 man page right before
  1281.     the BUGS section under the heading ERRATA AND ADDENDA. 
  1282.  
  1283.          Learning Perl (the Llama Book):
  1284.              ISBN 1-56592-042-2      (English)
  1285.          ISBN 4-89502-678-1      (Japanese)
  1286.          ISBN 2-84177-005-2      (French)
  1287.          ISBN 3-930673-08-8      (German)
  1288.  
  1289.     Another of O'Reilly's "Nutshell Handbooks", by Randal Schwartz.  This
  1290.     book is a smaller, gentler introduction to perl and is based off of
  1291.     Randal's perl classes.  While in general this is a good book for
  1292.     learning perl (like it's title), early printings did contain many typos
  1293.     and don't cover some of the more interesting features of perl.  Please
  1294.     check the errata sheet at ftp.ora.com, as well as the on-line examples.
  1295.     
  1296.     If you can't find these books in your local technical bookstore, they 
  1297.     may be ordered directly from O'Reilly by calling 1-800-998-9938 if in
  1298.     North America and 1-707-829-0515 otherwise.
  1299.    
  1300.     Johan Vromans* created a beautiful reference guide.  The reference
  1301.     guide comes with the Camel book in a nice, glossy format.  The LaTeX
  1302.     (source) and PostScript (ready to print) versions are available for FTP
  1303.     from ftp.cs.ruu.nl:/pub/DOC/perlref-4.036.1.tar.Z in Europe or from
  1304.     ftp.cis.ufl.edu:/pub/perl/doc/perlref-4.036.tar.gz in the United
  1305.     States.  Obsolete versions in TeX or troff may still be available, but
  1306.     these versions don't print as nicely.  See also:
  1307.  
  1308.         [] ftp://ftp.uu.net/languages/perl/perlref-4.036.1.tar.gz
  1309.         [] ftp://ftp.cs.ruu.nl/pub/DOC/perlref-4.036.1.tar.gz
  1310.         [] ftp://ftp.khoros.unm.edu/pub/perl/perlref-4.036.1.tar.gz
  1311.  
  1312.     Johan has also updated and released a reference guide based on version
  1313.     5.000.  This is available from the same places as the 4.036 guide.
  1314.     This version is also available from prep.gnu.ai.mit.edu in the /pub/gnu
  1315.     section along with the perl5 source.  It may be added to the standard
  1316.     perl5 distribution sometime after 5.002.  If you are using version
  1317.     5.000, you will want to get this version rather than the 4.036 version.
  1318.  
  1319.     Larry routinely carries around a camel stamp to use when autographing
  1320.     copies of his book.  If you can catch him at a conference you can
  1321.     usually get him to sign your book for you.
  1322.  
  1323.     Prentice Hall also has two perl books.  The first is ``Perl by
  1324.     Example'' by Ellie Quigley. (385 pages, $26.96, ISBN 0-13-122839-0) A
  1325.     perl tutorial (perl4); every feature is presented via an annotated
  1326.     example and sample output.  Reviews of this book have varied widely.
  1327.     Many new perl users have used this book with much success, while many
  1328.     "veteran" programmers have had many complaints about it.
  1329.  
  1330.     The second book is called ``Software Engineering with Perl'' by Carl
  1331.     Dichter and Mark Pease.  Randal Schwartz was a technical reviewer for
  1332.     this book and notes this:
  1333.  
  1334.     SEwP is not meant as instruction in the Perl language, but rather
  1335.     as an example of how Perl may be used to assist in the semi-formal 
  1336.     software engineering development cycles.  There's a lot of Perl
  1337.     code that's fairly well commented, but most of the book describes
  1338.     software engineering methodologies.  For the perl-challenged,
  1339.     there's a *light* treatment of the language as well, but they refer
  1340.     to the llama and the camel for the real meat.
  1341.  
  1342.     SAMS Publishing also has a Perl book available, as part of their "Teach
  1343.     Yourself in 21 Days" series, called "Teach Yourself Perl in 21 Days".
  1344.     ISBN 0-672-30586-0 Price: $29.95, 841 Pages.  This book is the first
  1345.     book to have a section devoted to version 5.000, although it was
  1346.     written during an alpha stage and may not necessarily reflect current
  1347.     reality.
  1348.  
  1349.     Please note that none of the above books are perfect, all have some
  1350.     inaccurances and typos.  The two which Larry is directly associated
  1351.     with (the O'Reilly books) are probably the most technically correct,
  1352.     but also the most dated.  Carefully looking over any book you are
  1353.     considering purchasing will save you much time, money, and frustration.
  1354.  
  1355.     Starting in the March, 1995 edition of ``Unix Review''. Randal
  1356.     Schwartz* has been authoring a bi-monthly Perl column.  This has so
  1357.     far been an introductory tutorial.
  1358.  
  1359.     Larry Wall has published a 3-part article on perl in Unix World
  1360.     (August through October of 1991), and Rob Kolstad also had a 3-parter
  1361.     in Unix Review (May through July of 1990).  Tom Christiansen also has
  1362.     a brief overview article in the trade newsletter Unix Technology
  1363.     Advisor from November of 1989.  You might also investigate "The Wisdom
  1364.     of Perl" by Gordon Galligher from SunExpert magazine;  April 1991
  1365.     Volume 2 Number 4.  The Dec 92 Computer Language magazine also
  1366.     contains a cover article on Perl, "Perl: the Programmers Toolbox".
  1367.  
  1368.     Many other articles on Perl have been recently published.  If you 
  1369.     have references, especially on-line copies, please mail them to 
  1370.     the FAQ maintainer for inclusion is this notice.
  1371.  
  1372.     The USENIX LISA (Large Installations Systems Administration) Conference
  1373.     have for several years now included many papers of tools written in
  1374.     Perl.  Old proceedings of these conferences are available; look in
  1375.     your current issue of ";login:" or send mail to office@usenix.org 
  1376.     for further information.
  1377.  
  1378.     Japan seems to be jumping with Perl books.  If you can read japanese
  1379.     here are a few you might be interested in.  Thanks to Jeffrey Friedl*
  1380.     and Ken Lunde* for this list (NOTE: my screen cannot handle japanese
  1381.     characters, so this is all in English for the moment  NOTE2: These
  1382.     books are written in Japanese, these titles are just translations):
  1383.  
  1384.     Title: Welcome to Perl Country    (Perl-no Kuni-he Youkoso)
  1385.     Authors: Kaoru Maeda, Hiroshi Koyama, Yasushi Saito and Arihito
  1386.          Fuse
  1387.         Pages: 268+9                    Publisher: Science Company    
  1388.         Pub. Date: April 25, 1993       ISBN: 4-7819-0697-4         
  1389.         Price: 2472Y                    Author Email: maeda@src.ricoh.co.jp
  1390.     Comments: Written during the time the Camel book was being 
  1391.     translated.  A useful introduction, but uses jperl (Japanese Perl)
  1392.     which is not necessarily compatible.
  1393.  
  1394.     Title: How to Write Perl        (Perl Shohou)
  1395.     Author: Toshiyuki Masui
  1396.         Pages: 352                      Publisher: ASCII Corporation    
  1397.         Pub. Date: July 1, 1993            ISBN: 4-7561-0281-6        
  1398.         Price: 3200Y                    Author Email: masui@shocsl.sharp.co.jp
  1399.     Comments: More advanced than "Welcome.." and not meant as an
  1400.     introduction.  Uses the standard perl and has examples for handling
  1401.     Japanese text.
  1402.  
  1403.     Title: Introduction to Perl     (Nyuumon Perl)
  1404.     Author: Shinji Kono
  1405.         Pages: 203                      Publisher: ASCII Corporation    
  1406.         Date: July 11, 1994             ISBN: 4-7561-0292-1        
  1407.         Price: 1800Y                    Author Email: kono@csl.sony.co.jp
  1408.     Comments: Uses the interactive Perl debugger to explain how things
  1409.     work.
  1410.  
  1411.     Title: Perl Programming 
  1412.     Authors: L Wall & R Schwartz    Translator: Yoshiyuki Kondo
  1413.         Pages: 637+32                    Publisher: Softbank Corporation    
  1414.         Pub. Date: February 28, 1993    ISBN: 4-89052-384-7        
  1415.         Price: 4500Y                    Author Email: cond@lsi-j.co.jp
  1416.     Comments: Official Japanese translation of the Camel book,
  1417.         "Programming Perl".  Somewhat laced with translator notes to
  1418.         explain the humour.  The most useful book.  Also includes the Perl
  1419.         Quick Reference -- in Japanese!
  1420.  
  1421.  
  1422. 2.3) When will the Camel and Llama books be updated?
  1423.  
  1424.     As of August, 1995, ORA has contracted with Stephen to handle the
  1425.     Camel update.  According to the accepted timeline, the first draft
  1426.     is to be finished by the end of April, 1996.  The tutorial sections
  1427.     are being cut some, and the book will take on much more of a reference
  1428.     style.  Don't worry, it will still contain it's distinctive humor and
  1429.     flair.
  1430.  
  1431.     There are no current plans to update the Llama.  For the most part,
  1432.     it serves as a good introduction for both major versions of perl.  
  1433.     There may be some minor editing to it, but probably nothing major.  
  1434.     If anything, it is more likely that a third book (working title:
  1435.     Learning More Perl) will be written as a tutorial for the new perl5
  1436.     paradigm.
  1437.  
  1438. 2.4) What FTP resources are available?
  1439.  
  1440.     Since 1993, several ftp sites have sprung up for Perl and Perl related
  1441.     items.  The site with the biggest repository of Perl scripts right now
  1442.     seems to be ftp.cis.ufl.edu [128.227.100.198] in /pub/perl.  The
  1443.     scripts directory has an INDEX with over 400 lines in it, each
  1444.     describing what the script does.  The src directory has sources and/or
  1445.     binaries for a number of different perl ports, including MS-Dos,
  1446.     Macintosh and Windows/NT.  This is maintained by the Computing Staff at
  1447.     UF*.  
  1448.  
  1449.     Note:  European users please use the site src.doc.ic.ac.uk
  1450.     [149.169.2.1] in /pub/computing/programming/languages/perl/
  1451.     The link speed would be a lot better for all.  Contact
  1452.     L.McLoughlin@doc.ic.ac.uk for more information.  It is updated
  1453.     daily. 
  1454.  
  1455.     There are also a number of other sites.  I'll add more of them as I get
  1456.     information on them.
  1457.     [site maintainers: if you want to add a blurb here, especially if you
  1458.     have something unique, please let me know. -spp]
  1459.  
  1460.     The Comprehensive Perl Archive Network (CPAN) is in heavy development.
  1461.     Once the main site and its mirrors are fully operational, this answer
  1462.     will change to reflect it's existance.
  1463.  
  1464.  
  1465. 2.5) What WWW/gopher resources are available?
  1466.  
  1467.     The World Wide Web is exploding with new Perl sites all the time.  Some
  1468.     of the more notable ones are:  
  1469.     http://www.cis.ufl.edu/perl
  1470.     http://www.metronet.com/1h/perlinfo, which has a great section on
  1471.         Perl5. 
  1472.     http://www.eecs.nwu.edu/perl/perl.html
  1473.         http://web.nexor.co.uk/perl/perl.html, a great site for European
  1474.         and UK users.
  1475.  
  1476.  
  1477. 2.6) Can people who don't have access to USENET get comp.lang.perl.misc?
  1478.  
  1479.     "Perl-Users" is the mailing list version of the comp.lang.perl.misc
  1480.     newsgroup.  If you're not lucky enough to be on USENET you can post to
  1481.     comp.lang.perl.misc by sending to one of the following addresses.
  1482.     Which one will work best for you depends on which nets your site is
  1483.     hooked into.  Ask your local network guru if you're not certain.
  1484.  
  1485.     Internet: PERL-USERS@VIRGINIA.EDU
  1486.               Perl-Users@UVAARPA.VIRGINIA.EDU
  1487.  
  1488.     BitNet: Perl@Virginia
  1489.  
  1490.     uucp: ...!uunet!virginia!perl-users
  1491.  
  1492.     The Perl-Users list is bidirectionally gatewayed with the USENET
  1493.     newsgroup comp.lang.perl.misc.  This means that VIRGINIA functions as a
  1494.     reflector.  All traffic coming in from the non-USENET side is
  1495.     immediately posted to the newsgroup.  Postings from the USENET side are
  1496.     periodically digested and mailed out to the Perl-Users mailing list.  A
  1497.     digest is created and distributed at least once per day, more often if
  1498.     traffic warrants.
  1499.  
  1500.     All requests to be added to or deleted from this list, problems,
  1501.     questions, etc., should be sent to:
  1502.  
  1503.     Internet: Perl-Users-Request@Virginia.EDU
  1504.               Perl-Users-Request@uvaarpa.Virginia.EDU
  1505.  
  1506.     BitNet: Perl-Req@Virginia
  1507.  
  1508.     uucp: ...!uunet!virginia!perl-users-request
  1509.  
  1510.     Coordinator: Marc Rouleau <mer6g@VIRGINIA.EDU>
  1511.  
  1512.  
  1513. 2.7) Are archives of comp.lang.perl.misc available?
  1514.  
  1515.     Yes, there are.  ftp.cis.ufl.edu:/pub/perl/comp.lang.perl.*/monthly has
  1516.     an almost complete collection dating back to 12/89 (missing 08/91
  1517.     through 12/93).  They are kept as one large file for each month.
  1518.  
  1519.     A more sophisticated query and retrieval mechanism is desirable.
  1520.     Preferably one that allows you to retrieve article using a fast-access
  1521.     indices, keyed on at least author, date, subject, thread (as in "trn")
  1522.     and probably keywords.  Right now, the MH pick command works for this,
  1523.     but it is very slow to select on 18000 articles.
  1524.  
  1525.     If you have, or know where I can find, the missing sections, please let
  1526.     perlfaq@perl.com know.
  1527.  
  1528.  
  1529. 2.8) Is there a WAIS server for comp.lang.perl.*?
  1530.  
  1531.     Yes there is.  Set your WAIS client to 
  1532.     archive.orst.edu:9000/comp.lang.perl.*.  According to their
  1533.     introduction, they have a complete selection from 1989 on.
  1534.  
  1535. 2.9) What other sources of information about Perl or training are available?
  1536.  
  1537.     There is a #Perl channel on IRC (Internet Relay Chat) where Tom and
  1538.     Randal have been known to hang out.  Here you can get immediate answers
  1539.     to questions from some of the most well-known Perl Hackers.
  1540.  
  1541.     The perl5-porters (perl5-porters@nicoh.com) mailing list was created to
  1542.     aid in communication among the people working on perl5.  However, it
  1543.     has overgrown this function and now also handles a good deal of traffic
  1544.     about perl internals.
  1545.  
  1546. 2.10) Where can I get training classes on Perl?
  1547.  
  1548.     USENIX, LISA, SUG, WCSAS, AUUG, FedUnix and Europen sponsor tutorials
  1549.     of varying lengths on Perl at the System Administration and General
  1550.     Conferences.  These public classes are typically taught by Tom
  1551.     Christiansen*.  
  1552.  
  1553.     In part, Tom and Randal teach Perl to help keep bread on their tables
  1554.     long enough while they continue their pro bono efforts of documenting
  1555.     perl (Tom keeps writing more man pages for it :-) and expanding the
  1556.     perl toolkit through extension libraries, work which they enjoy doing
  1557.     as it's fun and helps out the whole world, but which really doesn't
  1558.     pay the bills.  Such is the nature of free(ly available) software.
  1559.     Send mail to <perlclasses@perl.com> for details and availability.
  1560.  
  1561.     Tom is also available to teach on-site classes, included courses on
  1562.     advanced perl and perl5.  Classes run anywhere from one day to week
  1563.     long sessions and cover a wide range of subject matter.  Classes can
  1564.     include lab time with exercises, a generally beneficial aspect.  If you
  1565.     would like more information regarding Perl classes or when the next
  1566.     public appearances are, please contact Tom directly at 1.303.444.3212.
  1567.  
  1568.     Randal Schwartz* provides a 2-day lecture-only and a 4-5 day lecture-lab
  1569.     course based on his popular book "Learning Perl".  For details, contact
  1570.     Randal directly via email or at 1.503.777.0095.
  1571.     
  1572.     Internet One provides a 2 day "Introduction to Perl"  and  2  day
  1573.     "Advanced Perl" workshop. The 50% hands-on and 50% lecture format
  1574.     allow attendees to write several programs  themselves.   Supplied
  1575.     are  the user manuals, reference copies of Larry Wall's "Program-
  1576.     ming Perl", and a UNIX directory of  all  training  examples  and
  1577.     labs. To obtain outlines, pricing, or scheduling information, use
  1578.     the following:
  1579.  
  1580.         o Phone: 1.303.444.1993
  1581.         o Email: info@InternetOne.COM
  1582.         o See our Ad in the "SysAdmin" magazine
  1583.         o View the outlines via the Web: http://www.InternetOne.COM/
  1584.  
  1585.  
  1586. 2.11) What companies use or ship Perl?
  1587.  
  1588.     At this time, the known list of companies that ship Perl includes at
  1589.     least the following, although some have snuck it into /usr/contrib or
  1590.     its moral equivalent: 
  1591.  
  1592.     BSDI
  1593.     Comdisco Systems
  1594.     CONVEX Computer Corporation
  1595.     Crosspoint Solutions
  1596.         Data General
  1597.     Dell
  1598.     DRD Corporation
  1599.     IBM (SP systems)
  1600.     Intergraph
  1601.     Kubota Pacific 
  1602.     Netlabs
  1603.     SGI (without taintperl)
  1604.     Univel
  1605.  
  1606.     Some companies ship it on their "User Contributed Software Tape",
  1607.     such as DEC and HP.  Apple Computer has shipped the MPW version of
  1608.     Macintosh Perl on one of their Developer CDs (Essentials*Tools*Objects 
  1609.     #11) (and they included it under "Essentials" :-)
  1610.  
  1611.     Many other companies use Perl internally for purposes of tools
  1612.     development, systems administration, installation scripts, and test
  1613.     suites.  Rumor has it that the large workstation vendors (the TLA set)
  1614.     are seriously looking into shipping Perl with their standard systems
  1615.     "soon".
  1616.  
  1617.     People with support contracts with their vendors are actively 
  1618.     encouraged to submit enhancement requests that Perl be shipped 
  1619.     as part of their standard system.  It would, at the very least,
  1620.     reduce the FTP load on the Internet. :-)
  1621.  
  1622.     If you know of any others, please send them in.
  1623.  
  1624.  
  1625. 2.12) Is there commercial, third-party support for Perl?
  1626.  
  1627.     Not really.  Although perl is included in the GNU distribution, at last
  1628.     check, Cygnus does not offer support for it.  However, it's unclear
  1629.     whether they've ever been offered sufficient financial incentive to do
  1630.     so.  Feel free to try.
  1631.  
  1632.     On the other hand, you do have comp.lang.perl.misc as a totally gratis
  1633.     support mechanism.  As long as you ask "interesting" questions, you'll
  1634.     probably get plenty of help. :-) 
  1635.  
  1636.     While some vendors do ship Perl with their platforms, that doesn't mean
  1637.     they support it on arbitrary other platforms.  And in fact, all they'll
  1638.     probably do is forward any bug reports on to Larry.  In practice, this
  1639.     is far better support than you could hope for from nearly any vendor.
  1640.  
  1641.     If you purchase a product from Netlabs (the company Larry works for),
  1642.     you actually can get a support contract that includes Perl.
  1643.  
  1644.     The companies who won't use something unless they can pay money for it
  1645.     will be left out.  Often they're motivated by wanting someone whom they
  1646.     could sue.  If all they want is someone to help them out with Perl
  1647.     problems, there's always the net.  And if they really want to pay
  1648.     someone for that help, well, any of a number of the regular Perl
  1649.     "dignitaries" would appreciate the money.  ;-)
  1650.  
  1651.     If companies want "commercial support" for it badly enough, speak up --
  1652.     something might be able to be arranged. 
  1653.  
  1654.  
  1655. 2.13) What is a JAPH?  What does "Will hack perl for ..." mean?
  1656.  
  1657.     These are the "just another perl hacker" signatures that some people
  1658.     sign their postings with.  About 100 of the of the earlier ones are
  1659.     available from the various FTP sites.
  1660.  
  1661.     When people started running out of tricky and interesting JAPHs, some
  1662.     of them turned to writing "Will hack perl for ..." quotes.  While
  1663.     sometimes humourous, they just didn't have the flair of the JAPHs and
  1664.     have since almost completely vanished.
  1665.  
  1666.  
  1667. 2.14) Where can I get a list of Larry Wall witticisms?
  1668.  
  1669.     Over a hundred quips by Larry, from postings of his or source code,
  1670.     can be found in many of the FTP sites or through the World Wide Web at
  1671.     "ftp://ftp.cis.ufl.edu/pub/perl/misc/lwall-quotes"
  1672.  
  1673.  
  1674. 2.15) What are the known bugs?
  1675.  
  1676.     This is *NOT* a complete list, just some of the more common bugs that
  1677.     tend to bite people.
  1678.  
  1679.     5.001:
  1680.     op.c: Inconsistent parameter definition for pad_findlex - fixed
  1681.         in 5.001a, get development patches a-l.
  1682.  
  1683.     walk.c: redeclaration of emit_split - fixed in perl5.001a, get
  1684.         development patches a-l.
  1685.  
  1686.     On linux systems "make test" fails on "op/exec Failed test 5".  This
  1687.         is a known bug with bash, not perl.  You can get a new version 
  1688.         of bash.
  1689.  
  1690.     Also on linux systems, "make test" hangs on lib/anydbm if you include
  1691.         NDBM in the extentions.  Do not include NDBM.
  1692.  
  1693.     Another linux problem is getting Dynamic Loading to work.  You must
  1694.         use dld-2.3.6 (the newest version at the time of writing) to
  1695.         use Dynamic Loading.
  1696.  
  1697.     - All versions of h2ph previous to the one supplied with perl5.001 tended
  1698.     to generate improper header files.  Something such as:
  1699.  
  1700.         #if __GNUC__
  1701.     
  1702.     was incorrectly translated into
  1703.  
  1704.         if ( &__GNUC__ ) {
  1705.  
  1706.     instead of 
  1707.  
  1708.         if ( defined(&__GNUC__) ? &__GNUC__ : 0 ) {
  1709.  
  1710.     Perl5 binaries compiled on SunOS4 exhibit strange behaviour on SunOS5.
  1711.     For example, backticks do not work in the scripts.  You need to
  1712.     compile perl for both architectures, even with Binary Compatibility.
  1713.  
  1714.  
  1715. 2.16) Where should I post bugs?
  1716.  
  1717.     Before posting about a bug, please make sure that you are using the
  1718.     most recent versions of perl (currently 4.036 and 5.001) available.
  1719.     Please also check at the major archive sites to see if there are any
  1720.     development patches available (usually named something like
  1721.     perl5.001a.patch or patch5.001a - the patch itself, or
  1722.     perl5.001a.tar.gz - a prepatched distribution).  If you are not using
  1723.     one of these versions, chances are you will be told to upgrade because   
  1724.     the bug has already been fixed.
  1725.  
  1726.     If you are reporting a bug in perl5, the best place to send your bug
  1727.     is <perlbug@perl.com>, which is currently just an alias for
  1728.     <perl5-porters@nicoh.com>.  In the past, there have been problems with
  1729.     the perlbug address.  If you have problems with it, please send your
  1730.     bug directly to <perl5-porters@nicoh.com>.  You may subscribe to the list
  1731.     in the customary fashion via mail to <perl5-porters-request@nicoh.com>.
  1732.     Feel free to post your bugs to the comp.lang.perl.misc newsgroup as
  1733.     well, but do make sure they still go to the mailing list.
  1734.  
  1735.     If you are posting a bug with a non-Unix port, a non-standard Module
  1736.     (such as Tk, Sx, etc) please see the documentation that came with it
  1737.     to determine the correct place to post bugs.
  1738.  
  1739.     To enhance your chances of getting any bug you report fixed:
  1740.  
  1741.     1. Make sure you are using a production version of perl.  Alpha and
  1742.        Beta version problems have probably already been reported and
  1743.        fixed.
  1744.  
  1745.     2. Try to narrow the problem down to as small a piece of code as
  1746.        possible.  If you can get it down to 1 line of Perl then so much
  1747.        the better.
  1748.  
  1749.     3. Include a copy of the output from the myconfig script from the
  1750.        Perl source distribution in your posting.
  1751.  
  1752. 2.17) Where should I post source code?
  1753.  
  1754.     You should post source code to whichever group is most appropriate,
  1755.     but feel free to cross-post to comp.lang.perl.misc.  If you want to
  1756.     cross-post to alt.sources, please make sure it follows their
  1757.     posting standards, including setting the Followups-To header
  1758.     line to NOT include alt.sources; see their FAQ for details.
  1759.  
  1760.  
  1761. 2.18) Where can I learn about object-oriented Perl programming?
  1762.  
  1763.     The perlobj(1) man page is a good place to start, and then you can
  1764.     check out the excellent perlbot(1) man page written by the dean of perl
  1765.     o-o himself, Dean Roehrich.  Areas covered include the following:
  1766.  
  1767.         Idx  Subsections in perlobj.1          Lines
  1768.          1   NAME                                  2
  1769.          2   DESCRIPTION                          16
  1770.          3   An Object is Simply a Reference      60
  1771.          4   A Class is Simply a Package          31
  1772.          5   A Method is Simply a Subroutine      34
  1773.          6   Method Invocation                    75
  1774.          7   Destructors                          14
  1775.          8   Summary                               7
  1776.  
  1777.         Idx  Subsections in perlbot.1          Lines
  1778.          1   NAME                                  2
  1779.          2   INTRODUCTION                          9
  1780.          3   Instance Variables                   43
  1781.          4   Scalar Instance Variables            21
  1782.          5   Instance Variable Inheritance        35
  1783.          6   Object Relationships                 33
  1784.          7   Overriding Superclass Methods        49
  1785.          8   Using Relationship with Sdbm         45
  1786.          9   Thinking of Code Reuse              111
  1787.  
  1788.     The section on instance variables should prove very helpful to those
  1789.     wondering how to get data inheritance in perl. 
  1790.  
  1791.  
  1792. 2.19) Where can I learn about linking C with Perl? [h2xs, xsubpp]
  1793.  
  1794.     While it used to be deep magic, how to do this is now revealed in the
  1795.     perlapi(1), perlguts(1), and perlcall(1) man pages, which treat with
  1796.     this matter extensively.  You should also check the many extensions
  1797.     that people have written (see question 1.19), many of which do this
  1798.     very thing.
  1799.  
  1800.  
  1801. 2.20) What is perl.com?
  1802.  
  1803.     Perl.com is just Tom's domain name, registered as dedicated to "Perl
  1804.     training and consulting".  While not a full ftp site (he hasn't got
  1805.     the bandwidth (yet)), it does have some interesting bits, most of which
  1806.     are replicated elsewhere.  It serves as a clearinghouse for certain
  1807.     perl related mailing lists.  The following aliases work:
  1808.  
  1809.         perl-packrats:          The archivist list
  1810.           perl-porters:           The porters list
  1811.         perlbook:               The Camel/Llama/Alpaca writing committee
  1812.         perlbugs:               The bug list (perl-porters for now)
  1813.         perlclasses:            Info on Perl training
  1814.         perlfaq:                Submissions/Errata to the Perl FAQ
  1815.                                 (Tom and Steve)
  1816.         perlrefguide:           Submissions/Errata to the Perl RefGuide
  1817.                                 (Johan) 
  1818.  
  1819. 2.21) What do the asterisks (*) throughout the FAQ stand for?
  1820.  
  1821.     To keep from cluttering up the FAQ and for easy reference all email
  1822.     addresses have been collected in this location.  For each person
  1823.     listed, I offer my thanks for their input and help.
  1824.  
  1825.     * Larry Wall        <lwall@netlabs.com>
  1826.     * Tom Christiansen        <tchrist@wraeththu.cs.colorado.edu>
  1827.     * Stephen P Potter        <spp@pencom.com>
  1828.     * Andreas Koenig        <k@franz.ww.TU-Berlin.DE>
  1829.     * Bill Eldridge        <bill@cognet.ucla.edu>
  1830.     * Buzz Moschetti        <buzz@bear.com>
  1831.     * Casper H.S. Dik        <casper@fwi.uva.nl>
  1832.     * David Muir Sharnoff   <muir@tfs.com>
  1833.     * Dean Roehrich         <roehrich@ironwood.cray.com>
  1834.     * Dominic Giampaolo     <dbg@sgi.com>,
  1835.     * Frederic Chauveau     <fmc@pasteur.fr>
  1836.     * Gene Spafford         <spaf@cs.purdue.edu>
  1837.     * Guido van Rossum        <guido@cwi.nl>
  1838.     * Henk P Penning        <henkp@cs.ruu.nl>
  1839.     * Jeff Friedl        <jfriedl@omron.co.jp>
  1840.     * Johan Vromans        <jvromans@squirrel.nl>
  1841.     * John Dallman        <jgd@cix.compulink.co.uk>
  1842.     * John Lees            <lees@pixel.cps.msu.edu>
  1843.     * John Ousterhout        <ouster@eng.sun.com>
  1844.     * Jon Biggar        <jon@netlabs.com>
  1845.     * Ken Lunde                <lunde@mv.us.adobe.com>
  1846.     * Malcolm Beattie        <mbeattie@sable.ox.ac.uk>
  1847.     * Matthias Neeracher    <neeri@iis.ee.ethz.ch>
  1848.     * Michael D'Errico        <mike@software.com>
  1849.     * Nick Ing-Simmons        <Nick.Ing-Simmons@tiuk.ti.com>
  1850.     * Randal Schwartz        <merlyn@stonehenge.com>
  1851.     * Roberto Salama        <rs@fi.gs.com>
  1852.     * Steven L Kunz        <skunz@iastate.edu>
  1853.     * Theodore C. Law        <TEDLAW@TOROLAB6.VNET.IBM.COM>
  1854.     * Thomas R. Kimpton        <tom@dtint.dtint.com>
  1855.     * Timothy Murphy        <tim@maths.tcd.ie>
  1856.     * UF Computer Staff        <consult@cis.ufl.edu>
  1857.  
  1858. --
  1859. Stephen P Potter        Pencom Systems Administration              Beaching It 
  1860. spp@psa.pencom.com    Pager: 1-800-759-8888, 547-9561     Work: 703-860-2222
  1861.   Cthulhu for President in '96: When You're Tired of the Lesser of Two Evils
  1862. --
  1863. Stephen P Potter        Pencom Systems Administration              Beaching It 
  1864. spp@psa.pencom.com    Pager: 1-800-759-8888, 547-9561     Work: 703-860-2222
  1865. "I don't care whether people actually like Perl, just so long as they *think*
  1866.     they like it...  ;-)"    -Larry Wall
  1867.  
  1868. Article: 62275 in news.answers
  1869. Path: Dortmund.Germany.EU.net!Germany.EU.net!wizard.pn.com!satisfied.apocalypse.org!news2.near.net!cocoa.brown.edu!ride.ri.net!news3.near.net!paperboy.wellfleet.com!news-feed-1.peachnet.edu!gatech!newsfeed.internetmci.com!in2.uu.net!news1.radix.net!news1.radix.net!spp
  1870. From: spp@psa.pencom.com
  1871. Newsgroups: comp.lang.perl.announce,comp.lang.perl.misc,comp.answers,news.answers
  1872. Subject: comp.lang.perl.* FAQ 3/5 - Programming Aids
  1873. Followup-To: poster
  1874. Date: 27 Jan 1996 01:25:01 GMT
  1875. Organization: Pencom Systems Administration
  1876. Lines: 653
  1877. Approved: news-answers-request@MIT.EDU
  1878. Distribution: world
  1879. Message-ID: <SPP.96Jan26202501@syrinx.hideout.com>
  1880. NNTP-Posting-Host: dialin23.annex1.radix.net
  1881. Xref: Dortmund.Germany.EU.net comp.lang.perl.announce:243 comp.lang.perl.misc:18678 comp.answers:16594 news.answers:62275
  1882.  
  1883.  
  1884. Archive-name: perl-faq/part3
  1885. Version: $Id: part3,v 2.7 1995/05/15 15:44:43 spp Exp spp $
  1886. Posting-Frequency: bi-weekly
  1887. Last Edited: Thu Jan 11 00:55:42 1996 by spp (Stephen P Potter) on syrinx.psa.com
  1888.  
  1889. This posting contains answers to general information questions, mostly
  1890. about programming aids.  
  1891.  
  1892.  
  1893. 3.1) How can I use Perl interactively?
  1894.     
  1895.     The easiest way to do this is to run Perl under its debugger.  If you
  1896.     have no program to debug, you can invoke the debugger on an `empty'
  1897.     program like this: 
  1898.  
  1899.         perl -de 0
  1900.  
  1901.     (The more positive hackers prefer "perl -de 1". :-)
  1902.  
  1903.     Now you can type in any legal Perl code, and it will be immediately
  1904.     evaluated.  You can also examine the symbol table, get stack
  1905.     backtraces, check variable values, and if you want to, set breakpoints
  1906.     and do the other things you can do in a symbolic debugger. 
  1907.  
  1908.  
  1909. 3.2) Is there a Perl profiler?
  1910.  
  1911.     While there isn't one included with the perl source distribution (yet) 
  1912.     various folks have written packages that allow you to do at least some 
  1913.     sort of profiling.  The strategy usually includes modifying the perl 
  1914.     debugger to handle profiling.  Authors of these packages include 
  1915.  
  1916.     Wayne Thompson         <me@anywhere.EBay.Sun.COM>
  1917.     Ray Lischner         <lisch@sysserver1.mentor.com>
  1918.     Kresten Krab Thorup     <krab@iesd.auc.dk>  
  1919.  
  1920.     The original articles by these folks containing their profilers are
  1921.     available at ftp://convex.com/pub/perl/info/profiling.shar.
  1922.  
  1923.     Recently, Dean Roerich* has written a profiler for version 5 that
  1924.     likely will be distributed with the standard release.  For now, it
  1925.     should be available through any of the extension archives as
  1926.     DProf.tar.gz.
  1927.  
  1928.  
  1929. 3.3) Is there a yacc for Perl?
  1930.  
  1931.     Yes!! It's a version of Berkeley yacc that outputs Perl code instead
  1932.     of C code!  You can get this from
  1933.     ftp://ftp.sterling.com/local/perl-byacc1.8.2.tar.Z, or send the author
  1934.     mail for details. 
  1935.  
  1936.  
  1937. 3.4) Is there a pretty-printer (similar to indent(1)) for Perl?
  1938.  
  1939.     That depends on what you mean.  If you want something that works like
  1940.     vgrind on Perl programs, then the answer is "yes, nearly".  Here's a
  1941.     vgrind entry for perl: 
  1942.  
  1943.     PERL|perl|Perl:\
  1944.         :pb=^\d?(sub|package)\d\p\d:\
  1945.         :bb={:be=}:cb=#:ce=$:sb=":se=\e":lb=':\
  1946.         :le=\e':tl:\
  1947.         :id=_:\
  1948.         :kw=\
  1949.         if for foreach unless until while continue else elsif \
  1950.         do eval require \
  1951.         die exit \
  1952.         defined delete reset \
  1953.         goto last redo next dump \
  1954.         local undef return  \
  1955.         write format  \
  1956.         sub package
  1957.  
  1958.     It doesn't actually do everything right; in particular, 
  1959.     things like $#, $', s#/foo##, and $foo'bar all confuse it.
  1960.  
  1961.     David Levine uses this:
  1962.  
  1963.     # perl 4.x                    David Levine <levine@ics.uci.edu> 05 apr 1993
  1964.     # Derived from Tom Christiansen's perl vgrindef.  I'd like to treat all  of
  1965.     # perl's built-ins as  keywords,  but vgrind   fields are  limited  to 1024
  1966.     # characters  and the built-ins overflow that (surprise  :-).  So, I didn't
  1967.     # include the dbm*, end*, get*, msg*, sem*, set*,  and  shm* functions.   I
  1968.     # couldn't come up with an easy way to  distinguish beginnings  of literals
  1969.     # ('...') from package prefixes, so literals are not marked.
  1970.     # Be sure to:
  1971.     # 1) include whitespace between a subprogram name and its opening {
  1972.     # 2) include whitespace before a comment (so that $# doesn't get
  1973.     # interpreted as one).
  1974.     perl4:\
  1975.         :pb=^\d?(sub|package)\d\p\d:\
  1976.         :id=$%@_:\
  1977.         :bb=\e{:be=\e}:cb=\d\e#:ce=$:sb=\e":se=\e":\
  1978.         :kw=accept alarm atan2 bind binmode caller chdir chmod chop \
  1979.     chown chroot close closedir connect continue cos crypt defined delete \
  1980.     die do dump each else elsif eof eval exec exit exp fcntl fileno flock \
  1981.     for foreach fork format getc gmtime goto grep hex if include index int \
  1982.     ioctl join keys kill last length link listen local localtime log lstat \
  1983.     m mkdir next oct open opendir ord pack package pipe pop print printf \
  1984.     push q qq qx rand read readdir readlink recv redo rename require reset \
  1985.     return reverse rewinddir rindex rmdir s scalar seek seekdir select send \
  1986.     shift shutdown sin sleep socket socketpair sort splice split sprintf \
  1987.     sqrt srand stat study sub substr symlink syscall sysread system \
  1988.     syswrite tell telldir time times tr truncate umask undef unless unlink \
  1989.     unpack unshift until utime values vec wait waitpid wantarray warn while \
  1990.     write y: 
  1991.  
  1992.     If what you mean is whether there is a program that will reformat the
  1993.     program much as indent(1) will do for C, then the answer is no.  The
  1994.     complex feedback between the scanner and the parser (as in the things
  1995.     that confuse vgrind) make it challenging at best to write a stand-alone
  1996.     Perl parser. 
  1997.  
  1998.     Of course, if you follow the guidelines in perlstyle(1), you shouldn't
  1999.     need to reformat.
  2000.  
  2001.  
  2002. 3.5) How can I convert my perl scripts directly to C or compile them into
  2003.      binary form?
  2004.  
  2005.     The short answer is: "No, you can't compile perl into C.  Period."
  2006.  
  2007.     However, having said that, it is believed that it would be possible to
  2008.     write a perl to C translator, although it is a PhD thesis waiting to
  2009.     happen.  Anyone need a good challenging thesis?
  2010.  
  2011.     In the way of further, detailed explication, it seems that the reasons
  2012.     people want to do this usaully break down into one or more of the
  2013.     following:
  2014.  
  2015.     A) speed
  2016.     B) secrecy
  2017.     C) maintainability
  2018.  
  2019.     SPEED:
  2020.  
  2021.     1)    You can't turn perl source code or perl intermediary code into
  2022.     native machine code to make it run faster, and saving the perl
  2023.     intermediary code doesn't really buy you as much as you'd like.
  2024.     If you really must, check out the undump and unexec alternatives.
  2025.     If your motivations are speed, then this may or may not help you
  2026.     much.  
  2027.  
  2028.     You might also look into autoloading functions on the fly, which
  2029.     can greatly reduce start-up time.
  2030.  
  2031.     If you have a few routines that are bogging you down, you just
  2032.     possibly might wish to hand-translate just them into C, then
  2033.     dynamically load these in.  See perlapi(1) for details.  Most
  2034.     of the time, however, reorganizing your perl algorithm is the best
  2035.     way to address this.
  2036.  
  2037.  
  2038.     SOURCE-CODE SECRECY:
  2039.  
  2040.     2)  If you're trying to stop people from seeing what you're doing,
  2041.     you can shroud it, i.e. turn all the idents into silly stuff, 
  2042.     rearrange strings, and remove redundant white space.  There's
  2043.     a program out there called ShroudIt! that works on a number of
  2044.         languages, including Perl.  Note that it is a commercial product
  2045.         though.  Contact David Webber (webber@lnk.com) for more
  2046.         information.
  2047.         
  2048.     3)  You might also look into the cryptswitch() stuff in the perl
  2049.         source, which would allow you to ship something in a form they
  2050.         can't read.  This isn't particulary well-documented.
  2051.  
  2052.     4)  If you're worried about them using your software without licence,
  2053.     you put some huge disclaimer at the top that says something like
  2054.     the following.  This is actually the best solution, because only a
  2055.     legal solution will really work if legality is what you're worried
  2056.     about: trying to solve legal problems with technical solutions
  2057.     is not worth the effort, and too easily circumvented.
  2058.  
  2059.         This is UNPUBLISHED PROPRIETARY SOURCE CODE of XYZZY, Inc.; the
  2060.         contents of this file may not be disclosed to third parties,
  2061.         copied or duplicated in any form, in whole or in part, without
  2062.         the prior written permission of XYZZY, Inc.
  2063.  
  2064.         Permission is hereby granted soley to the licencee for use of
  2065.         this source code in its unaltered state.  This source code may
  2066.         not be modified by licencee except under direction of XYZZY
  2067.         Inc.  Neither may this source code be given under any
  2068.         circumstances to non-licensees in any form, including source
  2069.         or binary.  Modification of this source constitutes breach of
  2070.         contract, which voids any potential pending support
  2071.         responsibilities by XYZZY Inc.  Divulging the exact or
  2072.         paraphrased contents of this source code to unlicensed parties
  2073.         either directly or indirectly constitutes violation of federal
  2074.         and international copyright and trade secret laws, and will be
  2075.         duly prosecuted to the fullest extent permitted under law.
  2076.  
  2077.         This software is provided by XYZZY Inc. ``as is'' and any
  2078.         express or implied warranties, including, but not limited to,
  2079.         the implied warranties of merchantability and fitness for a
  2080.         particular purpose are disclaimed.  In no event shall the
  2081.         regents or contributors be liable for any direct, indirect,
  2082.         incidental, special, exemplary, or consequential damages
  2083.         (including, but not limited to, procurement of substitute
  2084.         goods or services; loss of use, data, or profits; or business
  2085.         interruption) however caused and on any theory of liability,
  2086.         whether in contract, strict liability, or tort (including
  2087.         negligence or otherwise) arising in any way out of the use of
  2088.         this software, even if advised of the possibility of such
  2089.         damage.
  2090.  
  2091.     MAINTAINABILITY:
  2092.  
  2093.     5)  If you just want to stop people from changing it because you're
  2094.     concerned about support issues, you can put in a big disclaimer at
  2095.     the top that says that if they touch the file they void the
  2096.     warranty, and then make them give you a size, checksum, and
  2097.     version of the file before answering any questions about it.
  2098.  
  2099.     If you maintain a central site that distributes software to
  2100.     internal client machines, use rdist(1) to send around a proper
  2101.     version periodically, perhaps using the -y option on the install
  2102.     to flag destinations younger than the source.
  2103.  
  2104.     Let it be noted than in the many, many years that Perl's author
  2105.     has been releasing and supporting freely redistributable software,
  2106.     he has NEVER ONCE been bitten by a bogus bug report generated by
  2107.     someone breaking his code because they had access to it.  Rather,
  2108.     he and many other open software provided (where open software
  2109.     means that for which the source is provided, the only truly open
  2110.     software) have saved themselves countless hours of labor thousands
  2111.     of times over because they've allowed people to inspect the source
  2112.     for themselves.  Proprietary source-code hoarding is its own
  2113.         headache. 
  2114.  
  2115.     Thus, obscurity for the sake of maintainability would seem to be a
  2116.     red herring.
  2117.  
  2118.     6)  If you can't count on perl being installed at the destination
  2119.         customer, then by all means, merely ship it with your program.
  2120.         This is no hardship, since software providers are accustomed to
  2121.         shipping software in machine-specific binary form.  The basic idea
  2122.         is as simple as: 
  2123.  
  2124.         shar /usr/local/{lib,bin,man}/perl myprog
  2125.  
  2126.     Just don't overwrite their own Perl installation if they have one!
  2127.  
  2128.  
  2129. 3.6) Where can I get a perl-mode for emacs?
  2130.  
  2131.     Since Emacs version 19 patchlevel 22 or so, there has been both a
  2132.     perl-mode.el and support for the perl debugger built in.  These should
  2133.     come with the standard Emacs 19 distribution.
  2134.  
  2135.     In the perl source directory, you'll find a directory called
  2136.     "emacs", which contains several files that should help you.
  2137.  
  2138.     Note that the perl-mode of emacs will have fits with "main'foo" (single
  2139.     quote), and mess up the indentation and hilighting.  However, note that
  2140.     in perl5, you should be using "main::foo".  By the way, did we mention
  2141.     that you should upgrade?
  2142.  
  2143.  
  2144. 3.7) Is there a Perl shell? 
  2145.     
  2146.     Not really.  Perl is a programming language, not a command
  2147.     interpreter.  There is a very simple one called "perlsh"
  2148.     included in the Perl source distribution.  It just does this:
  2149.  
  2150.     $/ = '';        # set paragraph mode
  2151.     $SHlinesep = "\n";
  2152.     while ($SHcmd = <>) {
  2153.         $/ = $SHlinesep;
  2154.         eval $SHcmd; print $@ || "\n";
  2155.         $SHlinesep = $/; $/ = '';
  2156.     }
  2157.  
  2158.     Not very interesting, eh?  
  2159.  
  2160.     Daniel Smith <dls@best.com> is working on an interactive Perl shell
  2161.     called SoftList.  It's currently at version 3.0b7a (beta).  SoftList 
  2162.     3.0b7a has tcsh-like command line editing, can let you define a file of
  2163.     aliases so that you can run chunks of perl or UNIX commands, and so
  2164.     on.  You can pick up a copy at ftp.best.com in
  2165.     /pub/dls/SoftList-3.0b7a.gz. 
  2166.  
  2167.  
  2168. 3.8) How can I use curses with perl?
  2169.  
  2170.     In release 4 of perl, the only way to do this was was to build a
  2171.     curseperl binary by linking in your C curses library as described in
  2172.     the usub subdirectory of the perl sources.  This requires a modicum of
  2173.     work, but it will be reasonably fast since it's all in C (assuming you
  2174.     consider curses reasonably fast. :-) Programs written using this
  2175.     method require the modified curseperl, not vanilla perl, to run.
  2176.     While this is something of a disadvantage, experience indicates that
  2177.     it's better to use curseperl than to try to roll your own using
  2178.     termcap directly.
  2179.  
  2180.     Fortunately, in version 5, Curses is a dynamically loaded extension
  2181.     by William Setzer*.  You should be able to pick it up wherever you
  2182.     get Perl 5 from, or at least these places (expect that the version may
  2183.     change by the time you read this):
  2184.  
  2185.     ftp://ftp.ncsu.edu/pub/math/wsetzer/cursperl5a6.tar.gz
  2186.         ftp://ftp.metronet.com/pub/perlinfo/perl5/cursperl5a6.tar.gz
  2187.         ftp://ftp.cs.ruu.nl/pub/PERL/perl5.0/cursperl5a6.tar.gz
  2188.  
  2189.     For a good example of using curses with Perl, you might want to pick
  2190.     up a copy of Steven L. Kunz's* "perl menus" package ("menu.pl") via
  2191.     anonymous FTP from "ftp.iastate.edu".  It's in the directory /pub/perl
  2192.     as:
  2193.  
  2194.         menu.pl.v3.1.tar.Z
  2195.  
  2196.     menu.pl is a complete menu front-end for perl+curses and demonstrates
  2197.     a lot of things (plus it is useful to boot if you want full-screen
  2198.     menu selection ability).  It provides full-screen menu selection
  2199.     ability for three menu styles (single-selection, multiple-selection,
  2200.     and "radio-button").  The "perl menus" package also includes routines
  2201.     for full-screen data entry.  A "template" concept is implemented to
  2202.     create a simple (yet flexible) perl interface for building data-entry
  2203.     screens for registration, database, or other record-oriented tasks.
  2204.  
  2205.     menu.pl is supported on Perl4/curseperl and Perl5/Curses.  Complete
  2206.     user documentation is provided along with several demos and "beginner
  2207.     applications".  A menu utility module is provided that is a collection
  2208.     of useful Perl curses routines (such as "pop-up query boxes) that may
  2209.     be called from your applications.
  2210.  
  2211.     Another possibility is to use Henk Penning's cterm package, a curses
  2212.     emulation library written in perl.  cterm is actually a separate
  2213.     program with which you communicate via a pipe.  It is available from
  2214.     ftp.cs.ruu.nl [131.211.80.17] via anonymous ftp. in the directory
  2215.     pub/PERL.  You may also acquire the package via email in compressed,
  2216.     uuencoded form by sending a message to mail-server@cs.ruu.nl
  2217.     containing these lines:
  2218.  
  2219.     begin
  2220.     send PERL/cterm.shar.Z
  2221.     end
  2222.  
  2223.     See the question on retrieving perl via mail for more information on
  2224.     how to retrieve other items of interest from the mail server
  2225.     there.
  2226.  
  2227.  
  2228. 3.9) How can I use X or Tk with Perl?
  2229.  
  2230.     Right now, you have several choices.  If you are still using perl4, use
  2231.     the WAFE or STDWIN packages, or try to make your own usub binding.
  2232.  
  2233.     However, if you've upgraded to version 5, you have several exciting
  2234.     possibilities, with more popping up each day.  Right now, Tk and Sx
  2235.     are the best known such extensions.
  2236.  
  2237.     If you like the tk package, you should get the Tk extension kit,
  2238.     written by Nick Ing-Simmons*.  The official distribution point is at
  2239.  
  2240.         ftp://ftp.wpi.edu/perl5/private/Tk-b8.tar.gz
  2241.  
  2242.     but many of the major archive sites now have it in their /ext{entions}
  2243.     directory also.  Depending upon your location, you may be better off
  2244.     checking there.  Also, understand that the version number may have
  2245.     changed by the time you read this.
  2246.  
  2247.     This package replaced the tkperl5 project, by Malcolm Beattie*, which
  2248.     was based on an older version of Tk, 3.6 as compared to the current
  2249.     4.X.  This package was also known as nTk (new Tk) while it was in the
  2250.     alpha stages, but has been changed to just Tk now that it is in beta.
  2251.     Also, be advised that you need at least perl5.001 (preferably 5.002,
  2252.     when it becomes available) and the official unofficial patches.
  2253.  
  2254.     You may also use the old Sx package, (Athena & Xlib), written by
  2255.     originally written by by Dominic Giampaolo*, then and rewritten for Sx
  2256.     by Frederic Chauveau*.  It's available from these sites:
  2257.  
  2258.         ftp://ftp.pasteur.fr/pub/Perl/Sx.tar.gz
  2259.         ftp://ftp.khoros.unm.edu/pub/perl/extensions/Sx.tar.gz
  2260.         ftp://ftp.metronet.com/pub/perlinfo/perl5/Sx.tar.gz
  2261.  
  2262.     STDWIN is a library written by Guido van Rossum* (author of the Python
  2263.     programming language) that is portable between Mac, Dos and X11.  One
  2264.     could write a Perl agent to speak to this STDWIN server.
  2265.  
  2266.     WAFE is a package that implements a symbolic interface to the Athena
  2267.     widgets (X11R5). A typical Wafe application consists in our framework
  2268.     of two parts: the front-end (we call it Wafe for Widget[Athena]front
  2269.     end) and an application program running typically as a separate
  2270.     process.  The application program can be implemented in an arbitrary
  2271.     programming language and talks to the front-end via stdio.  Since Wafe
  2272.     (the front-end) was developed using the extensible TCL shell (cite John
  2273.     Ousterhout), an application program can dynamically submit requests to
  2274.     the front-end to build up the graphical user interface; the
  2275.     application can even down-load application specific procedures into
  2276.     the front-end.  The distribution contains sample application programs
  2277.     in Perl, GAWK, Prolog, TCL, and C talking to the same Wafe binary.
  2278.     Many of the demo applications are implemented in Perl.  Wafe 0.9 can
  2279.     be obtained via anonymous ftp from 
  2280.     ftp.wu-wien.ac.at[137.208.3.5]:pub/src/X11/wafe-0.9.tar.Z
  2281.  
  2282.     Alternatively, you could use wish from tcl. 
  2283.  
  2284.     #!/usr/local/bin/perl
  2285.     #####################################################################
  2286.     #  An example of calling wish as a subshell under Perl and
  2287.     #  interactively communicating with it through sockets.
  2288.     #
  2289.     #  The script is directly based on Gustaf Neumann's perlwafe script.
  2290.     #
  2291.     #  Dov Grobgeld dov@menora.weizmann.ac.il
  2292.     #  1993-05-17
  2293.     #####################################################################
  2294.  
  2295.     $wishbin = "/usr/local/bin/wish";
  2296.  
  2297.     die "socketpair unsuccessful: $!!\n" unless socketpair(W0,WISH,1,1,0);
  2298.     if ($pid=fork) {
  2299.         select(WISH); $| = 1;
  2300.         select(STDOUT);
  2301.  
  2302.     # Create some TCL procedures
  2303.         print WISH 'proc echo {s} {puts stdout $s; flush stdout}',"\n";
  2304.  
  2305.     # Create the widgets
  2306.     print WISH <<TCL;
  2307.     # This is a comment "inside" wish
  2308.  
  2309.     frame .f -relief raised -border 1 -bg green
  2310.     pack append . .f {top fill expand}
  2311.  
  2312.     button .f.button-pressme -text "Press me" -command {
  2313.         echo "That's nice."
  2314.     }
  2315.     button .f.button-quit -text quit -command {
  2316.         echo "quit"
  2317.     }
  2318.     pack append .f .f.button-pressme {top fill expand} \\
  2319.                .f.button-quit {top expand}
  2320.  
  2321. TCL
  2322.     ;
  2323.     # Here is the main loop which receives and sends commands
  2324.     # to wish.
  2325.     while (<WISH>) {
  2326.         chop;
  2327.         print "Wish sais: <$_>\n";
  2328.         if (/^quit/) { print WISH "destroy .\n"; last; }
  2329.     }
  2330.         wait;
  2331.     } elsif (defined $pid) {
  2332.     open(STDOUT, ">&W0");
  2333.     open(STDIN, ">&W0");
  2334.     close(W0);
  2335.     select(STDOUT); $| = 1;
  2336.     exec "$wishbin --";
  2337.     } else {
  2338.     die "fork error: $!\n";
  2339.     }
  2340.  
  2341.  
  2342. 3.10) Can I dynamically load C user routines?
  2343.  
  2344.     Yes -- dynamic loading comes with the distribution.  That means that
  2345.     you no longer need 18 different versions of fooperl floating around.
  2346.     In fact, all of perl can be stuck into a libperl.so library and
  2347.     then your /usr/local/bin/perl binary reduced to just 50k or so.
  2348.     See DynLoader(3pm) for details.
  2349.  
  2350.     In perl4, the answer was kinda.  One package has been released that does
  2351.     this, by Roberto Salama*.  He writes:
  2352.  
  2353.     Here is a version of dylperl, dynamic linker for perl. The code here is
  2354.     based on Oliver Sharp's May 1993 article in Dr. Dobbs Journal (Dynamic
  2355.     Linking under Berkeley UNIX). 
  2356.  
  2357.           dyl.h 
  2358.           dyl.c - code extracted from Oliver Sharp's article
  2359.  
  2360.           hash.h
  2361.           hash.c - Berkeley's hash functions, should use perl's but
  2362.                could not be bothered
  2363.  
  2364.        dylperl.c - perl usersubs
  2365.           user.c - userinit function
  2366.  
  2367.         sample.c - sample code to be dyl'ed
  2368.        sample2.c -          "
  2369.          test.pl - sample perl script that dyl's sample*.o
  2370.  
  2371.     The Makefile assumes that uperl.o is in /usr/local/src/perl/... You
  2372.     will probably have to change this to reflect your installation. Other
  2373.     than that, just type 'make'...
  2374.  
  2375.     The idea behind being able to dynamically link code into perl is that
  2376.     the linked code should become perl functions, i.e. they can be invoked
  2377.     as &foo(...).  For this to happen, the incrementally loaded code must
  2378.     use the perl stack, look at sample.c to get a better idea.
  2379.  
  2380.     The few functions that make up this package are outlined below.
  2381.  
  2382.     &dyl("file.o"): dynamically link file.o. All functions and non-static
  2383.            variables become visible from within perl. This
  2384.            function returns a pointer to an internal hash table
  2385.            corresponding to the symbol table of the newly loaded
  2386.            code.
  2387.  
  2388.            eg: $ht = &dyl("sample.o")
  2389.  
  2390.        This function can also be called with the -L and -l ld options.
  2391.  
  2392.            eg: $ht = &dyl(""sample2.o", "-L/usr/lib", "-lm")
  2393.                will also pick up the math library if sample.o
  2394.                accesses any symbols there.
  2395.  
  2396.     &dyl_find("func"): find symbol 'func' and return its symbol table entry
  2397.  
  2398.     &dyl_functions($ht): print the contents of the internal hash table
  2399.     &dyl_print_symbols($f): prints the contents of the symbol returned by
  2400.     dyl_find() 
  2401.  
  2402.     There is very little documentation, maybe something to do for a future
  2403.     release.  The files sample.o, and sample2.o contain code to be
  2404.     incrementally loaded, test.pl is the test perl script.
  2405.  
  2406.     Comments are welcome. I submit this code for public consumption and,
  2407.     basically, am not responsible for it in any way.
  2408.  
  2409.  
  2410. 3.11) What is undump and where can I get it?
  2411.  
  2412.     The undump program comes from the TeX distribution.  If you have TeX,
  2413.     then you may have a working undump.  If you don't, and you can't get
  2414.     one, *AND* you have a GNU emacs working on your machine that can clone
  2415.     itself, then you might try taking its unexec() function and compiling
  2416.     Perl with -DUNEXEC, which will make Perl call unexec() instead of
  2417.     abort().  You'll have to add unexec.o to the objects line in the
  2418.     Makefile.  If you succeed, post to comp.lang.perl.misc about your
  2419.     experience so others can benefit from it. 
  2420.  
  2421.     If you have a version of undump that works with Perl, please submit
  2422.     its anon-FTP whereabouts to the FAQ maintainer.
  2423.  
  2424.  
  2425. 3.12) How can I get '#!perl' to work under MS-DOS?
  2426.  
  2427.     John Dallman* has written a program "#!perl.exe" which will do this.
  2428.     It is available through anonymous ftp from ftp.ee.umanitoba.ca in the
  2429.     directory /pub/msdos/perl/hbp_30.zip.  This program works by finding
  2430.     the script and perl.exe, building a command line and running perl.exe
  2431.     as a child process.  For more information on this, contact John
  2432.     directly.
  2433.  
  2434. 3.13) Can I write useful perl programs on the command line?
  2435.  
  2436.     Sure, if they're simple enough.  Of course, for most programs,
  2437.     you'll enter them in a file and call perl on them from your
  2438.     shell.  That way you can go into the hack/execute/debug cycle.
  2439.     But there are plenty of useful one-liner: see below.  (Things
  2440.     marked perl5 need to be run from v5.000 or better, but the
  2441.     rest don't care.)
  2442.  
  2443.     # what's octal value of random char (":" in this case)?
  2444.     perl -e 'printf "%#o\n", ord(shift)' ":"
  2445.  
  2446.     # sum first and last fields
  2447.     perl -lane 'print $F[0] + $F[1]'
  2448.  
  2449.     # strip high bits
  2450.     perl -pe 'tr/\200-\377/\000-\177/'
  2451.  
  2452.     # find text files
  2453.     perl -le 'for(@ARGV) {print if -f && -T}' *
  2454.  
  2455.     # trim newsrc
  2456.     perl5 -i.old -pe 's/!.*?(\d+)$/! 1-$1/' ~/.newsrc
  2457.  
  2458.     # cat a dbmfile
  2459.     perl -e 'dbmopen(%f,shift,undef);while(($k,$v)=each%f){print "$k:\
  2460.             $v\n"}' /etc/aliases 
  2461.  
  2462.     # remove comments from C program
  2463.     perl5 -0777 -pe 's{/\*.*?\*/}{}gs' foo.c
  2464.  
  2465.     # make file a month younger than today, defeating reaper daemons
  2466.     perl -e '$X=24*60*60; utime(time(),time() + 30 * $X,@ARGV)' *
  2467.  
  2468.     # find first unused uid
  2469.     perl5 -le '$i++ while getpwuid($i); print $i'
  2470.  
  2471.     # find first unused uid after 100, even with perl4
  2472.     perl -le '$i = 100; $i++ while ($x) = getpwuid($i); print $i'
  2473.  
  2474.     # detect pathetically insecurable systems
  2475.     perl5 -le 'use POSIX; print "INSECURE" unless sysconf(_PC_CHOWN_RESTRICTED)'
  2476.  
  2477.     # display reasonable manpath
  2478.     echo $PATH | perl5 -nl -072 -e '
  2479.     s![^/+]*$!man!&&-d&&!$s{$_}++&&push@m,$_;END{print"@m"}'
  2480.  
  2481.     Ok, the last one was actually an obfuscate perl entry. :-) 
  2482.  
  2483. 3.14) What's a "closure"?
  2484.  
  2485.     (Larry wrote) This is a notion out of the Lisp world that says if you
  2486.     define an anonymous function in a particular lexical context, it
  2487.     pretends to run in that context even when it's called outside of the
  2488.     context.
  2489.  
  2490.     In human terms, it's a funny way of passing arguments to a subroutine
  2491.     when you define it as well as when you call it.  It's useful for
  2492.     setting up little bits of code to run later, such as callbacks.  You
  2493.     can even do object-oriented stuff with it, though Perl provides a
  2494.     different mechanism to do that already.
  2495.  
  2496.     You can also think of it as a way to write a subroutine template without
  2497.     using eval.
  2498.  
  2499.     Here's a small example of how this works:
  2500.  
  2501.     sub newprint {
  2502.         my $x = shift;
  2503.         return sub { my $y = shift; print "$x, $y!\n"; };
  2504.     }
  2505.     $h = newprint("Howdy");
  2506.     $g = newprint("Greetings");
  2507.  
  2508.     # Time passes...
  2509.  
  2510.     &$h("world");
  2511.     &$g("earthlings");
  2512.  
  2513.     This prints:
  2514.  
  2515.     Howdy, world!
  2516.     Greetings, earthlings!
  2517.  
  2518.     Note particularly that $x continues to refer to the value passed into
  2519.     newprint() *despite* the fact that the "my $x" has seemingly gone out
  2520.     of scope by the time the anonymous subroutine runs.  That's what
  2521.     closure is all about.
  2522.  
  2523.     This only applies to lexical variables, by the way.  Dynamic variables
  2524.     continue to work as they have always worked.  Closure is not something
  2525.     that most Perl programmers need trouble themselves about to begin with.
  2526.  
  2527. --
  2528. Stephen P Potter        Pencom Systems Administration              Beaching It 
  2529. spp@psa.pencom.com    Pager: 1-800-759-8888, 547-9561     Work: 703-860-2222
  2530.   Cthulhu for President in '96: When You're Tired of the Lesser of Two Evils
  2531. --
  2532. Stephen P Potter        Pencom Systems Administration              Beaching It 
  2533. spp@psa.pencom.com    Pager: 1-800-759-8888, 547-9561     Work: 703-860-2222
  2534. "I don't care whether people actually like Perl, just so long as they *think*
  2535.     they like it...  ;-)"    -Larry Wall
  2536.  
  2537. Article: 62262 in news.answers
  2538. Path: Dortmund.Germany.EU.net!Germany.EU.net!howland.reston.ans.net!gatech!newsxfer2.itd.umich.edu!newsxfer.itd.umich.edu!news.kreonet.re.kr!usenet.seri.re.kr!news.cais.net!news1.radix.net!news1.radix.net!spp
  2539. From: spp@psa.pencom.com
  2540. Newsgroups: comp.lang.perl.announce,comp.lang.perl.misc,comp.answers,news.answers
  2541. Subject: comp.lang.perl.* FAQ 4/5 - General Programming
  2542. Followup-To: poster
  2543. Date: 27 Jan 1996 04:20:08 GMT
  2544. Organization: Pencom Systems Administration
  2545. Lines: 1465
  2546. Approved: news-answers-request@MIT.EDU
  2547. Distribution: world
  2548. Message-ID: <SPP.96Jan26232008@syrinx.hideout.com>
  2549. NNTP-Posting-Host: dialin23.annex1.radix.net
  2550. Xref: Dortmund.Germany.EU.net comp.lang.perl.announce:238 comp.lang.perl.misc:18652 comp.answers:16586 news.answers:62262
  2551.  
  2552.  
  2553. Archive-name: perl-faq/part4
  2554. Version: $Id: part4,v 2.9 1995/05/15 15:46:10 spp Exp spp $
  2555. Posting-Frequency: bi-weekly
  2556. Last Edited: Thu Jan 11 00:52:25 1996 by spp (Stephen P Potter) on syrinx.psa.com
  2557.  
  2558. This posting contains answers to the following questions about General
  2559. Programming, Regular Expressions (Regexp) and Input/Output:
  2560.  
  2561.  
  2562. 4.1) What are all these $@%*<> signs and how do I know when to use them?
  2563.  
  2564.     Those are type specifiers: 
  2565.     $ for scalar values
  2566.     @ for indexed arrays
  2567.     % for hashed arrays (associative arrays)
  2568.     * for all types of that symbol name.  These are sometimes used like
  2569.         pointers in perl4, but perl5 uses references.
  2570.     <> are used for inputting a record from a filehandle.  
  2571.         \ takes a reference to something.
  2572.  
  2573.     See the question on arrays of arrays for more about Perl pointers.
  2574.  
  2575.     While there are a few places where you don't actually need these type
  2576.     specifiers, except for files, you should always use them.  Note that
  2577.     <FILE> is NOT the type specifier for files; it's the equivalent of awk's
  2578.     getline function, that is, it reads a line from the handle FILE.  When
  2579.     doing open, close, and other operations besides the getline function on
  2580.     files, do NOT use the brackets.
  2581.  
  2582.     Beware of saying:
  2583.     $foo = BAR;
  2584.     Which wil be interpreted as 
  2585.     $foo = 'BAR';
  2586.     and not as 
  2587.     $foo = <BAR>;
  2588.     If you always quote your strings, you'll avoid this trap.
  2589.  
  2590.     Normally, files are manipulated something like this (with appropriate
  2591.     error checking added if it were production code):
  2592.  
  2593.     open (FILE, ">/tmp/foo.$$");
  2594.     print FILE "string\n";
  2595.     close FILE;
  2596.  
  2597.     If instead of a filehandle, you use a normal scalar variable with file
  2598.     manipulation functions, this is considered an indirect reference to a
  2599.     filehandle.  For example,
  2600.  
  2601.     $foo = "TEST01";
  2602.     open($foo, "file");
  2603.  
  2604.     After the open, these two while loops are equivalent:
  2605.  
  2606.     while (<$foo>) {}
  2607.     while (<TEST01>) {}
  2608.  
  2609.     as are these two statements:
  2610.     
  2611.     close $foo;
  2612.     close TEST01;
  2613.  
  2614.     but NOT to this:
  2615.  
  2616.     while (<$TEST01>) {} # error
  2617.         ^
  2618.         ^ note spurious dollar sign
  2619.  
  2620.     This is another common novice mistake; often it's assumed that
  2621.  
  2622.     open($foo, "output.$$");
  2623.  
  2624.     will fill in the value of $foo, which was previously undefined.  This
  2625.     just isn't so -- you must set $foo to be the name of a filehandle
  2626.     before you attempt to open it.   
  2627.  
  2628.     Often people request:
  2629.  
  2630.     : How about changing perl syntax to be more like awk or C?  I $$mean @less
  2631.     : $-signs = <and> &other *special \%characters?
  2632.  
  2633.     Larry's answer is:
  2634.  
  2635.     Then it would be less like the shell.  :-)
  2636.  
  2637.     You'll be pleased to know that I've been trying real hard to get
  2638.     rid of unnecessary punctuation in Perl 5.  You'll be displeased to
  2639.     know that I don't think noun markers like $ and @ unnecessary.
  2640.     Not only do they function like case markers do in human language,
  2641.     but they are automatically distinguished within interpolative
  2642.     contexts, and the user doesn't have to worry about different
  2643.     syntactic treatments for variable references within or without
  2644.     such a context.
  2645.  
  2646.     But the & prefix on verbs is now optional, just as "do" is in
  2647.     English.  I do hope you do understand what I mean.
  2648.  
  2649.     For example, you used to have to write this:
  2650.  
  2651.         &california || &bust;
  2652.  
  2653.     It can now be written more cleanly like this:
  2654.  
  2655.         california or bust;
  2656.  
  2657.     Strictly speaking, of course, $ and @ aren't case markers, but
  2658.     number markers.  English has mandatory number markers, and people
  2659.     get upset when they doesn't agree.
  2660.  
  2661.     It were just convenient in Perl (for the shellish interplative
  2662.     reasons mentioned above) to pull the markers out to the front of
  2663.     each noun phrase.  Most people seems to like it that way.  It
  2664.     certainly seem to make more sense than putting them on the end,
  2665.     like most varieties of BASIC does.
  2666.  
  2667.  
  2668. 4.2) How come Perl operators have different precedence than C operators?
  2669.  
  2670.     Actually, they don't; all C operators have the same precedence in Perl as
  2671.     they do in C.  The problem is with a class of functions called list
  2672.     operators, e.g. print, chdir, exec, system, and so on.  These are somewhat
  2673.     bizarre in that they have different precedence depending on whether you
  2674.     look on the left or right of them.  Basically, they gobble up all things
  2675.     on their right.  For example,
  2676.  
  2677.     unlink $foo, "bar", @names, "others";
  2678.  
  2679.     will unlink all those file names.  A common mistake is to write:
  2680.  
  2681.     unlink "a_file" || die "snafu";
  2682.  
  2683.     The problem is that this gets interpreted as
  2684.  
  2685.     unlink("a_file" || die "snafu");
  2686.  
  2687.     To avoid this problem, you can always make them look like function calls
  2688.     or use an extra level of parentheses:
  2689.  
  2690.     unlink("a_file")  || die "snafu";
  2691.     (unlink "a_file") || die "snafu";
  2692.  
  2693.     In perl5, there are low precedence "and", "or", and "not" operators,
  2694.     which bind less tightly than comma.  This allows you to write:
  2695.  
  2696.     unlink $foo, "bar", @names, "others"     or die "snafu";
  2697.  
  2698.     Sometimes you actually do care about the return value:
  2699.  
  2700.     unless ($io_ok = print("some", "list")) { } 
  2701.  
  2702.     Yes, print() returns I/O success.  That means
  2703.  
  2704.     $io_ok = print(2+4) * 5;
  2705.  
  2706.     returns 5 times whether printing (2+4) succeeded, and 
  2707.     print(2+4) * 5;
  2708.     returns the same 5*io_success value and tosses it.
  2709.  
  2710.     See the perlop(1) man page's section on Precedence for more gory details,
  2711.     and be sure to use the -w flag to catch things like this.
  2712.  
  2713.     One very important thing to be aware of is that if you start thinking
  2714.     of Perl's $, @, %, and & as just flavored versions of C's * operator,
  2715.     you're going to be sorry.  They aren't really operators, per se, and
  2716.     even if you do think of them that way.  In C, if you write
  2717.  
  2718.     *x[i]
  2719.  
  2720.     then the brackets will bind more tightly than the star, yielding
  2721.  
  2722.     *(x[i])
  2723.  
  2724.     But in perl, they DO NOT!  That's because the ${}, @{}, %{}, and &{}
  2725.     notations (and I suppose the *{} one as well for completeness) aren't
  2726.     actually operators.  If they were, you'd be able to write them as *()
  2727.     and that's not feasible.  Instead of operators whose precedence is
  2728.     easily understandable, they are instead figments of yacc's grammar.
  2729.     This means that:
  2730.  
  2731.     $$x[$i]
  2732.  
  2733.     is really
  2734.  
  2735.     {$$x}[$i]
  2736.  
  2737.     (by which I actually mean)
  2738.  
  2739.     ${$x}[$i]
  2740.  
  2741.     and not
  2742.  
  2743.     ${$x[$i]}
  2744.  
  2745.     See the difference?  If not, check out perlref(1) for gory details.
  2746.  
  2747.  
  2748. 4.3) What's the difference between dynamic and static (lexical) scoping?
  2749.      What are my() and local()?
  2750.  
  2751.     [NOTE: This question refers to perl5 only.  There is no my() in perl4]
  2752.     Scoping refers to visibility of variables.  A dynamic variable is
  2753.     created via local() and is just a local value for a global variable,
  2754.     whereas a lexical variable created via my() is more what you're
  2755.     expecting from a C auto.  (See also "What's the difference between
  2756.     deep and shallow binding.")  In general, we suggest you use lexical
  2757.     variables wherever possible, as they're faster to access and easier to
  2758.     understand.   The "use strict vars" pragma will enforce that all
  2759.     variables are either lexical, or full classified by package name.  We
  2760.     strongly suggest that you develop your code with "use strict;" and the
  2761.     -w flag.  (When using formats, however, you will still have to use
  2762.     dynamic variables.)  Here's an example of the difference:
  2763.  
  2764.         #!/usr/local/bin/perl
  2765.         $myvar = 10;
  2766.         $localvar = 10;
  2767.  
  2768.         print "Before the sub call - my: $myvar, local: $localvar\n";
  2769.         &sub1();
  2770.  
  2771.         print "After the sub call - my: $myvar, local: $localvar\n";
  2772.  
  2773.         exit(0);
  2774.  
  2775.         sub sub1 {
  2776.             my $myvar;
  2777.             local $localvar;
  2778.  
  2779.             $myvar = 5;     # Only in this block
  2780.             $localvar = 20; # Accessible to children
  2781.  
  2782.             print "Inside first sub call - my: $myvar, local: $localvar\n";
  2783.  
  2784.             &sub2();
  2785.         }
  2786.  
  2787.         sub sub2 {
  2788.             print "Inside second sub - my: $myvar, local: $localvar\n";
  2789.         }
  2790.  
  2791.     Notice that the variables declared with my() are visible only within
  2792.     the scope of the block which names them.  They are not visible outside
  2793.     of this block, not even in routines or blocks that it calls.  local() 
  2794.     variables, on the other hand, are visible to routines that are called
  2795.     from the block where they are declared.  Neither is visible after the
  2796.     end (the final closing curly brace) of the block at all.
  2797.  
  2798.     Oh, lexical variables are only available in perl5.  Have we mentioned
  2799.     yet that you might consider upgrading? :-) 
  2800.  
  2801.  
  2802. 4.4) What's the difference between deep and shallow binding?
  2803.  
  2804.     5.000 answer:
  2805.  
  2806.     This only matters when you're making subroutines yourself, at least
  2807.     so far.   This will give you shallow binding:
  2808.  
  2809.     {
  2810.           my $x = time;
  2811.           $coderef = sub { $x };
  2812.         }
  2813.  
  2814.     When you call &$coderef(), it will get whatever dynamic $x happens
  2815.     to be around when invoked.  However, you can get the other behaviour
  2816.     this way:
  2817.  
  2818.     {
  2819.           my $x = time;
  2820.           $coderef = eval "sub { \$x }";
  2821.         }
  2822.  
  2823.     Now you'll access the lexical variable $x which is set to the
  2824.     time the subroutine was created.  Note that the difference in these
  2825.     two behaviours can be considered a bug, not a feature, so you should
  2826.     in particular not rely upon shallow binding, as it will likely go
  2827.     away in the future.  See perlref(1).
  2828.  
  2829.     5.001 Answer:
  2830.  
  2831.     Perl will always give deep binding to functions, so you don't need the
  2832.     eval hack anymore.   Furthermore,  functions and even formats
  2833.     lexically declared nested within another lexical scope have access to
  2834.     that scope.
  2835.  
  2836.     require 5.001;
  2837.  
  2838.     sub mkcounter {
  2839.         my $start = shift;
  2840.         return sub {
  2841.         return ++$start;
  2842.         } 
  2843.     } 
  2844.     $f1 = mkcounter(10);
  2845.     $f2 = mkcounter(20);
  2846.     print &$f1(), &$f2(); 
  2847.     11 21
  2848.     print &$f1(), &$f2(), &$f1();
  2849.     12 22 13
  2850.  
  2851.     See the question on "What's a closure?"
  2852.  
  2853.  
  2854. 4.5) How can I manipulate fixed-record-length files?
  2855.  
  2856.     The most efficient way is using pack and unpack.  This is faster than
  2857.     using substr.  Here is a sample chunk of code to break up and put back
  2858.     together again some fixed-format input lines, in this case, from ps.
  2859.  
  2860.     # sample input line:
  2861.     #   15158 p5  T      0:00 perl /mnt/tchrist/scripts/now-what
  2862.     $ps_t = 'A6 A4 A7 A5 A*';
  2863.     open(PS, "ps|");
  2864.     $_ = <PS>; print;
  2865.     while (<PS>) {
  2866.         ($pid, $tt, $stat, $time, $command) = unpack($ps_t, $_);
  2867.         for $var ('pid', 'tt', 'stat', 'time', 'command' ) {
  2868.         print "$var: <", eval "\$$var", ">\n";
  2869.         }
  2870.         print 'line=', pack($ps_t, $pid, $tt, $stat, $time, $command),  "\n";
  2871.     }
  2872.  
  2873.  
  2874. 4.6) How can I make a file handle local to a subroutine?
  2875.  
  2876.     You must use the type-globbing *VAR notation.  Here is some code to
  2877.     cat an include file, calling itself recursively on nested local
  2878.     include files (i.e. those with #include "file", not #include <file>):
  2879.  
  2880.     sub cat_include {
  2881.         local($name) = @_;
  2882.         local(*FILE);
  2883.         local($_);
  2884.  
  2885.         warn "<INCLUDING $name>\n";
  2886.         if (!open (FILE, $name)) {
  2887.         warn "can't open $name: $!\n";
  2888.         return;
  2889.         }
  2890.         while (<FILE>) {
  2891.         if (/^#\s*include "([^"]*)"/) {
  2892.             &cat_include($1);
  2893.         } else {
  2894.             print;
  2895.         }
  2896.         }
  2897.         close FILE;
  2898.     }
  2899.  
  2900.  
  2901. 4.7) How can I call alarm() or usleep() from Perl?
  2902.  
  2903.     If you want finer granularity than 1 second (as usleep() provides) and
  2904.     have itimers and syscall() on your system, you can use the following.
  2905.     You could also use select().
  2906.  
  2907.     It takes a floating-point number representing how long to delay until
  2908.     you get the SIGALRM, and returns a floating- point number representing
  2909.     how much time was left in the old timer, if any.  Note that the C
  2910.     function uses integers, but this one doesn't mind fractional numbers.
  2911.  
  2912.     # alarm; send me a SIGALRM in this many seconds (fractions ok)
  2913.     # tom christiansen <tchrist@convex.com>
  2914.     sub alarm {
  2915.     require 'syscall.ph';
  2916.     require 'sys/time.ph';
  2917.  
  2918.     local($ticks) = @_;
  2919.     local($in_timer,$out_timer);
  2920.     local($isecs, $iusecs, $secs, $usecs);
  2921.  
  2922.     local($itimer_t) = 'L4'; # should be &itimer'typedef()
  2923.  
  2924.     $secs = int($ticks);
  2925.     $usecs = ($ticks - $secs) * 1e6;
  2926.  
  2927.     $out_timer = pack($itimer_t,0,0,0,0);  
  2928.     $in_timer  = pack($itimer_t,0,0,$secs,$usecs);
  2929.  
  2930.     syscall(&SYS_setitimer, &ITIMER_REAL, $in_timer, $out_timer)
  2931.         && die "alarm: setitimer syscall failed: $!";
  2932.  
  2933.     ($isecs, $iusecs, $secs, $usecs) = unpack($itimer_t,$out_timer);
  2934.     return $secs + ($usecs/1e6);
  2935.     }
  2936.  
  2937.  
  2938. 4.8) How can I do an atexit() or setjmp()/longjmp() in Perl?  (Exception handling)
  2939.  
  2940.     Perl's exception-handling mechanism is its eval operator.  You 
  2941.     can use eval as setjmp and die as longjmp.  Here's an example
  2942.     of Larry's for timed-out input, which in C is often implemented
  2943.     using setjmp and longjmp:
  2944.  
  2945.       $SIG{ALRM} = TIMEOUT;
  2946.       sub TIMEOUT { die "restart input\n" }
  2947.  
  2948.       do { eval { &realcode } } while $@ =~ /^restart input/;
  2949.  
  2950.       sub realcode {
  2951.           alarm 15;
  2952.           $ans = <STDIN>;
  2953.           alarm 0;
  2954.       }
  2955.  
  2956.    Here's an example of Tom's for doing atexit() handling:
  2957.  
  2958.     sub atexit { push(@_exit_subs, @_) }
  2959.  
  2960.     sub _cleanup { unlink $tmp }
  2961.  
  2962.     &atexit('_cleanup');
  2963.  
  2964.     eval <<'End_Of_Eval';  $here = __LINE__;
  2965.     # as much code here as you want
  2966.     End_Of_Eval
  2967.  
  2968.     $oops = $@;  # save error message
  2969.  
  2970.     # now call his stuff
  2971.     for (@_exit_subs) { &$_() }
  2972.  
  2973.     $oops && ($oops =~ s/\(eval\) line (\d+)/$0 .
  2974.         " line " . ($1+$here)/e, die $oops);
  2975.  
  2976.     You can register your own routines via the &atexit function now.  You
  2977.     might also want to use the &realcode method of Larry's rather than
  2978.     embedding all your code in the here-is document.  Make sure to leave
  2979.     via die rather than exit, or write your own &exit routine and call
  2980.     that instead.   In general, it's better for nested routines to exit
  2981.     via die rather than exit for just this reason.
  2982.  
  2983.     In Perl5, it is easy to set this up because of the automatic processing
  2984.     of per-package END functions.  These work much like they would in awk.
  2985.     See perlfunc(1), perlmod(1) and perlrun(1).
  2986.  
  2987.     Eval is also quite useful for testing for system dependent features,
  2988.     like symlinks, or using a user-input regexp that might otherwise
  2989.     blowup on you.
  2990.  
  2991.  
  2992. 4.9) How do I catch signals in perl?
  2993.  
  2994.     Perl allows you to trap signals using the %SIG associative array.
  2995.     Using the signals you want to trap as the key, you can assign a
  2996.     subroutine to that signal.  The %SIG array will only contain those
  2997.     values which the programmer defines.  Therefore, you do not have to
  2998.     assign all signals.  For example, to exit cleanly from a ^C:
  2999.  
  3000.     $SIG{'INT'} = 'CLEANUP';
  3001.     sub CLEANUP {
  3002.         print "\n\nCaught Interrupt (^C), Aborting\n";
  3003.         exit(1);
  3004.     }
  3005.  
  3006.     There are two special "routines" for signals called DEFAULT and IGNORE.
  3007.     DEFAULT erases the current assignment, restoring the default value of
  3008.     the signal.  IGNORE causes the signal to be ignored.  In general, you
  3009.     don't need to remember these as you can emulate their functionality
  3010.     with standard programming features.  DEFAULT can be emulated by
  3011.     deleting the signal from the array and IGNORE can be emulated by any
  3012.     undeclared subroutine.
  3013.  
  3014.     In 5.001, the $SIG{__WARN__} and $SIG{__DIE__} handlers may be used to
  3015.     intercept die() and warn().  For example, here's how you could promote
  3016.     unitialized variables to trigger a fatal rather merely complaining:
  3017.  
  3018.     #!/usr/bin/perl -w 
  3019.     require 5.001;
  3020.     $SIG{__WARN__} = sub {
  3021.         if ($_[0] =~ /uninit/) {
  3022.         die $@;
  3023.         } else {
  3024.         warn $@;
  3025.         } 
  3026.     };
  3027.  
  3028.  
  3029. 4.10) Why doesn't Perl interpret my octal data octally?
  3030.  
  3031.     Perl only understands octal and hex numbers as such when they occur
  3032.     as literals in your program.  If they are read in from somewhere and
  3033.     assigned, then no automatic conversion takes place.  You must
  3034.     explicitly use oct() or hex() if you want this kind of thing to happen. 
  3035.     Actually, oct() knows to interpret both hex and octal numbers, while
  3036.     hex only converts hexadecimal ones.  For example:
  3037.  
  3038.     {
  3039.         print "What mode would you like? ";
  3040.         $mode = <STDIN>;
  3041.         $mode = oct($mode);
  3042.         unless ($mode) {
  3043.         print "You can't really want mode 0!\n";
  3044.         redo;
  3045.         } 
  3046.         chmod $mode, $file;
  3047.     } 
  3048.  
  3049.     Without the octal conversion, a requested mode of 755 would turn 
  3050.     into 01363, yielding bizarre file permissions of --wxrw--wt.
  3051.  
  3052.     If you want something that handles decimal, octal and hex input, 
  3053.     you could follow the suggestion in the man page and use:
  3054.  
  3055.     $val = oct($val) if $val =~ /^0/;
  3056.  
  3057.  
  3058. 4.11) How can I compare two date strings?
  3059.  
  3060.     If the dates are in an easily parsed, predetermined format, then you
  3061.     can break them up into their component parts and call &timelocal from
  3062.     the distributed perl library.  If the date strings are in arbitrary
  3063.     formats, however, it's probably easier to use the getdate program from
  3064.     the Cnews distribution, since it accepts a wide variety of dates.  Note
  3065.     that in either case the return values you will really be comparing will
  3066.     be the total time in seconds as returned by time(). 
  3067.    
  3068.     Here's a getdate function for perl that's not very efficient; you can
  3069.     do better than this by sending it many dates at once or modifying
  3070.     getdate to behave better on a pipe.  Beware the hardcoded pathname. 
  3071.  
  3072.     sub getdate {
  3073.         local($_) = shift;
  3074.  
  3075.         s/-(\d{4})$/+$1/ || s/\+(\d{4})$/-$1/; 
  3076.         # getdate has broken timezone sign reversal!
  3077.  
  3078.         $_ = `/usr/local/lib/news/newsbin/getdate '$_'`;
  3079.         chop;
  3080.         $_;
  3081.     } 
  3082.  
  3083.     You can also get the  GetDate extension module that's actually the C
  3084.     code linked into perl from wherever fine Perl extensions are given
  3085.     away.  It's about 50x faster.  If you can't find it elsewhere, I
  3086.     usually keep a copy on perl.com for ftp, since I (Tom) ported it.
  3087.  
  3088.     Richard Ohnemus <Rick_Ohnemus@Sterling.COM> actually has a getdate.y for
  3089.     use with the Perl yacc (see question 3.3 "Is there a yacc for Perl?").  
  3090.  
  3091.     You might also consider using these: 
  3092.  
  3093.     date.pl        - print dates how you want with the sysv +FORMAT method 
  3094.     date.shar      - routines to manipulate and calculate dates
  3095.     ftp-chat2.shar - updated version of ftpget. includes library and demo 
  3096.              programs 
  3097.     getdate.shar   - returns number of seconds since epoch for any given
  3098.              date 
  3099.     ptime.shar     - print dates how you want with the sysv +FORMAT method 
  3100.  
  3101.     You probably want 'getdate.shar'... these and other files can be ftp'd
  3102.     from the /pub/perl/scripts directory on ftp.cis.ufl.edu. See the README
  3103.     file in the /pub/perl directory for time and the European mirror site
  3104.     details. 
  3105.  
  3106.  
  3107. 4.12) How can I find the Julian Day?
  3108.  
  3109.     Here's an example of a Julian Date function provided by Thomas R.
  3110.     Kimpton*.
  3111.  
  3112.     #!/usr/local/bin/perl
  3113.  
  3114.     @theJulianDate = ( 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 );
  3115.  
  3116.     #************************************************************************
  3117.     #****   Return 1 if we are after the leap day in a leap year.       *****
  3118.     #************************************************************************
  3119.                    
  3120.     sub leapDay             
  3121.     {                 
  3122.         my($year,$month,$day) = @_;
  3123.     
  3124.         if (year % 4) {
  3125.         return(0);
  3126.         }
  3127.  
  3128.         if (!(year % 100)) {             # years that are multiples of 100
  3129.                                      # are not leap years
  3130.         if (year % 400) {            # unless they are multiples of 400
  3131.             return(0);
  3132.         }
  3133.         }
  3134.         if (month < 2) {
  3135.             return(0);
  3136.         } elsif ((month == 2) && (day < 29)) {
  3137.         return(0);
  3138.         } else {
  3139.         return(1);
  3140.         }
  3141.     }
  3142.     
  3143.     #************************************************************************
  3144.     #****   Pass in the date, in seconds, of the day you want the       *****
  3145.     #****   julian date for.  If your localtime() returns the year day  *****
  3146.     #****   return that, otherwise figure out the julian date.          *****
  3147.     #************************************************************************
  3148.         
  3149.     sub julianDate    
  3150.     {        
  3151.         my($dateInSeconds) = @_;
  3152.         my($sec, $min, $hour, $mday, $mon, $year, $wday, $yday);
  3153.     
  3154.         ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) =
  3155.         localtime($dateInSeconds);
  3156.         if (defined($yday)) {
  3157.         return($yday+1);
  3158.         } else {
  3159.         return($theJulianDate[$mon] + $mday + &leapDay($year,$mon,$mday));
  3160.         }
  3161.     
  3162.     }
  3163.  
  3164.     print "Today's julian date is: ",&julianDate(time),"\n";
  3165.  
  3166.  
  3167. 4.13) Does perl have a round function?  What about ceil() and floor()?
  3168.  
  3169.     Perl does not have an explicit round function.  However, it is very
  3170.     simple to create a rounding function.  Since the int() function simply
  3171.     removes the decimal value and returns the integer portion of a number,
  3172.     you can use 
  3173.  
  3174.         sub round {
  3175.             my($number) = shift;
  3176.  
  3177.             return int($number + .5);
  3178.         }
  3179.  
  3180.     If you examine what this function is doing, you will see that any
  3181.     number greater than .5 will be increased to the next highest integer,
  3182.     and any number less than .5 will remain the current integer, which has
  3183.     the same effect as rounding.
  3184.  
  3185.     A slightly better solution, one which handles negative numbers as well,
  3186.     might be to change the return (above) to:
  3187.  
  3188.         return int($number + .5 * ($number <=> 0));
  3189.  
  3190.     which will modify the .5 to be either positive or negative, based on
  3191.     the number passed into it.
  3192.  
  3193.     If you wish to round to a specific significant digit, you can use the
  3194.     printf function (or sprintf, depending upon the situation), which does
  3195.     proper rounding automatically.  See the perlfunc man page for more
  3196.     information on the (s)printf function.
  3197.  
  3198.     Version 5 includes a POSIX module which defines the standard C math
  3199.     library functions, including floor() and ceil().  floor($num) returns
  3200.     the largest integer not greater than $num, while ceil($num) returns the
  3201.     smallest integer not less than $num.  For example:
  3202.  
  3203.         #!/usr/local/bin/perl
  3204.         use POSIX qw(ceil floor);
  3205.  
  3206.         $num = 42.4;  # The Answer to the Great Question (on a Pentium)!
  3207.  
  3208.         print "Floor returns: ", floor($num), "\n";
  3209.         print "Ceil returns:  ", ceil($num), "\n";
  3210.  
  3211.     Which prints:
  3212.  
  3213.         Floor returns: 42
  3214.         Ceil returns:  43
  3215.  
  3216.  
  3217. 4.14) What's the fastest way to code up a given task in perl?
  3218.  
  3219.     Post it to comp.lang.perl.misc and ask Tom or Randal a question about
  3220.     it.  ;) 
  3221.  
  3222.     Because Perl so lends itself to a variety of different approaches for
  3223.     any given task, a common question is which is the fastest way to code a
  3224.     given task.  Since some approaches can be dramatically more efficient
  3225.     that others, it's sometimes worth knowing which is best.
  3226.     Unfortunately, the implementation that first comes to mind, perhaps as
  3227.     a direct translation from C or the shell, often yields suboptimal
  3228.     performance.  Not all approaches have the same results across different
  3229.     hardware and software platforms.  Furthermore, legibility must
  3230.     sometimes be sacrificed for speed. 
  3231.  
  3232.     While an experienced perl programmer can sometimes eye-ball the code
  3233.     and make an educated guess regarding which way would be fastest,
  3234.     surprises can still occur.  So, in the spirit of perl programming
  3235.     being an empirical science, the best way to find out which of several
  3236.     different methods runs the fastest is simply to code them all up and
  3237.     time them. For example:
  3238.  
  3239.     $COUNT = 10_000; $| = 1;
  3240.  
  3241.     print "method 1: ";
  3242.  
  3243.         ($u, $s) = times;
  3244.         for ($i = 0; $i < $COUNT; $i++) {
  3245.         # code for method 1
  3246.         }
  3247.         ($nu, $ns) = times;
  3248.         printf "%8.4fu %8.4fs\n", ($nu - $u), ($ns - $s);
  3249.  
  3250.     print "method 2: ";
  3251.  
  3252.         ($u, $s) = times;
  3253.         for ($i = 0; $i < $COUNT; $i++) {
  3254.         # code for method 2
  3255.         }
  3256.         ($nu, $ns) = times;
  3257.         printf "%8.4fu %8.4fs\n", ($nu - $u), ($ns - $s);
  3258.  
  3259.     Perl5 includes a new module called Benchmark.pm.  You can now simplify
  3260.     the code to use the Benchmarking, like so:
  3261.  
  3262.         use Benchmark;
  3263.  
  3264.             timethese($count, {
  3265.                 Name1 => '...code for method 1...',
  3266.                 Name2 => '...code for method 2...',
  3267.                 ... });
  3268.  
  3269.     It will output something that looks similar to this:
  3270.  
  3271.         Benchmark: timing 100 iterations of Name1, Name2...
  3272.                 Name1:  2 secs (0.50 usr 0.00 sys = 0.50 cpu)
  3273.                 Name2:  1 secs (0.48 usr 0.00 sys = 0.48 cpu)
  3274.  
  3275.  
  3276.     For example, the following code will show the time difference between
  3277.     three different ways of assigning the first character of a string to
  3278.     a variable:
  3279.  
  3280.     use Benchmark;
  3281.     timethese(100000, {
  3282.         'regex1' => '$str="ABCD"; $str =~ s/^(.)//; $ch = $1',
  3283.         'regex2' => '$str="ABCD"; $str =~ s/^.//; $ch = $&',
  3284.         'substr' => '$str="ABCD"; $ch=substr($str,0,1); substr($str,0,1)="",
  3285.     });
  3286.  
  3287.     The results will be returned like this:
  3288.  
  3289.     Benchmark: timing 100000 iterations of regex1, regex2, substr...
  3290.        regex1: 11 secs (10.80 usr   0.00 sys =  10.80 cpu)
  3291.        regex2: 10 secs (10.23 usr   0.00 sys =  10.23 cpu)
  3292.        substr:  7 secs ( 5.62 usr    0.00 sys =   5.62 cpu)
  3293.  
  3294.     For more specific tips, see the section on Efficiency in the
  3295.     ``Other Oddments'' chapter at the end of the Camel Book.
  3296.  
  3297.  
  3298. 4.15) Do I always/never have to quote my strings or use semicolons?
  3299.  
  3300.     You don't have to quote strings that can't mean anything else in the
  3301.     language, like identifiers with any upper-case letters in them.
  3302.     Therefore, it's fine to do this: 
  3303.  
  3304.     $SIG{INT} = Timeout_Routine;
  3305.     or 
  3306.  
  3307.     @Days = (Sun, Mon, Tue, Wed, Thu, Fri, Sat, Sun);
  3308.  
  3309.     but you can't get away with this:
  3310.  
  3311.     $foo{while} = until;
  3312.  
  3313.     in place of 
  3314.  
  3315.     $foo{'while'} = 'until';
  3316.  
  3317.     The requirements on semicolons have been increasingly relaxed.  You no 
  3318.     longer need one at the end of a block, but stylistically, you're better
  3319.     to use them if you don't put the curly brace on the same line: 
  3320.  
  3321.     for (1..10) { print }
  3322.  
  3323.     is ok, as is
  3324.  
  3325.     @nlist = sort { $a <=> $b } @olist;
  3326.  
  3327.     but you probably shouldn't do this:
  3328.     
  3329.     for ($i = 0; $i < @a; $i++) {
  3330.         print "i is $i\n"  # <-- oops!
  3331.     } 
  3332.  
  3333.     because you might want to add lines later, and anyway, it looks
  3334.     funny. :-) 
  3335.  
  3336.     Actually, I lied.  As of 5.001, there are two autoquoting contexts:
  3337.  
  3338.     This            is like this
  3339.     ------------            ---------------
  3340.     $foo{line}        $foo{"line"}
  3341.     bar => stuff        "bar" => stuff
  3342.  
  3343.  
  3344. 4.16) What is variable suicide and how can I prevent it?
  3345.  
  3346.     Variable suicide is a nasty side effect of dynamic scoping and the way
  3347.     variables are passed by reference.  If you say 
  3348.  
  3349.     $x = 17;
  3350.     &munge($x);
  3351.     sub munge {
  3352.         local($x);
  3353.         local($myvar) = $_[0];
  3354.         ...
  3355.     } 
  3356.  
  3357.     Then you have just clobbered $_[0]!  Why this is occurring is pretty
  3358.     heavy wizardry: the reference to $x stored in $_[0] was temporarily
  3359.     occluded by the previous local($x) statement (which, you're recall,
  3360.     occurs at run-time, not compile-time).  The work around is simple,
  3361.     however: declare your formal parameters first:
  3362.  
  3363.     sub munge {
  3364.         local($myvar) = $_[0];
  3365.         local($x);
  3366.         ...
  3367.     }
  3368.  
  3369.     That doesn't help you if you're going to be trying to access @_
  3370.     directly after the local()s.  In this case, careful use of the package
  3371.     facility is your only recourse. 
  3372.  
  3373.     Another manifestation of this problem occurs due to the magical nature
  3374.     of the index variable in a foreach() loop. 
  3375.  
  3376.     @num = 0 .. 4;
  3377.     print "num begin  @num\n";
  3378.     foreach $m (@num) { &ug }
  3379.     print "num finish @num\n";
  3380.     sub ug {
  3381.         local($m) = 42;
  3382.         print "m=$m  $num[0],$num[1],$num[2],$num[3]\n";
  3383.     }
  3384.     
  3385.     Which prints out the mysterious:
  3386.  
  3387.     num begin  0 1 2 3 4
  3388.     m=42  42,1,2,3
  3389.     m=42  0,42,2,3
  3390.     m=42  0,1,42,3
  3391.     m=42  0,1,2,42
  3392.     m=42  0,1,2,3
  3393.     num finish 0 1 2 3 4
  3394.  
  3395.     What's happening here is that $m is an alias for each element of @num.
  3396.     Inside &ug, you temporarily change $m.  Well, that means that you've
  3397.     also temporarily changed whatever $m is an alias to!!  The only
  3398.     workaround is to be careful with global variables, using packages,
  3399.     and/or just be aware of this potential in foreach() loops. 
  3400.  
  3401.     The perl5 static autos via "my" do not exhibit this problem.
  3402.  
  3403.  
  3404. 4.17) What does "Malformed command links" mean?
  3405.  
  3406.     This is a bug in 4.035.  While in general it's merely a cosmetic
  3407.     problem, it often comanifests with a highly undesirable coredumping 
  3408.     problem.  Programs known to be affected by the fatal coredump include
  3409.     plum and pcops.  This bug has been fixed since 4.036.  It did not
  3410.     resurface in 5.001.
  3411.  
  3412.  
  3413. 4.18) How can I set up a footer format to be used with write()?
  3414.  
  3415.     While the $^ variable contains the name of the current header format,
  3416.     there is no corresponding mechanism to automatically do the same thing
  3417.     for a footer.  Not knowing how big a format is going to be until you
  3418.     evaluate it is one of the major problems.
  3419.  
  3420.     If you have a fixed-size footer, you can get footers by checking for
  3421.     line left on page ($-) before each write, and printing the footer
  3422.     yourself if necessary.
  3423.  
  3424.     Another strategy is to open a pipe to yourself, using open(KID, "|-")
  3425.     and always write()ing to the KID, who then postprocesses its STDIN to
  3426.     rearrange headers and footers however you like.  Not very convenient,
  3427.     but doable.
  3428.  
  3429.     See the perlform(1) man page for other tricks.
  3430.  
  3431.  
  3432. 4.19) Why does my Perl program keep growing in size?
  3433.  
  3434.     This is caused by a strange occurrence that Larry has dubbed "feeping
  3435.     creaturism".  Larry is always adding one more feature, always getting
  3436.     Perl to handle one more problem.  Hence, it keeps growing.  Once you've
  3437.     worked with perl long enough, you will probably start to do the same
  3438.     thing.  You will then notice this problem as you see your scripts
  3439.     becoming larger and larger.
  3440.  
  3441.     Oh, wait... you meant a currently running program and its stack size.
  3442.     Mea culpa, I misunderstood you.  ;)  While there may be a real memory
  3443.     leak in the Perl source code or even whichever malloc() you're using,
  3444.     common causes are incomplete eval()s or local()s in loops.
  3445.  
  3446.     An eval() which terminates in error due to a failed parsing will leave
  3447.     a bit of memory unusable. 
  3448.  
  3449.     A local() inside a loop:
  3450.  
  3451.     for (1..100) {
  3452.         local(@array);
  3453.     } 
  3454.  
  3455.     will build up 100 versions of @array before the loop is done.  The
  3456.     work-around is:   
  3457.  
  3458.     local(@array);
  3459.     for (1..100) {
  3460.         undef @array;
  3461.     } 
  3462.  
  3463.     This local array behaviour has been fixed for perl5, but a failed
  3464.     eval() still leaks.
  3465.  
  3466.     One other possibility, due to the way reference counting works, is
  3467.     when you've introduced a circularity in a data structure that would
  3468.     normally go out of scope and be unreachable.  For example:
  3469.  
  3470.     sub oops {
  3471.         my $x;
  3472.         $x = \$x;
  3473.     } 
  3474.  
  3475.     When $x goes out of scope, the memory can't be reclaimed, because
  3476.     there's still something point to $x (itself, in this case).  A 
  3477.     full garbage collection system could solve this, but at the cost
  3478.     of a great deal of complexity in perl itself and some inevitable
  3479.     performance problems as well.  If you're making a circular data
  3480.     structure that you want freed eventually, you'll have to break the
  3481.     self-reference links yourself.
  3482.  
  3483.  
  3484. 4.20) Can I do RPC in Perl?
  3485.  
  3486.     Yes, you can, since Perl has access to sockets.  An example of the rup
  3487.     program written in Perl can be found in the script ruptime.pl at the
  3488.     scripts archive on ftp.cis.ufl.edu.  I warn you, however, that it's not
  3489.     a pretty sight, as it's used nothing from h2ph or c2ph, so everything is
  3490.     utterly hard-wired. 
  3491.  
  3492.  
  3493. 4.21) Why doesn't my sockets program work under System V (Solaris)?  What
  3494.     does the error message "Protocol not supported" mean?
  3495.  
  3496.     Some System V based systems, notably Solaris 2.X, redefined some of the
  3497.     standard socket constants.  Since these were constant across all
  3498.     architectures, they were often hardwired into the perl code.  The
  3499.     "proper" way to deal with this is to make sure that you run h2ph
  3500.     against sys/socket.h, require that file and use the symbolic names
  3501.     (SOCK_STREAM, SOCK_DGRAM, SOCK_RAW, SOCK_RDM, and SOCK_SEQPACKET).
  3502.  
  3503.     Note that even though SunOS 4 and SunOS 5 are binary compatible, these
  3504.     values are different, and require a different socket.ph for each OS.
  3505.  
  3506.     Under version 5, you can also "use Socket" to get the proper values.
  3507.  
  3508.  
  3509. 4.22) How can I quote a variable to use in a regexp?
  3510.  
  3511.     From the manual:
  3512.  
  3513.     $pattern =~ s/(\W)/\\$1/g;
  3514.  
  3515.     Now you can freely use /$pattern/ without fear of any unexpected meta-
  3516.     characters in it throwing off the search.  If you don't know whether a
  3517.     pattern is valid or not, enclose it in an eval to avoid a fatal run-
  3518.     time error.  
  3519.  
  3520.     Perl5 provides a vastly improved way of doing this.  Simply use the
  3521.     new quotemeta character (\Q) within your variable.
  3522.  
  3523. 4.23) How can I change the first N letters of a string?
  3524.  
  3525.     Remember that the substr() function produces an lvalue, that is, it may
  3526.     be assigned to.  Therefore, to change the first character to an S, you
  3527.     could do this:
  3528.     
  3529.     substr($var,0,1) = 'S';
  3530.  
  3531.     This assumes that $[ is 0;  for a library routine where you can't know
  3532.     $[, you should use this instead:
  3533.  
  3534.     substr($var,$[,1) = 'S';
  3535.  
  3536.     While it would be slower, you could in this case use a substitute:
  3537.  
  3538.     $var =~ s/^./S/;
  3539.     
  3540.     But this won't work if the string is empty or its first character is a
  3541.     newline, which "." will never match.  So you could use this instead:
  3542.  
  3543.     $var =~ s/^[^\0]?/S/;
  3544.  
  3545.     To do things like translation of the first part of a string, use
  3546.     substr, as in:
  3547.  
  3548.     substr($var, $[, 10) =~ tr/a-z/A-Z/;
  3549.  
  3550.     If you don't know the length of what to translate, something like this
  3551.     works: 
  3552.  
  3553.     /^(\S+)/ && substr($_,$[,length($1)) =~ tr/a-z/A-Z/;
  3554.     
  3555.     For some things it's convenient to use the /e switch of the substitute
  3556.     operator: 
  3557.  
  3558.     s/^(\S+)/($tmp = $1) =~ tr#a-z#A-Z#, $tmp/e
  3559.  
  3560.     although in this case, it runs more slowly than does the previous
  3561.     example. 
  3562.  
  3563.  
  3564. 4.24) How can I count the number of occurrences of a substring within a
  3565.     string? 
  3566.  
  3567.     If you want a count of a certain character (X) within a string, you can
  3568.     use the tr/// function like so:
  3569.  
  3570.     $string="ThisXlineXhasXsomeXx'sXinXit":
  3571.     $count = ($string =~ tr/X//);
  3572.     print "There are $count Xs in the string";
  3573.  
  3574.     This is fine if you are just looking for a single character.  However,
  3575.     if you are trying to count multiple character substrings within a
  3576.     larger string, tr/// won't work.  What you can do is wrap a while loop
  3577.     around a pattern match.
  3578.  
  3579.     $string="-9 55 48 -2 23 -76 4 14 -44";
  3580.     $count++ while $string =~ /-\d+/g;
  3581.     print "There are $count negative numbers in the string";
  3582.  
  3583.  
  3584. 4.25) Can I use Perl regular expressions to match balanced text?
  3585.  
  3586.     No, or at least, not by themselves.
  3587.  
  3588.     Regexps just aren't powerful enough.  Although Perl's patterns aren't
  3589.     strictly regular because they do backreferencing (the \1 notation), you
  3590.     still can't do it.  You need to employ auxiliary logic.  A simple
  3591.     approach would involve keeping a bit of state around, something 
  3592.     vaguely like this (although we don't handle patterns on the same line):
  3593.  
  3594.     while(<>) {
  3595.         if (/pat1/) {
  3596.         if ($inpat++ > 0) { warn "already saw pat1" } 
  3597.         redo;
  3598.         } 
  3599.         if (/pat2/) {
  3600.         if (--$inpat < 0) { warn "never saw pat1" } 
  3601.         redo;
  3602.         } 
  3603.     }
  3604.  
  3605.     A rather more elaborate subroutine to pull out balanced and possibly
  3606.     nested single chars, like ` and ', { and }, or ( and ) can be found
  3607.     on convex.com in /pub/perl/scripts/pull_quotes.
  3608.  
  3609.  
  3610. 4.26) What does it mean that regexps are greedy?  How can I get around it?
  3611.  
  3612.     The basic idea behind regexps being greedy is that they will match the
  3613.     maximum amount of data that they can, sometimes resulting in incorrect
  3614.     or strange answers.
  3615.  
  3616.     For example, I recently came across something like this:
  3617.  
  3618.     $_="this (is) an (example) of multiple parens";
  3619.     while ( m#\((.*)\)#g ) {
  3620.         print "$1\n";
  3621.     }
  3622.  
  3623.     This code was supposed to match everything between a set of
  3624.     parentheses.  The expected output was:
  3625.  
  3626.     is
  3627.     example
  3628.  
  3629.     However, the backreference ($1) ended up containing "is) an (example",
  3630.     clearly not what was intended.
  3631.  
  3632.     In perl4, the way to stop this from happening is to use a negated
  3633.     group.  If the above example is rewritten as follows, the results are
  3634.     correct: 
  3635.  
  3636.     while ( m#\(([^)]*)\)#g ) {
  3637.  
  3638.     In perl5 there is a new minimal matching metacharacter, '?'.  This
  3639.     character is added to the normal metacharacters to modify their
  3640.     behaviour, such as "*?", "+?", or even "??".  The example would now be
  3641.     written in the following style:
  3642.  
  3643.     while (m#\((.*?)\)#g )
  3644.  
  3645.     Hint: This new operator leads to a very elegant method of stripping
  3646.     comments from C code:
  3647.  
  3648.     s:/\*.*?\*/::gs
  3649.  
  3650.  
  3651. 4.27) How do I use a regular expression to strip C style comments from a
  3652.       file?
  3653.  
  3654.     Since we're talking about how to strip comments under perl5, now is a
  3655.     good time to talk about doing it in perl4.  Since comments can be
  3656.     embedded in strings, or look like function prototypes, care must be
  3657.     taken to ignore these cases.  Jeffrey Friedl* proposes the following
  3658.     two programs to strip C comments and C++ comments respectively:
  3659.  
  3660.     C comments:
  3661.         #!/usr/bin/perl
  3662.         $/ = undef;
  3663.         $_ = <>; 
  3664.  
  3665.         s#/\*[^*]*\*+([^/*][^*]*\*+)*/|([^/"']*("[^"\\]*(\\[\d\D][^"\\]*)*"[^/"']*|'[^'\\]*(\\[\d\D][^'\\]*)*'[^/"']*|/+[^*/][^/"']*)*)#$2#g;
  3666.         print; 
  3667.  
  3668.     C++ comments:
  3669.         #!/usr/local/bin/perl
  3670.         $/ = undef;
  3671.         $_ = <>;
  3672.         s#//(.*)|/\*[^*]*\*+([^/*][^*]*\*+)*/|"(\\.|[^"\\])*"|'(\\.|[^'\\])*'|[^/"']+#  $1 ? "/*$1 */" : $& #ge;
  3673.         print;
  3674.  
  3675.     (Yes, Jeffrey says, those are complete programs to strip comments
  3676.     correctly.) 
  3677.  
  3678.  
  3679. 4.28) How can I split a [character] delimited string except when inside
  3680.     [character]?
  3681.  
  3682.     I'm trying to split a string that is comma delimited into its different
  3683.     fields.  I could easily use split(/,/), except that I need to not split
  3684.     if the comma is inside quotes.  For example, my data file has a line
  3685.     like this:
  3686.  
  3687.     SAR001,"","Cimetrix, Inc","Bob Smith","CAM",N,8,1,0,7,"Error, Core Dumped"
  3688.  
  3689.     Due to the restriction of the quotes, this is a fairly complex
  3690.     solution.  However, we thankfully have Jeff Friedl* to handle these for
  3691.     us.  He suggests (assuming that your data is contained in the special
  3692.     variable $_):
  3693.  
  3694.     undef @field;
  3695.     push(@fields, defined($1) ? $1:$3) while 
  3696.         m/"([^"\\]*(\\.[^"\\]*)*)"|([^,]+)/g;
  3697.  
  3698.  
  3699. 4.29) Why doesn't "local($foo) = <FILE>;" work right?
  3700.  
  3701.     Well, it does.  The thing to remember is that local() provides an array
  3702.     context, and that the <FILE> syntax in an array context will read all the
  3703.     lines in a file.  To work around this, use:
  3704.  
  3705.     local($foo);
  3706.     $foo = <FILE>;
  3707.  
  3708.     You can use the scalar() operator to cast the expression into a scalar
  3709.     context:
  3710.  
  3711.     local($foo) = scalar(<FILE>);
  3712.  
  3713.  
  3714. 4.30) How can I detect keyboard input without reading it? 
  3715.  
  3716.     You should check out the Frequently Asked Questions list in
  3717.     comp.unix.* for things like this: the answer is essentially the same.
  3718.     It's very system dependent.  Here's one solution that works on BSD
  3719.     systems:
  3720.  
  3721.     sub key_ready {
  3722.         local($rin, $nfd);
  3723.         vec($rin, fileno(STDIN), 1) = 1;
  3724.         return $nfd = select($rin,undef,undef,0);
  3725.     }
  3726.  
  3727.     Under perl5, you should look into getting the ReadKey extension from
  3728.     your regular perl archive.
  3729.  
  3730.  
  3731. 4.31) How can I read a single character from the keyboard under UNIX and DOS?
  3732.  
  3733.     A closely related question to the no-echo question below is how to
  3734.     input a single character from the keyboard.  Again, this is a system
  3735.     dependent operation.  As with the previous question, you probably want
  3736.     to get the ReadKey extension.  The following code may or may not help
  3737.     you.  It should work on both SysV and BSD flavors of UNIX:
  3738.  
  3739.     $BSD = -f '/vmunix';
  3740.     if ($BSD) {
  3741.         system "stty cbreak </dev/tty >/dev/tty 2>&1";
  3742.     }
  3743.     else {
  3744.         system "stty", '-icanon',
  3745.         system "stty", 'eol', "\001"; 
  3746.     }
  3747.  
  3748.     $key = getc(STDIN);
  3749.  
  3750.     if ($BSD) {
  3751.         system "stty -cbreak </dev/tty >/dev/tty 2>&1";
  3752.     }
  3753.     else {
  3754.         system "stty", 'icanon';
  3755.         system "stty", 'eol', '^@'; # ascii null
  3756.     }
  3757.     print "\n";
  3758.  
  3759.     You could also handle the stty operations yourself for speed if you're
  3760.     going to be doing a lot of them.  This code works to toggle cbreak
  3761.     and echo modes on a BSD system:
  3762.  
  3763.     sub set_cbreak { # &set_cbreak(1) or &set_cbreak(0)
  3764.     local($on) = $_[0];
  3765.     local($sgttyb,@ary);
  3766.     require 'sys/ioctl.ph';
  3767.     $sgttyb_t   = 'C4 S' unless $sgttyb_t;  # c2ph: &sgttyb'typedef()
  3768.  
  3769.     ioctl(STDIN,&TIOCGETP,$sgttyb) || die "Can't ioctl TIOCGETP: $!";
  3770.  
  3771.     @ary = unpack($sgttyb_t,$sgttyb);
  3772.     if ($on) {
  3773.         $ary[4] |= &CBREAK;
  3774.         $ary[4] &= ~&ECHO;
  3775.     } else {
  3776.         $ary[4] &= ~&CBREAK;
  3777.         $ary[4] |= &ECHO;
  3778.     }
  3779.     $sgttyb = pack($sgttyb_t,@ary);
  3780.  
  3781.     ioctl(STDIN,&TIOCSETP,$sgttyb) || die "Can't ioctl TIOCSETP: $!";
  3782.     }
  3783.  
  3784.     Note that this is one of the few times you actually want to use the
  3785.     getc() function; it's in general way too expensive to call for normal
  3786.     I/O.  Normally, you just use the <FILE> syntax, or perhaps the read()
  3787.     or sysread() functions.
  3788.  
  3789.     For perspectives on more portable solutions, use anon ftp to retrieve
  3790.     the file /pub/perl/info/keypress from convex.com.
  3791.  
  3792.     Under Perl5, with William Setzer's Curses module, you can call
  3793.     &Curses::cbreak() and &Curses::nocbreak() to turn cbreak mode on and
  3794.     off.  You can then use getc() to read each character.  This should work
  3795.     under both BSD and SVR systems.  If anyone can confirm or deny
  3796.     (especially William), please contact the maintainers.
  3797.  
  3798.     For DOS systems, Dan Carson <dbc@tc.fluke.COM> reports:
  3799.  
  3800.     To put the PC in "raw" mode, use ioctl with some magic numbers gleaned
  3801.     from msdos.c (Perl source file) and Ralf Brown's interrupt list (comes
  3802.     across the net every so often):
  3803.  
  3804.     $old_ioctl = ioctl(STDIN,0,0);     # Gets device info
  3805.     $old_ioctl &= 0xff;
  3806.     ioctl(STDIN,1,$old_ioctl | 32);    # Writes it back, setting bit 5
  3807.  
  3808.     Then to read a single character:
  3809.  
  3810.     sysread(STDIN,$c,1);               # Read a single character
  3811.  
  3812.     And to put the PC back to "cooked" mode:
  3813.  
  3814.     ioctl(STDIN,1,$old_ioctl);         # Sets it back to cooked mode.
  3815.  
  3816.  
  3817.     So now you have $c.  If ord($c) == 0, you have a two byte code, which
  3818.     means you hit a special key.  Read another byte (sysread(STDIN,$c,1)),
  3819.     and that value tells you what combination it was according to this
  3820.     table:
  3821.  
  3822.     # PC 2-byte keycodes = ^@ + the following:
  3823.  
  3824.     # HEX     KEYS
  3825.     # ---     ----
  3826.     # 0F      SHF TAB
  3827.     # 10-19   ALT QWERTYUIOP
  3828.     # 1E-26   ALT ASDFGHJKL
  3829.     # 2C-32   ALT ZXCVBNM
  3830.     # 3B-44   F1-F10
  3831.     # 47-49   HOME,UP,PgUp
  3832.     # 4B      LEFT
  3833.     # 4D      RIGHT
  3834.     # 4F-53   END,DOWN,PgDn,Ins,Del
  3835.     # 54-5D   SHF F1-F10
  3836.     # 5E-67   CTR F1-F10
  3837.     # 68-71   ALT F1-F10
  3838.     # 73-77   CTR LEFT,RIGHT,END,PgDn,HOME
  3839.     # 78-83   ALT 1234567890-=
  3840.     # 84      CTR PgUp
  3841.  
  3842.     This is all trial and error I did a long time ago, I hope I'm reading the
  3843.     file that worked.
  3844.  
  3845.  
  3846. 4.32) How can I get input from the keyboard without it echoing to the
  3847.       screen?
  3848.  
  3849.     Terminal echoing is generally handled directly by the shell.
  3850.     Therefore, there is no direct way in perl to turn echoing on and off.
  3851.     However, you can call the command "stty [-]echo".  The following will
  3852.     allow you to accept input without it being echoed to the screen, for
  3853.     example as a way to accept passwords (error checking deleted for
  3854.     brevity):
  3855.  
  3856.     print "Please enter your password: ";
  3857.         system("stty -echo");
  3858.     chop($password=<STDIN>);
  3859.     print "\n";
  3860.     system("stty echo");
  3861.  
  3862.     Again, under perl 5, you can use Curses and call &Curses::noecho() and
  3863.     &Curses::echo() to turn echoing off and on.  Or, there's always the
  3864.     ReadKey extension.
  3865.  
  3866.  
  3867. 4.33) Is there any easy way to strip blank space from the beginning/end of
  3868.     a string?
  3869.  
  3870.     Yes, there is.  Using the substitution command, you can match the
  3871.     blanks and replace it with nothing.  For example, if you have the
  3872.     string "     String     " you can use this:
  3873.  
  3874.         s/^\s*(.*?)\s*$/$1/;     # perl5 only!
  3875.  
  3876.         s/^\s+|\s+$//g;            # perl4 or perl5
  3877.  
  3878.     or even
  3879.  
  3880.         s/^\s+//; s/\s+$//;
  3881.  
  3882.     Note however that Jeffrey Friedl* says these are only good for shortish
  3883.     strings.  For longer strings, and worse-case scenarios, they tend to
  3884.     break-down and become inefficient.
  3885.  
  3886.     For the longer strings, he suggests using either
  3887.  
  3888.         $_ = $1 if m/^\s*((.*\S)?)/;
  3889.  
  3890.     or
  3891.     
  3892.         s/^\s*((.*\S)?)\s*$/$1/;
  3893.  
  3894.     It should also be noted that for generally nice strings, these tend to
  3895.     be noticably slower than the simple ones above.  It is suggested that
  3896.     you use whichever one will fit your situation best, understanding that
  3897.     the first examples will work in roughly ever situation known even if
  3898.     slow at times.
  3899.  
  3900. 4.34) How can I print out a number with commas into it?
  3901.  
  3902.     This one will do it for you:
  3903.  
  3904.     sub commify {
  3905.         local($_) = shift;
  3906.         1 while s/^(-?\d+)(\d{3})/$1,$2/;
  3907.         return $_;
  3908.     } 
  3909.  
  3910.     $n = 23659019423.2331;
  3911.     print "GOT: ", &commify($n), "\n";
  3912.  
  3913.     GOT: 23,659,019,423.2331
  3914.  
  3915.     The reason you can't just do
  3916.  
  3917.     s/^(-?\d+)(\d{3})/$1,$2/g;
  3918.  
  3919.     Is that you have to put the comma in and then recalculate anything.  
  3920.     Some substitutions need to work this way.  See the question on 
  3921.     expanding tabs for another such.
  3922.  
  3923. 4.35) How do I expand tabs in a string?
  3924.  
  3925.     1 while s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e;
  3926.  
  3927.     You could have written that
  3928.  
  3929.     while (s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e) {
  3930.         # spin, spin, spin, ....
  3931.     } 
  3932.  
  3933.     Placed in a function:
  3934.  
  3935.     sub tab_expand {
  3936.         local($_) = shift;
  3937.         1 while s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e;
  3938.         return $_;
  3939.     } 
  3940.  
  3941.     This is especially important when you're working going to unpack 
  3942.     an ascii string that might have tabs in it.  Otherwise you'll be
  3943.     off on the byte count.  For example:
  3944.  
  3945.     $NG = "/usr/local/lib/news/newsgroups";
  3946.     open(NG, "< $NG") || die "can't open $NG: $!";
  3947.     while (<NG>) {
  3948.         chop;  # chomp would be better, but it's only perl5
  3949.         # now for the darned tabs in the newsgroups file
  3950.         1 while s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e;
  3951.         ($ng, $desc) = unpack("A24 A*", $_);
  3952.         if (length($ng) == 24) {
  3953.         $desc =~ s/^(\S+)\s*//;
  3954.         $ng .= $1;
  3955.         } 
  3956.  
  3957. 4.36) What's wrong with grep() or map() in a void context?
  3958.  
  3959.     Well, nothing precisely, but it's not a good way to write 
  3960.     maintainable code.  It's just fine to use grep when you want
  3961.     an answer, like
  3962.  
  3963.     @bignums = grep ($_ > 100, @allnums);
  3964.     @triplist = map {$_ * 3} @allnums;
  3965.  
  3966.     But using it in a void context like this:
  3967.  
  3968.     grep{ $_ *= 3, @nums);
  3969.  
  3970.     Is using it for its side-effects, and side-effects can be mystifying.
  3971.     There's no void grep that's not better written as a for() loop:
  3972.  
  3973.     for (@nums) { $_ *= 3 } 
  3974.  
  3975.     In the same way, a ?: in a void context is considered poor form:
  3976.  
  3977.     fork ? wait : exec $prog;
  3978.  
  3979.     When you can write it this way:
  3980.  
  3981.     if (fork) {
  3982.         wait;
  3983.     } else {
  3984.         exec $prog;
  3985.         die "can't exec $prog: $!";
  3986.     } 
  3987.  
  3988.     Of course, using ?: in expressions is just what it's made for, 
  3989.     and just fine (but try not to nest them.).
  3990.  
  3991.     Remember that the most important things in almost any program are,
  3992.     and in this order:
  3993.  
  3994.     1. correctness
  3995.     2. maintainability
  3996.     3. efficiency
  3997.  
  3998.     Notice at no point did cleverness enter the picture.
  3999.  
  4000.     On the other hand, if you're just trying write JAPHs (aka Obfuscated
  4001.     Perl entries), or write ugly code, you would probably invert these :-)
  4002.  
  4003.     1. cleverness
  4004.     2. efficiency
  4005.     3. maintainability
  4006.     4. correctness
  4007.  
  4008. --
  4009. Stephen P Potter        Pencom Systems Administration              Beaching It 
  4010. spp@psa.pencom.com    Pager: 1-800-759-8888, 547-9561     Work: 703-860-2222
  4011.   Cthulhu for President in '96: When You're Tired of the Lesser of Two Evils
  4012. --
  4013. Stephen P Potter        Pencom Systems Administration              Beaching It 
  4014. spp@psa.pencom.com    Pager: 1-800-759-8888, 547-9561     Work: 703-860-2222
  4015. "I don't care whether people actually like Perl, just so long as they *think*
  4016.     they like it...  ;-)"    -Larry Wall
  4017.  
  4018. Article: 62263 in news.answers
  4019. Path: Dortmund.Germany.EU.net!Germany.EU.net!howland.reston.ans.net!newsxfer.itd.umich.edu!news.kreonet.re.kr!usenet.seri.re.kr!news.cais.net!news1.radix.net!news1.radix.net!spp
  4020. From: spp@psa.pencom.com
  4021. Newsgroups: comp.lang.perl.announce,comp.lang.perl.misc,comp.answers,news.answers
  4022. Subject: comp.lang.perl.* FAQ 5/5 - External Program Interaction
  4023. Followup-To: poster
  4024. Date: 27 Jan 1996 04:20:50 GMT
  4025. Organization: Pencom Systems Administration
  4026. Lines: 1121
  4027. Approved: news-answers-request@MIT.EDU
  4028. Message-ID: <SPP.96Jan26232050@syrinx.hideout.com>
  4029. NNTP-Posting-Host: dialin23.annex1.radix.net
  4030. Xref: Dortmund.Germany.EU.net comp.lang.perl.announce:239 comp.lang.perl.misc:18653 comp.answers:16587 news.answers:62263
  4031.  
  4032.  
  4033. Archive-name: perl-faq/part5
  4034. Version: $Id: part5,v 2.8 1995/05/15 15:47:16 spp Exp spp $
  4035. Posting-Frequency: bi-weekly
  4036. Last Edited: Thu Jan 11 00:57:03 1996 by spp (Stephen P Potter) on syrinx.psa.com
  4037.  
  4038. This posting contains answers to the following questions about Array, Shell
  4039. and External Program Interactions with Perl: 
  4040.  
  4041.  
  4042. 5.1) What is the difference between $array[1] and @array[1]?
  4043.  
  4044.     Always make sure to use a $ for single values and @ for multiple ones. 
  4045.     Thus element 2 of the @foo array is accessed as $foo[1], not @foo[1],
  4046.     which is a list of length one (not a scalar), and is a fairly common
  4047.     novice mistake.  Sometimes you can get by with @foo[1], but it's
  4048.     not really doing what you think it's doing for the reason you think
  4049.     it's doing it, which means one of these days, you'll shoot yourself
  4050.     in the foot; ponder for a moment what these will really do:
  4051.         @foo[0] = `cmd args`;
  4052.         @foo[1] = <FILE>;
  4053.     Just always say $foo[1] and you'll be happier.
  4054.  
  4055.     This may seem confusing, but try to think of it this way:  you use the
  4056.     character of the type which you *want back*.  You could use @foo[1..3] for
  4057.     a slice of three elements of @foo, or even @foo{A,B,C} for a slice of
  4058.     of %foo.  This is the same as using ($foo[1], $foo[2], $foo[3]) and
  4059.     ($foo{A}, $foo{B}, $foo{C}) respectively.  In fact, you can even use
  4060.     lists to subscript arrays and pull out more lists, like @foo[@bar] or
  4061.     @foo{@bar}, where @bar is in both cases presumably a list of subscripts.
  4062.  
  4063.  
  4064. 5.2) How can I make an array of arrays or other recursive data types?
  4065.  
  4066.  
  4067.     In Perl5, it's quite easy to declare these things.  For example 
  4068.  
  4069.         @A = (
  4070.             [ 'ww' .. 'xx'  ], 
  4071.             [ 'xx' .. 'yy'  ], 
  4072.             [ 'yy' .. 'zz'  ], 
  4073.             [ 'zz' .. 'zzz' ], 
  4074.         );
  4075.  
  4076.     And now reference $A[2]->[0] to pull out "yy".  These may also nest
  4077.     and mix with tables:
  4078.  
  4079.         %T = (
  4080.             key0, { k0, v0, k1, v1 },   
  4081.             key1, { k2, v2, k3, v3 },   
  4082.             key2, { k2, v2, k3, [ 'a' .. 'z' ] },    
  4083.         );
  4084.     
  4085.     Allowing you to reference $T{key2}->{k3}->[3] to pull out 'd'.
  4086.  
  4087.     Perl4 is infinitely more difficult.  Remember that Perl[0..4] isn't
  4088.     about nested data structures.  It's about flat ones, so if you're
  4089.     trying to do this, you may be going about it the wrong way or using the
  4090.     wrong tools.  You might try parallel arrays with common subscripts. 
  4091.  
  4092.     But if you're bound and determined, you can use the multi-dimensional
  4093.     array emulation of $a{'x','y','z'}, or you can make an array of names
  4094.     of arrays and eval it.
  4095.  
  4096.     For example, if @name contains a list of names of arrays, you can get
  4097.     at a the j-th element of the i-th array like so: 
  4098.  
  4099.         $ary = $name[$i];
  4100.         $val = eval "\$$ary[$j]";
  4101.  
  4102.     or in one line
  4103.  
  4104.         $val = eval "\$$name[$i][\$j]";
  4105.  
  4106.     You could also use the type-globbing syntax to make an array of *name
  4107.     values, which will be more efficient than eval.  Here @name hold a list
  4108.     of pointers, which we'll have to dereference through a temporary
  4109.     variable. 
  4110.  
  4111.     For example:
  4112.  
  4113.         { local(*ary) = $name[$i]; $val = $ary[$j]; }
  4114.  
  4115.     In fact, you can use this method to make arbitrarily nested data
  4116.     structures.  You really have to want to do this kind of thing badly to
  4117.     go this far, however, as it is notationally cumbersome. 
  4118.  
  4119.     Let's assume you just simply *have* to have an array of arrays of
  4120.     arrays.  What you do is make an array of pointers to arrays of
  4121.     pointers, where pointers are *name values described above.  You  
  4122.     initialize the outermost array normally, and then you build up your
  4123.     pointers from there.  For example:
  4124.  
  4125.         @w = ( 'ww' .. 'xx' );
  4126.         @x = ( 'xx' .. 'yy' );
  4127.         @y = ( 'yy' .. 'zz' );
  4128.         @z = ( 'zz' .. 'zzz' );
  4129.  
  4130.         @ww = reverse @w;
  4131.         @xx = reverse @x;
  4132.         @yy = reverse @y;
  4133.         @zz = reverse @z;
  4134.  
  4135.     Now make a couple of arrays of pointers to these:
  4136.  
  4137.         @A = ( *w, *x, *y, *z );
  4138.         @B = ( *ww, *xx, *yy, *zz );
  4139.  
  4140.     And finally make an array of pointers to these arrays:
  4141.  
  4142.         @AAA = ( *A, *B );
  4143.  
  4144.     To access an element, such as AAA[i][j][k], you must do this:
  4145.  
  4146.         local(*foo) = $AAA[$i];
  4147.         local(*bar) = $foo[$j];
  4148.         $answer = $bar[$k];
  4149.  
  4150.     Similar manipulations on associative arrays are also feasible.
  4151.  
  4152.     You could take a look at recurse.pl package posted by Felix Lee*, which
  4153.     lets you simulate vectors and tables (lists and associative arrays) by
  4154.     using type glob references and some pretty serious wizardry.
  4155.  
  4156.     In C, you're used to creating recursive datatypes for operations like
  4157.     recursive decent parsing or tree traversal.  In Perl, these algorithms
  4158.     are best implemented using associative arrays.  Take an array called
  4159.     %parent, and build up pointers such that $parent{$person} is the name
  4160.     of that person's parent.  Make sure you remember that $parent{'adam'}
  4161.     is 'adam'. :-) With a little care, this approach can be used to
  4162.     implement general graph traversal algorithms as well. 
  4163.  
  4164.  
  4165. 5.3) How do I make an array of structures containing various data types?
  4166.  
  4167.     This answer will work under perl5 only.  Did we mention that you should
  4168.     upgrade?  There is a perl4 solution, but you are using perl5 now,
  4169.     anyway, so there's no point in posting it.  Right?
  4170.  
  4171.     The best way to do this is to use an associative array to model your
  4172.     structure, then either a regular array (AKA list) or another
  4173.     associative array (AKA hash, table, or hash table) to store it.
  4174.  
  4175.         %foo = (
  4176.                    'field1'        => "value1",
  4177.                    'field2'        => "value2",
  4178.                    'field3'        => "value3",
  4179.                    ...
  4180.                );
  4181.         ...
  4182.  
  4183.         @all = ( \%foo, \%bar, ... );
  4184.  
  4185.         print $all[0]{'field1'};
  4186.  
  4187.     Or even
  4188.  
  4189.         @all = (
  4190.            {
  4191.                'field1'        => "value1",
  4192.                'field2'        => "value2",
  4193.                'field3'        => "value3",
  4194.                ...
  4195.            },
  4196.            {
  4197.                'field1'        => "value1",
  4198.                'field2'        => "value2",
  4199.                'field3'        => "value3",
  4200.                ...
  4201.            },
  4202.            ...
  4203.         )
  4204.  
  4205.     Note that if you want an associative array of lists, you'll want to make
  4206.     assignments like
  4207.  
  4208.         $t{$value} = [ @bar ];
  4209.  
  4210.     And with lists of associative arrays, you'll use
  4211.  
  4212.         %{$a[$i]} = %old;
  4213.  
  4214.     Study these for a while, and in an upcoming FAQ, we'll explain them fully:
  4215.  
  4216.         $table{'some key'}    =   @big_list_o_stuff;   # SCARY #0
  4217.         $table{'some key'}    =  \@big_list_o_stuff;   # SCARY #1
  4218.         @$table{'some key'}   =   @big_list_o_stuff;   # SCARY #2
  4219.         @{$table{'some key'}} =   @big_list_o_stuff;   # ICKY RANDALIAN CODE
  4220.         $table{'some key'}    = [ @big_list_o_stuff ]; # same, but NICE
  4221.  
  4222.     And while you're at it, take a look at these:
  4223.  
  4224.         $table{"051"}         = $some_scalar;          # SCARY #3
  4225.         $table{"0x51"}        = $some_scalar;          # ditto
  4226.         $table{051}           = $some_scalar;          # ditto
  4227.         $table{0x51}          = $some_scalar;          # ditto
  4228.         $table{51}            = $some_scalar;          # ok, i guess
  4229.         $table{"51"}          = $some_scalar;          # better
  4230.  
  4231.         $table{\@x}           = $some_scalar;          # SCARY #4
  4232.         $table{[@x]}          = $some_scalar;          # ditto
  4233.         $table{@x}            = $some_scalar;          # SCARY #5 (cf #0)
  4234.  
  4235.  
  4236.     See perlref(1) for details.
  4237.  
  4238.  
  4239. 5.4) How can I extract just the unique elements of an array?
  4240.  
  4241.     There are several possible ways, depending on whether the
  4242.     array is ordered and you wish to preserve the ordering.
  4243.  
  4244.     a) If @in is sorted, and you want @out to be sorted:
  4245.  
  4246.         $prev = 'nonesuch';
  4247.         @out = grep($_ ne $prev && (($prev) = $_), @in);
  4248.  
  4249.        This is nice in that it doesn't use much extra memory, 
  4250.        simulating uniq's behavior of removing only adjacent
  4251.        duplicates.
  4252.  
  4253.     b) If you don't know whether @in is sorted:
  4254.  
  4255.         undef %saw;
  4256.         @out = grep(!$saw{$_}++, @in);
  4257.  
  4258.     c) Like (b), but @in contains only small integers:
  4259.  
  4260.         @out = grep(!$saw[$_]++, @in);
  4261.  
  4262.     d) A way to do (b) without any loops or greps:
  4263.  
  4264.         undef %saw;
  4265.         @saw{@in} = ();
  4266.         @out = sort keys %saw;  # remove sort if undesired
  4267.  
  4268.     e) Like (d), but @in contains only small positive integers:
  4269.  
  4270.         undef @ary;
  4271.         @ary[@in] = @in;
  4272.         @out = sort @ary;
  4273.  
  4274.  
  4275. 5.5) How can I tell whether an array contains a certain element?
  4276.  
  4277.     There are several ways to approach this.  If you are going to make
  4278.     this query many times and the values are arbitrary strings, the
  4279.     fastest way is probably to invert the original array and keep an
  4280.     associative array lying about whose keys are the first array's values.
  4281.  
  4282.         @blues = ('turquoise', 'teal', 'lapis lazuli');
  4283.         undef %is_blue;
  4284.         for (@blues) { $is_blue{$_} = 1; }
  4285.  
  4286.     Now you can check whether $is_blue{$some_color}.  It might have been
  4287.     a good idea to keep the blues all in an assoc array in the first place.
  4288.  
  4289.     If the values are all small integers, you could use a simple
  4290.     indexed array.  This kind of an array will take up less space:
  4291.  
  4292.         @primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31);
  4293.         undef @is_tiny_prime;
  4294.         for (@primes) { $is_tiny_prime[$_] = 1; }
  4295.  
  4296.     Now you check whether $is_tiny_prime[$some_number].
  4297.  
  4298.     If the values in question are integers instead of strings, you can save
  4299.     quite a lot of space by using bit strings instead: 
  4300.  
  4301.         @articles = ( 1..10, 150..2000, 2017 );
  4302.         undef $read;
  4303.         grep (vec($read,$_,1) = 1, @articles);
  4304.     
  4305.     Now check whether vec($read,$n,1) is true for some $n.
  4306.  
  4307.  
  4308. 5.6) How do I sort an associative array by value instead of by key?
  4309.  
  4310.     You have to declare a sort subroutine to do this, or use an inline
  4311.     function.  Let's assume you want an ASCII sort on the values of the
  4312.     associative array %ary.  You could do so this way:
  4313.  
  4314.         foreach $key (sort by_value keys %ary) {
  4315.             print $key, '=', $ary{$key}, "\n";
  4316.         } 
  4317.         sub by_value { $ary{$a} cmp $ary{$b}; }
  4318.  
  4319.     If you wanted a descending numeric sort, you could do this:
  4320.  
  4321.         sub by_value { $ary{$b} <=> $ary{$a}; }
  4322.  
  4323.     You can also inline your sort function, like this, at least if 
  4324.     you have a relatively recent patchlevel of perl4 or are running perl5:
  4325.  
  4326.         foreach $key ( sort { $ary{$b} <=> $ary{$a} } keys %ary ) {
  4327.             print $key, '=', $ary{$key}, "\n";
  4328.         } 
  4329.  
  4330.     If you wanted a function that didn't have the array name hard-wired
  4331.     into it, you could so this:
  4332.  
  4333.         foreach $key (&sort_by_value(*ary)) {
  4334.             print $key, '=', $ary{$key}, "\n";
  4335.         } 
  4336.         sub sort_by_value {
  4337.             local(*x) = @_;
  4338.             sub _by_value { $x{$a} cmp $x{$b}; } 
  4339.             sort _by_value keys %x;
  4340.         } 
  4341.  
  4342.     If you want neither an alphabetic nor a numeric sort, then you'll 
  4343.     have to code in your own logic instead of relying on the built-in
  4344.     signed comparison operators "cmp" and "<=>".
  4345.  
  4346.     Note that if you're sorting on just a part of the value, such as a
  4347.     piece you might extract via split, unpack, pattern-matching, or
  4348.     substr, then rather than performing that operation inside your sort
  4349.     routine on each call to it, it is significantly more efficient to
  4350.     build a parallel array of just those portions you're sorting on, sort
  4351.     the indices of this parallel array, and then to subscript your original
  4352.     array using the newly sorted indices.  This method works on both
  4353.     regular and associative arrays, since both @ary[@idx] and @ary{@idx}
  4354.     make sense.  See page 245 in the Camel Book on "Sorting an Array by a
  4355.     Computable Field" for a simple example of this.
  4356.  
  4357.     For example, here's an efficient case-insensitive comparison:
  4358.  
  4359.         @idx = ();
  4360.         for (@data) { push (@idx, "\U$_") }
  4361.         @sorted = @data[ sort { $idx[$a] cmp $idx[$b] } 0..$#data];
  4362.  
  4363.  
  4364. 5.7) How can I know how many entries are in an associative array?
  4365.  
  4366.     While the number of elements in a @foobar array is simply @foobar when
  4367.     used in a scalar, you can't figure out how many elements are in an
  4368.     associative array in an analogous fashion.  That's because %foobar in
  4369.     a scalar context returns the ratio (as a string) of number of buckets
  4370.     filled versus the number allocated.  For example, scalar(%ENV) might
  4371.     return "20/32".  While perl could in theory keep a count, this would
  4372.     break down on associative arrays that have been bound to dbm files.
  4373.  
  4374.     However, while you can't get a count this way, one thing you *can* use
  4375.     it for is to determine whether there are any elements whatsoever in
  4376.     the array, since "if (%table)" is guaranteed to be false if nothing
  4377.     has ever been stored in it.  
  4378.  
  4379.     As of perl4.035, you can says
  4380.  
  4381.         $count = keys %ARRAY;
  4382.  
  4383.     keys() when used in a scalar context will return the number of keys,
  4384.     rather than the keys themselves.
  4385.  
  4386.  
  4387. 5.8) What's the difference between "delete" and "undef" with %arrays?
  4388.  
  4389.     Pictures help...  here's the %ary table:
  4390.  
  4391.               keys  values
  4392.             +------+------+
  4393.             |  a   |  3   |
  4394.             |  x   |  7   |
  4395.             |  d   |  0   |
  4396.             |  e   |  2   |
  4397.             +------+------+
  4398.  
  4399.     And these conditions hold
  4400.  
  4401.             $ary{'a'}                       is true
  4402.             $ary{'d'}                       is false
  4403.             defined $ary{'d'}               is true
  4404.             defined $ary{'a'}               is true
  4405.             exists $ary{'a'}                is true (perl5 only)
  4406.             grep ($_ eq 'a', keys %ary)     is true
  4407.  
  4408.     If you now say 
  4409.  
  4410.             undef $ary{'a'}
  4411.  
  4412.     your table now reads:
  4413.             
  4414.  
  4415.               keys  values
  4416.             +------+------+
  4417.             |  a   | undef|
  4418.             |  x   |  7   |
  4419.             |  d   |  0   |
  4420.             |  e   |  2   |
  4421.             +------+------+
  4422.  
  4423.     and these conditions now hold; changes in caps:
  4424.  
  4425.             $ary{'a'}                       is FALSE
  4426.             $ary{'d'}                       is false
  4427.             defined $ary{'d'}               is true
  4428.             defined $ary{'a'}               is FALSE
  4429.             exists $ary{'a'}                is true (perl5 only)
  4430.             grep ($_ eq 'a', keys %ary)     is true
  4431.  
  4432.     Notice the last two: you have an undef value, but a defined key!
  4433.  
  4434.     Now, consider this:
  4435.  
  4436.             delete $ary{'a'}
  4437.  
  4438.     your table now reads:
  4439.  
  4440.               keys  values
  4441.             +------+------+
  4442.             |  x   |  7   |
  4443.             |  d   |  0   |
  4444.             |  e   |  2   |
  4445.             +------+------+
  4446.  
  4447.     and these conditions now hold; changes in caps:
  4448.  
  4449.             $ary{'a'}                       is false
  4450.             $ary{'d'}                       is false
  4451.             defined $ary{'d'}               is true
  4452.             defined $ary{'a'}               is false
  4453.             exists $ary{'a'}                is FALSE (perl5 only)
  4454.             grep ($_ eq 'a', keys %ary)     is FALSE
  4455.  
  4456.     See, the whole entry is gone!
  4457.  
  4458.  
  4459. 5.9) Why don't backticks work as they do in shells?  
  4460.  
  4461.     Several reasons.  One is because backticks do not interpolate within
  4462.     double quotes in Perl as they do in shells.  
  4463.     
  4464.     Let's look at two common mistakes:
  4465.  
  4466.          $foo = "$bar is `wc $file`";  # WRONG
  4467.  
  4468.     This should have been:
  4469.  
  4470.          $foo = "$bar is " . `wc $file`;
  4471.  
  4472.     But you'll have an extra newline you might not expect.  This
  4473.     does not work as expected:
  4474.  
  4475.       $back = `pwd`; chdir($somewhere); chdir($back); # WRONG
  4476.  
  4477.     Because backticks do not automatically eat trailing or embedded
  4478.     newlines.  The chop() function will remove the last character from
  4479.     a string.  This should have been:
  4480.  
  4481.           chop($back = `pwd`); chdir($somewhere); chdir($back);
  4482.  
  4483.     You should also be aware that while in the shells, embedding
  4484.     single quotes will protect variables, in Perl, you'll need 
  4485.     to escape the dollar signs.
  4486.  
  4487.         Shell: foo=`cmd 'safe $dollar'`
  4488.         Perl:  $foo=`cmd 'safe \$dollar'`;
  4489.         
  4490.  
  4491. 5.10) How come my converted awk/sed/sh script runs more slowly in Perl?
  4492.  
  4493.     The natural way to program in those languages may not make for the fastest
  4494.     Perl code.  Notably, the awk-to-perl translator produces sub-optimal code;
  4495.     see the a2p man page for tweaks you can make.
  4496.  
  4497.     Two of Perl's strongest points are its associative arrays and its regular
  4498.     expressions.  They can dramatically speed up your code when applied
  4499.     properly.  Recasting your code to use them can help a lot.
  4500.  
  4501.     How complex are your regexps?  Deeply nested sub-expressions with {n,m} or
  4502.     * operators can take a very long time to compute.  Don't use ()'s unless
  4503.     you really need them.  Anchor your string to the front if you can.
  4504.  
  4505.     Something like this:
  4506.         next unless /^.*%.*$/; 
  4507.     runs more slowly than the equivalent:
  4508.         next unless /%/;
  4509.  
  4510.     Note that this:
  4511.         next if /Mon/;
  4512.         next if /Tue/;
  4513.         next if /Wed/;
  4514.         next if /Thu/;
  4515.         next if /Fri/;
  4516.     runs faster than this:
  4517.         next if /Mon/ || /Tue/ || /Wed/ || /Thu/ || /Fri/;
  4518.     which in turn runs faster than this:
  4519.         next if /Mon|Tue|Wed|Thu|Fri/;
  4520.     which runs *much* faster than:
  4521.         next if /(Mon|Tue|Wed|Thu|Fri)/;
  4522.  
  4523.     There's no need to use /^.*foo.*$/ when /foo/ will do.
  4524.  
  4525.     Remember that a printf costs more than a simple print.
  4526.  
  4527.     Don't split() every line if you don't have to.
  4528.  
  4529.     Another thing to look at is your loops.  Are you iterating through 
  4530.     indexed arrays rather than just putting everything into a hashed 
  4531.     array?  For example,
  4532.  
  4533.         @list = ('abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stv');
  4534.  
  4535.         for $i ($[ .. $#list) {
  4536.             if ($pattern eq $list[$i]) { $found++; } 
  4537.         } 
  4538.  
  4539.     First of all, it would be faster to use Perl's foreach mechanism
  4540.     instead of using subscripts:
  4541.  
  4542.         foreach $elt (@list) {
  4543.             if ($pattern eq $elt) { $found++; } 
  4544.         } 
  4545.  
  4546.     Better yet, this could be sped up dramatically by placing the whole
  4547.     thing in an associative array like this:
  4548.  
  4549.         %list = ('abc', 1, 'def', 1, 'ghi', 1, 'jkl', 1, 
  4550.                  'mno', 1, 'pqr', 1, 'stv', 1 );
  4551.         $found += $list{$pattern};
  4552.     
  4553.     (but put the %list assignment outside of your input loop.)
  4554.  
  4555.     You should also look at variables in regular expressions, which is
  4556.     expensive.  If the variable to be interpolated doesn't change over the
  4557.     life of the process, use the /o modifier to tell Perl to compile the
  4558.     regexp only once, like this:
  4559.  
  4560.         for $i (1..100) {
  4561.             if (/$foo/o) {
  4562.                 &some_func($i);
  4563.             } 
  4564.         } 
  4565.  
  4566.     Finally, if you have a bunch of patterns in a list that you'd like to 
  4567.     compare against, instead of doing this:
  4568.  
  4569.         @pats = ('_get.*', 'bogus', '_read', '.*exit', '_write');
  4570.         foreach $pat (@pats) {
  4571.             if ( $name =~ /^$pat$/ ) {
  4572.                 &some_func();
  4573.                 last;
  4574.             }
  4575.         }
  4576.  
  4577.     If you build your code and then eval it, it will be much faster.
  4578.     For example:
  4579.  
  4580.         @pats = ('_get.*', 'bogus', '_read', '.*exit', '_write');
  4581.         $code = <<EOS
  4582.                 while (<>) { 
  4583.                     study;
  4584. EOS
  4585.         foreach $pat (@pats) {
  4586.             $code .= <<EOS
  4587.                 if ( /^$pat\$/ ) {
  4588.                     &some_func();
  4589.                     next;
  4590.                 }
  4591. EOS
  4592.         }
  4593.         $code .= "}\n";
  4594.         print $code if $debugging;
  4595.         eval $code;
  4596.  
  4597.  
  4598.  
  4599. 5.11) How can I call my system's unique C functions from Perl?
  4600.  
  4601.     If these are system calls and you have the syscall() function, then
  4602.     you're probably in luck -- see the next question.  If you're using a 
  4603.     POSIX function, and are running perl5, you're also in luck: see
  4604.     POSIX(3m).  For arbitrary library functions, however, it's not quite so 
  4605.     straight-forward.  See "Where can I learn about linking C with Perl?".
  4606.  
  4607.  
  4608. 5.12) Where do I get the include files to do ioctl() or syscall()? [h2ph]
  4609.  
  4610.     [Note: as of perl5, you probably want to just use h2xs instead, at
  4611.     least, if your system supports dynamic loading.]
  4612.  
  4613.     These are generated from your system's C include files using the h2ph
  4614.     script (once called makelib) from the Perl source directory.  This will
  4615.     make files containing subroutine definitions, like &SYS_getitimer, which
  4616.     you can use as arguments to your function.
  4617.  
  4618.     You might also look at the h2pl subdirectory in the Perl source for how to
  4619.     convert these to forms like $SYS_getitimer; there are both advantages and
  4620.     disadvantages to this.  Read the notes in that directory for details.  
  4621.    
  4622.     In both cases, you may well have to fiddle with it to make these work; it
  4623.     depends how funny-looking your system's C include files happen to be.
  4624.  
  4625.     If you're trying to get at C structures, then you should take a look
  4626.     at using c2ph, which uses debugger "stab" entries generated by your
  4627.     BSD or GNU C compiler to produce machine-independent perl definitions
  4628.     for the data structures.  This allows to you avoid hardcoding
  4629.     structure layouts, types, padding, or sizes, greatly enhancing
  4630.     portability.  c2ph comes with the perl distribution.  On an SCO
  4631.     system, GCC only has COFF debugging support by default, so you'll have
  4632.     to build GCC 2.1 with DBX_DEBUGGING_INFO defined, and use -gstabs to
  4633.     get c2ph to work there.
  4634.  
  4635.     See the file /pub/perl/info/ch2ph on convex.com via anon ftp 
  4636.     for more traps and tips on this process.
  4637.  
  4638.  
  4639. 5.13) Why do setuid Perl scripts complain about kernel problems?
  4640.  
  4641.     This message:
  4642.  
  4643.     YOU HAVEN'T DISABLED SET-ID SCRIPTS IN THE KERNEL YET!
  4644.     FIX YOUR KERNEL, PUT A C WRAPPER AROUND THIS SCRIPT, OR USE -u AND UNDUMP!
  4645.  
  4646.     is triggered because setuid scripts are inherently insecure due to a
  4647.     kernel bug.  If your system has fixed this bug, you can compile Perl
  4648.     so that it knows this.  Otherwise, create a setuid C program that just
  4649.     execs Perl with the full name of the script.  Here's what the
  4650.     perldiag(1) man page says about this message:
  4651.  
  4652.         YOU HAVEN'T DISABLED SET-ID SCRIPTS IN THE KERNEL YET!
  4653.           (F) And you probably never will, since you probably don't have
  4654.           the sources to your kernel, and your vendor probably doesn't
  4655.           give a rip about what you want.  Your best bet is to use the
  4656.           wrapsuid script in the eg directory to put a setuid C wrapper
  4657.           around your script.
  4658.  
  4659.  
  4660. 5.14) How do I open a pipe both to and from a command?
  4661.  
  4662.     In general, this is a dangerous move because you can find yourself in a
  4663.     deadlock situation.  It's better to put one end of the pipe to a file.
  4664.     For example:
  4665.  
  4666.         # first write some_cmd's input into a_file, then 
  4667.         open(CMD, "some_cmd its_args < a_file |");
  4668.         while (<CMD>) {
  4669.  
  4670.         # or else the other way; run the cmd
  4671.         open(CMD, "| some_cmd its_args > a_file");
  4672.         while ($condition) {
  4673.             print CMD "some output\n";
  4674.             # other code deleted
  4675.         } 
  4676.         close CMD || warn "cmd exited $?";
  4677.  
  4678.         # now read the file
  4679.         open(FILE,"a_file");
  4680.         while (<FILE>) {
  4681.  
  4682.     If you have ptys, you could arrange to run the command on a pty and
  4683.     avoid the deadlock problem.  See the chat2.pl package in the
  4684.     distributed library for ways to do this.
  4685.  
  4686.     At the risk of deadlock, it is theoretically possible to use a
  4687.     fork, two pipe calls, and an exec to manually set up the two-way
  4688.     pipe.  (BSD system may use socketpair() in place of the two pipes,
  4689.     but this is not as portable.)  The open2 library function distributed
  4690.     with the current perl release will do this for you.
  4691.  
  4692.     This assumes it's going to talk to something like adb, both writing to
  4693.     it and reading from it.  This is presumably safe because you "know"
  4694.     that commands like adb will read a line at a time and output a line at
  4695.     a time.  Programs like sort or cat that read their entire input stream
  4696.     first, however, are quite apt to cause deadlock.
  4697.  
  4698.     There's also an open3.pl library that handles this for stderr as well.
  4699.  
  4700.  
  4701. 5.15) How can I capture STDERR from an external command?
  4702.  
  4703.     There are three basic ways of running external commands:
  4704.  
  4705.         system $cmd;
  4706.         $output = `$cmd`;
  4707.         open (PIPE, "cmd |");
  4708.  
  4709.     In the first case, both STDOUT and STDERR will go the same place as
  4710.     the script's versions of these, unless redirected.  You can always put
  4711.     them where you want them and then read them back when the system
  4712.     returns.  In the second and third cases, you are reading the STDOUT
  4713.     *only* of your command.  If you would like to have merged STDOUT and
  4714.     STDERR, you can use shell file-descriptor redirection to dup STDERR to
  4715.     STDOUT:
  4716.  
  4717.         $output = `$cmd 2>&1`;
  4718.         open (PIPE, "cmd 2>&1 |");
  4719.  
  4720.     Another possibility is to run STDERR into a file and read the file 
  4721.     later, as in 
  4722.  
  4723.         $output = `$cmd 2>some_file`;
  4724.         open (PIPE, "cmd 2>some_file |");
  4725.  
  4726.     Note that you *cannot* simply open STDERR to be a dup of STDOUT 
  4727.     in your perl program and avoid calling the shell to do the redirection.
  4728.     This doesn't work:
  4729.  
  4730.         open(STDERR, ">&STDOUT");
  4731.         $alloutput = `cmd args`;  # stderr still escapes
  4732.     
  4733.     Here's a way to read from both of them and know which descriptor
  4734.     you got each line from.  The trick is to pipe only STDOUT through
  4735.     sed, which then marks each of its lines, and then sends that
  4736.     back into a merged STDOUT/STDERR stream, from which your Perl program
  4737.     then reads a line at a time:
  4738.  
  4739.         open (CMD, 
  4740.           "(cmd args | sed 's/^/STDOUT:/') 2>&1 |");
  4741.  
  4742.         while (<CMD>) {
  4743.           if (s/^STDOUT://)  {
  4744.               print "line from stdout: ", $_;
  4745.           } else {
  4746.               print "line from stderr: ", $_;
  4747.           }
  4748.         }
  4749.  
  4750.     Be apprised that you *must* use Bourne shell redirection syntax in
  4751.     backticks, not csh!  For details on how lucky you are that perl's
  4752.     system() and backtick and pipe opens all use Bourne shell, fetch the
  4753.     file from convex.com called /pub/csh.whynot -- and you'll be glad that
  4754.     perl's shell interface is the Bourne shell.
  4755.  
  4756.     There's an &open3 routine out there which was merged with &open2 in
  4757.     perl5 production. 
  4758.  
  4759.  
  4760. 5.16) Why doesn't open return an error when a pipe open fails?
  4761.  
  4762.     These statements:
  4763.  
  4764.         open(TOPIPE, "|bogus_command") || die ...
  4765.         open(FROMPIPE, "bogus_command|") || die ...
  4766.  
  4767.     will not fail just for lack of the bogus_command.  They'll only
  4768.     fail if the fork to run them fails, which is seldom the problem.
  4769.  
  4770.     If you're writing to the TOPIPE, you'll get a SIGPIPE if the child
  4771.     exits prematurely or doesn't run.  If you are reading from the
  4772.     FROMPIPE, you need to check the close() to see what happened.
  4773.  
  4774.     If you want an answer sooner than pipe buffering might otherwise
  4775.     afford you, you can do something like this:
  4776.  
  4777.         $kid = open (PIPE, "bogus_command |");   # XXX: check defined($kid)
  4778.         (kill 0, $kid) || die "bogus_command failed";
  4779.  
  4780.     This works fine if bogus_command doesn't have shell metas in it, but
  4781.     if it does, the shell may well not have exited before the kill 0.  You
  4782.     could always introduce a delay:
  4783.  
  4784.         $kid = open (PIPE, "bogus_command </dev/null |");
  4785.         sleep 1;
  4786.         (kill 0, $kid) || die "bogus_command failed";
  4787.  
  4788.     but this is sometimes undesirable, and in any event does not guarantee
  4789.     correct behavior.  But it seems slightly better than nothing.
  4790.  
  4791.     Similar tricks can be played with writable pipes if you don't wish to
  4792.     catch the SIGPIPE.
  4793.  
  4794.  
  4795. 5.##) How do I capture the exit status from an external program?
  4796.  
  4797.     Perl provides a builtin variable which holds the status of the last
  4798.     backtick command: $?.  Here is exactly what the perlvar page says about
  4799.     this variable:
  4800.  
  4801.      $?      The status returned by the last pipe close, backtick
  4802.              (``) command, or system() operator.  Note that this
  4803.              is the status word returned by the wait() system
  4804.              call, so the exit value of the subprocess is
  4805.              actually ($? >> 8).  Thus on many systems, $? & 255
  4806.              gives which signal, if any, the process died from,
  4807.              and whether there was a core dump.  (Mnemonic:
  4808.              similar to sh and ksh.)
  4809.  
  4810.  
  4811. 5.17) Why can't my perl program read from STDIN after I gave it ^D (EOF) ?
  4812.  
  4813.     Because some stdio's set error and eof flags that need clearing.
  4814.  
  4815.     Try keeping around the seekpointer and go there, like this:
  4816.          $where = tell(LOG);
  4817.          seek(LOG, $where, 0);
  4818.  
  4819.     If that doesn't work, try seeking to a different part of the file and
  4820.     then back.  If that doesn't work, try seeking to a different part of
  4821.     the file, reading something, and then seeking back.  If that doesn't
  4822.     work, give up on your stdio package and use sysread.  You can't call
  4823.     stdio's clearerr() from Perl, so if you get EINTR from a signal
  4824.     handler, you're out of luck.  Best to just use sysread() from the
  4825.     start for the tty.
  4826.  
  4827.  
  4828. 5.18) How can I translate tildes in a filename?
  4829.  
  4830.     Perl doesn't expand tildes -- the shell (ok, some shells) do.
  4831.     The classic request is to be able to do something like:
  4832.  
  4833.         open(FILE, "~/dir1/file1");
  4834.         open(FILE, "~tchrist/dir1/file1");
  4835.  
  4836.     which doesn't work.  (And you don't know it, because you 
  4837.     did a system call without an "|| die" clause! :-)
  4838.  
  4839.     If you *know* you're on a system with the csh, and you *know*
  4840.     that Larry hasn't internalized file globbing, then you could
  4841.     get away with 
  4842.  
  4843.         $filename = <~tchrist/dir1/file1>;
  4844.  
  4845.     but that's pretty iffy.
  4846.  
  4847.     A better way is to do the translation yourself, as in:
  4848.  
  4849.         $filename =~ s#^~(\w+)(/.*)?$#(getpwnam($1))[7].$2#e;
  4850.  
  4851.     More robust and efficient versions that checked for error conditions,
  4852.     handed simple ~/blah notation, and cached lookups are all reasonable
  4853.     enhancements.
  4854.  
  4855.  
  4856. 5.19) How can I convert my shell script to Perl?
  4857.  
  4858.     Larry's standard answer is to send it through the shell to perl filter,
  4859.     otherwise known at tchrist@perl.com.  Contrary to popular belief, Tom
  4860.     Christiansen isn't a real person.  He is actually a highly advanced 
  4861.     artificial intelligence experiment written by a graduate student at the
  4862.     University of Colorado.  Some of the earlier tasks he was programmed to
  4863.     perform included:
  4864.  
  4865.         * monitor comp.lang.perl.misc and collect statistics on which
  4866.       questions were asked with which frequency and to respond to them
  4867.       with stock answers.  Tom's programming has since outgrown this
  4868.       paltry task, and it was assigned to an undergraduate student from
  4869.       the University of Florida.  After all, we all know that students
  4870.       from UF aren't able to do much more than documentation anyway.
  4871.       Against all odds, that undergraduate student has become a
  4872.       professional system administrator, perl programmer, and now
  4873.       author of the second edition of "Programming Perl".
  4874.         * convert shell programs to perl programs
  4875.  
  4876.     (This *IS* a joke... please quit calling me and asking about it!)
  4877.  
  4878.     Actually, there is no automatic machine translator.  Even if there
  4879.     were, you wouldn't gain a lot, as most of the external programs would 
  4880.     still get called.  It's the same problem as blind translation into C:
  4881.     you're still apt to be bogged down by exec()s.  You have to analyze
  4882.     the dataflow and algorithm and rethink it for optimal speedup.  It's
  4883.     not uncommon to see one, two, or even three orders of magnitude of
  4884.     speed difference between the brute-force and the recoded approaches.
  4885.  
  4886.  
  4887. 5.20) Can I use Perl to run a telnet or ftp session?
  4888.  
  4889.     Sure, you can connect directly to them using sockets, or you can run a
  4890.     session on a pty.  In either case, Randal's chat2 package, which is
  4891.     distributed with the perl source, will come in handly.  It address
  4892.     much the same problem space as Don Libes's expect package does.  Two
  4893.     examples of using managing an ftp session using chat2 can be found on
  4894.     convex.com in /pub/perl/scripts/ftp-chat2.shar .
  4895.  
  4896.     Caveat lector: chat2 is documented only by example, may not run on
  4897.     System V systems, and is subtly machine dependent both in its ideas
  4898.     of networking and in pseudottys.  See also question 4.21, "Why doesn't
  4899.     my sockets program work under System V (Solaris)?"
  4900.  
  4901.     Randal also has code showing an example socket session for handling the
  4902.     telnet protocol to get a weather report.  This can be found at
  4903.     ftp.cis.ufl.edu:/pub/perl/scripts/getduatweather.pl.
  4904.  
  4905.     Gene Spafford* has a nice ftp library package that will help with ftp.
  4906.  
  4907.  
  4908. 5.21) Why do I sometimes get an "Arguments too long" error when I use <*>?
  4909.  
  4910.     As of perl4.036, there is a certain amount of globbing that is passed
  4911.     out to the shell and not handled internally.  The following code (which
  4912.     will, roughly, emulate "chmod 0644 *")
  4913.  
  4914.         while (<*>) {
  4915.             chmod 0644, $_;
  4916.         }
  4917.  
  4918.     is the equivalent of
  4919.  
  4920.         open(FOO, "echo * | tr -s ' \t\r\f' '\\012\\012\\012\\012'|");
  4921.         while (<FOO>) {
  4922.             chop;
  4923.             chmod 0644, $_;
  4924.         }
  4925.  
  4926.     Until globbing is built into Perl, you will need to use some form of
  4927.     non-globbing work around.
  4928.  
  4929.     Something like the following will work:
  4930.  
  4931.         opendir(DIR,'.');
  4932.         chmod 0644, grep(/\.c$/, readdir(DIR));
  4933.         closedir(DIR);
  4934.     
  4935.     This example is taken directly from "Programming Perl" page 78.
  4936.  
  4937.     If you've installed tcsh as /bin/csh, you'll never have this problem.
  4938.  
  4939. 5.22) How do I do a "tail -f" in Perl?
  4940.  
  4941.     Larry says that the solution is to put a call to seek in yourself. 
  4942.     First try
  4943.  
  4944.             seek(GWFILE, 0, 1);
  4945.  
  4946.     The statement seek(GWFILE, 0, 1); doesn't change the current position,
  4947.     but it does clear the end-of-file condition on the handle, so that the
  4948.     next <GWFILE> makes Perl try again to read something.
  4949.  
  4950.     If that doesn't work (depends on your stdio implementation), then
  4951.     you need something more like this:
  4952.  
  4953.  
  4954.     for (;;) {
  4955.         for ($curpos = tell(GWFILE); $_ = <GWFILE>; $curpos = tell(GWFILE)) {
  4956.             # search for some stuff and put it into files
  4957.         }
  4958.         sleep for a while
  4959.         seek(GWFILE, $curpos, 0);
  4960.     }
  4961.  
  4962.  
  4963. 5.23) Is there a way to hide perl's command line from programs such as "ps"?
  4964.  
  4965.     Generally speaking, if you need to do this you're either using poor
  4966.     programming practices or are far too paranoid for your own good.  If you
  4967.     need to do this to hide a password being entered on the command line,
  4968.     recode the program to read the password from a file or to prompt for
  4969.     it. (see question 4.24)  Typing a password on the command line is
  4970.     inherently insecure as anyone can look over your shoulder to see it.
  4971.  
  4972.     If you feel you really must overwrite the command line and hide it, you
  4973.     can assign to the variable "$0".  For example:
  4974.  
  4975.         #!/usr/local/bin/perl
  4976.         $0 = "Hidden from prying eyes";
  4977.  
  4978.         open(PS, "ps |") || die "Can't PS: $!";
  4979.         while (<PS>) {
  4980.             next unless m/$$/;
  4981.             print
  4982.         }
  4983.  
  4984.     It should be noted that some OSes, like Solaris 2.X, read directly from
  4985.     the kernel information, instead of from the program's stack, and hence
  4986.     don't allow you to change the command line.
  4987.  
  4988.  
  4989. 5.24) I {changed directory, modified my environment} in a perl script.  How
  4990.       come the change disappeared when I exited the script?  How do I get
  4991.       my changes to be visible?
  4992.  
  4993.     In the strictest sense, it "can't" be done.  However, there is special
  4994.     shell magic which may allow you to do it.  I suggest checking out
  4995.     comp.unix.shell and reading the comp.unix.questions FAQ.
  4996.  
  4997.     When perl is started, you are creating a child process.  Due to the way
  4998.     the Unix system is designed, children cannot permanently affect their
  4999.     parent shells.
  5000.  
  5001.     When a child process is created, it inherits a copy of its parents
  5002.     environment (variables, current directory, etc).  When the child
  5003.     changes this environment, it is changing the copy and not the original,
  5004.     so the parent isn't affected.
  5005.  
  5006.     If you must change the parent from within a perl script, you could try
  5007.     having it write out a shell script or a C-shell script and then using
  5008.     ". script" or "source script" (sh, Csh, respectively)
  5009.     
  5010.  
  5011. 5.25) How can I use pass a filehandle to a function, or make a list of 
  5012.       filehandles?
  5013.  
  5014.     If you've ever tried to use a variable for a filehandle, you may well
  5015.     have had some problems.  This is just revealing one of the icky places
  5016.     in perl: filehandles aren't first-class citizens the way everything
  5017.     else is, and it really gets in the way sometimes.  
  5018.  
  5019.     Of course, it's just fine to say
  5020.  
  5021.         $fh = "/some/path";
  5022.         open($fh, "< $fh");
  5023.         print $fh "string\n";
  5024.  
  5025.     But you'll still get into trouble for trying:
  5026.  
  5027.         $fharray[$i] = "/some/path";
  5028.         open($fharray[$i], "< $fharray[$i]");
  5029.         print $fharray[$i] "stuff\n";
  5030.  
  5031.     You can also do this:
  5032.  
  5033.         $tmp_fh = $fharray[$i];
  5034.         print $tmp_fh "stuff\n";
  5035.  
  5036.     But this is ok:
  5037.  
  5038.         print { $fharray[$i] } "stuff\n";
  5039.  
  5040.     There are about four ways of passing in a filehandle.  The way
  5041.     everyone tries is just to pass it as a string.  
  5042.  
  5043.         printit(Some_Handle);
  5044.  
  5045.     Unfortunately, that doesn't work so well, because the package that
  5046.     the printit() function is executing in may in fact not be the
  5047.     one that the handle was opened it:
  5048.  
  5049.     A simple fix would be to pass it in fully qualified;
  5050.  
  5051.         printit(main::Some_Handle);
  5052.  
  5053.     because if you don't, the function is going to have to do 
  5054.     some crazy thing like this:
  5055.  
  5056.     CODE 1:
  5057.  
  5058.         sub printit {
  5059.             my $fh = shift;
  5060.             my $package = (caller)[0];
  5061.             $fh =~ s/^[^':]+$/$package::$&/;
  5062.             while (<$fh>) {
  5063.                 print;
  5064.             } 
  5065.         } 
  5066.      
  5067.     A better solution is to pass a typeglob instead:
  5068.  
  5069.     CODE 2:
  5070.  
  5071.         printit(*Some_Handle);
  5072.         sub printit {
  5073.             local *FH = shift;
  5074.             while (<FH>) {
  5075.                 print;
  5076.             } 
  5077.         }
  5078.  
  5079.     However, it turns out that you don't have to use a typeglob inside
  5080.     the function.  This also works:
  5081.  
  5082.     CODE 3:
  5083.  
  5084.         printit(*Some_Handle);
  5085.         sub printit {
  5086.             my $fh = shift;
  5087.             while (<$fh>) {
  5088.                 print;
  5089.             } 
  5090.         }
  5091.  
  5092.     As does this even, in case you want to make an object by blessing
  5093.     your reference:
  5094.  
  5095.     CODE 4:
  5096.  
  5097.         printit(\*Some_Handle);
  5098.         sub printit {
  5099.             my $fh = shift;
  5100.             while (<$fh>) {
  5101.                 print;
  5102.             } 
  5103.         }
  5104.  
  5105.     I used to think that you had to use 1 or preferably 2, but apparently
  5106.     you can get away with number 3 and 4 as well.  This is nice because it
  5107.     avoids ever assigning to a typeglob as we do it 2, which is a bit
  5108.     risky.
  5109.  
  5110.     Some other problems with #1: if you're using strict subs, then you
  5111.     aren't going to be able to do that: the strict subs will gets you.
  5112.     Instead, you'll have to pass in 'main::Some_Handle', but then down in
  5113.     your function, you'll get blown away by strict refs, because you'll be
  5114.     using a string a symbol.  So really, the best way is to pass the
  5115.     typeglob (or occasionally a reference to the same).
  5116.  
  5117. 5.26) How can open a file with a leading ">" or trailing blanks?
  5118.  
  5119.     Normally perl ignores trailing blanks in filenames, and interprets
  5120.     certain leading characters (or a trailing "|") to mean something
  5121.     special.  To avoid this, you might want to use a routine like this.
  5122.     It makes non-fullpathnames into explicit relative ones, and tacks
  5123.     a trailing null byte on the name to make perl leave it alone:
  5124.  
  5125.         sub safe_filename {
  5126.           local($_) = shift;
  5127.           m#^/# ? "$_\0" : "./$_\0";
  5128.         }
  5129.         $fn = &safe_filename("<<<something really wicked   ");
  5130.         open(FH, "> $fn") || "couldn't open $fn: $!";
  5131.  
  5132.  
  5133. 5.27) How can I tell if a variable is tainted?
  5134.  
  5135.     This function works reasonably well to figure out whether a variable
  5136.     will be disliked by the taint checks automatically enabled by setuid
  5137.     execution:
  5138.  
  5139.         sub tainted {
  5140.             ! eval { join('',@_), kill 0; 1; };
  5141.         }
  5142.  
  5143.     and in particular, never does any system calls.
  5144. --
  5145. Stephen P Potter        Pencom Systems Administration              Beaching It 
  5146. spp@psa.pencom.com    Pager: 1-800-759-8888, 547-9561     Work: 703-860-2222
  5147.   Cthulhu for President in '96: When You're Tired of the Lesser of Two Evils
  5148. --
  5149. Stephen P Potter        Pencom Systems Administration              Beaching It 
  5150. spp@psa.pencom.com    Pager: 1-800-759-8888, 547-9561     Work: 703-860-2222
  5151. "I don't care whether people actually like Perl, just so long as they *think*
  5152.     they like it...  ;-)"    -Larry Wall
  5153.  
  5154.