home *** CD-ROM | disk | FTP | other *** search
/ ftp.pasteur.org/FAQ/ / ftp-pasteur-org-FAQ.zip / FAQ / perl-faq / part4 < prev    next >
Internet Message Format  |  1996-01-31  |  48KB

  1. Path: senator-bedfellow.mit.edu!bloom-beacon.mit.edu!eru.mt.luth.se!news.kth.se!nntp.uio.no!news.cais.net!news1.radix.net!news1.radix.net!spp
  2. From: spp@psa.pencom.com
  3. Newsgroups: comp.lang.perl.announce,comp.lang.perl.misc,comp.answers,news.answers
  4. Subject: comp.lang.perl.* FAQ 4/5 - General Programming
  5. Followup-To: poster
  6. Date: 27 Jan 1996 04:20:08 GMT
  7. Organization: Pencom Systems Administration
  8. Lines: 1465
  9. Approved: news-answers-request@MIT.EDU
  10. Distribution: world
  11. Message-ID: <SPP.96Jan26232008@syrinx.hideout.com>
  12. NNTP-Posting-Host: dialin23.annex1.radix.net
  13. Xref: senator-bedfellow.mit.edu comp.lang.perl.announce:241 comp.lang.perl.misc:18984 comp.answers:16750 news.answers:63417
  14.  
  15.  
  16. Archive-name: perl-faq/part4
  17. Version: $Id: part4,v 2.9 1995/05/15 15:46:10 spp Exp spp $
  18. Posting-Frequency: bi-weekly
  19. Last Edited: Thu Jan 11 00:52:25 1996 by spp (Stephen P Potter) on syrinx.psa.com
  20.  
  21. This posting contains answers to the following questions about General
  22. Programming, Regular Expressions (Regexp) and Input/Output:
  23.  
  24.  
  25. 4.1) What are all these $@%*<> signs and how do I know when to use them?
  26.  
  27.     Those are type specifiers: 
  28.     $ for scalar values
  29.     @ for indexed arrays
  30.     % for hashed arrays (associative arrays)
  31.     * for all types of that symbol name.  These are sometimes used like
  32.         pointers in perl4, but perl5 uses references.
  33.     <> are used for inputting a record from a filehandle.  
  34.         \ takes a reference to something.
  35.  
  36.     See the question on arrays of arrays for more about Perl pointers.
  37.  
  38.     While there are a few places where you don't actually need these type
  39.     specifiers, except for files, you should always use them.  Note that
  40.     <FILE> is NOT the type specifier for files; it's the equivalent of awk's
  41.     getline function, that is, it reads a line from the handle FILE.  When
  42.     doing open, close, and other operations besides the getline function on
  43.     files, do NOT use the brackets.
  44.  
  45.     Beware of saying:
  46.     $foo = BAR;
  47.     Which wil be interpreted as 
  48.     $foo = 'BAR';
  49.     and not as 
  50.     $foo = <BAR>;
  51.     If you always quote your strings, you'll avoid this trap.
  52.  
  53.     Normally, files are manipulated something like this (with appropriate
  54.     error checking added if it were production code):
  55.  
  56.     open (FILE, ">/tmp/foo.$$");
  57.     print FILE "string\n";
  58.     close FILE;
  59.  
  60.     If instead of a filehandle, you use a normal scalar variable with file
  61.     manipulation functions, this is considered an indirect reference to a
  62.     filehandle.  For example,
  63.  
  64.     $foo = "TEST01";
  65.     open($foo, "file");
  66.  
  67.     After the open, these two while loops are equivalent:
  68.  
  69.     while (<$foo>) {}
  70.     while (<TEST01>) {}
  71.  
  72.     as are these two statements:
  73.     
  74.     close $foo;
  75.     close TEST01;
  76.  
  77.     but NOT to this:
  78.  
  79.     while (<$TEST01>) {} # error
  80.         ^
  81.         ^ note spurious dollar sign
  82.  
  83.     This is another common novice mistake; often it's assumed that
  84.  
  85.     open($foo, "output.$$");
  86.  
  87.     will fill in the value of $foo, which was previously undefined.  This
  88.     just isn't so -- you must set $foo to be the name of a filehandle
  89.     before you attempt to open it.   
  90.  
  91.     Often people request:
  92.  
  93.     : How about changing perl syntax to be more like awk or C?  I $$mean @less
  94.     : $-signs = <and> &other *special \%characters?
  95.  
  96.     Larry's answer is:
  97.  
  98.     Then it would be less like the shell.  :-)
  99.  
  100.     You'll be pleased to know that I've been trying real hard to get
  101.     rid of unnecessary punctuation in Perl 5.  You'll be displeased to
  102.     know that I don't think noun markers like $ and @ unnecessary.
  103.     Not only do they function like case markers do in human language,
  104.     but they are automatically distinguished within interpolative
  105.     contexts, and the user doesn't have to worry about different
  106.     syntactic treatments for variable references within or without
  107.     such a context.
  108.  
  109.     But the & prefix on verbs is now optional, just as "do" is in
  110.     English.  I do hope you do understand what I mean.
  111.  
  112.     For example, you used to have to write this:
  113.  
  114.         &california || &bust;
  115.  
  116.     It can now be written more cleanly like this:
  117.  
  118.         california or bust;
  119.  
  120.     Strictly speaking, of course, $ and @ aren't case markers, but
  121.     number markers.  English has mandatory number markers, and people
  122.     get upset when they doesn't agree.
  123.  
  124.     It were just convenient in Perl (for the shellish interplative
  125.     reasons mentioned above) to pull the markers out to the front of
  126.     each noun phrase.  Most people seems to like it that way.  It
  127.     certainly seem to make more sense than putting them on the end,
  128.     like most varieties of BASIC does.
  129.  
  130.  
  131. 4.2) How come Perl operators have different precedence than C operators?
  132.  
  133.     Actually, they don't; all C operators have the same precedence in Perl as
  134.     they do in C.  The problem is with a class of functions called list
  135.     operators, e.g. print, chdir, exec, system, and so on.  These are somewhat
  136.     bizarre in that they have different precedence depending on whether you
  137.     look on the left or right of them.  Basically, they gobble up all things
  138.     on their right.  For example,
  139.  
  140.     unlink $foo, "bar", @names, "others";
  141.  
  142.     will unlink all those file names.  A common mistake is to write:
  143.  
  144.     unlink "a_file" || die "snafu";
  145.  
  146.     The problem is that this gets interpreted as
  147.  
  148.     unlink("a_file" || die "snafu");
  149.  
  150.     To avoid this problem, you can always make them look like function calls
  151.     or use an extra level of parentheses:
  152.  
  153.     unlink("a_file")  || die "snafu";
  154.     (unlink "a_file") || die "snafu";
  155.  
  156.     In perl5, there are low precedence "and", "or", and "not" operators,
  157.     which bind less tightly than comma.  This allows you to write:
  158.  
  159.     unlink $foo, "bar", @names, "others"     or die "snafu";
  160.  
  161.     Sometimes you actually do care about the return value:
  162.  
  163.     unless ($io_ok = print("some", "list")) { } 
  164.  
  165.     Yes, print() returns I/O success.  That means
  166.  
  167.     $io_ok = print(2+4) * 5;
  168.  
  169.     returns 5 times whether printing (2+4) succeeded, and 
  170.     print(2+4) * 5;
  171.     returns the same 5*io_success value and tosses it.
  172.  
  173.     See the perlop(1) man page's section on Precedence for more gory details,
  174.     and be sure to use the -w flag to catch things like this.
  175.  
  176.     One very important thing to be aware of is that if you start thinking
  177.     of Perl's $, @, %, and & as just flavored versions of C's * operator,
  178.     you're going to be sorry.  They aren't really operators, per se, and
  179.     even if you do think of them that way.  In C, if you write
  180.  
  181.     *x[i]
  182.  
  183.     then the brackets will bind more tightly than the star, yielding
  184.  
  185.     *(x[i])
  186.  
  187.     But in perl, they DO NOT!  That's because the ${}, @{}, %{}, and &{}
  188.     notations (and I suppose the *{} one as well for completeness) aren't
  189.     actually operators.  If they were, you'd be able to write them as *()
  190.     and that's not feasible.  Instead of operators whose precedence is
  191.     easily understandable, they are instead figments of yacc's grammar.
  192.     This means that:
  193.  
  194.     $$x[$i]
  195.  
  196.     is really
  197.  
  198.     {$$x}[$i]
  199.  
  200.     (by which I actually mean)
  201.  
  202.     ${$x}[$i]
  203.  
  204.     and not
  205.  
  206.     ${$x[$i]}
  207.  
  208.     See the difference?  If not, check out perlref(1) for gory details.
  209.  
  210.  
  211. 4.3) What's the difference between dynamic and static (lexical) scoping?
  212.      What are my() and local()?
  213.  
  214.     [NOTE: This question refers to perl5 only.  There is no my() in perl4]
  215.     Scoping refers to visibility of variables.  A dynamic variable is
  216.     created via local() and is just a local value for a global variable,
  217.     whereas a lexical variable created via my() is more what you're
  218.     expecting from a C auto.  (See also "What's the difference between
  219.     deep and shallow binding.")  In general, we suggest you use lexical
  220.     variables wherever possible, as they're faster to access and easier to
  221.     understand.   The "use strict vars" pragma will enforce that all
  222.     variables are either lexical, or full classified by package name.  We
  223.     strongly suggest that you develop your code with "use strict;" and the
  224.     -w flag.  (When using formats, however, you will still have to use
  225.     dynamic variables.)  Here's an example of the difference:
  226.  
  227.         #!/usr/local/bin/perl
  228.         $myvar = 10;
  229.         $localvar = 10;
  230.  
  231.         print "Before the sub call - my: $myvar, local: $localvar\n";
  232.         &sub1();
  233.  
  234.         print "After the sub call - my: $myvar, local: $localvar\n";
  235.  
  236.         exit(0);
  237.  
  238.         sub sub1 {
  239.             my $myvar;
  240.             local $localvar;
  241.  
  242.             $myvar = 5;     # Only in this block
  243.             $localvar = 20; # Accessible to children
  244.  
  245.             print "Inside first sub call - my: $myvar, local: $localvar\n";
  246.  
  247.             &sub2();
  248.         }
  249.  
  250.         sub sub2 {
  251.             print "Inside second sub - my: $myvar, local: $localvar\n";
  252.         }
  253.  
  254.     Notice that the variables declared with my() are visible only within
  255.     the scope of the block which names them.  They are not visible outside
  256.     of this block, not even in routines or blocks that it calls.  local() 
  257.     variables, on the other hand, are visible to routines that are called
  258.     from the block where they are declared.  Neither is visible after the
  259.     end (the final closing curly brace) of the block at all.
  260.  
  261.     Oh, lexical variables are only available in perl5.  Have we mentioned
  262.     yet that you might consider upgrading? :-) 
  263.  
  264.  
  265. 4.4) What's the difference between deep and shallow binding?
  266.  
  267.     5.000 answer:
  268.  
  269.     This only matters when you're making subroutines yourself, at least
  270.     so far.   This will give you shallow binding:
  271.  
  272.     {
  273.           my $x = time;
  274.           $coderef = sub { $x };
  275.         }
  276.  
  277.     When you call &$coderef(), it will get whatever dynamic $x happens
  278.     to be around when invoked.  However, you can get the other behaviour
  279.     this way:
  280.  
  281.     {
  282.           my $x = time;
  283.           $coderef = eval "sub { \$x }";
  284.         }
  285.  
  286.     Now you'll access the lexical variable $x which is set to the
  287.     time the subroutine was created.  Note that the difference in these
  288.     two behaviours can be considered a bug, not a feature, so you should
  289.     in particular not rely upon shallow binding, as it will likely go
  290.     away in the future.  See perlref(1).
  291.  
  292.     5.001 Answer:
  293.  
  294.     Perl will always give deep binding to functions, so you don't need the
  295.     eval hack anymore.   Furthermore,  functions and even formats
  296.     lexically declared nested within another lexical scope have access to
  297.     that scope.
  298.  
  299.     require 5.001;
  300.  
  301.     sub mkcounter {
  302.         my $start = shift;
  303.         return sub {
  304.         return ++$start;
  305.         } 
  306.     } 
  307.     $f1 = mkcounter(10);
  308.     $f2 = mkcounter(20);
  309.     print &$f1(), &$f2(); 
  310.     11 21
  311.     print &$f1(), &$f2(), &$f1();
  312.     12 22 13
  313.  
  314.     See the question on "What's a closure?"
  315.  
  316.  
  317. 4.5) How can I manipulate fixed-record-length files?
  318.  
  319.     The most efficient way is using pack and unpack.  This is faster than
  320.     using substr.  Here is a sample chunk of code to break up and put back
  321.     together again some fixed-format input lines, in this case, from ps.
  322.  
  323.     # sample input line:
  324.     #   15158 p5  T      0:00 perl /mnt/tchrist/scripts/now-what
  325.     $ps_t = 'A6 A4 A7 A5 A*';
  326.     open(PS, "ps|");
  327.     $_ = <PS>; print;
  328.     while (<PS>) {
  329.         ($pid, $tt, $stat, $time, $command) = unpack($ps_t, $_);
  330.         for $var ('pid', 'tt', 'stat', 'time', 'command' ) {
  331.         print "$var: <", eval "\$$var", ">\n";
  332.         }
  333.         print 'line=', pack($ps_t, $pid, $tt, $stat, $time, $command),  "\n";
  334.     }
  335.  
  336.  
  337. 4.6) How can I make a file handle local to a subroutine?
  338.  
  339.     You must use the type-globbing *VAR notation.  Here is some code to
  340.     cat an include file, calling itself recursively on nested local
  341.     include files (i.e. those with #include "file", not #include <file>):
  342.  
  343.     sub cat_include {
  344.         local($name) = @_;
  345.         local(*FILE);
  346.         local($_);
  347.  
  348.         warn "<INCLUDING $name>\n";
  349.         if (!open (FILE, $name)) {
  350.         warn "can't open $name: $!\n";
  351.         return;
  352.         }
  353.         while (<FILE>) {
  354.         if (/^#\s*include "([^"]*)"/) {
  355.             &cat_include($1);
  356.         } else {
  357.             print;
  358.         }
  359.         }
  360.         close FILE;
  361.     }
  362.  
  363.  
  364. 4.7) How can I call alarm() or usleep() from Perl?
  365.  
  366.     If you want finer granularity than 1 second (as usleep() provides) and
  367.     have itimers and syscall() on your system, you can use the following.
  368.     You could also use select().
  369.  
  370.     It takes a floating-point number representing how long to delay until
  371.     you get the SIGALRM, and returns a floating- point number representing
  372.     how much time was left in the old timer, if any.  Note that the C
  373.     function uses integers, but this one doesn't mind fractional numbers.
  374.  
  375.     # alarm; send me a SIGALRM in this many seconds (fractions ok)
  376.     # tom christiansen <tchrist@convex.com>
  377.     sub alarm {
  378.     require 'syscall.ph';
  379.     require 'sys/time.ph';
  380.  
  381.     local($ticks) = @_;
  382.     local($in_timer,$out_timer);
  383.     local($isecs, $iusecs, $secs, $usecs);
  384.  
  385.     local($itimer_t) = 'L4'; # should be &itimer'typedef()
  386.  
  387.     $secs = int($ticks);
  388.     $usecs = ($ticks - $secs) * 1e6;
  389.  
  390.     $out_timer = pack($itimer_t,0,0,0,0);  
  391.     $in_timer  = pack($itimer_t,0,0,$secs,$usecs);
  392.  
  393.     syscall(&SYS_setitimer, &ITIMER_REAL, $in_timer, $out_timer)
  394.         && die "alarm: setitimer syscall failed: $!";
  395.  
  396.     ($isecs, $iusecs, $secs, $usecs) = unpack($itimer_t,$out_timer);
  397.     return $secs + ($usecs/1e6);
  398.     }
  399.  
  400.  
  401. 4.8) How can I do an atexit() or setjmp()/longjmp() in Perl?  (Exception handling)
  402.  
  403.     Perl's exception-handling mechanism is its eval operator.  You 
  404.     can use eval as setjmp and die as longjmp.  Here's an example
  405.     of Larry's for timed-out input, which in C is often implemented
  406.     using setjmp and longjmp:
  407.  
  408.       $SIG{ALRM} = TIMEOUT;
  409.       sub TIMEOUT { die "restart input\n" }
  410.  
  411.       do { eval { &realcode } } while $@ =~ /^restart input/;
  412.  
  413.       sub realcode {
  414.           alarm 15;
  415.           $ans = <STDIN>;
  416.           alarm 0;
  417.       }
  418.  
  419.    Here's an example of Tom's for doing atexit() handling:
  420.  
  421.     sub atexit { push(@_exit_subs, @_) }
  422.  
  423.     sub _cleanup { unlink $tmp }
  424.  
  425.     &atexit('_cleanup');
  426.  
  427.     eval <<'End_Of_Eval';  $here = __LINE__;
  428.     # as much code here as you want
  429.     End_Of_Eval
  430.  
  431.     $oops = $@;  # save error message
  432.  
  433.     # now call his stuff
  434.     for (@_exit_subs) { &$_() }
  435.  
  436.     $oops && ($oops =~ s/\(eval\) line (\d+)/$0 .
  437.         " line " . ($1+$here)/e, die $oops);
  438.  
  439.     You can register your own routines via the &atexit function now.  You
  440.     might also want to use the &realcode method of Larry's rather than
  441.     embedding all your code in the here-is document.  Make sure to leave
  442.     via die rather than exit, or write your own &exit routine and call
  443.     that instead.   In general, it's better for nested routines to exit
  444.     via die rather than exit for just this reason.
  445.  
  446.     In Perl5, it is easy to set this up because of the automatic processing
  447.     of per-package END functions.  These work much like they would in awk.
  448.     See perlfunc(1), perlmod(1) and perlrun(1).
  449.  
  450.     Eval is also quite useful for testing for system dependent features,
  451.     like symlinks, or using a user-input regexp that might otherwise
  452.     blowup on you.
  453.  
  454.  
  455. 4.9) How do I catch signals in perl?
  456.  
  457.     Perl allows you to trap signals using the %SIG associative array.
  458.     Using the signals you want to trap as the key, you can assign a
  459.     subroutine to that signal.  The %SIG array will only contain those
  460.     values which the programmer defines.  Therefore, you do not have to
  461.     assign all signals.  For example, to exit cleanly from a ^C:
  462.  
  463.     $SIG{'INT'} = 'CLEANUP';
  464.     sub CLEANUP {
  465.         print "\n\nCaught Interrupt (^C), Aborting\n";
  466.         exit(1);
  467.     }
  468.  
  469.     There are two special "routines" for signals called DEFAULT and IGNORE.
  470.     DEFAULT erases the current assignment, restoring the default value of
  471.     the signal.  IGNORE causes the signal to be ignored.  In general, you
  472.     don't need to remember these as you can emulate their functionality
  473.     with standard programming features.  DEFAULT can be emulated by
  474.     deleting the signal from the array and IGNORE can be emulated by any
  475.     undeclared subroutine.
  476.  
  477.     In 5.001, the $SIG{__WARN__} and $SIG{__DIE__} handlers may be used to
  478.     intercept die() and warn().  For example, here's how you could promote
  479.     unitialized variables to trigger a fatal rather merely complaining:
  480.  
  481.     #!/usr/bin/perl -w 
  482.     require 5.001;
  483.     $SIG{__WARN__} = sub {
  484.         if ($_[0] =~ /uninit/) {
  485.         die $@;
  486.         } else {
  487.         warn $@;
  488.         } 
  489.     };
  490.  
  491.  
  492. 4.10) Why doesn't Perl interpret my octal data octally?
  493.  
  494.     Perl only understands octal and hex numbers as such when they occur
  495.     as literals in your program.  If they are read in from somewhere and
  496.     assigned, then no automatic conversion takes place.  You must
  497.     explicitly use oct() or hex() if you want this kind of thing to happen. 
  498.     Actually, oct() knows to interpret both hex and octal numbers, while
  499.     hex only converts hexadecimal ones.  For example:
  500.  
  501.     {
  502.         print "What mode would you like? ";
  503.         $mode = <STDIN>;
  504.         $mode = oct($mode);
  505.         unless ($mode) {
  506.         print "You can't really want mode 0!\n";
  507.         redo;
  508.         } 
  509.         chmod $mode, $file;
  510.     } 
  511.  
  512.     Without the octal conversion, a requested mode of 755 would turn 
  513.     into 01363, yielding bizarre file permissions of --wxrw--wt.
  514.  
  515.     If you want something that handles decimal, octal and hex input, 
  516.     you could follow the suggestion in the man page and use:
  517.  
  518.     $val = oct($val) if $val =~ /^0/;
  519.  
  520.  
  521. 4.11) How can I compare two date strings?
  522.  
  523.     If the dates are in an easily parsed, predetermined format, then you
  524.     can break them up into their component parts and call &timelocal from
  525.     the distributed perl library.  If the date strings are in arbitrary
  526.     formats, however, it's probably easier to use the getdate program from
  527.     the Cnews distribution, since it accepts a wide variety of dates.  Note
  528.     that in either case the return values you will really be comparing will
  529.     be the total time in seconds as returned by time(). 
  530.    
  531.     Here's a getdate function for perl that's not very efficient; you can
  532.     do better than this by sending it many dates at once or modifying
  533.     getdate to behave better on a pipe.  Beware the hardcoded pathname. 
  534.  
  535.     sub getdate {
  536.         local($_) = shift;
  537.  
  538.         s/-(\d{4})$/+$1/ || s/\+(\d{4})$/-$1/; 
  539.         # getdate has broken timezone sign reversal!
  540.  
  541.         $_ = `/usr/local/lib/news/newsbin/getdate '$_'`;
  542.         chop;
  543.         $_;
  544.     } 
  545.  
  546.     You can also get the  GetDate extension module that's actually the C
  547.     code linked into perl from wherever fine Perl extensions are given
  548.     away.  It's about 50x faster.  If you can't find it elsewhere, I
  549.     usually keep a copy on perl.com for ftp, since I (Tom) ported it.
  550.  
  551.     Richard Ohnemus <Rick_Ohnemus@Sterling.COM> actually has a getdate.y for
  552.     use with the Perl yacc (see question 3.3 "Is there a yacc for Perl?").  
  553.  
  554.     You might also consider using these: 
  555.  
  556.     date.pl        - print dates how you want with the sysv +FORMAT method 
  557.     date.shar      - routines to manipulate and calculate dates
  558.     ftp-chat2.shar - updated version of ftpget. includes library and demo 
  559.              programs 
  560.     getdate.shar   - returns number of seconds since epoch for any given
  561.              date 
  562.     ptime.shar     - print dates how you want with the sysv +FORMAT method 
  563.  
  564.     You probably want 'getdate.shar'... these and other files can be ftp'd
  565.     from the /pub/perl/scripts directory on ftp.cis.ufl.edu. See the README
  566.     file in the /pub/perl directory for time and the European mirror site
  567.     details. 
  568.  
  569.  
  570. 4.12) How can I find the Julian Day?
  571.  
  572.     Here's an example of a Julian Date function provided by Thomas R.
  573.     Kimpton*.
  574.  
  575.     #!/usr/local/bin/perl
  576.  
  577.     @theJulianDate = ( 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 );
  578.  
  579.     #************************************************************************
  580.     #****   Return 1 if we are after the leap day in a leap year.       *****
  581.     #************************************************************************
  582.                    
  583.     sub leapDay             
  584.     {                 
  585.         my($year,$month,$day) = @_;
  586.     
  587.         if (year % 4) {
  588.         return(0);
  589.         }
  590.  
  591.         if (!(year % 100)) {             # years that are multiples of 100
  592.                                      # are not leap years
  593.         if (year % 400) {            # unless they are multiples of 400
  594.             return(0);
  595.         }
  596.         }
  597.         if (month < 2) {
  598.             return(0);
  599.         } elsif ((month == 2) && (day < 29)) {
  600.         return(0);
  601.         } else {
  602.         return(1);
  603.         }
  604.     }
  605.     
  606.     #************************************************************************
  607.     #****   Pass in the date, in seconds, of the day you want the       *****
  608.     #****   julian date for.  If your localtime() returns the year day  *****
  609.     #****   return that, otherwise figure out the julian date.          *****
  610.     #************************************************************************
  611.         
  612.     sub julianDate    
  613.     {        
  614.         my($dateInSeconds) = @_;
  615.         my($sec, $min, $hour, $mday, $mon, $year, $wday, $yday);
  616.     
  617.         ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) =
  618.         localtime($dateInSeconds);
  619.         if (defined($yday)) {
  620.         return($yday+1);
  621.         } else {
  622.         return($theJulianDate[$mon] + $mday + &leapDay($year,$mon,$mday));
  623.         }
  624.     
  625.     }
  626.  
  627.     print "Today's julian date is: ",&julianDate(time),"\n";
  628.  
  629.  
  630. 4.13) Does perl have a round function?  What about ceil() and floor()?
  631.  
  632.     Perl does not have an explicit round function.  However, it is very
  633.     simple to create a rounding function.  Since the int() function simply
  634.     removes the decimal value and returns the integer portion of a number,
  635.     you can use 
  636.  
  637.         sub round {
  638.             my($number) = shift;
  639.  
  640.             return int($number + .5);
  641.         }
  642.  
  643.     If you examine what this function is doing, you will see that any
  644.     number greater than .5 will be increased to the next highest integer,
  645.     and any number less than .5 will remain the current integer, which has
  646.     the same effect as rounding.
  647.  
  648.     A slightly better solution, one which handles negative numbers as well,
  649.     might be to change the return (above) to:
  650.  
  651.         return int($number + .5 * ($number <=> 0));
  652.  
  653.     which will modify the .5 to be either positive or negative, based on
  654.     the number passed into it.
  655.  
  656.     If you wish to round to a specific significant digit, you can use the
  657.     printf function (or sprintf, depending upon the situation), which does
  658.     proper rounding automatically.  See the perlfunc man page for more
  659.     information on the (s)printf function.
  660.  
  661.     Version 5 includes a POSIX module which defines the standard C math
  662.     library functions, including floor() and ceil().  floor($num) returns
  663.     the largest integer not greater than $num, while ceil($num) returns the
  664.     smallest integer not less than $num.  For example:
  665.  
  666.         #!/usr/local/bin/perl
  667.         use POSIX qw(ceil floor);
  668.  
  669.         $num = 42.4;  # The Answer to the Great Question (on a Pentium)!
  670.  
  671.         print "Floor returns: ", floor($num), "\n";
  672.         print "Ceil returns:  ", ceil($num), "\n";
  673.  
  674.     Which prints:
  675.  
  676.         Floor returns: 42
  677.         Ceil returns:  43
  678.  
  679.  
  680. 4.14) What's the fastest way to code up a given task in perl?
  681.  
  682.     Post it to comp.lang.perl.misc and ask Tom or Randal a question about
  683.     it.  ;) 
  684.  
  685.     Because Perl so lends itself to a variety of different approaches for
  686.     any given task, a common question is which is the fastest way to code a
  687.     given task.  Since some approaches can be dramatically more efficient
  688.     that others, it's sometimes worth knowing which is best.
  689.     Unfortunately, the implementation that first comes to mind, perhaps as
  690.     a direct translation from C or the shell, often yields suboptimal
  691.     performance.  Not all approaches have the same results across different
  692.     hardware and software platforms.  Furthermore, legibility must
  693.     sometimes be sacrificed for speed. 
  694.  
  695.     While an experienced perl programmer can sometimes eye-ball the code
  696.     and make an educated guess regarding which way would be fastest,
  697.     surprises can still occur.  So, in the spirit of perl programming
  698.     being an empirical science, the best way to find out which of several
  699.     different methods runs the fastest is simply to code them all up and
  700.     time them. For example:
  701.  
  702.     $COUNT = 10_000; $| = 1;
  703.  
  704.     print "method 1: ";
  705.  
  706.         ($u, $s) = times;
  707.         for ($i = 0; $i < $COUNT; $i++) {
  708.         # code for method 1
  709.         }
  710.         ($nu, $ns) = times;
  711.         printf "%8.4fu %8.4fs\n", ($nu - $u), ($ns - $s);
  712.  
  713.     print "method 2: ";
  714.  
  715.         ($u, $s) = times;
  716.         for ($i = 0; $i < $COUNT; $i++) {
  717.         # code for method 2
  718.         }
  719.         ($nu, $ns) = times;
  720.         printf "%8.4fu %8.4fs\n", ($nu - $u), ($ns - $s);
  721.  
  722.     Perl5 includes a new module called Benchmark.pm.  You can now simplify
  723.     the code to use the Benchmarking, like so:
  724.  
  725.         use Benchmark;
  726.  
  727.             timethese($count, {
  728.                 Name1 => '...code for method 1...',
  729.                 Name2 => '...code for method 2...',
  730.                 ... });
  731.  
  732.     It will output something that looks similar to this:
  733.  
  734.         Benchmark: timing 100 iterations of Name1, Name2...
  735.                 Name1:  2 secs (0.50 usr 0.00 sys = 0.50 cpu)
  736.                 Name2:  1 secs (0.48 usr 0.00 sys = 0.48 cpu)
  737.  
  738.  
  739.     For example, the following code will show the time difference between
  740.     three different ways of assigning the first character of a string to
  741.     a variable:
  742.  
  743.     use Benchmark;
  744.     timethese(100000, {
  745.         'regex1' => '$str="ABCD"; $str =~ s/^(.)//; $ch = $1',
  746.         'regex2' => '$str="ABCD"; $str =~ s/^.//; $ch = $&',
  747.         'substr' => '$str="ABCD"; $ch=substr($str,0,1); substr($str,0,1)="",
  748.     });
  749.  
  750.     The results will be returned like this:
  751.  
  752.     Benchmark: timing 100000 iterations of regex1, regex2, substr...
  753.        regex1: 11 secs (10.80 usr   0.00 sys =  10.80 cpu)
  754.        regex2: 10 secs (10.23 usr   0.00 sys =  10.23 cpu)
  755.        substr:  7 secs ( 5.62 usr    0.00 sys =   5.62 cpu)
  756.  
  757.     For more specific tips, see the section on Efficiency in the
  758.     ``Other Oddments'' chapter at the end of the Camel Book.
  759.  
  760.  
  761. 4.15) Do I always/never have to quote my strings or use semicolons?
  762.  
  763.     You don't have to quote strings that can't mean anything else in the
  764.     language, like identifiers with any upper-case letters in them.
  765.     Therefore, it's fine to do this: 
  766.  
  767.     $SIG{INT} = Timeout_Routine;
  768.     or 
  769.  
  770.     @Days = (Sun, Mon, Tue, Wed, Thu, Fri, Sat, Sun);
  771.  
  772.     but you can't get away with this:
  773.  
  774.     $foo{while} = until;
  775.  
  776.     in place of 
  777.  
  778.     $foo{'while'} = 'until';
  779.  
  780.     The requirements on semicolons have been increasingly relaxed.  You no 
  781.     longer need one at the end of a block, but stylistically, you're better
  782.     to use them if you don't put the curly brace on the same line: 
  783.  
  784.     for (1..10) { print }
  785.  
  786.     is ok, as is
  787.  
  788.     @nlist = sort { $a <=> $b } @olist;
  789.  
  790.     but you probably shouldn't do this:
  791.     
  792.     for ($i = 0; $i < @a; $i++) {
  793.         print "i is $i\n"  # <-- oops!
  794.     } 
  795.  
  796.     because you might want to add lines later, and anyway, it looks
  797.     funny. :-) 
  798.  
  799.     Actually, I lied.  As of 5.001, there are two autoquoting contexts:
  800.  
  801.     This            is like this
  802.     ------------            ---------------
  803.     $foo{line}        $foo{"line"}
  804.     bar => stuff        "bar" => stuff
  805.  
  806.  
  807. 4.16) What is variable suicide and how can I prevent it?
  808.  
  809.     Variable suicide is a nasty side effect of dynamic scoping and the way
  810.     variables are passed by reference.  If you say 
  811.  
  812.     $x = 17;
  813.     &munge($x);
  814.     sub munge {
  815.         local($x);
  816.         local($myvar) = $_[0];
  817.         ...
  818.     } 
  819.  
  820.     Then you have just clobbered $_[0]!  Why this is occurring is pretty
  821.     heavy wizardry: the reference to $x stored in $_[0] was temporarily
  822.     occluded by the previous local($x) statement (which, you're recall,
  823.     occurs at run-time, not compile-time).  The work around is simple,
  824.     however: declare your formal parameters first:
  825.  
  826.     sub munge {
  827.         local($myvar) = $_[0];
  828.         local($x);
  829.         ...
  830.     }
  831.  
  832.     That doesn't help you if you're going to be trying to access @_
  833.     directly after the local()s.  In this case, careful use of the package
  834.     facility is your only recourse. 
  835.  
  836.     Another manifestation of this problem occurs due to the magical nature
  837.     of the index variable in a foreach() loop. 
  838.  
  839.     @num = 0 .. 4;
  840.     print "num begin  @num\n";
  841.     foreach $m (@num) { &ug }
  842.     print "num finish @num\n";
  843.     sub ug {
  844.         local($m) = 42;
  845.         print "m=$m  $num[0],$num[1],$num[2],$num[3]\n";
  846.     }
  847.     
  848.     Which prints out the mysterious:
  849.  
  850.     num begin  0 1 2 3 4
  851.     m=42  42,1,2,3
  852.     m=42  0,42,2,3
  853.     m=42  0,1,42,3
  854.     m=42  0,1,2,42
  855.     m=42  0,1,2,3
  856.     num finish 0 1 2 3 4
  857.  
  858.     What's happening here is that $m is an alias for each element of @num.
  859.     Inside &ug, you temporarily change $m.  Well, that means that you've
  860.     also temporarily changed whatever $m is an alias to!!  The only
  861.     workaround is to be careful with global variables, using packages,
  862.     and/or just be aware of this potential in foreach() loops. 
  863.  
  864.     The perl5 static autos via "my" do not exhibit this problem.
  865.  
  866.  
  867. 4.17) What does "Malformed command links" mean?
  868.  
  869.     This is a bug in 4.035.  While in general it's merely a cosmetic
  870.     problem, it often comanifests with a highly undesirable coredumping 
  871.     problem.  Programs known to be affected by the fatal coredump include
  872.     plum and pcops.  This bug has been fixed since 4.036.  It did not
  873.     resurface in 5.001.
  874.  
  875.  
  876. 4.18) How can I set up a footer format to be used with write()?
  877.  
  878.     While the $^ variable contains the name of the current header format,
  879.     there is no corresponding mechanism to automatically do the same thing
  880.     for a footer.  Not knowing how big a format is going to be until you
  881.     evaluate it is one of the major problems.
  882.  
  883.     If you have a fixed-size footer, you can get footers by checking for
  884.     line left on page ($-) before each write, and printing the footer
  885.     yourself if necessary.
  886.  
  887.     Another strategy is to open a pipe to yourself, using open(KID, "|-")
  888.     and always write()ing to the KID, who then postprocesses its STDIN to
  889.     rearrange headers and footers however you like.  Not very convenient,
  890.     but doable.
  891.  
  892.     See the perlform(1) man page for other tricks.
  893.  
  894.  
  895. 4.19) Why does my Perl program keep growing in size?
  896.  
  897.     This is caused by a strange occurrence that Larry has dubbed "feeping
  898.     creaturism".  Larry is always adding one more feature, always getting
  899.     Perl to handle one more problem.  Hence, it keeps growing.  Once you've
  900.     worked with perl long enough, you will probably start to do the same
  901.     thing.  You will then notice this problem as you see your scripts
  902.     becoming larger and larger.
  903.  
  904.     Oh, wait... you meant a currently running program and its stack size.
  905.     Mea culpa, I misunderstood you.  ;)  While there may be a real memory
  906.     leak in the Perl source code or even whichever malloc() you're using,
  907.     common causes are incomplete eval()s or local()s in loops.
  908.  
  909.     An eval() which terminates in error due to a failed parsing will leave
  910.     a bit of memory unusable. 
  911.  
  912.     A local() inside a loop:
  913.  
  914.     for (1..100) {
  915.         local(@array);
  916.     } 
  917.  
  918.     will build up 100 versions of @array before the loop is done.  The
  919.     work-around is:   
  920.  
  921.     local(@array);
  922.     for (1..100) {
  923.         undef @array;
  924.     } 
  925.  
  926.     This local array behaviour has been fixed for perl5, but a failed
  927.     eval() still leaks.
  928.  
  929.     One other possibility, due to the way reference counting works, is
  930.     when you've introduced a circularity in a data structure that would
  931.     normally go out of scope and be unreachable.  For example:
  932.  
  933.     sub oops {
  934.         my $x;
  935.         $x = \$x;
  936.     } 
  937.  
  938.     When $x goes out of scope, the memory can't be reclaimed, because
  939.     there's still something point to $x (itself, in this case).  A 
  940.     full garbage collection system could solve this, but at the cost
  941.     of a great deal of complexity in perl itself and some inevitable
  942.     performance problems as well.  If you're making a circular data
  943.     structure that you want freed eventually, you'll have to break the
  944.     self-reference links yourself.
  945.  
  946.  
  947. 4.20) Can I do RPC in Perl?
  948.  
  949.     Yes, you can, since Perl has access to sockets.  An example of the rup
  950.     program written in Perl can be found in the script ruptime.pl at the
  951.     scripts archive on ftp.cis.ufl.edu.  I warn you, however, that it's not
  952.     a pretty sight, as it's used nothing from h2ph or c2ph, so everything is
  953.     utterly hard-wired. 
  954.  
  955.  
  956. 4.21) Why doesn't my sockets program work under System V (Solaris)?  What
  957.     does the error message "Protocol not supported" mean?
  958.  
  959.     Some System V based systems, notably Solaris 2.X, redefined some of the
  960.     standard socket constants.  Since these were constant across all
  961.     architectures, they were often hardwired into the perl code.  The
  962.     "proper" way to deal with this is to make sure that you run h2ph
  963.     against sys/socket.h, require that file and use the symbolic names
  964.     (SOCK_STREAM, SOCK_DGRAM, SOCK_RAW, SOCK_RDM, and SOCK_SEQPACKET).
  965.  
  966.     Note that even though SunOS 4 and SunOS 5 are binary compatible, these
  967.     values are different, and require a different socket.ph for each OS.
  968.  
  969.     Under version 5, you can also "use Socket" to get the proper values.
  970.  
  971.  
  972. 4.22) How can I quote a variable to use in a regexp?
  973.  
  974.     From the manual:
  975.  
  976.     $pattern =~ s/(\W)/\\$1/g;
  977.  
  978.     Now you can freely use /$pattern/ without fear of any unexpected meta-
  979.     characters in it throwing off the search.  If you don't know whether a
  980.     pattern is valid or not, enclose it in an eval to avoid a fatal run-
  981.     time error.  
  982.  
  983.     Perl5 provides a vastly improved way of doing this.  Simply use the
  984.     new quotemeta character (\Q) within your variable.
  985.  
  986. 4.23) How can I change the first N letters of a string?
  987.  
  988.     Remember that the substr() function produces an lvalue, that is, it may
  989.     be assigned to.  Therefore, to change the first character to an S, you
  990.     could do this:
  991.     
  992.     substr($var,0,1) = 'S';
  993.  
  994.     This assumes that $[ is 0;  for a library routine where you can't know
  995.     $[, you should use this instead:
  996.  
  997.     substr($var,$[,1) = 'S';
  998.  
  999.     While it would be slower, you could in this case use a substitute:
  1000.  
  1001.     $var =~ s/^./S/;
  1002.     
  1003.     But this won't work if the string is empty or its first character is a
  1004.     newline, which "." will never match.  So you could use this instead:
  1005.  
  1006.     $var =~ s/^[^\0]?/S/;
  1007.  
  1008.     To do things like translation of the first part of a string, use
  1009.     substr, as in:
  1010.  
  1011.     substr($var, $[, 10) =~ tr/a-z/A-Z/;
  1012.  
  1013.     If you don't know the length of what to translate, something like this
  1014.     works: 
  1015.  
  1016.     /^(\S+)/ && substr($_,$[,length($1)) =~ tr/a-z/A-Z/;
  1017.     
  1018.     For some things it's convenient to use the /e switch of the substitute
  1019.     operator: 
  1020.  
  1021.     s/^(\S+)/($tmp = $1) =~ tr#a-z#A-Z#, $tmp/e
  1022.  
  1023.     although in this case, it runs more slowly than does the previous
  1024.     example. 
  1025.  
  1026.  
  1027. 4.24) How can I count the number of occurrences of a substring within a
  1028.     string? 
  1029.  
  1030.     If you want a count of a certain character (X) within a string, you can
  1031.     use the tr/// function like so:
  1032.  
  1033.     $string="ThisXlineXhasXsomeXx'sXinXit":
  1034.     $count = ($string =~ tr/X//);
  1035.     print "There are $count Xs in the string";
  1036.  
  1037.     This is fine if you are just looking for a single character.  However,
  1038.     if you are trying to count multiple character substrings within a
  1039.     larger string, tr/// won't work.  What you can do is wrap a while loop
  1040.     around a pattern match.
  1041.  
  1042.     $string="-9 55 48 -2 23 -76 4 14 -44";
  1043.     $count++ while $string =~ /-\d+/g;
  1044.     print "There are $count negative numbers in the string";
  1045.  
  1046.  
  1047. 4.25) Can I use Perl regular expressions to match balanced text?
  1048.  
  1049.     No, or at least, not by themselves.
  1050.  
  1051.     Regexps just aren't powerful enough.  Although Perl's patterns aren't
  1052.     strictly regular because they do backreferencing (the \1 notation), you
  1053.     still can't do it.  You need to employ auxiliary logic.  A simple
  1054.     approach would involve keeping a bit of state around, something 
  1055.     vaguely like this (although we don't handle patterns on the same line):
  1056.  
  1057.     while(<>) {
  1058.         if (/pat1/) {
  1059.         if ($inpat++ > 0) { warn "already saw pat1" } 
  1060.         redo;
  1061.         } 
  1062.         if (/pat2/) {
  1063.         if (--$inpat < 0) { warn "never saw pat1" } 
  1064.         redo;
  1065.         } 
  1066.     }
  1067.  
  1068.     A rather more elaborate subroutine to pull out balanced and possibly
  1069.     nested single chars, like ` and ', { and }, or ( and ) can be found
  1070.     on convex.com in /pub/perl/scripts/pull_quotes.
  1071.  
  1072.  
  1073. 4.26) What does it mean that regexps are greedy?  How can I get around it?
  1074.  
  1075.     The basic idea behind regexps being greedy is that they will match the
  1076.     maximum amount of data that they can, sometimes resulting in incorrect
  1077.     or strange answers.
  1078.  
  1079.     For example, I recently came across something like this:
  1080.  
  1081.     $_="this (is) an (example) of multiple parens";
  1082.     while ( m#\((.*)\)#g ) {
  1083.         print "$1\n";
  1084.     }
  1085.  
  1086.     This code was supposed to match everything between a set of
  1087.     parentheses.  The expected output was:
  1088.  
  1089.     is
  1090.     example
  1091.  
  1092.     However, the backreference ($1) ended up containing "is) an (example",
  1093.     clearly not what was intended.
  1094.  
  1095.     In perl4, the way to stop this from happening is to use a negated
  1096.     group.  If the above example is rewritten as follows, the results are
  1097.     correct: 
  1098.  
  1099.     while ( m#\(([^)]*)\)#g ) {
  1100.  
  1101.     In perl5 there is a new minimal matching metacharacter, '?'.  This
  1102.     character is added to the normal metacharacters to modify their
  1103.     behaviour, such as "*?", "+?", or even "??".  The example would now be
  1104.     written in the following style:
  1105.  
  1106.     while (m#\((.*?)\)#g )
  1107.  
  1108.     Hint: This new operator leads to a very elegant method of stripping
  1109.     comments from C code:
  1110.  
  1111.     s:/\*.*?\*/::gs
  1112.  
  1113.  
  1114. 4.27) How do I use a regular expression to strip C style comments from a
  1115.       file?
  1116.  
  1117.     Since we're talking about how to strip comments under perl5, now is a
  1118.     good time to talk about doing it in perl4.  Since comments can be
  1119.     embedded in strings, or look like function prototypes, care must be
  1120.     taken to ignore these cases.  Jeffrey Friedl* proposes the following
  1121.     two programs to strip C comments and C++ comments respectively:
  1122.  
  1123.     C comments:
  1124.         #!/usr/bin/perl
  1125.         $/ = undef;
  1126.         $_ = <>; 
  1127.  
  1128.         s#/\*[^*]*\*+([^/*][^*]*\*+)*/|([^/"']*("[^"\\]*(\\[\d\D][^"\\]*)*"[^/"']*|'[^'\\]*(\\[\d\D][^'\\]*)*'[^/"']*|/+[^*/][^/"']*)*)#$2#g;
  1129.         print; 
  1130.  
  1131.     C++ comments:
  1132.         #!/usr/local/bin/perl
  1133.         $/ = undef;
  1134.         $_ = <>;
  1135.         s#//(.*)|/\*[^*]*\*+([^/*][^*]*\*+)*/|"(\\.|[^"\\])*"|'(\\.|[^'\\])*'|[^/"']+#  $1 ? "/*$1 */" : $& #ge;
  1136.         print;
  1137.  
  1138.     (Yes, Jeffrey says, those are complete programs to strip comments
  1139.     correctly.) 
  1140.  
  1141.  
  1142. 4.28) How can I split a [character] delimited string except when inside
  1143.     [character]?
  1144.  
  1145.     I'm trying to split a string that is comma delimited into its different
  1146.     fields.  I could easily use split(/,/), except that I need to not split
  1147.     if the comma is inside quotes.  For example, my data file has a line
  1148.     like this:
  1149.  
  1150.     SAR001,"","Cimetrix, Inc","Bob Smith","CAM",N,8,1,0,7,"Error, Core Dumped"
  1151.  
  1152.     Due to the restriction of the quotes, this is a fairly complex
  1153.     solution.  However, we thankfully have Jeff Friedl* to handle these for
  1154.     us.  He suggests (assuming that your data is contained in the special
  1155.     variable $_):
  1156.  
  1157.     undef @field;
  1158.     push(@fields, defined($1) ? $1:$3) while 
  1159.         m/"([^"\\]*(\\.[^"\\]*)*)"|([^,]+)/g;
  1160.  
  1161.  
  1162. 4.29) Why doesn't "local($foo) = <FILE>;" work right?
  1163.  
  1164.     Well, it does.  The thing to remember is that local() provides an array
  1165.     context, and that the <FILE> syntax in an array context will read all the
  1166.     lines in a file.  To work around this, use:
  1167.  
  1168.     local($foo);
  1169.     $foo = <FILE>;
  1170.  
  1171.     You can use the scalar() operator to cast the expression into a scalar
  1172.     context:
  1173.  
  1174.     local($foo) = scalar(<FILE>);
  1175.  
  1176.  
  1177. 4.30) How can I detect keyboard input without reading it? 
  1178.  
  1179.     You should check out the Frequently Asked Questions list in
  1180.     comp.unix.* for things like this: the answer is essentially the same.
  1181.     It's very system dependent.  Here's one solution that works on BSD
  1182.     systems:
  1183.  
  1184.     sub key_ready {
  1185.         local($rin, $nfd);
  1186.         vec($rin, fileno(STDIN), 1) = 1;
  1187.         return $nfd = select($rin,undef,undef,0);
  1188.     }
  1189.  
  1190.     Under perl5, you should look into getting the ReadKey extension from
  1191.     your regular perl archive.
  1192.  
  1193.  
  1194. 4.31) How can I read a single character from the keyboard under UNIX and DOS?
  1195.  
  1196.     A closely related question to the no-echo question below is how to
  1197.     input a single character from the keyboard.  Again, this is a system
  1198.     dependent operation.  As with the previous question, you probably want
  1199.     to get the ReadKey extension.  The following code may or may not help
  1200.     you.  It should work on both SysV and BSD flavors of UNIX:
  1201.  
  1202.     $BSD = -f '/vmunix';
  1203.     if ($BSD) {
  1204.         system "stty cbreak </dev/tty >/dev/tty 2>&1";
  1205.     }
  1206.     else {
  1207.         system "stty", '-icanon',
  1208.         system "stty", 'eol', "\001"; 
  1209.     }
  1210.  
  1211.     $key = getc(STDIN);
  1212.  
  1213.     if ($BSD) {
  1214.         system "stty -cbreak </dev/tty >/dev/tty 2>&1";
  1215.     }
  1216.     else {
  1217.         system "stty", 'icanon';
  1218.         system "stty", 'eol', '^@'; # ascii null
  1219.     }
  1220.     print "\n";
  1221.  
  1222.     You could also handle the stty operations yourself for speed if you're
  1223.     going to be doing a lot of them.  This code works to toggle cbreak
  1224.     and echo modes on a BSD system:
  1225.  
  1226.     sub set_cbreak { # &set_cbreak(1) or &set_cbreak(0)
  1227.     local($on) = $_[0];
  1228.     local($sgttyb,@ary);
  1229.     require 'sys/ioctl.ph';
  1230.     $sgttyb_t   = 'C4 S' unless $sgttyb_t;  # c2ph: &sgttyb'typedef()
  1231.  
  1232.     ioctl(STDIN,&TIOCGETP,$sgttyb) || die "Can't ioctl TIOCGETP: $!";
  1233.  
  1234.     @ary = unpack($sgttyb_t,$sgttyb);
  1235.     if ($on) {
  1236.         $ary[4] |= &CBREAK;
  1237.         $ary[4] &= ~&ECHO;
  1238.     } else {
  1239.         $ary[4] &= ~&CBREAK;
  1240.         $ary[4] |= &ECHO;
  1241.     }
  1242.     $sgttyb = pack($sgttyb_t,@ary);
  1243.  
  1244.     ioctl(STDIN,&TIOCSETP,$sgttyb) || die "Can't ioctl TIOCSETP: $!";
  1245.     }
  1246.  
  1247.     Note that this is one of the few times you actually want to use the
  1248.     getc() function; it's in general way too expensive to call for normal
  1249.     I/O.  Normally, you just use the <FILE> syntax, or perhaps the read()
  1250.     or sysread() functions.
  1251.  
  1252.     For perspectives on more portable solutions, use anon ftp to retrieve
  1253.     the file /pub/perl/info/keypress from convex.com.
  1254.  
  1255.     Under Perl5, with William Setzer's Curses module, you can call
  1256.     &Curses::cbreak() and &Curses::nocbreak() to turn cbreak mode on and
  1257.     off.  You can then use getc() to read each character.  This should work
  1258.     under both BSD and SVR systems.  If anyone can confirm or deny
  1259.     (especially William), please contact the maintainers.
  1260.  
  1261.     For DOS systems, Dan Carson <dbc@tc.fluke.COM> reports:
  1262.  
  1263.     To put the PC in "raw" mode, use ioctl with some magic numbers gleaned
  1264.     from msdos.c (Perl source file) and Ralf Brown's interrupt list (comes
  1265.     across the net every so often):
  1266.  
  1267.     $old_ioctl = ioctl(STDIN,0,0);     # Gets device info
  1268.     $old_ioctl &= 0xff;
  1269.     ioctl(STDIN,1,$old_ioctl | 32);    # Writes it back, setting bit 5
  1270.  
  1271.     Then to read a single character:
  1272.  
  1273.     sysread(STDIN,$c,1);               # Read a single character
  1274.  
  1275.     And to put the PC back to "cooked" mode:
  1276.  
  1277.     ioctl(STDIN,1,$old_ioctl);         # Sets it back to cooked mode.
  1278.  
  1279.  
  1280.     So now you have $c.  If ord($c) == 0, you have a two byte code, which
  1281.     means you hit a special key.  Read another byte (sysread(STDIN,$c,1)),
  1282.     and that value tells you what combination it was according to this
  1283.     table:
  1284.  
  1285.     # PC 2-byte keycodes = ^@ + the following:
  1286.  
  1287.     # HEX     KEYS
  1288.     # ---     ----
  1289.     # 0F      SHF TAB
  1290.     # 10-19   ALT QWERTYUIOP
  1291.     # 1E-26   ALT ASDFGHJKL
  1292.     # 2C-32   ALT ZXCVBNM
  1293.     # 3B-44   F1-F10
  1294.     # 47-49   HOME,UP,PgUp
  1295.     # 4B      LEFT
  1296.     # 4D      RIGHT
  1297.     # 4F-53   END,DOWN,PgDn,Ins,Del
  1298.     # 54-5D   SHF F1-F10
  1299.     # 5E-67   CTR F1-F10
  1300.     # 68-71   ALT F1-F10
  1301.     # 73-77   CTR LEFT,RIGHT,END,PgDn,HOME
  1302.     # 78-83   ALT 1234567890-=
  1303.     # 84      CTR PgUp
  1304.  
  1305.     This is all trial and error I did a long time ago, I hope I'm reading the
  1306.     file that worked.
  1307.  
  1308.  
  1309. 4.32) How can I get input from the keyboard without it echoing to the
  1310.       screen?
  1311.  
  1312.     Terminal echoing is generally handled directly by the shell.
  1313.     Therefore, there is no direct way in perl to turn echoing on and off.
  1314.     However, you can call the command "stty [-]echo".  The following will
  1315.     allow you to accept input without it being echoed to the screen, for
  1316.     example as a way to accept passwords (error checking deleted for
  1317.     brevity):
  1318.  
  1319.     print "Please enter your password: ";
  1320.         system("stty -echo");
  1321.     chop($password=<STDIN>);
  1322.     print "\n";
  1323.     system("stty echo");
  1324.  
  1325.     Again, under perl 5, you can use Curses and call &Curses::noecho() and
  1326.     &Curses::echo() to turn echoing off and on.  Or, there's always the
  1327.     ReadKey extension.
  1328.  
  1329.  
  1330. 4.33) Is there any easy way to strip blank space from the beginning/end of
  1331.     a string?
  1332.  
  1333.     Yes, there is.  Using the substitution command, you can match the
  1334.     blanks and replace it with nothing.  For example, if you have the
  1335.     string "     String     " you can use this:
  1336.  
  1337.         s/^\s*(.*?)\s*$/$1/;     # perl5 only!
  1338.  
  1339.         s/^\s+|\s+$//g;            # perl4 or perl5
  1340.  
  1341.     or even
  1342.  
  1343.         s/^\s+//; s/\s+$//;
  1344.  
  1345.     Note however that Jeffrey Friedl* says these are only good for shortish
  1346.     strings.  For longer strings, and worse-case scenarios, they tend to
  1347.     break-down and become inefficient.
  1348.  
  1349.     For the longer strings, he suggests using either
  1350.  
  1351.         $_ = $1 if m/^\s*((.*\S)?)/;
  1352.  
  1353.     or
  1354.     
  1355.         s/^\s*((.*\S)?)\s*$/$1/;
  1356.  
  1357.     It should also be noted that for generally nice strings, these tend to
  1358.     be noticably slower than the simple ones above.  It is suggested that
  1359.     you use whichever one will fit your situation best, understanding that
  1360.     the first examples will work in roughly ever situation known even if
  1361.     slow at times.
  1362.  
  1363. 4.34) How can I print out a number with commas into it?
  1364.  
  1365.     This one will do it for you:
  1366.  
  1367.     sub commify {
  1368.         local($_) = shift;
  1369.         1 while s/^(-?\d+)(\d{3})/$1,$2/;
  1370.         return $_;
  1371.     } 
  1372.  
  1373.     $n = 23659019423.2331;
  1374.     print "GOT: ", &commify($n), "\n";
  1375.  
  1376.     GOT: 23,659,019,423.2331
  1377.  
  1378.     The reason you can't just do
  1379.  
  1380.     s/^(-?\d+)(\d{3})/$1,$2/g;
  1381.  
  1382.     Is that you have to put the comma in and then recalculate anything.  
  1383.     Some substitutions need to work this way.  See the question on 
  1384.     expanding tabs for another such.
  1385.  
  1386. 4.35) How do I expand tabs in a string?
  1387.  
  1388.     1 while s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e;
  1389.  
  1390.     You could have written that
  1391.  
  1392.     while (s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e) {
  1393.         # spin, spin, spin, ....
  1394.     } 
  1395.  
  1396.     Placed in a function:
  1397.  
  1398.     sub tab_expand {
  1399.         local($_) = shift;
  1400.         1 while s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e;
  1401.         return $_;
  1402.     } 
  1403.  
  1404.     This is especially important when you're working going to unpack 
  1405.     an ascii string that might have tabs in it.  Otherwise you'll be
  1406.     off on the byte count.  For example:
  1407.  
  1408.     $NG = "/usr/local/lib/news/newsgroups";
  1409.     open(NG, "< $NG") || die "can't open $NG: $!";
  1410.     while (<NG>) {
  1411.         chop;  # chomp would be better, but it's only perl5
  1412.         # now for the darned tabs in the newsgroups file
  1413.         1 while s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e;
  1414.         ($ng, $desc) = unpack("A24 A*", $_);
  1415.         if (length($ng) == 24) {
  1416.         $desc =~ s/^(\S+)\s*//;
  1417.         $ng .= $1;
  1418.         } 
  1419.  
  1420. 4.36) What's wrong with grep() or map() in a void context?
  1421.  
  1422.     Well, nothing precisely, but it's not a good way to write 
  1423.     maintainable code.  It's just fine to use grep when you want
  1424.     an answer, like
  1425.  
  1426.     @bignums = grep ($_ > 100, @allnums);
  1427.     @triplist = map {$_ * 3} @allnums;
  1428.  
  1429.     But using it in a void context like this:
  1430.  
  1431.     grep{ $_ *= 3, @nums);
  1432.  
  1433.     Is using it for its side-effects, and side-effects can be mystifying.
  1434.     There's no void grep that's not better written as a for() loop:
  1435.  
  1436.     for (@nums) { $_ *= 3 } 
  1437.  
  1438.     In the same way, a ?: in a void context is considered poor form:
  1439.  
  1440.     fork ? wait : exec $prog;
  1441.  
  1442.     When you can write it this way:
  1443.  
  1444.     if (fork) {
  1445.         wait;
  1446.     } else {
  1447.         exec $prog;
  1448.         die "can't exec $prog: $!";
  1449.     } 
  1450.  
  1451.     Of course, using ?: in expressions is just what it's made for, 
  1452.     and just fine (but try not to nest them.).
  1453.  
  1454.     Remember that the most important things in almost any program are,
  1455.     and in this order:
  1456.  
  1457.     1. correctness
  1458.     2. maintainability
  1459.     3. efficiency
  1460.  
  1461.     Notice at no point did cleverness enter the picture.
  1462.  
  1463.     On the other hand, if you're just trying write JAPHs (aka Obfuscated
  1464.     Perl entries), or write ugly code, you would probably invert these :-)
  1465.  
  1466.     1. cleverness
  1467.     2. efficiency
  1468.     3. maintainability
  1469.     4. correctness
  1470.  
  1471. --
  1472. Stephen P Potter        Pencom Systems Administration              Beaching It 
  1473. spp@psa.pencom.com    Pager: 1-800-759-8888, 547-9561     Work: 703-860-2222
  1474.   Cthulhu for President in '96: When You're Tired of the Lesser of Two Evils
  1475. --
  1476. Stephen P Potter        Pencom Systems Administration              Beaching It 
  1477. spp@psa.pencom.com    Pager: 1-800-759-8888, 547-9561     Work: 703-860-2222
  1478. "I don't care whether people actually like Perl, just so long as they *think*
  1479.     they like it...  ;-)"    -Larry Wall
  1480.