home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 2 / Apprentice-Release2.iso / Information / Languages / Perl / perl-faq⁄part4 < prev    next >
Encoding:
Internet Message Format  |  1994-12-03  |  34.9 KB  |  [TEXT/R*ch]

  1. Path: bloom-beacon.mit.edu!senator-bedfellow.mit.edu!faqserv
  2. From: spp@vx.com
  3. Newsgroups: comp.lang.perl,comp.answers,news.answers
  4. Subject: comp.lang.perl FAQ 4/5 - General Programming
  5. Supersedes: <perl-faq/part4_784894001@rtfm.mit.edu>
  6. Followup-To: poster
  7. Date: 30 Nov 1994 09:40:53 GMT
  8. Organization: none
  9. Lines: 1065
  10. Approved: news-answers-request@MIT.EDU
  11. Distribution: world
  12. Message-ID: <perl-faq/part4_786188328@rtfm.mit.edu>
  13. References: <perl-faq/part0_786188328@rtfm.mit.edu>
  14. NNTP-Posting-Host: bloom-picayune.mit.edu
  15. X-Last-Updated: 1994/11/14
  16. Originator: faqserv@bloom-picayune.MIT.EDU
  17. Xref: bloom-beacon.mit.edu comp.lang.perl:27006 comp.answers:8613 news.answers:30227
  18.  
  19. Archive-name: perl-faq/part4
  20. Version: $Id: part4,v 2.3 1994/11/07 18:06:47 spp Exp spp $
  21. Posting-Frequency: bi-weekly
  22.  
  23. This posting contains answers to the following questions about General
  24. Programming, Regular Expressions (Regexp) and Input/Output:
  25.  
  26.  
  27. 4.1) What are all these $@%*<> signs and how do I know when to use them?
  28.  
  29.     Those are type specifiers: 
  30.     $ for scalar values
  31.     @ for indexed arrays
  32.     % for hashed arrays (associative arrays)
  33.     * for all types of that symbol name.  These are sometimes used like
  34.         pointers
  35.     <> are used for inputting a record from a filehandle.  
  36.  
  37.     See the question on arrays of arrays for more about Perl pointers.
  38.  
  39.     While there are a few places where you don't actually need these type
  40.     specifiers, except for files, you should always use them.  Note that
  41.     <FILE> is NOT the type specifier for files; it's the equivalent of awk's
  42.     getline function, that is, it reads a line from the handle FILE.  When
  43.     doing open, close, and other operations besides the getline function on
  44.     files, do NOT use the brackets.
  45.  
  46.     Beware of saying:
  47.     $foo = BAR;
  48.     Which wil be interpreted as 
  49.     $foo = 'BAR';
  50.     and not as 
  51.     $foo = <BAR>;
  52.     If you always quote your strings, you'll avoid this trap.
  53.  
  54.     Normally, files are manipulated something like this (with appropriate
  55.     error checking added if it were production code):
  56.  
  57.     open (FILE, ">/tmp/foo.$$");
  58.     print FILE "string\n";
  59.     close FILE;
  60.  
  61.     If instead of a filehandle, you use a normal scalar variable with file
  62.     manipulation functions, this is considered an indirect reference to a
  63.     filehandle.  For example,
  64.  
  65.     $foo = "TEST01";
  66.     open($foo, "file");
  67.  
  68.     After the open, these two while loops are equivalent:
  69.  
  70.     while (<$foo>) {}
  71.     while (<TEST01>) {}
  72.  
  73.     as are these two statements:
  74.     
  75.     close $foo;
  76.     close TEST01;
  77.  
  78.     but NOT to this:
  79.  
  80.     while (<$TEST01>) {} # error
  81.         ^
  82.         ^ note spurious dollar sign
  83.  
  84.     This is another common novice mistake; often it's assumed that
  85.  
  86.     open($foo, "output.$$");
  87.  
  88.     will fill in the value of $foo, which was previously undefined.  This
  89.     just isn't so -- you must set $foo to be the name of a filehandle
  90.     before you attempt to open it.   
  91.  
  92.  
  93. 4.2) How come Perl operators have different precedence than C operators?
  94.  
  95.     Actually, they don't; all C operators have the same precedence in Perl as
  96.     they do in C.  The problem is with a class of functions called list
  97.     operators, e.g. print, chdir, exec, system, and so on.  These are somewhat
  98.     bizarre in that they have different precedence depending on whether you
  99.     look on the left or right of them.  Basically, they gobble up all things
  100.     on their right.  For example,
  101.  
  102.     unlink $foo, "bar", @names, "others";
  103.  
  104.     will unlink all those file names.  A common mistake is to write:
  105.  
  106.     unlink "a_file" || die "snafu";
  107.  
  108.     The problem is that this gets interpreted as
  109.  
  110.     unlink("a_file" || die "snafu");
  111.  
  112.     To avoid this problem, you can always make them look like function calls
  113.     or use an extra level of parentheses:
  114.  
  115.     unlink("a_file")  || die "snafu";
  116.     (unlink "a_file") || die "snafu";
  117.  
  118.     In perl5, there are low precedence "and", "or", and "not" operators,
  119.     which bind les tightly than comma.  This alllows you to write:
  120.  
  121.     unlink $foo, "bar", @names, "others"     or die "snafu";
  122.  
  123.     Sometimes you actually do care about the return value:
  124.  
  125.     unless ($io_ok = print("some", "list")) { } 
  126.  
  127.     Yes, print() returns I/O success.  That means
  128.  
  129.     $io_ok = print(2+4) * 5;
  130.  
  131.     returns 5 times whether printing (2+4) succeeded, and 
  132.     print(2+4) * 5;
  133.     returns the same 5*io_success value and tosses it.
  134.  
  135.     See the perlop(1) man page's section on Precedence for more gory details,
  136.     and be sure to use the -w flag to catch things like this.
  137.  
  138.  
  139. 4.3) What's the difference between dynamic and static (lexical) scoping?
  140.      What are my() and local()?
  141.  
  142.     [NOTE: This question refers to perl5 only.  There is no my() in perl4]
  143.     Scoping refers to visibility of variables.  A dynamic variable is
  144.     created via local() and is just a local value for a global variable,
  145.     whereas a lexical variable created via my() is more what you're
  146.     expecting from a C auto.  (See also "What's the difference between
  147.     deep and shallow binding.")  In general, we suggest you use lexical
  148.     variables wherever possible, as they're faster to access and easier to
  149.     understand.   The "use strict vars" pragma will enforce that all
  150.     variables are either lexical, or full classified by package name.  We
  151.     strongly suggest that you develop your code with "use strict;" and the
  152.     -w flag.  (When using formats, however, you will still have to use
  153.     dynamic variables.)  Here's an example of the difference:
  154.  
  155.     $scount = 1; $lcount = 2;
  156.         sub foo {
  157.             my($i,$j) = @_;
  158.             my    $scount = 10;
  159.             local $lcount = 20;
  160.             &bar();
  161.         }
  162.         sub bar {
  163.             print "scount is $scount\en";
  164.             print "lcount is $lcount\en";
  165.         }
  166.  
  167.     This prints:
  168.  
  169.         scount is 1
  170.         lcount is 20
  171.  
  172.     Notice that the variables declared with my() are visible only within
  173.     the scope of the block which names them.  They are not visible outside
  174.     of this block, not even in routines or blocks that it calls.  local() 
  175.     variables, on the other hand, are visible to routines that are called
  176.     from the block where they are declared.  Neither is visible after the
  177.     end (the final closing curly brace) of the block at all.
  178.  
  179.     Oh, lexical variables are only available in perl5.  Have we
  180.     mentioned yet that you might consider upgrading? :-)
  181.  
  182.  
  183. 4.4) What's the difference between deep and shallow binding?
  184.  
  185.     This only matters when you're making subroutines yourself, at least
  186.     so far.   This will give you shallow binding:
  187.  
  188.     {
  189.           my $x = time;
  190.           $coderef = sub { $x };
  191.         }
  192.  
  193.     When you call &$coderef(), it will get whatever dynamic $x happens
  194.     to be around when invoked.  However, you can get the other behaviour
  195.     this way:
  196.  
  197.     {
  198.           my $x = time;
  199.           $coderef = eval "sub { \$x }";
  200.         }
  201.  
  202.     Now you'll access the lexical variable $x which is set to the
  203.     time the subroutine was created.  Note that the difference in these
  204.     two behaviours can be considered a bug, not a feature, so you should
  205.     in particular not rely upon shallow binding, as it will likely go
  206.     away in the future.  See perlref(1).
  207.  
  208.  
  209. 4.5) How can I manipulate fixed-record-length files?
  210.  
  211.     The most efficient way is using pack and unpack.  This is faster than
  212.     using substr.  Here is a sample chunk of code to break up and put back
  213.     together again some fixed-format input lines, in this case, from ps.
  214.  
  215.     # sample input line:
  216.     #   15158 p5  T      0:00 perl /mnt/tchrist/scripts/now-what
  217.     $ps_t = 'A6 A4 A7 A5 A*';
  218.     open(PS, "ps|");
  219.     $_ = <PS>; print;
  220.     while (<PS>) {
  221.         ($pid, $tt, $stat, $time, $command) = unpack($ps_t, $_);
  222.         for $var ('pid', 'tt', 'stat', 'time', 'command' ) {
  223.         print "$var: <", eval "\$$var", ">\n";
  224.         }
  225.         print 'line=', pack($ps_t, $pid, $tt, $stat, $time, $command),  "\n";
  226.     }
  227.  
  228.  
  229. 4.6) How can I make a file handle local to a subroutine?
  230.  
  231.     You must use the type-globbing *VAR notation.  Here is some code to
  232.     cat an include file, calling itself recursively on nested local
  233.     include files (i.e. those with #include "file", not #include <file>):
  234.  
  235.     sub cat_include {
  236.         local($name) = @_;
  237.         local(*FILE);
  238.         local($_);
  239.  
  240.         warn "<INCLUDING $name>\n";
  241.         if (!open (FILE, $name)) {
  242.         warn "can't open $name: $!\n";
  243.         return;
  244.         }
  245.         while (<FILE>) {
  246.         if (/^#\s*include "([^"]*)"/) {
  247.             &cat_include($1);
  248.         } else {
  249.             print;
  250.         }
  251.         }
  252.         close FILE;
  253.     }
  254.  
  255.  
  256. 4.7) How can I call alarm() or usleep() from Perl?
  257.  
  258.     If you want finer granularity than 1 second (as usleep() provides) and
  259.     have itimers and syscall() on your system, you can use the following.
  260.     You could also use select().
  261.  
  262.     It takes a floating-point number representing how long to delay until
  263.     you get the SIGALRM, and returns a floating- point number representing
  264.     how much time was left in the old timer, if any.  Note that the C
  265.     function uses integers, but this one doesn't mind fractional numbers.
  266.  
  267.     # alarm; send me a SIGALRM in this many seconds (fractions ok)
  268.     # tom christiansen <tchrist@convex.com>
  269.     sub alarm {
  270.     require 'syscall.ph';
  271.     require 'sys/time.ph';
  272.  
  273.     local($ticks) = @_;
  274.     local($in_timer,$out_timer);
  275.     local($isecs, $iusecs, $secs, $usecs);
  276.  
  277.     local($itimer_t) = 'L4'; # should be &itimer'typedef()
  278.  
  279.     $secs = int($ticks);
  280.     $usecs = ($ticks - $secs) * 1e6;
  281.  
  282.     $out_timer = pack($itimer_t,0,0,0,0);  
  283.     $in_timer  = pack($itimer_t,0,0,$secs,$usecs);
  284.  
  285.     syscall(&SYS_setitimer, &ITIMER_REAL, $in_timer, $out_timer)
  286.         && die "alarm: setitimer syscall failed: $!";
  287.  
  288.     ($isecs, $iusecs, $secs, $usecs) = unpack($itimer_t,$out_timer);
  289.     return $secs + ($usecs/1e6);
  290.     }
  291.  
  292.  
  293. 4.8) How can I do an atexit() or setjmp()/longjmp() in Perl?  (Exception handling)
  294.  
  295.     Perl's exception-handling mechanism is its eval operator.  You 
  296.     can use eval as setjmp and die as longjmp.  Here's an example
  297.     of Larry's for timed-out input, which in C is often implemented
  298.     using setjmp and longjmp:
  299.  
  300.       $SIG{ALRM} = TIMEOUT;
  301.       sub TIMEOUT { die "restart input\n" }
  302.  
  303.       do { eval { &realcode } } while $@ =~ /^restart input/;
  304.  
  305.       sub realcode {
  306.           alarm 15;
  307.           $ans = <STDIN>;
  308.           alarm 0;
  309.       }
  310.  
  311.    Here's an example of Tom's for doing atexit() handling:
  312.  
  313.     sub atexit { push(@_exit_subs, @_) }
  314.  
  315.     sub _cleanup { unlink $tmp }
  316.  
  317.     &atexit('_cleanup');
  318.  
  319.     eval <<'End_Of_Eval';  $here = __LINE__;
  320.     # as much code here as you want
  321.     End_Of_Eval
  322.  
  323.     $oops = $@;  # save error message
  324.  
  325.     # now call his stuff
  326.     for (@_exit_subs) { &$_() }
  327.  
  328.     $oops && ($oops =~ s/\(eval\) line (\d+)/$0 .
  329.         " line " . ($1+$here)/e, die $oops);
  330.  
  331.     You can register your own routines via the &atexit function now.  You
  332.     might also want to use the &realcode method of Larry's rather than
  333.     embedding all your code in the here-is document.  Make sure to leave
  334.     via die rather than exit, or write your own &exit routine and call
  335.     that instead.   In general, it's better for nested routines to exit
  336.     via die rather than exit for just this reason.
  337.  
  338.     In Perl5, it is easy to set this up because of the automatic processing
  339.     of per-package END functions. 
  340.  
  341.     Eval is also quite useful for testing for system dependent features,
  342.     like symlinks, or using a user-input regexp that might otherwise
  343.     blowup on you.
  344.  
  345.  
  346. 4.9) How do I catch signals in perl?
  347.  
  348.     Perl allows you to trap signals using the %SIG associative array.
  349.     Using the signals you want to trap as the key, you can assign a
  350.     subroutine to that signal.  The %SIG array will only contain those
  351.     values which the programmer defines.  Therefore, you do not have to
  352.     assign all signals.  For example, to exit cleanly from a ^C:
  353.  
  354.     $SIG{'INT'} = 'CLEANUP';
  355.     sub CLEANUP {
  356.         print "\n\nCaught Interrupt (^C), Aborting\n";
  357.         exit(1);
  358.     }
  359.  
  360.     There are two special "routines" for signals called DEFAULT and IGNORE.
  361.     DEFAULT erases the current assignment, restoring the default value of
  362.     the signal.  IGNORE causes the signal to be ignored.  In general, you
  363.     don't need to remember these as you can emulate their functionality
  364.     with standard programming features.  DEFAULT can be emulated by
  365.     deleting the signal from the array and IGNORE can be emulated by any
  366.     undeclared subroutine.
  367.  
  368. 4.10) Why doesn't Perl interpret my octal data octally?
  369.  
  370.     Perl only understands octal and hex numbers as such when they occur
  371.     as literals in your program.  If they are read in from somewhere and
  372.     assigned, then no automatic conversion takes place.  You must
  373.     explicitly use oct() or hex() if you want this kind of thing to happen. 
  374.     Actually, oct() knows to interpret both hex and octal numbers, while
  375.     hex only converts hexadecimal ones.  For example:
  376.  
  377.     {
  378.         print "What mode would you like? ";
  379.         $mode = <STDIN>;
  380.         $mode = oct($mode);
  381.         unless ($mode) {
  382.         print "You can't really want mode 0!\n";
  383.         redo;
  384.         } 
  385.         chmod $mode, $file;
  386.     } 
  387.  
  388.     Without the octal conversion, a requested mode of 755 would turn 
  389.     into 01363, yielding bizarre file permissions of --wxrw--wt.
  390.  
  391.     If you want something that handles decimal, octal and hex input, 
  392.     you could follow the suggestion in the man page and use:
  393.  
  394.     $val = oct($val) if $val =~ /^0/;
  395.  
  396.  
  397. 4.11) How can I compare two date strings?
  398.  
  399.     If the dates are in an easily parsed, predetermined format, then you
  400.     can break them up into their component parts and call &timelocal from
  401.     the distributed perl library.  If the date strings are in arbitrary
  402.     formats, however, it's probably easier to use the getdate program from
  403.     the Cnews distribution, since it accepts a wide variety of dates.  Note
  404.     that in either case the return values you will really be comparing will
  405.     be the total time in seconds as returned by time(). 
  406.    
  407.     Here's a getdate function for perl that's not very efficient; you can
  408.     do better than this by sending it many dates at once or modifying
  409.     getdate to behave better on a pipe.  Beware the hardcoded pathname. 
  410.  
  411.     sub getdate {
  412.         local($_) = shift;
  413.  
  414.         s/-(\d{4})$/+$1/ || s/\+(\d{4})$/-$1/; 
  415.         # getdate has broken timezone sign reversal!
  416.  
  417.         $_ = `/usr/local/lib/news/newsbin/getdate '$_'`;
  418.         chop;
  419.         $_;
  420.     } 
  421.  
  422.     Richard Ohnemus <Rick_Ohnemus@Sterling.COM> actually has a getdate.y for
  423.     use with the Perl yacc.  You can get this from ftp.sterling.com
  424.     [192.124.9.1] in /local/perl-byacc1.8.1.tar.Z, or send the author mail
  425.     for details. 
  426.  
  427.     You might also consider using these: 
  428.  
  429.     date.pl        - print dates how you want with the sysv +FORMAT method 
  430.     date.shar      - routines to manipulate and calculate dates
  431.     ftp-chat2.shar - updated version of ftpget. includes library and demo 
  432.              programs 
  433.     getdate.shar   - returns number of seconds since epoch for any given
  434.              date 
  435.     ptime.shar     - print dates how you want with the sysv +FORMAT method 
  436.  
  437.     You probably want 'getdate.shar'... these and other files can be ftp'd
  438.     from the /pub/perl/scripts directory on ftp.cis.ufl.edu. See the README
  439.     file in the /pub/perl directory for time and the European mirror site
  440.     details. 
  441.  
  442.  
  443. 4.12) How can I find the Julian Day?
  444.  
  445.     Here's an example of a Julian Date function provided by Thomas R.
  446.     Kimpton*.
  447.  
  448.     #!/usr/local/bin/perl
  449.  
  450.     @theJulianDate = ( 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 );
  451.  
  452.     #************************************************************************
  453.     #****   Return 1 if we are after the leap day in a leap year.       *****
  454.     #************************************************************************
  455.                    
  456.     sub leapDay             
  457.     {                 
  458.         my($year,$month,$day) = @_;
  459.     
  460.         if (year % 4) {
  461.         return(0);
  462.         }
  463.  
  464.         if (!(year % 100)) {             # years that are multiples of 100
  465.                                      # are not leap years
  466.         if (year % 400) {            # unless they are multiples of 400
  467.             return(0);
  468.         }
  469.         }
  470.         if (month < 2) {
  471.             return(0);
  472.         } elsif ((month == 2) && (day < 29)) {
  473.         return(0);
  474.         } else {
  475.         return(1);
  476.         }
  477.     }
  478.     
  479.     #************************************************************************
  480.     #****   Pass in the date, in seconds, of the day you want the       *****
  481.     #****   julian date for.  If your localtime() returns the year day  *****
  482.     #****   return that, otherwise figure out the julian date.          *****
  483.     #************************************************************************
  484.         
  485.     sub julianDate    
  486.     {        
  487.         my($dateInSeconds) = @_;
  488.         my($sec, $min, $hour, $mday, $mon, $year, $wday, $yday);
  489.     
  490.         ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) =
  491.         localtime($dateInSeconds);
  492.         if (defined($yday)) {
  493.         return($yday+1);
  494.         } else {
  495.         return($theJulianDate[$mon] + $mday + &leapDay($year,$mon,$mday));
  496.         }
  497.     
  498.     }
  499.  
  500.     print "Today's julian date is: ",&julianDate(time),"\n";
  501.  
  502.  
  503. 4.13) What's the fastest way to code up a given task in perl?
  504.  
  505.     Post it to comp.lang.perl and ask Tom or Randal a question about it.
  506.     ;) 
  507.  
  508.     Because Perl so lends itself to a variety of different approaches for
  509.     any given task, a common question is which is the fastest way to code a
  510.     given task.  Since some approaches can be dramatically more efficient
  511.     that others, it's sometimes worth knowing which is best.
  512.     Unfortunately, the implementation that first comes to mind, perhaps as
  513.     a direct translation from C or the shell, often yields suboptimal
  514.     performance.  Not all approaches have the same results across different
  515.     hardware and software platforms.  Furthermore, legibility must
  516.     sometimes be sacrificed for speed. 
  517.  
  518.     While an experienced perl programmer can sometimes eye-ball the code
  519.     and make an educated guess regarding which way would be fastest,
  520.     surprises can still occur.  So, in the spirit of perl programming
  521.     being an empirical science, the best way to find out which of several
  522.     different methods runs the fastest is simply to code them all up and
  523.     time them. For example:
  524.  
  525.     $COUNT = 10_000; $| = 1;
  526.  
  527.     print "method 1: ";
  528.  
  529.         ($u, $s) = times;
  530.         for ($i = 0; $i < $COUNT; $i++) {
  531.         # code for method 1
  532.         }
  533.         ($nu, $ns) = times;
  534.         printf "%8.4fu %8.4fs\n", ($nu - $u), ($ns - $s);
  535.  
  536.     print "method 2: ";
  537.  
  538.         ($u, $s) = times;
  539.         for ($i = 0; $i < $COUNT; $i++) {
  540.         # code for method 2
  541.         }
  542.         ($nu, $ns) = times;
  543.         printf "%8.4fu %8.4fs\n", ($nu - $u), ($ns - $s);
  544.  
  545.     Perl5 includes a new module called Benchmark.pm.  You can now simplify
  546.     the code to use the Benchmarking, like so:
  547.  
  548.         use Benchmark;
  549.  
  550.             timethese($count, {
  551.                 Name1 => '...code for method 1...',
  552.                 Name2 => '...code for method 2...',
  553.                 ... });
  554.  
  555.     It will output something that looks similar to this:
  556.  
  557.         Benchmark: timing 100 iterations of Name1, Name2...
  558.                 Name1:  2 secs (0.50 usr 0.00 sys = 0.50 cpu)
  559.                 Name2:  1 secs (0.48 usr 0.00 sys = 0.48 cpu)
  560.  
  561.  
  562.     For example, the following code will show the time difference between
  563.     three different ways of assigning the first character of a string to
  564.     a variable:
  565.  
  566.     use Benchmark;
  567.     timethese(100000, {
  568.         'regex1' => '$str="ABCD"; $str =~ s/^(.)//; $ch = $1',
  569.         'regex2' => '$str="ABCD"; $str =~ s/^.//; $ch = $&',
  570.         'substr' => '$str="ABCD"; $ch=substr($str,0,1); substr($str,0,1)="",
  571.     });
  572.  
  573.     The results will be returned like this:
  574.  
  575.     Benchmark: timing 100000 iterations of regex1, regex2, substr...
  576.        regex1: 11 secs (10.80 usr   0.00 sys =  10.80 cpu)
  577.        regex2: 10 secs (10.23 usr   0.00 sys =  10.23 cpu)
  578.        substr:  7 secs ( 5.62 usr    0.00 sys =   5.62 cpu)
  579.  
  580.     For more specific tips, see the section on Efficiency in the
  581.     ``Other Oddments'' chapter at the end of the Camel Book.
  582.  
  583.  
  584. 4.14) Do I always/never have to quote my strings or use semicolons?
  585.  
  586.     You don't have to quote strings that can't mean anything else in the
  587.     language, like identifiers with any upper-case letters in them.
  588.     Therefore, it's fine to do this: 
  589.  
  590.     $SIG{INT} = Timeout_Routine;
  591.     or 
  592.  
  593.     @Days = (Sun, Mon, Tue, Wed, Thu, Fri, Sat, Sun);
  594.  
  595.     but you can't get away with this:
  596.  
  597.     $foo{while} = until;
  598.  
  599.     in place of 
  600.  
  601.     $foo{'while'} = 'until';
  602.  
  603.     The requirements on semicolons have been increasingly relaxed.  You no 
  604.     longer need one at the end of a block, but stylistically, you're better
  605.     to use them if you don't put the curly brace on the same line: 
  606.  
  607.     for (1..10) { print }
  608.  
  609.     is ok, as is
  610.  
  611.     @nlist = sort { $a <=> $b } @olist;
  612.  
  613.     but you probably shouldn't do this:
  614.     
  615.     for ($i = 0; $i < @a; $i++) {
  616.         print "i is $i\n"  # <-- oops!
  617.     } 
  618.  
  619.     because you might want to add lines later, and anyway, it looks
  620.     funny. :-) 
  621.  
  622.  
  623. 4.15) What is variable suicide and how can I prevent it?
  624.  
  625.     Variable suicide is a nasty side effect of dynamic scoping and the way
  626.     variables are passed by reference.  If you say 
  627.  
  628.     $x = 17;
  629.     &munge($x);
  630.     sub munge {
  631.         local($x);
  632.         local($myvar) = $_[0];
  633.         ...
  634.     } 
  635.  
  636.     Then you have just clobbered $_[0]!  Why this is occurring is pretty
  637.     heavy wizardry: the reference to $x stored in $_[0] was temporarily
  638.     occluded by the previous local($x) statement (which, you're recall,
  639.     occurs at run-time, not compile-time).  The work around is simple,
  640.     however: declare your formal parameters first:
  641.  
  642.     sub munge {
  643.         local($myvar) = $_[0];
  644.         local($x);
  645.         ...
  646.     }
  647.  
  648.     That doesn't help you if you're going to be trying to access @_
  649.     directly after the local()s.  In this case, careful use of the package
  650.     facility is your only recourse. 
  651.  
  652.     Another manifestation of this problem occurs due to the magical nature
  653.     of the index variable in a foreach() loop. 
  654.  
  655.     @num = 0 .. 4;
  656.     print "num begin  @num\n";
  657.     foreach $m (@num) { &ug }
  658.     print "num finish @num\n";
  659.     sub ug {
  660.         local($m) = 42;
  661.         print "m=$m  $num[0],$num[1],$num[2],$num[3]\n";
  662.     }
  663.     
  664.     Which prints out the mysterious:
  665.  
  666.     num begin  0 1 2 3 4
  667.     m=42  42,1,2,3
  668.     m=42  0,42,2,3
  669.     m=42  0,1,42,3
  670.     m=42  0,1,2,42
  671.     m=42  0,1,2,3
  672.     num finish 0 1 2 3 4
  673.  
  674.     What's happening here is that $m is an alias for each element of @num.
  675.     Inside &ug, you temporarily change $m.  Well, that means that you've
  676.     also temporarily changed whatever $m is an alias to!!  The only
  677.     workaround is to be careful with global variables, using packages,
  678.     and/or just be aware of this potential in foreach() loops. 
  679.  
  680.     The perl5 static autos via "my" will not have this problem.
  681.  
  682.  
  683. 4.16) What does "Malformed command links" mean?
  684.  
  685.     This is a bug in 4.035.  While in general it's merely a cosmetic
  686.     problem, it often comanifests with a highly undesirable coredumping 
  687.     problem.  Programs known to be affected by the fatal coredump include
  688.     plum and pcops.  This bug has been fixed since 4.036.  It did not
  689.     resurface in 5.000.
  690.  
  691.  
  692. 4.17) How can I set up a footer format to be used with write()?
  693.  
  694.     While the $^ variable contains the name of the current header format,
  695.     there is no corresponding mechanism to automatically do the same thing
  696.     for a footer.  Not knowing how big a format is going to be until you
  697.     evaluate it is one of the major problems.
  698.  
  699.     If you have a fixed-size footer, you can get footers by checking for
  700.     line left on page ($-) before each write, and printing the footer
  701.     yourself if necessary.
  702.  
  703.     Another strategy is to open a pipe to yourself, using open(KID, "|-")
  704.     and always write()ing to the KID, who then postprocesses its STDIN to
  705.     rearrange headers and footers however you like.  Not very convenient,
  706.     but doable.
  707.  
  708.  
  709. 4.18) Why does my Perl program keep growing in size?
  710.  
  711.     This is caused by a strange occurance that Larry has dubbed "feeping
  712.     creaturism".  Larry is always adding one more feature, always getting
  713.     Perl to handle one more problem.  Hence, it keeps growing.  Once you've
  714.     worked with perl long enough, you will probably start to do the same
  715.     thing.  You will then notice this problem as you see your scripts
  716.     becoming larger and larger.
  717.  
  718.     Oh, wait... you meant a currently running program and it's stack size.
  719.     Mea culpa, I misunderstood you.  ;)  While there may be a real memory
  720.     leak in the Perl source code or even whichever malloc() you're using,
  721.     common causes are incomplete eval()s or local()s in loops.
  722.  
  723.     An eval() which terminates in error due to a failed parsing will leave
  724.     a bit of memory unusable. 
  725.  
  726.     A local() inside a loop:
  727.  
  728.     for (1..100) {
  729.         local(@array);
  730.     } 
  731.  
  732.     will build up 100 versions of @array before the loop is done.  The
  733.     work-around is:   
  734.  
  735.     local(@array);
  736.     for (1..100) {
  737.         undef @array;
  738.     } 
  739.  
  740.     Larry reports that this behavior is fixed for perl5.
  741.  
  742.  
  743. 4.19) Can I do RPC in Perl?
  744.  
  745.     Yes, you can, since Perl has access to sockets.  An example of the rup
  746.     program written in Perl can be found in the script ruptime.pl at the
  747.     scripts archive on ftp.cis.ufl.edu.  I warn you, however, that it's not
  748.     a pretty sight, as it's used nothing from h2ph or c2ph, so everything is
  749.     utterly hard-wired. 
  750.  
  751.  
  752. 4.20) How can I quote a variable to use in a regexp?
  753.  
  754.     From the manual:
  755.  
  756.     $pattern =~ s/(\W)/\\$1/g;
  757.  
  758.     Now you can freely use /$pattern/ without fear of any unexpected meta-
  759.     characters in it throwing off the search.  If you don't know whether a
  760.     pattern is valid or not, enclose it in an eval to avoid a fatal run-
  761.     time error.  
  762.  
  763.     Perl5 provides a vastly improved way of doing this.  Simply use the
  764.     new quotemeta character (\Q) within your variable.
  765.  
  766. 4.21) How can I change the first N letters of a string?
  767.  
  768.     Remember that the substr() function produces an lvalue, that is, it may
  769.     be assigned to.  Therefore, to change the first character to an S, you
  770.     could do this:
  771.     
  772.     substr($var,0,1) = 'S';
  773.  
  774.     This assumes that $[ is 0;  for a library routine where you can't know
  775.     $[, you should use this instead:
  776.  
  777.     substr($var,$[,1) = 'S';
  778.  
  779.     While it would be slower, you could in this case use a substitute:
  780.  
  781.     $var =~ s/^./S/;
  782.     
  783.     But this won't work if the string is empty or its first character is a
  784.     newline, which "." will never match.  So you could use this instead:
  785.  
  786.     $var =~ s/^[^\0]?/S/;
  787.  
  788.     To do things like translation of the first part of a string, use
  789.     substr, as in:
  790.  
  791.     substr($var, $[, 10) =~ tr/a-z/A-Z/;
  792.  
  793.     If you don't know the length of what to translate, something like this
  794.     works: 
  795.  
  796.     /^(\S+)/ && substr($_,$[,length($1)) =~ tr/a-z/A-Z/;
  797.     
  798.     For some things it's convenient to use the /e switch of the substitute
  799.     operator: 
  800.  
  801.     s/^(\S+)/($tmp = $1) =~ tr#a-z#A-Z#, $tmp/e
  802.  
  803.     although in this case, it runs more slowly than does the previous
  804.     example. 
  805.  
  806.  
  807. 4.22) Can I use Perl regular expressions to match balanced text?
  808.  
  809.     No, or at least, not by the themselves.
  810.  
  811.     Regexps just aren't powerful enough.  Although Perl's patterns aren't
  812.     strictly regular because they do backreferencing (the \1 notation), you
  813.     still can't do it.  You need to employ auxiliary logic.  A simple
  814.     approach would involve keeping a bit of state around, something 
  815.     vaguely like this (although we don't handle patterns on the same line):
  816.  
  817.     while(<>) {
  818.         if (/pat1/) {
  819.         if ($inpat++ > 0) { warn "already saw pat1" } 
  820.         redo;
  821.         } 
  822.         if (/pat2/) {
  823.         if (--$inpat < 0) { warn "never saw pat1" } 
  824.         redo;
  825.         } 
  826.     }
  827.  
  828.     A rather more elaborate subroutine to pull out balanced and possibly
  829.     nested single chars, like ` and ', { and }, or ( and ) can be found
  830.     on convex.com in /pub/perl/scripts/pull_quotes.
  831.  
  832.  
  833. 4.23) What does it mean that regexps are greedy?  How can I get around it?
  834.  
  835.     The basic idea behind regexps being greedy is that they will match the
  836.     maximum amount of data that they can, sometimes resulting in incorrect
  837.     or strange answers.
  838.  
  839.     For example, I recently came across something like this:
  840.  
  841.     $_="this (is) an (example) of multiple parens";
  842.     while ( m#\((.*)\)#g ) {
  843.         print "$1\n";
  844.     }
  845.  
  846.     This code was supposed to match everything between a set of
  847.     parentheses.  The expected output was:
  848.  
  849.     is
  850.     example
  851.  
  852.     However, the backreference ($1) ended up containing "is) an (example",
  853.     clearly not what was intended.
  854.  
  855.     In perl4, the way to stop this from happening is to use a negated
  856.     group.  If the above example is rewritten as follows, the results are
  857.     correct: 
  858.  
  859.     while ( m#\(([^)]*)\)#g ) {
  860.  
  861.     In perl5 there is a new minimal matching metacharacter, '?'.  This
  862.     character is added to the normal metacharacters to modify their
  863.     behaviour, such as "*?", "+?", or even "??".  The example would now be
  864.     written in the following style:
  865.  
  866.     while (m#\((.*?)\)#g )
  867.  
  868.     Hint: This new operator leads to a very elegant method of stripping
  869.     comments from C code:
  870.  
  871.     s:/\*.*?\*/::gs
  872.  
  873.  
  874. 4.24) How do I use a regular expression to strip C style comments from a
  875.       file?
  876.  
  877.     Since we're talking about how to strip comments under perl5, now is a
  878.     good time to talk about doing it in perl4.  The easiest way to strip
  879.     comments in perl4 is to transform the comment close (*/) into something
  880.     that can't be in the string, or is at least extremely unlikely to be in
  881.     the string.  I find \256 (the registered or reserved sign, an R inside
  882.     a circle) is fairly unlikely to be used and is easy to remember.  So,
  883.     our code looks something like this:
  884.  
  885.     s:\*/:\256:g;        # Change all */ to circled R
  886.     s:/\*[^\256]*\256::g;   # Remove everything from \* to circled R
  887.     print;
  888.  
  889.     To ensure that you correctly handle multi-line comments, don't forget 
  890.     to set $* to 1, informing perl that it should do multi-line pattern
  891.     matching. 
  892.  
  893.     [Untested changes.  If it's wrong or you don't understand it, check 
  894.         with Jeff.  If it's wrong, let me know so I can change it. ] 
  895.  
  896.     Jeff Friedl* suggests that the above solution is incorrect.  He says it 
  897.     will fail on imbedded comments and function proto-typing as well as on
  898.     comments that are part of strings.  The following regexp should handle
  899.     everything:  
  900.  
  901.         $/ = undef;
  902.         $_ = <>; 
  903.  
  904.         s#/\*[^*]*\*+([^/*][^*]*\*+)*/|([^/"']*("[^"\\]*(\\[\d\D][^"\\]*)*"[^/"']*|'[^'\\]*(\\[\d\D][^'\\]*)*'[^/"']*|/+[^*/][^/"']*)*)#$2#g;
  905.         print; 
  906.  
  907.  
  908. 4.25) Why doesn't "local($foo) = <FILE>;" work right?
  909.  
  910.     Well, it does.  The thing to remember is that local() provides an array
  911.     context, and that the <FILE> syntax in an array context will read all the
  912.     lines in a file.  To work around this, use:
  913.  
  914.     local($foo);
  915.     $foo = <FILE>;
  916.  
  917.     You can use the scalar() operator to cast the expression into a scalar
  918.     context:
  919.  
  920.     local($foo) = scalar(<FILE>);
  921.  
  922.  
  923. 4.26) How can I detect keyboard input without reading it? 
  924.  
  925.     You should check out the Frequently Asked Questions list in
  926.     comp.unix.* for things like this: the answer is essentially the same.
  927.     It's very system dependent.  Here's one solution that works on BSD
  928.     systems:
  929.  
  930.     sub key_ready {
  931.         local($rin, $nfd);
  932.         vec($rin, fileno(STDIN), 1) = 1;
  933.         return $nfd = select($rin,undef,undef,0);
  934.     }
  935.  
  936.  
  937. 4.27) How can I read a single character from the keyboard under UNIX and DOS?
  938.  
  939.     A closely related question to the no-echo question below is how to
  940.     input a single character from the keyboard.  Again, this is a system
  941.     dependent operation.  The following code may or may not help you.  It
  942.     should work on both SysV and BSD flavors of UNIX:
  943.  
  944.     $BSD = -f '/vmunix';
  945.     if ($BSD) {
  946.         system "stty cbreak </dev/tty >/dev/tty 2>&1";
  947.     }
  948.     else {
  949.         system "stty", '-icanon',
  950.         system "stty", 'eol', "\001"; 
  951.     }
  952.  
  953.     $key = getc(STDIN);
  954.  
  955.     if ($BSD) {
  956.         system "stty -cbreak </dev/tty >/dev/tty 2>&1";
  957.     }
  958.     else {
  959.         system "stty", 'icanon';
  960.         system "stty", 'eol', '^@'; # ascii null
  961.     }
  962.     print "\n";
  963.  
  964.     You could also handle the stty operations yourself for speed if you're
  965.     going to be doing a lot of them.  This code works to toggle cbreak
  966.     and echo modes on a BSD system:
  967.  
  968.     sub set_cbreak { # &set_cbreak(1) or &set_cbreak(0)
  969.     local($on) = $_[0];
  970.     local($sgttyb,@ary);
  971.     require 'sys/ioctl.ph';
  972.     $sgttyb_t   = 'C4 S' unless $sgttyb_t;  # c2ph: &sgttyb'typedef()
  973.  
  974.     ioctl(STDIN,&TIOCGETP,$sgttyb) || die "Can't ioctl TIOCGETP: $!";
  975.  
  976.     @ary = unpack($sgttyb_t,$sgttyb);
  977.     if ($on) {
  978.         $ary[4] |= &CBREAK;
  979.         $ary[4] &= ~&ECHO;
  980.     } else {
  981.         $ary[4] &= ~&CBREAK;
  982.         $ary[4] |= &ECHO;
  983.     }
  984.     $sgttyb = pack($sgttyb_t,@ary);
  985.  
  986.     ioctl(STDIN,&TIOCSETP,$sgttyb) || die "Can't ioctl TIOCSETP: $!";
  987.     }
  988.  
  989.     Note that this is one of the few times you actually want to use the
  990.     getc() function; it's in general way too expensive to call for normal
  991.     I/O.  Normally, you just use the <FILE> syntax, or perhaps the read()
  992.     or sysread() functions.
  993.  
  994.     For perspectives on more portable solutions, use anon ftp to retrieve
  995.     the file /pub/perl/info/keypress from convex.com.
  996.  
  997.     For DOS systems, Dan Carson <dbc@tc.fluke.COM> reports:
  998.  
  999.     To put the PC in "raw" mode, use ioctl with some magic numbers gleaned
  1000.     from msdos.c (Perl source file) and Ralf Brown's interrupt list (comes
  1001.     across the net every so often):
  1002.  
  1003.     $old_ioctl = ioctl(STDIN,0,0);     # Gets device info
  1004.     $old_ioctl &= 0xff;
  1005.     ioctl(STDIN,1,$old_ioctl | 32);    # Writes it back, setting bit 5
  1006.  
  1007.     Then to read a single character:
  1008.  
  1009.     sysread(STDIN,$c,1);               # Read a single character
  1010.  
  1011.     And to put the PC back to "cooked" mode:
  1012.  
  1013.     ioctl(STDIN,1,$old_ioctl);         # Sets it back to cooked mode.
  1014.  
  1015.  
  1016.     So now you have $c.  If ord($c) == 0, you have a two byte code, which
  1017.     means you hit a special key.  Read another byte (sysread(STDIN,$c,1)),
  1018.     and that value tells you what combination it was according to this
  1019.     table:
  1020.  
  1021.     # PC 2-byte keycodes = ^@ + the following:
  1022.  
  1023.     # HEX     KEYS
  1024.     # ---     ----
  1025.     # 0F      SHF TAB
  1026.     # 10-19   ALT QWERTYUIOP
  1027.     # 1E-26   ALT ASDFGHJKL
  1028.     # 2C-32   ALT ZXCVBNM
  1029.     # 3B-44   F1-F10
  1030.     # 47-49   HOME,UP,PgUp
  1031.     # 4B      LEFT
  1032.     # 4D      RIGHT
  1033.     # 4F-53   END,DOWN,PgDn,Ins,Del
  1034.     # 54-5D   SHF F1-F10
  1035.     # 5E-67   CTR F1-F10
  1036.     # 68-71   ALT F1-F10
  1037.     # 73-77   CTR LEFT,RIGHT,END,PgDn,HOME
  1038.     # 78-83   ALT 1234567890-=
  1039.     # 84      CTR PgUp
  1040.  
  1041.     This is all trial and error I did a long time ago, I hope I'm reading the
  1042.     file that worked.
  1043.  
  1044.  
  1045. 4.28) How can I get input from the keyboard without it echoing to the
  1046.       screen?
  1047.  
  1048.     Terminal echoing is generally handled directly by the shell.
  1049.     Therefore, there is no direct way in perl to turn echoing on and off.
  1050.     However, you can call the command "stty [-]echo".  The following will
  1051.     allow you to accept input without it being echoed to the screen, for
  1052.     example as a way to accept passwords (error checking deleted for
  1053.     brevity):
  1054.  
  1055.     print "Please enter your password: ";
  1056.         system("stty -echo");
  1057.     chop($password=<STDIN>);
  1058.     print "\n";
  1059.     system("stty echo");
  1060.  
  1061. 4.29) Is there any easy way to strip blank space from the beginning/end of
  1062.     a string?
  1063.  
  1064.     Yes, there is.  Using the substitution command, you can match the
  1065.     blanks and replace it with nothing.  For example, if you have the
  1066.     string "     String     " you can use this:
  1067.  
  1068.         $_ = "     String     ";
  1069.     print ":$_:\n";        # OUTPUT: ":     String     :"
  1070.     s/^\s*//;
  1071.     print ":$_:\n";        # OUTPUT: ":String     :"
  1072.     s/\s*$//;
  1073.     print ":$_:\n";        # OUTPUT: ":String:"
  1074.  
  1075.     Unfortunately, there is no simple single statement that will strip
  1076.     whitespace from both the front and the back in perl4.  However, in
  1077.     perl5 you should be able to say:
  1078.  
  1079.     s/\s*(.*?)\s*$/$1/;
  1080. Stephen P Potter        spp@vx.com        Varimetrix Corporation
  1081. 2350 Commerce Park Drive, Suite 4                Palm Bay, FL 32905
  1082. (407) 676-3222                           CAD/CAM/CAE/Software
  1083.  
  1084.