home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1993 #1 / NN_1993_1.iso / spool / comp / os / coherent / 6659 < prev    next >
Encoding:
Internet Message Format  |  1993-01-07  |  83.4 KB

  1. Path: sparky!uunet!gatech!usenet.ins.cwru.edu!agate!biosci!ig!pixel.convex.com!tchrist
  2. From: tchrist@PIXEL.CONVEX.COM (Tom Christiansen)
  3. Newsgroups: comp.os.coherent
  4. Subject: Re: perl ported?
  5. Message-ID: <28887.726428093@pixel.convex.com>
  6. Date: 7 Jan 93 16:34:53 GMT
  7. References: <199301070949.AA05934@PCS3.ITI.INFORMATIK.TH-DARMSTADT.DE>
  8. Sender: daemon@presto.ig.com
  9. Reply-To: "Coherent operating system" <COHERENT@indycms.bitnet>
  10. Lines: 2107
  11.  
  12. This article contains the table of contents to some of the most
  13. frequently asked questions in comp.lang.perl, a newsgroup devoted to
  14. the Perl programming language.  There are two pieces following
  15. this, the general information questions in part1 and the largely
  16. technical opnes in part2.
  17.  
  18. They're all good questions, but they come up often enough that
  19. substantial net bandwidth can be saved by looking here first before
  20. asking.  Before posting a question, you really should consult the Perl
  21. man page; there's a lot of information packed in there.
  22.  
  23. Some questions in this group aren't really about Perl, but rather
  24. about system-specific issues.  You might also consult the Most
  25. Frequently Asked Questions list in comp.unix.questions for answers
  26. to this type of question.
  27.  
  28. The current version of perl is 4.035 (version 4, patchlevel 35).
  29. There haven't actually been 35 updates to perl4; rather, the context
  30. diffs posted to the net have been broken up into 35 news-digestable
  31. chunks.
  32.  
  33. This list is maintained by Tom Christiansen, and is archived on
  34. convex.com [130.168.1.1] in the file pub/perl/info/faq.  If you
  35. have any suggested additions or corrections to this article, please
  36. send them to Tom at either <tchrist@convex.com> or <convex!tchrist>.
  37. Special thanks to Larry Wall for initially reviewing this list for
  38. accuracy and especially for writing and releasing Perl in the first place.
  39.  
  40.  
  41. 1.1)  What is Perl?
  42. 1.2)  Is Perl hard to learn?
  43. 1.3)  Should I program everything in Perl?
  44. 1.4)  Where can I get Perl over the Internet?
  45. 1.5)  Where can I get Perl via Email?
  46. 1.6)  How can I get Perl via UUCP?
  47. 1.7)  Where can I get more information on Perl?
  48. 1.8)  Can people who aren't on USENET receive comp.lang.perl as a digest?
  49. 1.9)  Are archives of comp.lang.perl available?
  50. 1.10) How do I get Perl to run on machine FOO?
  51. 1.11) Where can I get (info|inter|ora|sql|syb)perl?
  52. 1.12) There's an a2p and an s2p; why isn't there a p2c (perl-to-C)?
  53. 1.13) Where can I get undump for my machine?
  54. 1.14) Where can I get a perl-mode for emacs?
  55. 1.15) How can I use Perl interactively?
  56. 1.16) Is there a Perl shell?
  57. 1.17) Is there a Perl profiler?
  58. 1.18) Is there a yacc for Perl?
  59. 1.19) How can I use curses with perl?
  60. 1.20) How can I use X with Perl?
  61. 1.21) What is perl4?  What is perl5?
  62. 1.22) How does Perl compare with languages like REXX or TCL?
  63. 1.23) Is it a Perl program or a Perl script?
  64. 1.24) What's the difference between "Perl" and "perl"?
  65. 1.25) What companies use or ship Perl?
  66. 1.26) Is there commercial, 3rd-party support for Perl?
  67. 1.27) Where can I get a list of the JAPH signature quotes?
  68. 1.28) Where can I get a list of Larry Wall witticisms?
  69.  
  70. 2.1)  What are all these $@*%<> signs and how do I know when to use them?
  71. 2.2)  Why don't backticks work as they do in shells?
  72. 2.3)  How come Perl operators have different precedence than C operators?
  73. 2.4)  How come my converted awk/sed/sh script runs more slowly in Perl?
  74. 2.5)  How can I call my system's unique C functions from Perl?
  75. 2.6)  Where do I get the include files to do ioctl() or syscall()?
  76. 2.7)  Why doesn't "local($foo) = <FILE>;" work right?
  77. 2.8)  How can I detect keyboard input without reading it?
  78. 2.9)  How can I make an array of arrays or other recursive data types?
  79. 2.10) How can I quote a variable to use in a regexp?
  80. 2.11) Why do setuid Perl scripts complain about kernel problems?
  81. 2.12) How do I open a pipe both to and from a command?
  82. 2.13) How can I change the first N letters of a string?
  83. 2.14) How can I manipulate fixed-record-length files?
  84. 2.15) How can I make a file handle local to a subroutine?
  85. 2.16) How can I extract just the unique elements of an array?
  86. 2.17) How can I call alarm() or usleep() from Perl?
  87. 2.18) How can I test whether an array contains a certain element?
  88. 2.19) How can I do an atexit() or setjmp()/longjmp() in Perl?
  89. 2.20) Why doesn't Perl interpret my octal data octally?
  90. 2.21) How do I sort an associative array by value instead of by key?
  91. 2.22) How can I capture STDERR from an external command?
  92. 2.23) Why doesn't open return an error when a pipe open fails?
  93. 2.24) How can I compare two date strings?
  94. 2.25) What's the fastest way to code up a given task in perl?
  95. 2.26) How can I know how many entries are in an associative array?
  96. 2.27) Why can't my perl program read from STDIN after I gave it ^D (EOF) ?
  97. 2.28) Do I always/never have to quote my strings or use semicolons?
  98. 2.29) How can I translate tildes in a filename?
  99. 2.30) How can I convert my shell script to Perl?
  100. 2.31) What is variable suicide and how can I prevent it?
  101. 2.32) Can I use Perl regular expressions to match balanced text?
  102. 2.33) Can I use Perl to run a telnet or ftp session?
  103. 2.34) What does "Malformed command links" mean?
  104.  
  105.  
  106.  
  107. 1.1) What is Perl?
  108.  
  109.     A programming language, by Larry Wall <lwall@netlabs.com>.
  110.  
  111.     Here's the beginning of the description from the man page:
  112.  
  113.     Perl is an interpreted language optimized for scanning arbitrary text
  114.     files, extracting information from those text files, and printing reports
  115.     based on that information.  It's also a good language for many system
  116.     management tasks.  The language is intended to be practical (easy to use,
  117.     efficient, complete) rather than beautiful (tiny, elegant, minimal).  It
  118.     combines (in the author's opinion, anyway) some of the best features of C,
  119.     sed, awk, and sh, so people familiar with those languages should have
  120.     little difficulty with it.  (Language historians will also note some
  121.     vestiges of csh, Pascal, and even BASIC-PLUS.)  Expression syntax
  122.     corresponds quite closely to C expression syntax.  Unlike most Unix
  123.     utilities, Perl does not arbitrarily limit the size of your data--if
  124.     you've got the memory, Perl can slurp in your whole file as a single
  125.     string.  Recursion is of unlimited depth.  And the hash tables used by
  126.     associative arrays grow as necessary to prevent degraded performance.
  127.     Perl uses sophisticated pattern matching techniques to scan large amounts
  128.     of data very quickly.  Although optimized for scanning text, Perl can also
  129.     deal with binary data, and can make dbm files look like associative arrays
  130.     (where dbm is available).  Setuid Perl scripts are safer than C programs
  131.     through a dataflow tracing mechanism which prevents many stupid security
  132.     holes.  If you have a problem that would ordinarily use sed or awk or sh,
  133.     but it exceeds their capabilities or must run a little faster, and you
  134.     don't want to write the silly thing in C, then Perl may be for you.  There
  135.     are also translators to turn your sed and awk scripts into Perl scripts.
  136.  
  137.  
  138. 1.2) Is Perl hard to learn?
  139.  
  140.     No, Perl is easy to learn for two reasons.
  141.  
  142.     The first reason is that most of Perl is derived from existing tools
  143.     and languages, ones that many people who turn to Perl already have
  144.     some familiarity with.  These include the C programming language, the
  145.     UNIX C library, the UNIX shell, sed, and awk.  If you already know
  146.     these somewhat, Perl should be very easy for you.
  147.  
  148.     The second reason that Perl is easy to learn is that you don't have to
  149.     know every thing there is to know about it in order to get good use
  150.     out of it.  In fact, just a very small subset, mostly borrowed from C,
  151.     the shell, and sed, will be enough for most tasks.  As you feel the
  152.     need or desire to use more sophisticated features (such as C
  153.     structures or networking), you can learn these as you go.  The
  154.     learning curve for Perl is not a steep one, especially if you have
  155.     the headstart of having a background in UNIX.  Rather, its learning
  156.     curve is gentle and gradual, but it *is* admittedly rather long.
  157.  
  158.     If you don't know C or UNIX at all, it'll be a steeper learning curve,
  159.     but what you then learn from Perl will carry over into other areas,
  160.     like using the C library, UNIX system call, regular expressions, and
  161.     associative arrays, just to name a few.  To know Perl is to know
  162.     UNIX, and vice versa.
  163.  
  164.  
  165. 1.3) Should I program everything in Perl?
  166.  
  167.     Of course not.  You should choose the appropriate tool for the task at
  168.     hand.  While it's true that the answer to the question "Can I do (some
  169.     arbitrary task) in Perl?" is almost always "yes", that doesn't mean
  170.     this is necessarily a good thing to do.  For many people, Perl serves
  171.     as a great replacement for shell programming.  For a few people, it
  172.     also serves as a replacement for most of what they'd do in C.  But
  173.     for some things, Perl just isn't the optimal choice, such as tasks
  174.     requiring very complex data structures.
  175.  
  176.  
  177. 1.4) Where can I get Perl over the Internet?
  178.  
  179.     From any comp.sources.misc archive.   Initial sources  were posted to
  180.     Volume 18, Issues 19-54 at patchlevel 3.  The Patches 4-10 were posted
  181.     to Volume 20, Issues 56-62.  You can use the archie server
  182.     (see the alt.sources FAQ in news.answers) for ways to find these.
  183.  
  184.     These machines, at the very least, definitely have it available for
  185.     anonymous FTP:
  186.  
  187.         ftp.uu.net                      137.39.1.2
  188.         archive.cis.ohio-state.edu      128.146.8.52
  189.         jpl-devvax.jpl.nasa.gov         128.149.1.143
  190.         ftp.netlabs.com                 192.94.48.152
  191.         prep.ai.mit.edu                 18.71.0.38
  192.         archive.cs.ruu.nl               131.211.80.5  (Europe)
  193.  
  194.  
  195.  
  196.  
  197. 1.5) Where can I get Perl via Email?
  198.  
  199.     If you are in Europe, you might using the following site.  (I'm still
  200.     looking for a domestic site.) This information thanks to "Henk P.
  201.     Penning" <henkp@cs.ruu.nl>:  One automated fashion is as follows:
  202.  
  203.     Email: Send a message to 'mail-server@cs.ruu.nl' containing:
  204.          begin
  205.          path your_email_address
  206.          send help
  207.          send PERL/INDEX
  208.          end
  209.     The path-line may be omitted if your message contains a normal From:-line.
  210.     You will receive a help-file and an index of the directory that contains
  211.     the Perl stuff.
  212.  
  213.     If all else fails, mail to Larry usually suffices.
  214.  
  215.  
  216. 1.6) How can I get Perl via UUCP?
  217.  
  218.     You can get it from the site osu-cis; here is the appropriate info,
  219.     thanks to J Greely <jgreely@cis.ohio-state.edu> or <osu-cis!jgreely>.
  220.  
  221.     E-mail contact:
  222.             osu-cis!uucp
  223.     Get these two files first:
  224.             osu-cis!~/GNU.how-to-get.
  225.             osu-cis!~/ls-lR.Z
  226.     Current Perl distribution:
  227.             osu-cis!~/perl/4.0/kits@10/perl.kitXX.Z (XX=01-37)
  228.     How to reach osu-cis via uucp(L.sys/Systems file lines):
  229.     #
  230.     # Direct Trailblazer
  231.     #
  232.     osu-cis Any ACU 19200 1-614-292-5112 in:--in:--in: Uanon
  233.     #
  234.     # Direct V.32 (MNP 4)
  235.     # dead, dead, dead...sigh.
  236.     #
  237.     #osu-cis Any ACU 9600 1-614-292-1153 in:--in:--in: Uanon
  238.     #
  239.     # Micom port selector, at 1200, 2400, or 9600 bps.
  240.     # Replace ##'s below with 12, 24, or 96 (both speed and phone number).
  241.     #
  242.     osu-cis Any ACU ##00 1-614-292-31## "" \r\c Name? osu-cis nected \c GO
  243.  \d\r\d\r\d\r in:--in:--in:
  244.      Uanon
  245.  
  246.     Modify as appropriate for your site, of course, to deal with your
  247.     local telephone system.  There are no limitations concerning the hours
  248.     of the day you may call.
  249.  
  250.     Another possibility is to use UUNET, although they charge you
  251.     for it.  You have been duly warned.  Here's the advert:
  252.  
  253.                Anonymous Access to UUNET's Source Archives
  254.  
  255.                              1-900-GOT-SRCS
  256.  
  257.          UUNET now provides access to its extensive collection of UNIX
  258.     related sources to non- subscribers.  By  calling  1-900-468-7727
  259.     and  using the login "uucp" with no password, anyone may uucp any
  260.     of UUNET's on line source collection.  Callers will be charged 40
  261.     cents  per  minute.   The charges will appear on their next tele-
  262.     phone bill.
  263.  
  264.          The  file  uunet!/info/help  contains  instructions.   The  file
  265.     uunet!/index//ls-lR.Z contains a complete list of the files available
  266.     and is updated daily.  Files ending in Z need to be uncompressed
  267.     before being used.   The file uunet!~/compress.tar is a tar
  268.     archive containing the C sources for the uncompress program.
  269.  
  270.          This service provides a  cost  effective  way  of  obtaining
  271.     current  releases  of sources without having to maintain accounts
  272.     with UUNET or some other service.  All modems  connected  to  the
  273.     900  number  are  Telebit T2500 modems.  These modems support all
  274.     standard modem speeds including PEP, V.32 (9600), V.22bis (2400),
  275.     Bell  212a  (1200), and Bell 103 (300).  Using PEP or V.32, a 1.5
  276.     megabyte file such as the GNU C compiler would cost $10  in  con-
  277.     nect  charges.   The  entire  55  megabyte X Window system V11 R4
  278.     would cost only $370 in connect time.  These costs are less  than
  279.     the  official  tape  distribution fees and they are available now
  280.     via modem.
  281.  
  282.                       UUNET Communications Services
  283.                    3110 Fairview Park Drive, Suite 570
  284.                          Falls Church, VA 22042
  285.                          +1 703 876 5050 (voice)
  286.                           +1 703 876 5059 (fax)
  287.                             info@uunet.uu.net
  288.  
  289.  
  290.  
  291. 1.7) Where can I get more information on Perl?
  292.  
  293.     We'll cover five areas here: USENET (where you're probably reading
  294.     this), publications, the reference guide, examples on the Internet,
  295.     and Perl instructional courses.
  296.  
  297.     A.  USENET
  298.  
  299.     You should definitely read the USENET comp.lang.perl newsgrouor
  300.     mailing list for all sorts of discussions regarding the language,
  301.     bugs, features, history, humor, and trivia.  In this respect, it
  302.     functions both as a comp.lang.* style newsgroup and also as a user
  303.     group for the language; in fact, there's a mailing list called
  304.     ``perl-users'' that is bidirectionally gatewayed to the newsgroup; see
  305.     question #38 for details.  Larry Wall is a very frequent poster here,
  306.     as well as many (if not most) of the other seasoned Perl programmers.
  307.     It's the best place for the very latest information on Perl.
  308.  
  309.     B.  PUBLICATIONS
  310.  
  311.     If you've been dismayed by the ~80-page troffed Perl man page (or is
  312.     that man treatise?) you should look to ``the Camel Book'', written by
  313.     Larry and Randal L. Schwartz <merlyn@ora.com>, published as a Nutshell
  314.     Handbook by O'Reilly & Associates and entitled _Programming Perl_.
  315.     Besides serving as a reference guide for Perl, it also contains
  316.     tutorial material and is a great source of examples and cookbook
  317.     procedures, as well as wit and wisdom, tricks and traps, pranks and
  318.     pitfalls.  The code examples contained therein are available via
  319.     anonymous FTP from ftp.uu.net in
  320.     /published/oreilly/nutshell/perl/perl.tar.Z for your retrieval.
  321.     Corrections and additions to the book can be found in the Perl man
  322.     page right before the BUGS section under the heading ERRATA AND
  323.     ADDENDA.
  324.  
  325.     If you can't find the book in your local technical bookstore, the book
  326.     may be ordered directly from O'Reilly by calling 1-800-998-9938 if in
  327.     North America and 1-707-829-0515.  Autographed copies are available
  328.     from TECHbooks by calling 1-503-646-8257 or mailing info@techbook.com.
  329.     Cost is ~30$US for the regular version, 40$US for the autographed one.
  330.     The book's ISBN is 0-937175-64-1.
  331.  
  332.     Reasonably substantiated rumor has it that there will be another Perl
  333.     book out pretty soon, this one aimed more at beginners.  Look for it
  334.     from ORA towards the beginning of 93.
  335.  
  336.     Larry Wall has published a 3-part article on perl in Unix World
  337.     (August through October of 1991), and Rob Kolstad also had a 3-parter
  338.     in Unix Review (May through July of 1990).  Tom Christiansen also has
  339.     a brief overview article in the trade newsletter Unix Technology
  340.     Advisor from November of 1989.  You might also investigate "The Wisdom
  341.     of Perl" by Gordon Galligher from SunExpert magazine;  April 1991
  342.     Volume 2 Number 4.
  343.  
  344.     The USENIX LISA (Large Installations Systems Adminstration) Conference
  345.     have for several years now included many papers of tools written in
  346.     Perl.  Old proceedings of these conferences are available; look in
  347.     your current issue of ";login:" or send mail to office@usenix.org
  348.     for futher information.
  349.  
  350.     C.  INTERNET
  351.  
  352.     For other examples of Perl scripts, look in the Perl source directory in
  353.     the eg subdirectory.  You can also find a good deal of them on
  354.     tut.cis.ohio-state.edu in the pub/perl/scripts/ subdirectory.
  355.  
  356.     Another source for examples, currently only for anonymous FTP, is on
  357.     convex.com [130.168.1.1].  This contains, amongst other things,
  358.     a copy of the newsgroup up through Aug 91, a text retrieval database
  359.     for the newsgroup, a rather old and short troff version of Tom
  360.  Christiansen's
  361.     perl tutorial (this was the version presented at Washington DC USENIX),
  362.     and quite a few of Tom's scripts.  You can look at the INDEX file
  363.     in /pub/perl/INDEX for a list of what's in that directory.
  364.  
  365.     The Convex and Ohio State archives are mirrored on uunet
  366.     in /languages/perl/scripts-{convex,osu}.
  367.  
  368.     D.  REFERENCE GUIDE
  369.  
  370.     A nice reference guide by Johan Vromans <jv@mh.nl> is also available;
  371.     It is distributed in LaTeX (source) and PostScript (ready to
  372.     print) forms. Obsolete versions may still be available in TeX and troff
  373.     forms, although these don't print as nicely. The official kit
  374.     includes both LaTeX and PostScript forms, and can be FTP'd from
  375.     archive.cs.ruu.nl [131.211.80.5], file /pub/DOC/perlref-4.035.tar.Z.
  376.     The reference guide comes with the O'Reilly book in a nice, glossy
  377.     card format.
  378.  
  379.     E.  PERL COURSES
  380.  
  381.     Various technical conferences, including USENIX, SUG, WCSAS, AUUG,
  382.     FedUnix, and Europen have been sponsoring tutorials of varying lengths
  383.     on Perl at their system administration and general conferences.  You
  384.     might consider attending one of these.  These classes are typically
  385.     taught by Tom Christiansen <tchrist@usenix.com>, although both Rob
  386.     Kolstad <kolstad@usenix.org> and Randal Schwartz <merlyn@ora.com> also
  387.     teach Perl on occasion.  Special appearances by Tom, Rob, and/or
  388.     Randal may also be negotiated.  Classes can run from one day up to a
  389.     week ranging over a wide range of subject matter (most are two or
  390.     three days), and can include lab time if you want; having lab time
  391.     with exercises is generally of great benefit.  Send us mail if your
  392.     organization is interested in having a Perl class taught at your site.
  393.  
  394.  
  395. 1.8) Can people who aren't on USENET receive comp.lang.perl as a digest?
  396.  
  397.     "Perl-Users" is the mailing list version of the comp.lang.perl
  398.     newsgroup.  If you're not lucky enough to be on USENET you can post to
  399.     comp.lang.perl by sending to one of the following addresses.  Which one
  400.     will work best for you depends on which nets your site is hooked into.
  401.     Ask your local network guru if you're not certain.
  402.  
  403.     Internet: PERL-USERS@VIRGINIA.EDU
  404.               Perl-Users@UVAARPA.VIRGINIA.EDU
  405.  
  406.     BitNet: Perl@Virginia
  407.  
  408.     uucp: ...!uunet!virginia!perl-users
  409.  
  410.     The Perl-Users list is bidirectionally gatewayed with the USENET
  411.     newsgroup comp.lang.perl.  This means that VIRGINIA functions as a
  412.     reflector.  All traffic coming in from the non-USENET side is
  413.     immediately posted to the newsgroup.  Postings from the USENET side are
  414.     periodically digested and mailed out to the Perl-Users mailing list.  A
  415.     digest is created and distributed at least once per day, more often if
  416.     traffic warrants.
  417.  
  418.     All requests to be added to or deleted from this list, problems,
  419.     questions, etc., should be sent to:
  420.  
  421.     Internet: Perl-Users-Request@Virginia.EDU
  422.               Perl-Users-Request@uvaarpa.Virginia.EDU
  423.  
  424.     BitNet: Perl-Req@Virginia
  425.  
  426.     uucp: ...!uunet!virginia!perl-users-request
  427.  
  428.     Coordinator: Marc Rouleau <mer6g@VIRGINIA.EDU>
  429.  
  430. 1.9) Are archives of comp.lang.perl available?
  431.  
  432.     Yes, although they're poorly organized.  You can get them from
  433.     the host betwixt.cs.caltech.edu (131.215.128.4) in the directory
  434.     /pub/comp.lang.perl.  They are also to uunet in
  435.     /languages/perl/comp.lang.perl .  It contains these things:
  436.  
  437.     comp.lang.perl.tar.Z  -- the 5M tarchive in MH/news format
  438.     archives/             -- the unpacked 5M tarchive
  439.     unviewed/             -- new comp.lang.perl messages
  440.  
  441.     These are currently stored in news- or MH-style format; there are
  442.     subdirectories named things like "arrays", "programs", "taint", and
  443.     "emacs".  Unfortunately, only the first ~1600 or so messages have been
  444.     so categorized, and we're now up to almost 15000.  Furthermore, even
  445.     this categorization was haphazardly done and contains errors.
  446.  
  447.     A more sophisticated query and retrieval mechanism is desirable.
  448.     Preferably one that allows you to retrieve article using a fast-access
  449.     indices, keyed on at least author, date, subject, thread (as in "trn")
  450.     and probably keywords.  Right now, the MH pick command works for this,
  451.     but it is very slow to select on 15000 articles.
  452.  
  453.     If you're serious about this, your best bet is probably to retrieve
  454.     the compressed tarchive and play with what you get.  Any suggestions
  455.     how to better sort this all out are extremely welcome.
  456.  
  457.     Currently the comp.lang.perl archives on convex.com are nearly a year
  458.     behind.  That's because I no longer have room to store them there.  I
  459.     do have them all on-line still, but they are not publicly accessible.
  460.     If you have a special request for a query on the old newsgroup
  461.     postings, and make nice noises in my direction, I can run the query
  462.     and send them to you.  Algebraic queries are like "find me anything
  463.     about this and that and the other thing but not this or whozits".  I
  464.     hope to put this in the form of a mailserver.  Donated software would
  465.     be fine. :-)
  466.  
  467.     The fast text-retrieval query system for this I'm currently using is
  468.     Liam Quin's excellent lqtext system, available from ftp.toronto.edu
  469.     in /pub/lq-text* .
  470.  
  471.     Rumor has it that there are WAIS servers out there for comp.lang.perl
  472.     these days, but I haven't used them.
  473.  
  474.  
  475. 1.10) How do I get Perl to run on machine FOO?
  476.  
  477.     Perl comes with an elaborate auto-configuration script that allows Perl
  478.     to be painlessly ported to a wide variety of platforms, including many
  479.     non-UNIX ones.  Amiga and MS-DOS binaries are available on
  480.     jpl-devvax.jpl.nasa.gov [128.149.1.143] for anonymous FTP.  Try to bring
  481.     Perl up on your machine, and if you have problems, examine the README
  482.     file carefully, and if all else fails, post to comp.lang.perl;
  483.     probably someone out there has run into your problem and will be able
  484.     to help you.
  485.  
  486.     In particular, since they're so often asked about, here's some information
  487.     for the MacIntosh from Matthias Ulrich Neeracher <neeri@iis.ethz.ch>:
  488.  
  489.         A port of Perl to the Apple Macintosh is available by anonymous
  490.         ftp to rascal.ics.utexas.edu from the file
  491.         ~ftp/mac/programming/Perl_402_MPW_CPT_bin .
  492.  
  493.         The file is 1.1M and must be transferred in BINARY mode. Please
  494.         be considerate of RASCAL's users during CDT working hours.
  495.         (And, no, there is no way to get it by email).
  496.  
  497.         For European users, the file should soon appear on lth.se.
  498.  
  499.         To make optimal use of all the features of this port, you
  500.         should have MPW, ToolServer, and 5M of memory. There is also a
  501.         standalone version included, but it's currently of very limited
  502.         usefulness.
  503.  
  504.         This package contains all of the sources for compilation with
  505.         MPW C 3.2
  506.  
  507.     And here's some VMS information from Rao V. Akella
  508.     <rao@moose.cccs.umn.edu>:  (this appears to be an old port)
  509.  
  510.         You can pick up Perl for VMS (version 3.0.1.1 patchlevel 4) via
  511.         anonymous ftp from ftp.pitt.edu [130.49.253.1] in the
  512.         software/vms/perl subdirectory (there are two files there:
  513.         perl-pl18.bck and perl-pl4.bck).
  514.  
  515.     There is also a v3.018 on info.rz.uni-ulm.de [134.60.1.125] or
  516.     vms.huji.ac.il [128.139.4.3] in /pub/VMS/misc (information courtesy
  517.     of Anders Rolff <rolff@scotty.eurokom.ie>).
  518.  
  519.     And here is a recent version for MS-DOS from Budi Rahard
  520.     <rahard@ee.UManitoba.CA>, who says:
  521.  
  522.         I am collecting MS-DOS Perl(s) in ftp.ee.umanitoba.ca directory
  523.         /pub/msdos/perl.  Currently I received three versions of Perl v4.019
  524.         and one of 4.010.  (Tommy Thorn <tthorn@daimi.aau.dk> and Len Reed
  525.         <holos0!lbr@gatech.edu>)
  526.  
  527.     There is now a 4.035 for 386 [DOS], Hitoshi Doi <doi@jrd.december.com>
  528.     port, is available ftp.ee.umanitoba.ca as /pub/msdos/perl/perl386.zoo .
  529.  
  530.     Please contact the porters directly in case of questions about
  531.     these ports.
  532.  
  533.  
  534. 1.11) Where can I get (info|inter|ora|sql|syb)perl?
  535.  
  536.     Numerous database-oriented extensions to Perl have been written.
  537.     These amount to using the usub mechanism (see the usub/ subdirectory
  538.     in the distribution tree) to link in a database library, allowing
  539.     embedded calls to Informix, Interbase, Oracle, Ingres, and Sybase.
  540.     There is currently a project underway, organized by Buzz Moschetti
  541.     <buzz@toxicavenger.bear.com>, to create a higher level interface
  542.     (DBperl) that will allow you to write your queries in a
  543.     database-independent fashion.  Meanwhile, here are the authors of the
  544.     various extensions:
  545.  
  546.     What            Target DB       Who
  547.     --------        -----------     ----------------------------------------
  548.     Infoperl        Informix        Kurt Andersen (kurt@hpsdid.sdd.hp.com)
  549.     Interperl       Interbase       Buzz Moschetti (buzz@fsrg.bear.com)
  550.     Oraperl         Oracle          Kevin Stock (kstock@encore.com)
  551.     Sqlperl         Ingres          Ted Lemon (mellon@ncd.com)
  552.     Sybperl         Sybase          Michael Peppler (mpeppler@itf.ch)
  553.  
  554.  
  555. 1.12) There's an a2p and an s2p; why isn't there a p2c (perl-to-C)?
  556.  
  557.     Because the Pascal people would be upset that we stole their name. :-)
  558.  
  559.     The dynamic nature of Perl's do and eval operators (and remember that
  560.     constructs like s/$mac_donald/$mac_gregor/eieio count as an eval) would
  561.     make this very difficult.  To fully support them, you would have to put
  562.     the whole Perl interpreter into each compiled version for those scripts
  563.     using them.  This is what undump does right now, if your machine has it.
  564.     If what you're doing will be faster in C than in Perl, maybe it should
  565.     have been written in C in the first place.  For things that ought to be
  566.     written in Perl, the interpreter will be just about as fast, because the
  567.     pattern matching routines won't work any faster linked into a C program.
  568.     Even in the case of simple Perl programs that don't do any fancy evals, the
  569.     major gain would be in compiling the control flow tests, with the rest
  570.     still being a maze of twisty, turny subroutine calls.  Since these are not
  571.     usually the major bottleneck in the program, there's not as much to be
  572.     gained via compilation as one might think.
  573.  
  574.  
  575. 1.13) Where can I get undump for my machine?
  576.  
  577.     The undump program comes from the TeX distribution.  If you have TeX, then
  578.     you may have a working undump.  If you don't, and you can't get one,
  579.     *AND* you have a GNU emacs working on your machine that can clone itself,
  580.     then you might try taking its unexec() function and compiling Perl with
  581.     -DUNEXEC, which will make Perl call unexec() instead of abort().  You'll
  582.     have to add unexec.o to the objects line in the Makefile.  If you succeed,
  583.     post to comp.lang.perl about your experience so others can benefit from it.
  584.  
  585.  
  586. 1.14) Where can I get a perl-mode for emacs?
  587.  
  588.     In the perl4.0 source directory, you'll find a directory called
  589.     "emacs", which contains several files that should help you.
  590.  
  591.  
  592. 1.15) How can I use Perl interactively?
  593.  
  594.     The easiest way to do this is to run Perl under its debugger.
  595.     If you have no program to debug, you can invoke the debugger
  596.     on an `empty' program like this:
  597.  
  598.         perl -de 0
  599.  
  600.     (The more positive amongst us prefer "perl -de 1". :-)
  601.  
  602.     Now you can type in any legal Perl code, and it will be immediately
  603.     evaluated.  You can also examine the symbol table, get stack
  604.     backtraces, check variable Values, and if you want to, set
  605.     breakpoints and do the other things you can do in a symbolic debugger.
  606.  
  607.  
  608. 1.16) Is there a Perl shell?
  609.  
  610.    Not really.  Perl is a programming language, not a command
  611.    interpreter.  There is a very simple one called "perlsh"
  612.    included in the Perl source distribution.  It just does this:
  613.  
  614.         $/ = '';        # set paragraph mode
  615.         $SHlinesep = "\n";
  616.         while ($SHcmd = <>) {
  617.             $/ = $SHlinesep;
  618.             eval $SHcmd; print $@ || "\n";
  619.             $SHlinesep = $/; $/ = '';
  620.         }
  621.  
  622.    Not very interesting, eh?
  623.  
  624.    Daniel Smith <dansmith@autodesk.com> is working on an interactive Perl
  625.    shell called SoftList.  It's currently at version 3.0beta.  SoftList
  626.    3.0 has tcsh-like command line editing, can let you define a file of
  627.    aliases so that you can run chunks of perl or UNIX commands, and so
  628.    on.  You can send mail to him for further information and availability.
  629.  
  630.  
  631. 1.17) Is there a Perl profiler?
  632.  
  633.     While there isn't one included with the perl source distribution,
  634.     various folks have written packages that allow you to do at least some
  635.     sort of profiling.  The strategy usually includes modifying the perl
  636.     debugger to handle profiling.  Authors of these packages include
  637.  
  638.         Wayne Thompson          <me@anywhere.EBay.Sun.COM>
  639.         Ray Lischner            <lisch@sysserver1.mentor.com>
  640.         Kresten Krab Thorup     <krab@iesd.auc.dk>
  641.  
  642.     The original articles by these folks containing their
  643.     profilers are available on convex.com in
  644.     /pub/perl/information/profiling.shar via anon ftp.
  645.  
  646.  
  647. 1.18) Is there a yacc for Perl?
  648.  
  649.     Yes!! It's a version of Berkeley yacc that outputs Perl code instead
  650.     of C code!  You can get this from ftp.sterling.com [192.124.9.1] in
  651.     /local/perl-byacc1.8.1.tar.Z, or send the author mail for details.
  652.  
  653.  
  654. 1.19) How can I use curses with perl?
  655.  
  656.     One way is to build a curseperl binary by linking in your C curses
  657.     library as described in the usub subdirectory of the perl sources.
  658.     This requires a modicum of work, but it will be reasonably fast
  659.     since it's all in C (assuming you consider curses reasonably fast. :-)
  660.     Programs written using this method require the modified curseperl,
  661.     not vanilla perl, to run.  While this is something of a disadvantage,
  662.     experience indicates that it's better to use curseperl than to
  663.     try to roll your own using termcap directly.
  664.  
  665.     Another possibility is to use Henk Penning's cterm package, a curses
  666.     emulation library written in perl.  cterm is actually a separate
  667.     program with which you communicate via a pipe.  It is available from
  668.     archive.cs.ruu.nl [131.211.80.5] via anonymous ftp in the directory
  669.     pub/PERL.  You may also acquire the package via email in compressed,
  670.     uuencoded form by sending a message to mail-server@cs.ruu.nl
  671.     containing these lines:
  672.  
  673.         begin
  674.         send PERL/cterm.shar.Z
  675.         end
  676.  
  677.     See the question on retrieving perl via mail for more information on
  678.     how to get retrieve other items of interest from the mail server
  679.     there.
  680.  
  681.  
  682. 1.20) How can I use X with Perl?
  683.  
  684.     Right now, you have several choices.  You can wait for perl5, use
  685.     the WAFE or STDWIN packages, or try to make your own usub bindings.
  686.  
  687.     Perl5 is anticipated to be released with bindings for X, called
  688.     guiperl.  An exciting prototype for this, written by Jon Biggar
  689.     <jon@netlabs.com>, Larry's *other* brother-in-law and officemate,
  690.     is already up and running inside of Netlabs.  This program addresses
  691.     the same dynamic gui-building problem space as does tcl/tk.
  692.  
  693.     If you can't wait or don't think that guiperl will do what you want,
  694.     a stab at Motif bindings was begun by Theodore C. Law
  695.     <TEDLAW@TOROLAB6.VNET.IBM.COM> area.  His article about this is
  696.     on convex.com in /pub/perl/info/motif for anon ftp.
  697.  
  698.     STDWIN is a library written by Guido van Rossum <guido@cwi.nl>
  699.     (author of the Python programming language) that is portable
  700.     between Mac, Dos and X11.  One could write a Perl agent to
  701.     speak to this STDIN server.
  702.  
  703.     WAFE is a package that implements a symbolic interface to the Athena
  704.     widgets (X11R5). A typical Wafe application consists in our framework
  705.     of two parts: the front-end (we call it Wafe for Widget[Athena]front
  706.     end) and an application program running typically as separate process.
  707.     The application program can be implemented in an arbitrary programming
  708.     language and talks to the front-end via stdio.  Since Wafe (the
  709.     front-end) was developed using the extensible TCL shell (cite John
  710.     Ousterhout), an application program can dynamically submit requests to
  711.     the front-end to build up the graphical user interface; the
  712.     application can even down-load application specific procedures into
  713.     the front-end.  The distribution contains sample application programs
  714.     in Perl, GAWK, Prolog, TCL, and C talking to the same Wafe binary.
  715.     Many of the demo applications are implemented in Perl.  Wafe 0.9 can
  716.     be obtained via anonymous ftp from
  717.         ftp.wu-wien.ac.at:pub/src/X11/wafe-0.9.tar.Z
  718.     (for people without name server: the ip address is 137.208.3.5)
  719.  
  720.  
  721. 1.21) What is perl4?  What is perl5?
  722.  
  723.     The answer to what is perl4 is nearly anything you might otherwise
  724.     program in shell or C.  The answer to what is perl5 is basically
  725.     Perl: the Next Generation.  In fact, it's essentially a complete
  726.     rewrite of perl from the bottom up, and back again.
  727.  
  728.     Larry gave a talk on perl5 at a Bay LISA meeting as well as at the
  729.     most recent USENIX LISA conference in Long Beach in which he timorously
  730.     admitted that perl5 might possibly be beta released in early 1993.
  731.     He enumerated some of the following features.  Note that not only have
  732.     not all these been implemented yet, the ones further down the list
  733.     might well not get done at all.
  734.  
  735.         a faster, tighter, more flexible interpreter
  736.         very easy GUI Perl applications using X bindings ("guiperl")
  737.         embeddable Perl code in C code: cc prog.c -lperl
  738.         multiple coresident perl interpreters:
  739.             perhaps threading and/or coroutines
  740.         named argument passing:
  741.             some_func( OC => $red, TOF => "\f");
  742.         recursive lists:
  743.             [a, b, [c, d], e] has 4 elts, the 3rd being itself a list
  744.         typed pointers and generalized indirection:
  745.             like @{$aptr} or &{$fptr} or &{ $table[$index] . "func" }().
  746.         merging of list operator and function calling syntax:
  747.             split /pat/, $string;
  748.         subroutines without &'s:   myfunc($arg);
  749.         generalization of dbm binding for assoc arrays to handle
  750.             any generic fetch/store/open/close/flush package.
  751.             (thus allowing both dbm and gdbm at once)
  752.         object oriented programming:
  753.             STDOUT->flush(1);
  754.             give dog $bone;
  755.         lexical scoping
  756.         dynamic loading of C libraries for systems that can
  757.         byte-compiled code for speed and maybe security
  758.  
  759.     It's tempting to want this stuff soon, since the sooner it comes
  760.     out the sooner we can all build really cool applications.  But the
  761.     longer Larry works on it, the more items from this list will actually
  762.     get done, and the more robust the release will be.  So let's not
  763.     ask him about it too often.
  764.  
  765.  
  766. 1.22) How does Perl compare with languages like REXX or TCL?
  767.  
  768.     REXX is an interpreted programming language first seen on IBM systems,
  769.     and TCL is John Ousterhout's embeddable command language.  TCL's most
  770.     intriguing feature for many people is the tcl/tk toolset that allows
  771.     for interpreted X-based tools.
  772.  
  773.     To avoid any flamage, if you really want to know the answer to this
  774.     question, probably the best thing to do is try to write equivalent
  775.     code to do a set of tasks.  All three have their own newsgroups in
  776.     which you can learn about (but hopefully not argue about) these
  777.     languages.
  778.  
  779.     To find out more about these or other languages, you might also check
  780.     out David Muir Sharnoff <muir@tfs.com>'s posting on "Catalog of
  781.     compilers, interpreters, and other language tools" which he posts to
  782.     comp.lang.misc, comp.sources.d, comp.archives.admin, and the
  783.     news.answers newsgroups.  It's a comprehensive treatment of many
  784.     different languages.  (Caveat lector: he considers Perl's syntax
  785.     "unappealing".)   This list is archived on convex.com in
  786.     /pub/perl/info/lang-survey.shar .
  787.  
  788.  
  789. 1.23) Is it a Perl program or a Perl script?
  790.  
  791.     Certainly. :-)
  792.  
  793.     Current UNIX parlance holds that anything interpreted
  794.     is a script, and anything compiled into native machine
  795.     code is a program.  However, others hold that a program
  796.     is a program is a program: after all, one seldom discusses
  797.     scripts written in BASIC or LISP.  Larry considers it
  798.     a program if it's set in stone and you can't change it,
  799.     whereas if you go in and hack on it, then it's a script.
  800.  
  801.     But doesn't really matter.  The terms are generally
  802.     interchangeable today.
  803.  
  804.  
  805. 1.24) What's the difference between "Perl" and "perl"?
  806.  
  807.      32 :-)  [  ord('p') - ord('P')  ]
  808.  
  809.      Larry now uses "Perl" to signify the language proper and "perl" the
  810.      implementation of it, i.e. the current interpreter.  Hence my quip
  811.      that "Nothing but perl can parse Perl."
  812.  
  813.      On the other hand, the aesthetic value of casewise parallelism
  814.      in "awk", "sed", and "perl" as much require the lower-case
  815.      version as "C", "Pascal", and "Perl" require the
  816.      upper-case version.  It's also easier to type "Perl" in
  817.      typeset print than to be constantly switching in Courier. :-)
  818.  
  819.      In other words, it doesn't matter much, especially if all
  820.      you're doing is hearing someone talk about the language;
  821.      case is hard to distingish aurally.
  822.  
  823.  
  824. 1.25) What companies use or ship Perl?
  825.  
  826.     At this time, the known list includes at least the following: Convex,
  827.     Netlabs, BSDI, Integraph, Dell, and Kubota Pacific, although the
  828.     latter is in /usr/contrib only.  Many other companies use Perl
  829.     internally for purposes of tools development, systems administration,
  830.     installation scripts, and test suites.  Rumor has it that the large
  831.     workstation vendors (the TLA set) are seriously looking into shipping
  832.     Perl with their standard systems "soon".
  833.  
  834.     People with support contracts with their vendors are actively
  835.     encouraged to submit enhancement requests that Perl be shipped
  836.     as part of their standard system.  It would, at the very least,
  837.     reduce the FTP load on the Internet. :-)
  838.  
  839. 1.26) Is there commercial, 3rd-party support for Perl?
  840.  
  841.     No.  Although perl is included in the GNU distribution, at last check,
  842.     Cygnus does not offer support for it.  However, it's unclear whether
  843.     they've ever been offered sufficient financial incentive to do so.
  844.  
  845.     On the other hand, you do have comp.lang.perl as a totally gratis
  846.     support mechanism.  As long as you ask "interesting" questions,
  847.     you'll probably get plenty of help. :-)
  848.  
  849. 1.27) Where can I get a list of the JAPH signature quotes?
  850.  
  851.     These are the "just another perl hacker" signatures that
  852.     some people sign their postings with.  About 100 of the
  853.     of the earlier ones are on convex.com in /pib/perl/info/japh.
  854.  
  855. 1.28) Where can I get a list of Larry Wall witticisms?
  856.  
  857.     Over a hundred quips by Larry, from postings of his or source code,
  858.     can be found on convex.com in /pub/perl/info/lwall-quotes.
  859.  
  860.  
  861.  
  862.  
  863. 2.1) What are all these $@*%<> signs and how do I know when to use them?
  864.  
  865.     Those are type specifiers: $ for scalar values, @ for indexed arrays,
  866.     and % for hashed arrays.  The * means all types of that symbol name
  867.     and are sometimes used like pointers; the <> are used for inputting
  868.     a record from a filehandle.  See the question on arrays of arrays
  869.     for more about Perl pointers.
  870.  
  871.     Always make sure to use a $ for single values and @ for multiple ones.
  872.     Thus element 2 of the @foo array is accessed as $foo[2], not @foo[2],
  873.     which is a list of length one (not a scalar), and is a fairly common
  874.     novice mistake.  Sometimes you can get by with @foo[2], but it's
  875.     not really doing what you think it's doing for the reason you think
  876.     it's doing it, which means one of these days, you'll shoot yourself
  877.     in the foot; ponder for a moment what these will really do:
  878.         @foo[0] = `cmd args`;
  879.         @foo[2] = <FILE>;
  880.     Just always say $foo[2] and you'll be happier.
  881.  
  882.     This may seem confusing, but try to think of it this way:  you use the
  883.     character of the type which you *want back*.  You could use @foo[1..3] for
  884.     a slice of three elements of @foo, or even @foo{A,B,C} for a slice of
  885.     of %foo.  This is the same as using ($foo[1], $foo[2], $foo[3]) and
  886.     ($foo{A}, $foo{B}, $foo{C}) respectively.  In fact, you can even use
  887.     lists to subscript arrays and pull out more lists, like @foo[@bar] or
  888.     @foo{@bar}, where @bar is in both cases presumably a list of subscripts.
  889.  
  890.     While there are a few places where you don't actually need these type
  891.     specifiers, except for files, you should always use them.  Note that
  892.     <FILE> is NOT the type specifier for files; it's the equivalent of awk's
  893.     getline function, that is, it reads a line from the handle FILE.  When
  894.     doing open, close, and other operations besides the getline function on
  895.     files, do NOT use the brackets.
  896.  
  897.     Beware of saying:
  898.         $foo = BAR;
  899.     Which wil be interpreted as
  900.         $foo = 'BAR';
  901.     and not as
  902.         $foo = <BAR>;
  903.     If you always quote your strings, you'll avoid this trap.
  904.  
  905.     Normally, files are manipulated something like this (with appropriate
  906.     error checking added if it were production code):
  907.  
  908.         open (FILE, ">/tmp/foo.$$");
  909.         print FILE "string\n";
  910.         close FILE;
  911.  
  912.     If instead of a filehandle, you use a normal scalar variable with file
  913.     manipulation functions, this is considered an indirect reference to a
  914.     filehandle.  For example,
  915.  
  916.         $foo = "TEST01";
  917.         open($foo, "file");
  918.  
  919.     After the open, these two while loops are equivalent:
  920.  
  921.         while (<$foo>) {}
  922.         while (<TEST01>) {}
  923.  
  924.     as are these two statements:
  925.  
  926.         close $foo;
  927.         close TEST01;
  928.  
  929.     but NOT to this:
  930.  
  931.         while (<$TEST01>) {} # error
  932.                 ^
  933.                 ^ note spurious dollar sign
  934.  
  935.     This is another common novice mistake; often it's assumed that
  936.  
  937.         open($foo, "output.$$");
  938.  
  939.     will fill in the value of $foo, which was previously undefined.
  940.     This just isn't so -- you must set $foo to be the name of a valid
  941.     filehandle before you attempt to open it.
  942.  
  943.  
  944. 2.2) Why don't backticks work as they do in shells?
  945.  
  946.     Several reason.  One is because backticks do not interpolate within
  947.     double quotes in Perl as they do in shells.
  948.  
  949.     Let's look at two common mistakes:
  950.  
  951.          $foo = "$bar is `wc $file`";  # WRONG
  952.  
  953.     This should have been:
  954.  
  955.          $foo = "$bar is " . `wc $file`;
  956.  
  957.     But you'll have an extra newline you might not expect.  This
  958.     does not work as expected:
  959.  
  960.       $back = `pwd`; chdir($somewhere); chdir($back); # WRONG
  961.  
  962.     Because backticks do not automatically eat trailing or embedded
  963.     newlines.  The chop() function will remove the last character from
  964.     a string.  This should have been:
  965.  
  966.           chop($back = `pwd`); chdir($somewhere); chdir($back);
  967.  
  968.     You should also be aware that while in the shells, embedding
  969.     single quotes will protect variables, in Perl, you'll need
  970.     to escape the dollar signs.
  971.  
  972.         Shell: foo=`cmd 'safe $dollar'`
  973.         Perl:  $foo=`cmd 'safe \$dollar'`;
  974.  
  975.  
  976. 2.3) How come Perl operators have different precedence than C operators?
  977.  
  978.     Actually, they don't; all C operators have the same precedence in Perl as
  979.     they do in C.  The problem is with a class of functions called list
  980.     operators, e.g. print, chdir, exec, system, and so on.  These are somewhat
  981.     bizarre in that they have different precedence depending on whether you
  982.     look on the left or right of them.  Basically, they gobble up all things
  983.     on their right.  For example,
  984.  
  985.         unlink $foo, "bar", @names, "others";
  986.  
  987.     will unlink all those file names.  A common mistake is to write:
  988.  
  989.         unlink "a_file" || die "snafu";
  990.  
  991.     The problem is that this gets interpreted as
  992.  
  993.         unlink("a_file" || die "snafu");
  994.  
  995.     To avoid this problem, you can always make them look like function calls
  996.     or use an extra level of parentheses:
  997.  
  998.         (unlink "a_file") || die "snafu";
  999.         unlink("a_file")  || die "snafu";
  1000.  
  1001.     Sometimes you actually do care about the return value:
  1002.  
  1003.         unless ($io_ok = print("some", "list")) { }
  1004.  
  1005.     Yes, print() return I/O success.  That means
  1006.  
  1007.         $io_ok = print(2+4) * 5;
  1008.  
  1009.     reutrns 5 times whether printing (2+4) succeeded, and
  1010.         print(2+4) * 5;
  1011.     returns the same 5*io_success value and tosses it.
  1012.  
  1013.     See the Perl man page's section on Precedence for more gory details,
  1014.     and be sure to use the -w flag to catch things like this.
  1015.  
  1016.  
  1017. 2.4) How come my converted awk/sed/sh script runs more slowly in Perl?
  1018.  
  1019.     The natural way to program in those languages may not make for the fastest
  1020.     Perl code.  Notably, the awk-to-perl translator produces sub-optimal code;
  1021.     see the a2p man page for tweaks you can make.
  1022.  
  1023.     Two of Perl's strongest points are its associative arrays and its regular
  1024.     expressions.  They can dramatically speed up your code when applied
  1025.     properly.  Recasting your code to use them can help alot.
  1026.  
  1027.     How complex are your regexps?  Deeply nested sub-expressions with {n,m} or
  1028.     * operators can take a very long time to compute.  Don't use ()'s unless
  1029.     you really need them.  Anchor your string to the front if you can.
  1030.  
  1031.     Something like this:
  1032.         next unless /^.*%.*$/;
  1033.     runs more slowly than the equivalent:
  1034.         next unless /%/;
  1035.  
  1036.     Note that this:
  1037.         next if /Mon/;
  1038.         next if /Tue/;
  1039.         next if /Wed/;
  1040.         next if /Thu/;
  1041.         next if /Fri/;
  1042.     runs faster than this:
  1043.         next if /Mon/ || /Tue/ || /Wed/ || /Thu/ || /Fri/;
  1044.     which in turn runs faster than this:
  1045.         next if /Mon|Tue|Wed|Thu|Fri/;
  1046.     which runs *much* faster than:
  1047.         next if /(Mon|Tue|Wed|Thu|Fri)/;
  1048.  
  1049.     There's no need to use /^.*foo.*$/ when /foo/ will do.
  1050.  
  1051.     Remember that a printf costs more than a simple print.
  1052.  
  1053.     Don't split() every line if you don't have to.
  1054.  
  1055.     Another thing to look at is your loops.  Are you iterating through
  1056.     indexed arrays rather than just putting everything into a hashed
  1057.     array?  For example,
  1058.  
  1059.         @list = ('abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stv');
  1060.  
  1061.         for $i ($[ .. $#list) {
  1062.             if ($pattern eq $list[$i]) { $found++; }
  1063.         }
  1064.  
  1065.     First of all, it would be faster to use Perl's foreach mechanism
  1066.     instead of using subscripts:
  1067.  
  1068.         foreach $elt (@list) {
  1069.             if ($pattern eq $elt) { $found++; }
  1070.         }
  1071.  
  1072.     Better yet, this could be sped up dramatically by placing the whole
  1073.     thing in an associative array like this:
  1074.  
  1075.         %list = ('abc', 1, 'def', 1, 'ghi', 1, 'jkl', 1,
  1076.                  'mno', 1, 'pqr', 1, 'stv', 1 );
  1077.         $found += $list{$pattern};
  1078.  
  1079.     (but put the %list assignment outside of your input loop.)
  1080.  
  1081.     You should also look at variables in regular expressions, which is
  1082.     expensive.  If the variable to be interpolated doesn't change over the
  1083.     life of the process, use the /o modifier to tell Perl to compile the
  1084.     regexp only once, like this:
  1085.  
  1086.         for $i (1..100) {
  1087.             if (/$foo/o) {
  1088.                 &some_func($i);
  1089.             }
  1090.         }
  1091.  
  1092.     Finally, if you have a bunch of patterns in a list that you'd like to
  1093.     compare against, instead of doing this:
  1094.  
  1095.         @pats = ('_get.*', 'bogus', '_read', '.*exit', '_write');
  1096.         foreach $pat (@pats) {
  1097.             if ( $name =~ /^$pat$/ ) {
  1098.                 &some_func();
  1099.                 last;
  1100.             }
  1101.         }
  1102.  
  1103.     If you build your code and then eval it, it will be much faster.
  1104.     For example:
  1105.  
  1106.         @pats = ('_get.*', 'bogus', '_read', '.*exit', '_write');
  1107.         $code = <<EOS
  1108.                 while () {
  1109.                     study;
  1110. EOS
  1111.         foreach $pat (@pats) {
  1112.             $code .= <<EOS
  1113.                 if ( /^$pat\$/ ) {
  1114.                     &some_func();
  1115.                     next;
  1116.                 }
  1117. EOS
  1118.         }
  1119.         $code .= "}\n";
  1120.         print $code if $debugging;
  1121.         eval $code;
  1122.  
  1123.  
  1124.  
  1125. 2.5) How can I call my system's unique C functions from Perl?
  1126.  
  1127.     If these are system calls and you have the syscall() function, then
  1128.     you're probably in luck -- see the next question.  For arbitrary
  1129.     library functions, it's not quite so straight-forward.  While you
  1130.     can't have a C main and link in Perl routines, if you're
  1131.     determined, you can extend Perl by linking in your own C routines.
  1132.     See the usub/ subdirectory in the Perl distribution kit for an example
  1133.     of doing this to build a Perl that understands curses functions.  It's
  1134.     neither particularly easy nor overly-documented, but it is feasible.
  1135.  
  1136.  
  1137. 2.6) Where do I get the include files to do ioctl() or syscall()?
  1138.  
  1139.     These are generated from your system's C include files using the h2ph
  1140.     script (once called makelib) from the Perl source directory.  This will
  1141.     make files containing subroutine definitions, like &SYS_getitimer, which
  1142.     you can use as arguments to your function.
  1143.  
  1144.     You might also look at the h2pl subdirectory in the Perl source for how to
  1145.     convert these to forms like $SYS_getitimer; there are both advantages and
  1146.     disadvantages to this.  Read the notes in that directory for details.
  1147.  
  1148.     In both cases, you may well have to fiddle with it to make these work; it
  1149.     depends how funny-looking your system's C include files happen to be.
  1150.  
  1151.     If you're trying to get at C structures, then you should take a look
  1152.     at using c2ph, which uses debugger "stab" entries generated by your
  1153.     BSD or GNU C compiler to produce machine-independent perl definitions
  1154.     for the data structures.  This allows to you avoid hardcoding
  1155.     structure layouts, types, padding, or sizes, greatly enhancing
  1156.     portability.  c2ph comes with the perl distribution.  On an SCO
  1157.     system, GCC only has COFF debugging support by default, so you'll have
  1158.     to build GCC 2.1 with DBX_DEBUGGING_INFO defined, and use -gstabs to
  1159.     get c2ph to work there.
  1160.  
  1161.     See the file /pub/perl/info/ch2ph on convex.com via anon ftp
  1162.     for more traps and tips on this process.
  1163.  
  1164.  
  1165. 2.7) Why doesn't "local($foo) = <FILE>;" work right?
  1166.  
  1167.     Well, it does.  The thing to remember is that local() provides an array
  1168.     context, an that the <FILE> syntax in an array context will read all the
  1169.     lines in a file.  To work around this, use:
  1170.  
  1171.         local($foo);
  1172.         $foo = <FILE>;
  1173.  
  1174.     You can use the scalar() operator to cast the expression into a scalar
  1175.     context:
  1176.  
  1177.         local($foo) = scalar(<FILE>);
  1178.  
  1179.  
  1180. 2.8) How can I detect keyboard input without reading it?
  1181.  
  1182.     You should check out the Frequently Asked Questions list in
  1183.     comp.unix.* for things like this: the answer is essentially the same.
  1184.     It's very system dependent.  Here's one solution that works on BSD
  1185.     systems:
  1186.  
  1187.         sub key_ready {
  1188.             local($rin, $nfd);
  1189.             vec($rin, fileno(STDIN), 1) = 1;
  1190.             return $nfd = select($rin,undef,undef,0);
  1191.         }
  1192.  
  1193.     A closely related question is how to input a single character from the
  1194.     keyboard.  Again, this is a system dependent operation.  The following
  1195.     code that may or may not help you:
  1196.  
  1197.         $BSD = -f '/vmunix';
  1198.         if ($BSD) {
  1199.             system "stty cbreak </dev/tty >/dev/tty 2>&1";
  1200.         }
  1201.         else {
  1202.             system "stty", 'cbreak',
  1203.             system "stty", 'eol', "\001";
  1204.         }
  1205.  
  1206.         $key = getc(STDIN);
  1207.  
  1208.         if ($BSD) {
  1209.             system "stty -cbreak </dev/tty >/dev/tty 2>&1";
  1210.         }
  1211.         else {
  1212.             system "stty", 'icanon';
  1213.             system "stty", 'eol', '^@'; # ascii null
  1214.         }
  1215.         print "\n";
  1216.  
  1217.     You could also handle the stty operations yourself for speed if you're
  1218.     going to be doing a lot of them.  This code works to toggle cbreak
  1219.     and echo modes on a BSD system:
  1220.  
  1221.     sub set_cbreak { # &set_cbreak(1) or &set_cbreak(0)
  1222.         local($on) = $_[0];
  1223.         local($sgttyb,@ary);
  1224.         require 'sys/ioctl.ph';
  1225.         $sgttyb_t   = 'C4 S' unless $sgttyb_t;  # c2ph: &sgttyb'typedef()
  1226.  
  1227.         ioctl(STDIN,&TIOCGETP,$sgttyb) || die "Can't ioctl TIOCGETP: $!";
  1228.  
  1229.         @ary = unpack($sgttyb_t,$sgttyb);
  1230.         if ($on) {
  1231.             $ary[4] |= &CBREAK;
  1232.             $ary[4] &= ~&ECHO;
  1233.         } else {
  1234.             $ary[4] &= ~&CBREAK;
  1235.             $ary[4] |= &ECHO;
  1236.         }
  1237.         $sgttyb = pack($sgttyb_t,@ary);
  1238.  
  1239.         ioctl(STDIN,&TIOCSETP,$sgttyb) || die "Can't ioctl TIOCSETP: $!";
  1240.     }
  1241.  
  1242.     Note that this is one of the few times you actually want to use the
  1243.     getc() function; it's in general way too expensive to call for normal
  1244.     I/O.  Normally, you just use the <FILE> syntax, or perhaps the read()
  1245.     or sysread() functions.
  1246.  
  1247.     For perspectives on more portable solutions, use anon ftp to retrieve
  1248.     the file /pub/perl/info/keypress from convex.com.
  1249.  
  1250.  
  1251. 2.9) How can I make an array of arrays or other recursive data types?
  1252.  
  1253.     Remember that Perl isn't about nested data structures (actually,
  1254.     perl0 ..  perl4 weren't, but maybe perl5 will be, at least
  1255.     somewhat).  It's about flat ones, so if you're trying to do this, you
  1256.     may be going about it the wrong way or using the wrong tools.  You
  1257.     might try parallel arrays with common subscripts.
  1258.  
  1259.     But if you're bound and determined, you can use the multi-dimensional
  1260.     array emulation of $a{'x','y','z'}, or you can make an array of names
  1261.     of arrays and eval it.
  1262.  
  1263.     For example, if @name contains a list of names of arrays, you can
  1264.     get at a the j-th element of the i-th array like so:
  1265.  
  1266.         $ary = $name[$i];
  1267.         $val = eval "\$$ary[$j]";
  1268.  
  1269.     or in one line
  1270.  
  1271.         $val = eval "\$$name[$i][\$j]";
  1272.  
  1273.     You could also use the type-globbing syntax to make an array of *name
  1274.     values, which will be more efficient than eval.  Here @name hold
  1275.     a list of pointers, which we'll have to dereference through a temporary
  1276.     variable.
  1277.  
  1278.     For example:
  1279.  
  1280.         { local(*ary) = $name[$i]; $val = $ary[$j]; }
  1281.  
  1282.     In fact, you can use this method to make arbitrarily nested data
  1283.     structures.  You really have to want to do this kind of thing
  1284.     badly to go this far, however, as it is notationally cumbersome.
  1285.  
  1286.     Let's assume you just simply *have* to have an array of arrays of
  1287.     arrays.  What you do is make an array of pointers to arrays of
  1288.     pointers, where pointers are *name values described above.  You
  1289.     initialize the outermost array normally, and then you build up your
  1290.     pointers from there.  For example:
  1291.  
  1292.         @w = ( 'ww' .. 'xx' );
  1293.         @x = ( 'xx' .. 'yy' );
  1294.         @y = ( 'yy' .. 'zz' );
  1295.         @z = ( 'zz' .. 'zzz' );
  1296.  
  1297.         @ww = reverse @w;
  1298.         @xx = reverse @x;
  1299.         @yy = reverse @y;
  1300.         @zz = reverse @z;
  1301.  
  1302.     Now make a couple of array of pointers to these:
  1303.  
  1304.         @A = ( *w, *x, *y, *z );
  1305.         @B = ( *ww, *xx, *yy, *zz );
  1306.  
  1307.     And finally make an array of pointers to these arrays:
  1308.  
  1309.         @AAA = ( *A, *B );
  1310.  
  1311.     To access an element, such as AAA[i][j][k], you must do this:
  1312.  
  1313.         local(*foo) = $AAA[$i];
  1314.         local(*bar) = $foo[$j];
  1315.         $answer = $bar[$k];
  1316.  
  1317.     Similar manipulations on associative arrays are also feasible.
  1318.  
  1319.     You could take a look at recurse.pl package posted by Felix Lee
  1320.     <flee@cs.psu.edu>, which lets you simulate vectors and tables (lists and
  1321.     associative arrays) by using type glob references and some pretty serious
  1322.     wizardry.
  1323.  
  1324.     In C, you're used to creating recursive datatypes for operations
  1325.     like recursive decent parsing or tree traversal.  In Perl, these
  1326.     algorithms are best implemented using associative arrays.  Take an
  1327.     array called %parent, and build up pointers such that $parent{$person}
  1328.     is the name of that person's parent.  Make sure you remember that
  1329.     $parent{'adam'} is 'adam'. :-) With a little care, this approach can
  1330.     be used to implement general graph traversal algorithms as well.
  1331.  
  1332.  
  1333. 2.10) How can I quote a variable to use in a regexp?
  1334.  
  1335.     From the manual:
  1336.  
  1337.         $pattern =~ s/(\W)/\\$1/g;
  1338.  
  1339.     Now you can freely use /$pattern/ without fear of any unexpected
  1340.     meta-characters in it throwing off the search.  If you don't know
  1341.     whether a pattern is valid or not, enclose it in an eval to avoid
  1342.     a fatal run-time error.
  1343.  
  1344.  
  1345. 2.11) Why do setuid Perl scripts complain about kernel problems?
  1346.  
  1347.     This message:
  1348.  
  1349.     YOU HAVEN'T DISABLED SET-ID SCRIPTS IN THE KERNEL YET!
  1350.     FIX YOUR KERNEL, PUT A C WRAPPER AROUND THIS SCRIPT, OR USE -u AND UNDUMP!
  1351.  
  1352.     is triggered because setuid scripts are inherently insecure due to a
  1353.     kernel bug.  If your system has fixed this bug, you can compile Perl
  1354.     so that it knows this.  Otherwise, create a setuid C program that just
  1355.     execs Perl with the full name of the script.
  1356.  
  1357.  
  1358. 2.12) How do I open a pipe both to and from a command?
  1359.  
  1360.     In general, this is a dangerous move because you can find yourself in a
  1361.     deadlock situation.  It's better to put one end of the pipe to a file.
  1362.     For example:
  1363.  
  1364.         # first write some_cmd's input into a_file, then
  1365.         open(CMD, "some_cmd its_args < a_file |");
  1366.         while (<CMD>) {
  1367.  
  1368.         # or else the other way; run the cmd
  1369.         open(CMD, "| some_cmd its_args > a_file");
  1370.         while ($condition) {
  1371.             print CMD "some output\n";
  1372.             # other code deleted
  1373.         }
  1374.         close CMD || warn "cmd exited $?";
  1375.  
  1376.         # now read the file
  1377.         open(FILE,"a_file");
  1378.         while (<FILE>) {
  1379.  
  1380.     If you have ptys, you could arrange to run the command on a pty and
  1381.     avoid the deadlock problem.  See the chat2.pl package in the
  1382.     distributed library for ways to do this.
  1383.  
  1384.     At the risk of deadlock, it is theoretically possible to use a
  1385.     fork, two pipe calls, and an exec to manually set up the two-way
  1386.     pipe.  (BSD system may use socketpair() in place of the two pipes,
  1387.     but this is not as portable.)  The open2 library function distributed
  1388.     with the current perl release will do this for you.
  1389.  
  1390.     It assumes it's going to talk to something like adb, both writing to
  1391.     it and reading from it.  This is presumably safe because you "know"
  1392.     that commands like adb will read a line at a time and output a line at
  1393.     a time.  Programs like sort that read their entire input stream first,
  1394.     however, are quite apt to cause deadlock.
  1395.  
  1396.  
  1397. 2.13) How can I change the first N letters of a string?
  1398.  
  1399.     Remember that the substr() function produces an lvalue, that is, it may be
  1400.     assigned to.  Therefore, to change the first character to an S, you could
  1401.     do this:
  1402.  
  1403.         substr($var,0,1) = 'S';
  1404.  
  1405.     This assumes that $[ is 0;  for a library routine where you can't know $[,
  1406.     you should use this instead:
  1407.  
  1408.         substr($var,$[,1) = 'S';
  1409.  
  1410.     While it would be slower, you could in this case use a substitute:
  1411.  
  1412.         $var =~ s/^./S/;
  1413.  
  1414.     But this won't work if the string is empty or its first character is a
  1415.     newline, which "." will never match.  So you could use this instead:
  1416.  
  1417.         $var =~ s/^[^\0]?/S/;
  1418.  
  1419.     To do things like translation of the first part of a string, use substr,
  1420.     as in:
  1421.  
  1422.         substr($var, $[, 10) =~ tr/a-z/A-Z/;
  1423.  
  1424.     If you don't know then length of what to translate, something like
  1425.     this works:
  1426.  
  1427.         /^(\S+)/ && substr($_,$[,length($1)) =~ tr/a-z/A-Z/;
  1428.  
  1429.     For some things it's convenient to use the /e switch of the
  1430.     substitute operator:
  1431.  
  1432.         s/^(\S+)/($tmp = $1) =~ tr#a-z#A-Z#, $tmp/e
  1433.  
  1434.     although in this case, it runs more slowly than does the previous example.
  1435.  
  1436.  
  1437. 2.14) How can I manipulate fixed-record-length files?
  1438.  
  1439.     The most efficient way is using pack and unpack.  This is faster than
  1440.     using substr.  Here is a sample chunk of code to break up and put back
  1441.     together again some fixed-format input lines, in this case, from ps.
  1442.  
  1443.         # sample input line:
  1444.         #   15158 p5  T      0:00 perl /mnt/tchrist/scripts/now-what
  1445.         $ps_t = 'A6 A4 A7 A5 A*';
  1446.         open(PS, "ps|");
  1447.         $_ = <PS>; print;
  1448.         while (<PS>) {
  1449.             ($pid, $tt, $stat, $time, $command) = unpack($ps_t, $_);
  1450.             for $var ('pid', 'tt', 'stat', 'time', 'command' ) {
  1451.                 print "$var: <", eval "\$$var", ">\n";
  1452.             }
  1453.             print 'line=', pack($ps_t, $pid, $tt, $stat, $time, $command),  "\n"
  1454. ;
  1455.         }
  1456.  
  1457.  
  1458. 2.15) How can I make a file handle local to a subroutine?
  1459.  
  1460.     You must use the type-globbing *VAR notation.  Here is some code to
  1461.     cat an include file, calling itself recursively on nested local
  1462.     include files (i.e. those with #include "file", not #include <file>):
  1463.  
  1464.         sub cat_include {
  1465.             local($name) = @_;
  1466.             local(*FILE);
  1467.             local($_);
  1468.  
  1469.             warn "<INCLUDING $name>\n";
  1470.             if (!open (FILE, $name)) {
  1471.                 warn "can't open $name: $!\n";
  1472.                 return;
  1473.             }
  1474.             while (<FILE>) {
  1475.                 if (/^#\s*include "([^"]*)"/) {
  1476.                     &cat_include($1);
  1477.                 } else {
  1478.                     print;
  1479.                 }
  1480.             }
  1481.             close FILE;
  1482.         }
  1483.  
  1484.  
  1485. 2.16) How can I extract just the unique elements of an array?
  1486.  
  1487.     There are several possible ways, depending on whether the
  1488.     array is ordered and you wish to preserve the ordering.
  1489.  
  1490.     a) If @in is sorted, and you want @out to be sorted:
  1491.  
  1492.         $prev = 'nonesuch';
  1493.         @out = grep($_ ne $prev && (($prev) = $_), @in);
  1494.  
  1495.        This is nice in that it doesn't use much extra memory,
  1496.        simulating uniq's behavior of removing only adjacent
  1497.        duplicates.
  1498.  
  1499.     b) If you don't know whether @in is sorted:
  1500.  
  1501.         undef %saw;
  1502.         @out = grep(!$saw{$_}++, @in);
  1503.  
  1504.     c) Like (b), but @in contains only small integers:
  1505.  
  1506.         @out = grep(!$saw[$_]++, @in);
  1507.  
  1508.     d) A way to do (b) without any loops or greps:
  1509.  
  1510.         undef %saw;
  1511.         @saw{@in} = ();
  1512.         @out = sort keys %saw;  # remove sort if undesired
  1513.  
  1514.     e) Like (d), but @in contains only small positive integers:
  1515.  
  1516.         undef @ary;
  1517.         @ary[@in] = @in;
  1518.         @out = sort @ary;
  1519.  
  1520.  
  1521. 2.17) How can I call alarm() or usleep() from Perl?
  1522.  
  1523.     It's available as a built-in as of version 3.038.  If you want finer
  1524.     granularity than 1 second (as usleep() provides) and have itimers and
  1525.     syscall() on your system, you can use the following.  You could also
  1526.     use select().
  1527.  
  1528.     It takes a floating-point number representing how long to delay until
  1529.     you get the SIGALRM, and returns a floating- point number representing
  1530.     how much time was left in the old timer, if any.  Note that the C
  1531.     function uses integers, but this one doesn't mind fractional numbers.
  1532.  
  1533.     # alarm; send me a SIGALRM in this many seconds (fractions ok)
  1534.     # tom christiansen <tchrist@convex.com>
  1535.     sub alarm {
  1536.         require 'syscall.ph';
  1537.         require 'sys/time.ph';
  1538.  
  1539.         local($ticks) = @_;
  1540.         local($in_timer,$out_timer);
  1541.         local($isecs, $iusecs, $secs, $usecs);
  1542.  
  1543.         local($itimer_t) = 'L4'; # should be &itimer'typedef()
  1544.  
  1545.         $secs = int($ticks);
  1546.         $usecs = ($ticks - $secs) * 1e6;
  1547.  
  1548.         $out_timer = pack($itimer_t,0,0,0,0);
  1549.         $in_timer  = pack($itimer_t,0,0,$secs,$usecs);
  1550.  
  1551.         syscall(&SYS_setitimer, &ITIMER_REAL, $in_timer, $out_timer)
  1552.             && die "alarm: setitimer syscall failed: $!";
  1553.  
  1554.         ($isecs, $iusecs, $secs, $usecs) = unpack($itimer_t,$out_timer);
  1555.         return $secs + ($usecs/1e6);
  1556.     }
  1557.  
  1558.  
  1559. 2.18) How can I test whether an array contains a certain element?
  1560.  
  1561.     There are several ways to approach this.  If you are going to make
  1562.     this query many times and the values are arbitrary strings, the
  1563.     fastest way is probably to invert the original array and keep an
  1564.     associative array lying about whose keys are the first array's values.
  1565.  
  1566.         @blues = ('turquoise', 'teal', 'lapis lazuli');
  1567.         undef %is_blue;
  1568.         for (@blues) { $is_blue{$_} = 1; }
  1569.  
  1570.     Now you can check whether $is_blue{$some_color}.  It might have been
  1571.     a good idea to keep the blues all in an assoc array in the first place.
  1572.  
  1573.     If the values are all small integers, you could use a simple
  1574.     indexed array.  This kind of an array will take up less space:
  1575.  
  1576.         @primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31);
  1577.         undef @is_tiny_prime;
  1578.         for (@primes) { $is_tiny_prime[$_] = 1; }
  1579.  
  1580.     Now you check whether $is_tiny_prime[$some_number].
  1581.  
  1582.     If the values in question are integers, but instead of strings,
  1583.     you can save quite a lot of space by using bit strings instead:
  1584.  
  1585.         @articles = ( 1..10, 150..2000, 2017 );
  1586.         undef $read;
  1587.         grep (vec($read,$_,1) = 1, @articles);
  1588.  
  1589.     Now check whether vec($read,$n,1) is true for some $n.
  1590.  
  1591.  
  1592. 2.19) How can I do an atexit() or setjmp()/longjmp() in Perl?
  1593.  
  1594.     Perl's exception-handling mechanism is its eval operator.  You
  1595.     can use eval as setjmp and die as longjmp.  Here's an example
  1596.     of Larry's for timed-out input, which in C is often implemented
  1597.     using setjmp and longjmp:
  1598.  
  1599.           $SIG{ALRM} = TIMEOUT;
  1600.           sub TIMEOUT { die "restart input\n" }
  1601.  
  1602.           do { eval { &realcode } } while $@ =~ /^restart input/;
  1603.  
  1604.           sub realcode {
  1605.               alarm 15;
  1606.               $ans = <STDIN>;
  1607.               alarm 0;
  1608.           }
  1609.  
  1610.    Here's an example of Tom's for doing atexit() handling:
  1611.  
  1612.         sub atexit { push(@_exit_subs, @_) }
  1613.  
  1614.         sub _cleanup { unlink $tmp }
  1615.  
  1616.         &atexit('_cleanup');
  1617.  
  1618.         eval <<'End_Of_Eval';  $here = __LINE__;
  1619.         # as much code here as you want
  1620.         End_Of_Eval
  1621.  
  1622.         $oops = $@;  # save error message
  1623.  
  1624.         # now call his stuff
  1625.         for (@_exit_subs) { &$_() }
  1626.  
  1627.         $oops && ($oops =~ s/\(eval\) line (\d+)/$0 .
  1628.             " line " . ($1+$here)/e, die $oops);
  1629.  
  1630.     You can register your own routines via the &atexit function now.  You
  1631.     might also want to use the &realcode method of Larry's rather than
  1632.     embedding all your code in the here-is document.  Make sure to leave
  1633.     via die rather than exit, or write your own &exit routine and call
  1634.     that instead.   In general, it's better for nested routines to exit
  1635.     via die rather than exit for just this reason.
  1636.  
  1637.     Eval is also quite useful for testing for system dependent features,
  1638.     like symlinks, or using a user-input regexp that might otherwise
  1639.     blowup on you.
  1640.  
  1641.  
  1642. 2.20) Why doesn't Perl interpret my octal data octally?
  1643.  
  1644.     Perl only understands octal and hex numbers as such when they occur
  1645.     as constants in your program.  If they are read in from somewhere
  1646.     and assigned, then no automatic conversion takes place.  You must
  1647.     explicitly use oct() or hex() if you want this kind of thing to happen.
  1648.     Actually, oct() knows to interpret both hex and octal numbers, while
  1649.     hex only converts hexadecimal ones.  For example:
  1650.  
  1651.         {
  1652.             print "What mode would you like? ";
  1653.             $mode = <STDIN>;
  1654.             $mode = oct($mode);
  1655.             unless ($mode) {
  1656.                 print "You can't really want mode 0!\n";
  1657.                 redo;
  1658.             }
  1659.             chmod $mode, $file;
  1660.         }
  1661.  
  1662.     Without the octal conversion, a requested mode of 755 would turn
  1663.     into 01363, yielding bizarre file permissions of --wxrw--wt.
  1664.  
  1665.     If you want something that handles decimal, octal and hex input,
  1666.     you could follow the suggestion in the man page and use:
  1667.  
  1668.         $val = oct($val) if $val =~ /^0/;
  1669.  
  1670. 2.21) How do I sort an associative array by value instead of by key?
  1671.  
  1672.     You have to declare a sort subroutine to do this.  Let's assume
  1673.     you want an ASCII sort on the values of the associative array %ary.
  1674.     You could do so this way:
  1675.  
  1676.         foreach $key (sort by_value keys %ary) {
  1677.             print $key, '=', $ary{$key}, "\n";
  1678.         }
  1679.         sub by_value { $ary{$a} cmp $ary{$b}; }
  1680.  
  1681.     If you wanted a descending numeric sort, you could do this:
  1682.  
  1683.         sub by_value { $ary{$b} <=> $ary{$a}; }
  1684.  
  1685.     You can also inline your sort function, like this:
  1686.  
  1687.         foreach $key ( sort { $x{$b} <=> $a{$a} } keys %ary ) {
  1688.             print $key, '=', $ary{$key}, "\n";
  1689.         }
  1690.  
  1691.     If you wanted a function that didn't have the array name hard-wired
  1692.     into it, you could so this:
  1693.  
  1694.         foreach $key (&sort_by_value(*ary)) {
  1695.             print $key, '=', $ary{$key}, "\n";
  1696.         }
  1697.         sub sort_by_value {
  1698.             local(*x) = @_;
  1699.             sub _by_value { $x{$a} cmp $x{$b}; }
  1700.             sort _by_value keys %x;
  1701.         }
  1702.  
  1703.     If you want neither an alphabetic nor a numeric sort, then you'll
  1704.     have to code in your own logic instead of relying on the built-in
  1705.     signed comparison operators "cmp" and "<=>".
  1706.  
  1707.     Note that if you're sorting on just a part of the value, such as a
  1708.     piece you might extract via split, unpack, pattern-matching, or
  1709.     substr, then rather than performing that operation inside your sort
  1710.     routine on each call to it, it is significantly more efficient to
  1711.     build a parallel array of just those portions you're sorting on, sort
  1712.     the indices of this parallel array, and then to subscript your original
  1713.     array using the newly sorted indices.  This method works on both
  1714.     regular and associative arrays, since both @ary[@idx] and @ary{@idx}
  1715.     make sense.  See page 245 in the Camel Book on "Sorting an Array by a
  1716.     Computable Field" for a simple example of this.
  1717.  
  1718.  
  1719. 2.22) How can I capture STDERR from an external command?
  1720.  
  1721.     There are three basic ways of running external commands:
  1722.  
  1723.         system $cmd;
  1724.         $output = `$cmd`;
  1725.         open (PIPE, "cmd |");
  1726.  
  1727.     In the first case, both STDOUT and STDERR will go the same place as
  1728.     the script's versions of these, unless redirected.  You can always put
  1729.     them where you want them and then read them back when the system
  1730.     returns.  In the second and third cases, you are reading the STDOUT
  1731.     *only* of your command.  If you would like to have merged STDOUT and
  1732.     STDERR, you can use shell file-descriptor redirection to dup STDERR to
  1733.     STDOUT:
  1734.  
  1735.         $output = `$cmd 2>&1`;
  1736.         open (PIPE, "cmd 2>&1 |");
  1737.  
  1738.     Another possibility is to run STDERR into a file and read the file
  1739.     later, as in
  1740.  
  1741.         $output = `$cmd 2>some_file`;
  1742.         open (PIPE, "cmd 2>some_file |");
  1743.  
  1744.     Here's a way to read from both of them and know which descriptor
  1745.     you got each line from.  The trick is to pipe only STDERR through
  1746.     sed, which then marks each of its lines, and then sends that
  1747.     back into a merged STDOUT/STDERR stream, from which your Perl program
  1748.     then reads a line at a time:
  1749.  
  1750.         open (CMD,
  1751.           "3>&1 (cmd args 2>&1 1>&3 3>&- | sed 's/^/STDERR:/' 3>&-) 3>&- |");
  1752.  
  1753.         while (<CMD>) {
  1754.           if (s/^STDERR://)  {
  1755.               print "line from stderr: ", $_;
  1756.           } else {
  1757.               print "line from stdout: ", $_;
  1758.           }
  1759.         }
  1760.  
  1761.     Be apprised that you *must* use Bourne shell redirection syntax
  1762.     here, not csh!  In fact, you can't even do these things with csh.
  1763.     For details on how lucky you are that perl's system() and backtick
  1764.     and pipe opens all use Bourne shell, fetch the file from convex.com
  1765.     called /pub/csh.whynot -- and you'll be glad that perl's shell
  1766.     interface is the Bourne shell.
  1767.  
  1768.  
  1769. 2.23) Why doesn't open return an error when a pipe open fails?
  1770.  
  1771.     These statements:
  1772.  
  1773.         open(TOPIPE, "|bogus_command") || die ...
  1774.         open(FROMPIPE, "bogus_command|") || die ...
  1775.  
  1776.     will not fail just for lack of the bogus_command.  They'll only
  1777.     fail if the fork to run them fails, which is seldom the problem.
  1778.  
  1779.     If you're writing to the TOPIPE, you'll get a SIGPIPE if the child
  1780.     exits prematurely or doesn't run.  If you are reading from the
  1781.     FROMPIPE, you need to check the close() to see what happened.
  1782.  
  1783.     If you want an answer sooner than pipe buffering might otherwise
  1784.     afford you, you can do something like this:
  1785.  
  1786.         $kid = open (PIPE, "bogus_command |");   # XXX: check defined($kid)
  1787.         (kill 0, $kid) || die "bogus_command failed";
  1788.  
  1789.     This works fine if bogus_command doesn't have shell metas in it, but
  1790.     if it does, the shell may well not have exited before the kill 0.  You
  1791.     could always introduce a delay:
  1792.  
  1793.         $kid = open (PIPE, "bogus_command </dev/null |");
  1794.         sleep 1;
  1795.         (kill 0, $kid) || die "bogus_command failed";
  1796.  
  1797.     but this is sometimes undesirable, and in any event does not guarantee
  1798.     correct behavior.  But it seems slightly better than nothing.
  1799.  
  1800.     Similar tricks can be played with writable pipes if you don't wish to
  1801.     catch the SIGPIPE.
  1802.  
  1803.  
  1804. 2.24) How can I compare two date strings?
  1805.  
  1806.     If the dates are in an easily parsed, predetermined format, then you
  1807.     can break them up into their component parts and call &timelocal from
  1808.     the distributed perl library.  If the date strings are in arbitrary
  1809.     formats, however, it's probably easier to use the getdate program
  1810.     from the Cnews distribution, since it accepts a wide variety of dates.
  1811.     Note that in either case the return values you will really be
  1812.     comparing will be the total time in seconds as return by time().
  1813.  
  1814.     Here's a getdate function for perl that's not very efficient; you
  1815.     can do better this by sending it many dates at once or modifying
  1816.     getdate to behave better on a pipe.  Beware the hardcoded pathname.
  1817.  
  1818.         sub getdate {
  1819.             local($_) = shift;
  1820.  
  1821.             s/-(\d{4})$/+$1/ || s/\+(\d{4})$/-$1/;
  1822.                 # getdate has broken timezone sign reversal!
  1823.  
  1824.             $_ = `/usr/local/lib/news/newsbin/getdate '$_'`;
  1825.             chop;
  1826.             $_;
  1827.         }
  1828.  
  1829.     Richard Ohnemus <rick@IMD.Sterling.COM> actually has a getdate.y
  1830.     for use with the Perl yacc.  You can get this from ftp.sterling.com
  1831.     [192.124.9.1] in /local/perl-byacc1.8.1.tar.Z, or send the author
  1832.     mail for details.
  1833.  
  1834.  
  1835. 2.25) What's the fastest way to code up a given task in perl?
  1836.  
  1837.     Because Perl so lends itself to a variety of different approaches
  1838.     for any given task, a common question is which is the fastest way
  1839.     to code a given task.  Since some approaches can be dramatically
  1840.     more efficient that others, it's sometimes worth knowing which is
  1841.     best.  Unfortunately, the implementation that first comes to mind,
  1842.     perhaps as a direct translation from C or the shell, often yields
  1843.     suboptimal performance.  Not all approaches have the same results
  1844.     across different hardware and software platforms.  Furthermore,
  1845.     legibility must sometimes be sacrificed for speed.
  1846.  
  1847.     While an experienced perl programmer can sometimes eye-ball the code
  1848.     and make an educated guess regarding which way would be fastest,
  1849.     surprises can still occur.  So, in the spirit of perl programming
  1850.     being an empirical science, the best way to find out which of several
  1851.     different methods runs the fastest is simply to code them all up and
  1852.     time them. For example:
  1853.  
  1854.         $COUNT = 10_000; $| = 1;
  1855.  
  1856.         print "method 1: ";
  1857.  
  1858.             ($u, $s) = times;
  1859.             for ($i = 0; $i < $COUNT; $i++) {
  1860.                 # code for method 1
  1861.             }
  1862.             ($nu, $ns) = times;
  1863.             printf "%8.4fu %8.4fs\n", ($nu - $u), ($ns - $s);
  1864.  
  1865.         print "method 2: ";
  1866.  
  1867.             ($u, $s) = times;
  1868.             for ($i = 0; $i < $COUNT; $i++) {
  1869.                 # code for method 2
  1870.             }
  1871.             ($nu, $ns) = times;
  1872.             printf "%8.4fu %8.4fs\n", ($nu - $u), ($ns - $s);
  1873.  
  1874.     For more specific tips, see the section on Efficiency in the
  1875.     ``Other Oddments'' chapter at the end of the Camel Book.
  1876.  
  1877.  
  1878. 2.26) How can I know how many entries are in an associative array?
  1879.  
  1880.     While the number of elements in a @foobar array is simply @foobar when
  1881.     used in a scalar, you can't figure out how many elements are in an
  1882.     associative array in an analagous fashion.  That's because %foobar in
  1883.     a scalar context returns the ratio (as a string) of number of buckets
  1884.     filled versus the number allocated.  For example, scalar(%ENV) might
  1885.     return "20/32".  While perl could in theory keep a count, this would
  1886.     break down on associative arrays that have been bound to dbm files.
  1887.  
  1888.     However, while you can't get a count this way, one thing you *can* use
  1889.     it for is to determine whether there are any elements whatsoever in
  1890.     the array, since "if (%table)" is guaranteed to be false if nothing
  1891.     has ever been stored in it.
  1892.  
  1893.     So you either have to keep your own count around and increments
  1894.     it every time you store a new key in the array, or else do it
  1895.     on the fly when you really care, perhaps like this:
  1896.  
  1897.         $count++ while each %ENV;
  1898.  
  1899.     This preceding method will be faster than extracting the
  1900.     keys into a temporary array to count them.
  1901.  
  1902.     As of a very recent patch, you can say
  1903.  
  1904.         $count = keys %ENV;
  1905.  
  1906.  
  1907.  
  1908. 2.27) Why can't my perl program read from STDIN after I gave it ^D (EOF) ?
  1909.  
  1910.     Because some stdio's set error and eof flags that need clearing.
  1911.  
  1912.     Try keeping around the seekpointer and go there, like this:
  1913.          $where = tell(LOG);
  1914.          seek(LOG, $where, 0);
  1915.  
  1916.     If that doesn't work, try seeking to a different part of the file and
  1917.     then back.  If that doesn't work, try seeking to a different part of
  1918.     the file, reading something, and then seeking back.  If that doesn't
  1919.     work, give up on your stdio package and use sysread.  You can't call
  1920.     stdio's clearerr() from Perl, so if you get EINTR from a signal
  1921.     handler, you're out of luck.  Best to just use sysread() from the
  1922.     start for the tty.
  1923.  
  1924.  
  1925. 2.28) Do I always/never have to quote my strings or use semicolons?
  1926.  
  1927.     You don't have to quote strings that can't mean anything else
  1928.     in the language, like identifiers with any upper-case letters
  1929.     in them.  Therefore, it's fine to do this:
  1930.  
  1931.         $SIG{INT} = Timeout_Routine;
  1932.     or
  1933.  
  1934.     @Days = (Sun, Mon, Tue, Wed, Thu, Fri, Sat, Sun);
  1935.  
  1936.     but you can't get away with this:
  1937.  
  1938.         $foo{while} = until;
  1939.  
  1940.     in place of
  1941.  
  1942.         $foo{'while'} = 'until';
  1943.  
  1944.     The requirements on semicolons have been increasingly relaxed.  You no
  1945.     longer need one at the end of a block, but stylistically, you're
  1946.     better to use them if you don't put the curly brace on the same line:
  1947.  
  1948.         for (1..10) { print }
  1949.  
  1950.     is ok, as is
  1951.  
  1952.         @nlist = sort { $a <=> $b } @olist;
  1953.  
  1954.     but you probably shouldn't do this:
  1955.  
  1956.         for ($i = 0; $i < @a; $i++) {
  1957.             print "i is $i\n"  # <-- oops!
  1958.         }
  1959.  
  1960.     because you might want to add lines later, and anyway,
  1961.     it looks funny. :-)
  1962.  
  1963.  
  1964. 2.29) How can I translate tildes in a filename?
  1965.  
  1966.     Perl doesn't expand tildes -- the shell (ok, some shells) do.
  1967.     The classic request is to be able to do something like:
  1968.  
  1969.         open(FILE, "~/dir1/file1");
  1970.         open(FILE, "~tchrist/dir1/file1");
  1971.  
  1972.     which doesn't work.  (And you don't know it, because you
  1973.     did a system call without an "|| die" clause! :-)
  1974.  
  1975.     If you *know* you're on a system with the csh, and you *know*
  1976.     that Larry hasn't internalized file globbing, then you could
  1977.     get away with
  1978.  
  1979.         $filename = <~tchrist/dir1/file1>;
  1980.  
  1981.     but that's pretty iffy.
  1982.  
  1983.     A better way is to do the translation yourself, as in:
  1984.  
  1985.         $filename =~ s#^~(\w+)(/.*)?$#(getpwnam($1))[7].$2#e;
  1986.  
  1987.     More robust and efficient versions that checked for error conditions,
  1988.     handed simple ~/blah notation, and cached lookups are all reasonable
  1989.     enhancements.
  1990.  
  1991.  
  1992. 2.30) How can I convert my shell script to Perl?
  1993.  
  1994.     Larry's standard answer for this is to send your script to me (Tom
  1995.     Christiansen) with appropriate supplications and offerings.  :-(
  1996.     That's because there's no automatic machine translator.  Even if you
  1997.     were, you wouldn't gain a lot, as most of the external programs would
  1998.     still get called.  It's the same problem as blind translation into C:
  1999.     you're still apt to be bogged down by exec()s.  You have to analize
  2000.     the dataflow and algorithm and rethink it for optimal speedup.  It's
  2001.     not uncommon to see one, two, or even three orders of magnitude of
  2002.     speed difference between the brute-force and the recoded approaches.
  2003.  
  2004.  
  2005. 2.31) What is variable suicide and how can I prevent it?
  2006.  
  2007.     Variable suicide is a nasty sideeffect of dynamic scoping and
  2008.     the way variables are passed by reference.  If you say
  2009.  
  2010.         $x = 17;
  2011.         &munge($x);
  2012.         sub munge {
  2013.             local($x);
  2014.             local($myvar) = $_[0];
  2015.             ...
  2016.         }
  2017.  
  2018.     Then you have just clubbered $_[0]!  Why this is occurring
  2019.     is pretty heavy wizardry: the reference to $x stored in
  2020.     $_[0] was temporarily occluded by the previous local($x)
  2021.     statement (which, you're recall, occurs at run-time, not
  2022.     compile-time).  The work around is simple, however: declare
  2023.     your formal parameters first:
  2024.  
  2025.         sub munge {
  2026.             local($myvar) = $_[0];
  2027.             local($x);
  2028.             ...
  2029.         }
  2030.  
  2031.     That doesn't help you if you're going to be trying to access
  2032.     @_ directly after the local()s.  In this case, careful use
  2033.     of the package facility is your only recourse.
  2034.  
  2035.     Another manifestation of this problem occurs due to the
  2036.     magical nature of the index variable in a foreach() loop.
  2037.  
  2038.         @num = 0 .. 4;
  2039.         print "num begin  @num\n";
  2040.         foreach $m (@num) { &ug }
  2041.         print "num finish @num\n";
  2042.         sub ug {
  2043.             local($m) = 42;
  2044.             print "m=$m  $num[0],$num[1],$num[2],$num[3]\n";
  2045.         }
  2046.  
  2047.     Which prints out the mysterious:
  2048.  
  2049.         num begin  0 1 2 3 4
  2050.         m=42  42,1,2,3
  2051.         m=42  0,42,2,3
  2052.         m=42  0,1,42,3
  2053.         m=42  0,1,2,42
  2054.         m=42  0,1,2,3
  2055.         num finish 0 1 2 3 4
  2056.  
  2057.     What's happening here is that $m is an alias for each
  2058.     element of @num.  Inside &ug, you temporarily change
  2059.     $m.  Well, that means that you've also temporarily
  2060.     changed whatever $m is an alias to!!  The only workaround
  2061.     is to be careful with global variables, using packages,
  2062.     and/or just be aware of this potential in foreach() loops.
  2063.  
  2064.  
  2065. 2.32) Can I use Perl regular expressions to match balanced text?
  2066.  
  2067.     No, or at least, not by the themselves.
  2068.  
  2069.     Regexps just aren't powerful enough.  Although Perl's patterns aren't
  2070.     strictly regular because they do backtracking (the \1 notation), you
  2071.     still can't do it.  You need to employ auxiliary logic.  A simple
  2072.     approach would involve keeping a bit of state around, something
  2073.     vaguely like this (although we don't handle patterns on the same line):
  2074.  
  2075.         while(<>) {
  2076.             if (/pat1/) {
  2077.                 if ($inpat++ > 0) { warn "already saw pat1" }
  2078.                 redo;
  2079.             }
  2080.             if (/pat2/) {
  2081.                 if (--$inpat < 0) { warn "never saw pat1" }
  2082.                 redo;
  2083.             }
  2084.         }
  2085.  
  2086.     A rather more elaborate subroutine to pull out balanced and possibly
  2087.     nested single chars, like ` and ', { and }, or ( and ) can be found
  2088.     on convex.com in /pub/perl/scripts/pull_quotes.
  2089.  
  2090.  
  2091. 2.33) Can I use Perl to run a telnet or ftp session?
  2092.  
  2093.     Sure, you can connect directly to them using sockets, or you can run a
  2094.     session on a pty.  In either case, Randal's chat2 package, which is
  2095.     distributed with the perl source, will come in handly.  It address
  2096.     much the same problem space as Don Libes's expect package does.  Two
  2097.     examples of using managing an ftp session using chat2 can be found on
  2098.     convex.com in /pub/perl/scripts/ftp-chat2.shar .
  2099.  
  2100.     Caveat lector: chat2 is documented only by example, may not run on
  2101.     System V systems, and is subtly machine dependent both in its ideas
  2102.     of networking and in pseudottys.
  2103.  
  2104.  
  2105. 2.34) What does "Malformed command links" mean?
  2106.  
  2107.     This is a bug in 4.035.  While in general it's merely a cosmetic
  2108.     problem, it often comanifests with a highly undesirable coredumping
  2109.     problem.  Programs known to be affected by the fatal coredump include
  2110.     plum and pcops.  Since perl5 is prety much a total rewrite, we can
  2111.     count on it being fixed then, but if anyone tracks down the coredump
  2112.     problem before then, a signifcant portion of the perl world would
  2113.     rejoice.
  2114. --
  2115.     Tom Christiansen      tchrist@convex.com      convex!tchrist
  2116.  
  2117.  
  2118. If God had meant for us to be naked, we would have been born that way.
  2119.