home *** CD-ROM | disk | FTP | other *** search
/ Danny Amor's Online Library / Danny Amor's Online Library - Volume 1.iso / html / faqs / faq / perl-faq / part4 < prev    next >
Encoding:
Text File  |  1995-07-25  |  34.4 KB  |  1,072 lines

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