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 / part5 < prev   
Encoding:
Text File  |  1995-07-25  |  30.0 KB  |  890 lines

  1. Subject: comp.lang.perl FAQ 5/5 - External Program Interaction
  2. Newsgroups: comp.lang.perl,comp.answers,news.answers
  3. From: spp@vx.com
  4. Date: 15 Nov 1994 10:09:31 GMT
  5.  
  6. Archive-name: perl-faq/part5
  7. Version: $Id: part5,v 2.2 1994/11/07 18:06:59 spp Exp spp $
  8. Posting-Frequency: bi-weekly
  9.  
  10. This posting contains answers to the following questions about Array, Shell
  11. and External Program Interactions with Perl: 
  12.  
  13.  
  14. 5.1) What is the difference between $array[1] and @array[1]?
  15.  
  16.     Always make sure to use a $ for single values and @ for multiple ones. 
  17.     Thus element 2 of the @foo array is accessed as $foo[2], not @foo[2],
  18.     which is a list of length one (not a scalar), and is a fairly common
  19.     novice mistake.  Sometimes you can get by with @foo[2], but it's
  20.     not really doing what you think it's doing for the reason you think
  21.     it's doing it, which means one of these days, you'll shoot yourself
  22.     in the foot; ponder for a moment what these will really do:
  23.     @foo[0] = `cmd args`;
  24.     @foo[2] = <FILE>;
  25.     Just always say $foo[2] and you'll be happier.
  26.  
  27.     This may seem confusing, but try to think of it this way:  you use the
  28.     character of the type which you *want back*.  You could use @foo[1..3] for
  29.     a slice of three elements of @foo, or even @foo{A,B,C} for a slice of
  30.     of %foo.  This is the same as using ($foo[1], $foo[2], $foo[3]) and
  31.     ($foo{A}, $foo{B}, $foo{C}) respectively.  In fact, you can even use
  32.     lists to subscript arrays and pull out more lists, like @foo[@bar] or
  33.     @foo{@bar}, where @bar is in both cases presumably a list of subscripts.
  34.  
  35.  
  36. 5.2) How can I make an array of arrays or other recursive data types?
  37.  
  38.  
  39.     In Perl5, it's quite easy to declare these things.  For example 
  40.  
  41.     @A = (
  42.         [ 'ww' .. 'xx'  ], 
  43.         [ 'xx' .. 'yy'  ], 
  44.         [ 'yy' .. 'zz'  ], 
  45.         [ 'zz' .. 'zzz' ], 
  46.     );
  47.  
  48.     And now reference $A[2]->[0] to pull out "yy".  These may also nest
  49.     and mix with tables:
  50.  
  51.     %T = (
  52.         key0, { k0, v0, k1, v1 },    
  53.         key1, { k2, v2, k3, v3 },    
  54.         key2, { k2, v2, k3, [ 0, 'a' .. 'z' ] },    
  55.     );
  56.     
  57.     Allowing you to reference $T{key2}->{k3}->[3] to pull out 'c'.
  58.  
  59.     Perl4 is infinitely more difficult.  Remember that Perl[0..4] isn't
  60.     about nested data structures.  It's about flat ones, so if you're
  61.     trying to do this, you may be going about it the wrong way or using the
  62.     wrong tools.  You might try parallel arrays with common subscripts. 
  63.  
  64.     But if you're bound and determined, you can use the multi-dimensional
  65.     array emulation of $a{'x','y','z'}, or you can make an array of names
  66.     of arrays and eval it.
  67.  
  68.     For example, if @name contains a list of names of arrays, you can get
  69.     at a the j-th element of the i-th array like so: 
  70.  
  71.     $ary = $name[$i];
  72.     $val = eval "\$$ary[$j]";
  73.  
  74.     or in one line
  75.  
  76.     $val = eval "\$$name[$i][\$j]";
  77.  
  78.     You could also use the type-globbing syntax to make an array of *name
  79.     values, which will be more efficient than eval.  Here @name hold a list
  80.     of pointers, which we'll have to dereference through a temporary
  81.     variable. 
  82.  
  83.     For example:
  84.  
  85.     { local(*ary) = $name[$i]; $val = $ary[$j]; }
  86.  
  87.     In fact, you can use this method to make arbitrarily nested data
  88.     structures.  You really have to want to do this kind of thing badly to
  89.     go this far, however, as it is notationally cumbersome. 
  90.  
  91.     Let's assume you just simply *have* to have an array of arrays of
  92.     arrays.  What you do is make an array of pointers to arrays of
  93.     pointers, where pointers are *name values described above.  You  
  94.     initialize the outermost array normally, and then you build up your
  95.     pointers from there.  For example:
  96.  
  97.     @w = ( 'ww' .. 'xx' );
  98.     @x = ( 'xx' .. 'yy' );
  99.     @y = ( 'yy' .. 'zz' );
  100.     @z = ( 'zz' .. 'zzz' );
  101.  
  102.     @ww = reverse @w;
  103.     @xx = reverse @x;
  104.     @yy = reverse @y;
  105.     @zz = reverse @z;
  106.  
  107.     Now make a couple of arrays of pointers to these:
  108.  
  109.     @A = ( *w, *x, *y, *z );
  110.     @B = ( *ww, *xx, *yy, *zz );
  111.  
  112.     And finally make an array of pointers to these arrays:
  113.  
  114.     @AAA = ( *A, *B );
  115.  
  116.     To access an element, such as AAA[i][j][k], you must do this:
  117.  
  118.     local(*foo) = $AAA[$i];
  119.     local(*bar) = $foo[$j];
  120.     $answer = $bar[$k];
  121.  
  122.     Similar manipulations on associative arrays are also feasible.
  123.  
  124.     You could take a look at recurse.pl package posted by Felix Lee*, which
  125.     lets you simulate vectors and tables (lists and associative arrays) by
  126.     using type glob references and some pretty serious wizardry.
  127.  
  128.     In C, you're used to creating recursive datatypes for operations like
  129.     recursive decent parsing or tree traversal.  In Perl, these algorithms
  130.     are best implemented using associative arrays.  Take an array called
  131.     %parent, and build up pointers such that $parent{$person} is the name
  132.     of that person's parent.  Make sure you remember that $parent{'adam'}
  133.     is 'adam'. :-) With a little care, this approach can be used to
  134.     implement general graph traversal algorithms as well. 
  135.  
  136.  
  137. 5.3) How do I make an array of structures containing various data types?
  138.  
  139.     The best way to do this is to use an associative array to model your
  140.     structure, then either a regular array (AKA list) or another
  141.     associative array (AKA hash, table, or hash table) to store it.
  142.  
  143.     %foo = (
  144.                'field1'        => "value1",
  145.                    'field2'        => "value2",
  146.                    'field3'        => "value3",
  147.                    ...
  148.                );
  149.     ...
  150.  
  151.         @all = ( \%foo, \%bar, ... );
  152.  
  153.         print $all[0]{'field1'};
  154.  
  155.     Or even
  156.  
  157.     @all = (
  158.            {
  159.                'field1'        => "value1",
  160.                'field2'        => "value2",
  161.                'field3'        => "value3",
  162.                ...
  163.            },
  164.            {
  165.                'field1'        => "value1",
  166.                'field2'        => "value2",
  167.                'field3'        => "value3",
  168.                ...
  169.            },
  170.            ...
  171.     )
  172.  
  173.     See perlref(1).
  174.  
  175.  
  176. 5.4) How can I extract just the unique elements of an array?
  177.  
  178.     There are several possible ways, depending on whether the
  179.     array is ordered and you wish to preserve the ordering.
  180.  
  181.     a) If @in is sorted, and you want @out to be sorted:
  182.  
  183.     $prev = 'nonesuch';
  184.     @out = grep($_ ne $prev && (($prev) = $_), @in);
  185.  
  186.        This is nice in that it doesn't use much extra memory, 
  187.        simulating uniq's behavior of removing only adjacent
  188.        duplicates.
  189.  
  190.     b) If you don't know whether @in is sorted:
  191.  
  192.     undef %saw;
  193.     @out = grep(!$saw{$_}++, @in);
  194.  
  195.     c) Like (b), but @in contains only small integers:
  196.  
  197.     @out = grep(!$saw[$_]++, @in);
  198.  
  199.     d) A way to do (b) without any loops or greps:
  200.  
  201.     undef %saw;
  202.     @saw{@in} = ();
  203.     @out = sort keys %saw;  # remove sort if undesired
  204.  
  205.     e) Like (d), but @in contains only small positive integers:
  206.  
  207.     undef @ary;
  208.     @ary[@in] = @in;
  209.     @out = sort @ary;
  210.  
  211.  
  212. 5.5) How can I tell whether an array contains a certain element?
  213.  
  214.     There are several ways to approach this.  If you are going to make
  215.     this query many times and the values are arbitrary strings, the
  216.     fastest way is probably to invert the original array and keep an
  217.     associative array lying about whose keys are the first array's values.
  218.  
  219.     @blues = ('turquoise', 'teal', 'lapis lazuli');
  220.     undef %is_blue;
  221.     for (@blues) { $is_blue{$_} = 1; }
  222.  
  223.     Now you can check whether $is_blue{$some_color}.  It might have been
  224.     a good idea to keep the blues all in an assoc array in the first place.
  225.  
  226.     If the values are all small integers, you could use a simple
  227.     indexed array.  This kind of an array will take up less space:
  228.  
  229.     @primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31);
  230.     undef @is_tiny_prime;
  231.     for (@primes) { $is_tiny_prime[$_] = 1; }
  232.  
  233.     Now you check whether $is_tiny_prime[$some_number].
  234.  
  235.     If the values in question are integers instead of strings, you can save
  236.     quite a lot of space by using bit strings instead: 
  237.  
  238.     @articles = ( 1..10, 150..2000, 2017 );
  239.     undef $read;
  240.     grep (vec($read,$_,1) = 1, @articles);
  241.     
  242.     Now check whether vec($read,$n,1) is true for some $n.
  243.  
  244.  
  245. 5.6) How do I sort an associative array by value instead of by key?
  246.  
  247.     You have to declare a sort subroutine to do this, or use an inline
  248.     function.  Let's assume you want an ASCII sort on the values of the
  249.     associative array %ary.  You could do so this way:
  250.  
  251.     foreach $key (sort by_value keys %ary) {
  252.         print $key, '=', $ary{$key}, "\n";
  253.     } 
  254.     sub by_value { $ary{$a} cmp $ary{$b}; }
  255.  
  256.     If you wanted a descending numeric sort, you could do this:
  257.  
  258.     sub by_value { $ary{$b} <=> $ary{$a}; }
  259.  
  260.     You can also inline your sort function, like this, at least if 
  261.     you have a relatively recent patchlevel of perl4 or are running perl5:
  262.  
  263.     foreach $key ( sort { $ary{$b} <=> $ary{$a} } keys %ary ) {
  264.         print $key, '=', $ary{$key}, "\n";
  265.     } 
  266.  
  267.     If you wanted a function that didn't have the array name hard-wired
  268.     into it, you could so this:
  269.  
  270.     foreach $key (&sort_by_value(*ary)) {
  271.         print $key, '=', $ary{$key}, "\n";
  272.     } 
  273.     sub sort_by_value {
  274.         local(*x) = @_;
  275.         sub _by_value { $x{$a} cmp $x{$b}; } 
  276.         sort _by_value keys %x;
  277.     } 
  278.  
  279.     If you want neither an alphabetic nor a numeric sort, then you'll 
  280.     have to code in your own logic instead of relying on the built-in
  281.     signed comparison operators "cmp" and "<=>".
  282.  
  283.     Note that if you're sorting on just a part of the value, such as a
  284.     piece you might extract via split, unpack, pattern-matching, or
  285.     substr, then rather than performing that operation inside your sort
  286.     routine on each call to it, it is significantly more efficient to
  287.     build a parallel array of just those portions you're sorting on, sort
  288.     the indices of this parallel array, and then to subscript your original
  289.     array using the newly sorted indices.  This method works on both
  290.     regular and associative arrays, since both @ary[@idx] and @ary{@idx}
  291.     make sense.  See page 245 in the Camel Book on "Sorting an Array by a
  292.     Computable Field" for a simple example of this.
  293.  
  294.  
  295. 5.7) How can I know how many entries are in an associative array?
  296.  
  297.     While the number of elements in a @foobar array is simply @foobar when
  298.     used in a scalar, you can't figure out how many elements are in an
  299.     associative array in an analogous fashion.  That's because %foobar in
  300.     a scalar context returns the ratio (as a string) of number of buckets
  301.     filled versus the number allocated.  For example, scalar(%ENV) might
  302.     return "20/32".  While perl could in theory keep a count, this would
  303.     break down on associative arrays that have been bound to dbm files.
  304.  
  305.     However, while you can't get a count this way, one thing you *can* use
  306.     it for is to determine whether there are any elements whatsoever in
  307.     the array, since "if (%table)" is guaranteed to be false if nothing
  308.     has ever been stored in it.  
  309.  
  310.     As of perl4.035, you can says
  311.  
  312.         $count = keys %ARRAY;
  313.  
  314.     keys() when used in a scalar context will return the number of keys,
  315.     rather than the keys themselves.
  316.  
  317.  
  318. 5.8) What's the difference between "delete" and "undef" with %arrays?
  319.  
  320.     Pictures help...  here's the %ary table:
  321.  
  322.           keys  values
  323.         +------+------+
  324.         |  a   |  3   |
  325.         |  x   |  7   |
  326.         |  d   |  0   |
  327.         |  e   |  2   |
  328.         +------+------+
  329.  
  330.     And these conditions hold
  331.  
  332.         $ary{'a'}                       is true
  333.         $ary{'d'}                       is false
  334.         defined $ary{'d'}               is true
  335.         defined $ary{'a'}               is true
  336.         exists $ary{'a'}            is true (perl5 only)
  337.         grep ($_ eq 'a', keys %ary)     is true
  338.  
  339.     If you now say 
  340.  
  341.         undef $ary{'a'}
  342.  
  343.     your table now reads:
  344.         
  345.  
  346.           keys  values
  347.         +------+------+
  348.         |  a   | undef|
  349.         |  x   |  7   |
  350.         |  d   |  0   |
  351.         |  e   |  2   |
  352.         +------+------+
  353.  
  354.     and these conditions now hold; changes in caps:
  355.  
  356.         $ary{'a'}                       is FALSE
  357.         $ary{'d'}                       is false
  358.         defined $ary{'d'}               is true
  359.         defined $ary{'a'}               is FALSE
  360.         exists $ary{'a'}            is true (perl5 only)
  361.         grep ($_ eq 'a', keys %ary)     is true
  362.  
  363.     Notice the last two: you have an undef value, but a defined key!
  364.  
  365.     Now, consider this:
  366.  
  367.         delete $ary{'a'}
  368.  
  369.     your table now reads:
  370.  
  371.           keys  values
  372.         +------+------+
  373.         |  x   |  7   |
  374.         |  d   |  0   |
  375.         |  e   |  2   |
  376.         +------+------+
  377.  
  378.     and these conditions now hold; changes in caps:
  379.  
  380.         $ary{'a'}                       is false
  381.         $ary{'d'}                       is false
  382.         defined $ary{'d'}               is true
  383.         defined $ary{'a'}               is false
  384.         exists $ary{'a'}            is FALSE (perl5 only)
  385.         grep ($_ eq 'a', keys %ary)     is FALSE
  386.  
  387.     See, the whole entry is gone!
  388.  
  389.  
  390. 5.9) Why don't backticks work as they do in shells?  
  391.  
  392.     Several reason.  One is because backticks do not interpolate within
  393.     double quotes in Perl as they do in shells.  
  394.     
  395.     Let's look at two common mistakes:
  396.  
  397.          $foo = "$bar is `wc $file`";  # WRONG
  398.  
  399.     This should have been:
  400.  
  401.      $foo = "$bar is " . `wc $file`;
  402.  
  403.     But you'll have an extra newline you might not expect.  This
  404.     does not work as expected:
  405.  
  406.       $back = `pwd`; chdir($somewhere); chdir($back); # WRONG
  407.  
  408.     Because backticks do not automatically eat trailing or embedded
  409.     newlines.  The chop() function will remove the last character from
  410.     a string.  This should have been:
  411.  
  412.       chop($back = `pwd`); chdir($somewhere); chdir($back);
  413.  
  414.     You should also be aware that while in the shells, embedding
  415.     single quotes will protect variables, in Perl, you'll need 
  416.     to escape the dollar signs.
  417.  
  418.     Shell: foo=`cmd 'safe $dollar'`
  419.     Perl:  $foo=`cmd 'safe \$dollar'`;
  420.     
  421.  
  422. 5.10) How come my converted awk/sed/sh script runs more slowly in Perl?
  423.  
  424.     The natural way to program in those languages may not make for the fastest
  425.     Perl code.  Notably, the awk-to-perl translator produces sub-optimal code;
  426.     see the a2p man page for tweaks you can make.
  427.  
  428.     Two of Perl's strongest points are its associative arrays and its regular
  429.     expressions.  They can dramatically speed up your code when applied
  430.     properly.  Recasting your code to use them can help a lot.
  431.  
  432.     How complex are your regexps?  Deeply nested sub-expressions with {n,m} or
  433.     * operators can take a very long time to compute.  Don't use ()'s unless
  434.     you really need them.  Anchor your string to the front if you can.
  435.  
  436.     Something like this:
  437.     next unless /^.*%.*$/; 
  438.     runs more slowly than the equivalent:
  439.     next unless /%/;
  440.  
  441.     Note that this:
  442.     next if /Mon/;
  443.     next if /Tue/;
  444.     next if /Wed/;
  445.     next if /Thu/;
  446.     next if /Fri/;
  447.     runs faster than this:
  448.     next if /Mon/ || /Tue/ || /Wed/ || /Thu/ || /Fri/;
  449.     which in turn runs faster than this:
  450.     next if /Mon|Tue|Wed|Thu|Fri/;
  451.     which runs *much* faster than:
  452.     next if /(Mon|Tue|Wed|Thu|Fri)/;
  453.  
  454.     There's no need to use /^.*foo.*$/ when /foo/ will do.
  455.  
  456.     Remember that a printf costs more than a simple print.
  457.  
  458.     Don't split() every line if you don't have to.
  459.  
  460.     Another thing to look at is your loops.  Are you iterating through 
  461.     indexed arrays rather than just putting everything into a hashed 
  462.     array?  For example,
  463.  
  464.     @list = ('abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stv');
  465.  
  466.     for $i ($[ .. $#list) {
  467.         if ($pattern eq $list[$i]) { $found++; } 
  468.     } 
  469.  
  470.     First of all, it would be faster to use Perl's foreach mechanism
  471.     instead of using subscripts:
  472.  
  473.     foreach $elt (@list) {
  474.         if ($pattern eq $elt) { $found++; } 
  475.     } 
  476.  
  477.     Better yet, this could be sped up dramatically by placing the whole
  478.     thing in an associative array like this:
  479.  
  480.     %list = ('abc', 1, 'def', 1, 'ghi', 1, 'jkl', 1, 
  481.          'mno', 1, 'pqr', 1, 'stv', 1 );
  482.     $found += $list{$pattern};
  483.     
  484.     (but put the %list assignment outside of your input loop.)
  485.  
  486.     You should also look at variables in regular expressions, which is
  487.     expensive.  If the variable to be interpolated doesn't change over the
  488.     life of the process, use the /o modifier to tell Perl to compile the
  489.     regexp only once, like this:
  490.  
  491.     for $i (1..100) {
  492.         if (/$foo/o) {
  493.         &some_func($i);
  494.         } 
  495.     } 
  496.  
  497.     Finally, if you have a bunch of patterns in a list that you'd like to 
  498.     compare against, instead of doing this:
  499.  
  500.     @pats = ('_get.*', 'bogus', '_read', '.*exit', '_write');
  501.     foreach $pat (@pats) {
  502.         if ( $name =~ /^$pat$/ ) {
  503.         &some_func();
  504.         last;
  505.         }
  506.     }
  507.  
  508.     If you build your code and then eval it, it will be much faster.
  509.     For example:
  510.  
  511.     @pats = ('_get.*', 'bogus', '_read', '.*exit', '_write');
  512.     $code = <<EOS
  513.         while (<>) { 
  514.             study;
  515. EOS
  516.     foreach $pat (@pats) {
  517.         $code .= <<EOS
  518.         if ( /^$pat\$/ ) {
  519.             &some_func();
  520.             next;
  521.         }
  522. EOS
  523.     }
  524.     $code .= "}\n";
  525.     print $code if $debugging;
  526.     eval $code;
  527.  
  528.  
  529.  
  530. 5.11) How can I call my system's unique C functions from Perl?
  531.  
  532.     If these are system calls and you have the syscall() function, then
  533.     you're probably in luck -- see the next question.  If you're using a 
  534.     POSIX function, and are running perl5, you're also in luck: see
  535.     POSIX(3m).  For arbitrary library functions, however, it's not quite so 
  536.     straight-forward.  See "Where can I learn about linking C with Perl?".
  537.  
  538.  
  539. 5.12) Where do I get the include files to do ioctl() or syscall()? [h2ph]
  540.  
  541.     [Note: as of perl5, you probably want to just use h2xs instead, at
  542.     least, if your system supports dynamic loading.]
  543.  
  544.     These are generated from your system's C include files using the h2ph
  545.     script (once called makelib) from the Perl source directory.  This will
  546.     make files containing subroutine definitions, like &SYS_getitimer, which
  547.     you can use as arguments to your function.
  548.  
  549.     You might also look at the h2pl subdirectory in the Perl source for how to
  550.     convert these to forms like $SYS_getitimer; there are both advantages and
  551.     disadvantages to this.  Read the notes in that directory for details.  
  552.    
  553.     In both cases, you may well have to fiddle with it to make these work; it
  554.     depends how funny-looking your system's C include files happen to be.
  555.  
  556.     If you're trying to get at C structures, then you should take a look
  557.     at using c2ph, which uses debugger "stab" entries generated by your
  558.     BSD or GNU C compiler to produce machine-independent perl definitions
  559.     for the data structures.  This allows to you avoid hardcoding
  560.     structure layouts, types, padding, or sizes, greatly enhancing
  561.     portability.  c2ph comes with the perl distribution.  On an SCO
  562.     system, GCC only has COFF debugging support by default, so you'll have
  563.     to build GCC 2.1 with DBX_DEBUGGING_INFO defined, and use -gstabs to
  564.     get c2ph to work there.
  565.  
  566.     See the file /pub/perl/info/ch2ph on convex.com via anon ftp 
  567.     for more traps and tips on this process.
  568.  
  569.  
  570. 5.13) Why do setuid Perl scripts complain about kernel problems?
  571.  
  572.     This message:
  573.  
  574.     YOU HAVEN'T DISABLED SET-ID SCRIPTS IN THE KERNEL YET!
  575.     FIX YOUR KERNEL, PUT A C WRAPPER AROUND THIS SCRIPT, OR USE -u AND UNDUMP!
  576.  
  577.     is triggered because setuid scripts are inherently insecure due to a
  578.     kernel bug.  If your system has fixed this bug, you can compile Perl
  579.     so that it knows this.  Otherwise, create a setuid C program that just
  580.     execs Perl with the full name of the script.  Here's what the
  581.     perldiag(1) man page says about this message:
  582.  
  583.     YOU HAVEN'T DISABLED SET-ID SCRIPTS IN THE KERNEL YET!
  584.       (F) And you probably never will, since you probably don't have
  585.           the sources to your kernel, and your vendor probably doesn't
  586.           give a rip about what you want.  Your best bet is to use the
  587.           wrapsuid script in the eg directory to put a setuid C wrapper
  588.           around your script.
  589.  
  590.  
  591. 5.14) How do I open a pipe both to and from a command?
  592.  
  593.     In general, this is a dangerous move because you can find yourself in a
  594.     deadlock situation.  It's better to put one end of the pipe to a file.
  595.     For example:
  596.  
  597.     # first write some_cmd's input into a_file, then 
  598.     open(CMD, "some_cmd its_args < a_file |");
  599.     while (<CMD>) {
  600.  
  601.     # or else the other way; run the cmd
  602.     open(CMD, "| some_cmd its_args > a_file");
  603.     while ($condition) {
  604.         print CMD "some output\n";
  605.         # other code deleted
  606.     } 
  607.     close CMD || warn "cmd exited $?";
  608.  
  609.     # now read the file
  610.     open(FILE,"a_file");
  611.     while (<FILE>) {
  612.  
  613.     If you have ptys, you could arrange to run the command on a pty and
  614.     avoid the deadlock problem.  See the chat2.pl package in the
  615.     distributed library for ways to do this.
  616.  
  617.     At the risk of deadlock, it is theoretically possible to use a
  618.     fork, two pipe calls, and an exec to manually set up the two-way
  619.     pipe.  (BSD system may use socketpair() in place of the two pipes,
  620.     but this is not as portable.)  The open2 library function distributed
  621.     with the current perl release will do this for you.
  622.  
  623.     It assumes it's going to talk to something like adb, both writing to
  624.     it and reading from it.  This is presumably safe because you "know"
  625.     that commands like adb will read a line at a time and output a line at
  626.     a time.  Programs like sort that read their entire input stream first,
  627.     however, are quite apt to cause deadlock.
  628.  
  629.     There's also an open3.pl library that handles this for stderr as well.
  630.  
  631.  
  632. 5.15) How can I capture STDERR from an external command?
  633.  
  634.     There are three basic ways of running external commands:
  635.  
  636.     system $cmd;
  637.     $output = `$cmd`;
  638.     open (PIPE, "cmd |");
  639.  
  640.     In the first case, both STDOUT and STDERR will go the same place as
  641.     the script's versions of these, unless redirected.  You can always put
  642.     them where you want them and then read them back when the system
  643.     returns.  In the second and third cases, you are reading the STDOUT
  644.     *only* of your command.  If you would like to have merged STDOUT and
  645.     STDERR, you can use shell file-descriptor redirection to dup STDERR to
  646.     STDOUT:
  647.  
  648.     $output = `$cmd 2>&1`;
  649.     open (PIPE, "cmd 2>&1 |");
  650.  
  651.     Another possibility is to run STDERR into a file and read the file 
  652.     later, as in 
  653.  
  654.     $output = `$cmd 2>some_file`;
  655.     open (PIPE, "cmd 2>some_file |");
  656.     
  657.     Here's a way to read from both of them and know which descriptor
  658.     you got each line from.  The trick is to pipe only STDERR through
  659.     sed, which then marks each of its lines, and then sends that
  660.     back into a merged STDOUT/STDERR stream, from which your Perl program
  661.     then reads a line at a time:
  662.  
  663.         open (CMD, 
  664.           "cmd args | sed 's/^/STDOUT:/' |");
  665.  
  666.         while (<CMD>) {
  667.           if (s/^STDOUT://)  {
  668.               print "line from stdout: ", $_;
  669.           } else {
  670.               print "line from stdeff: ", $_;
  671.           }
  672.         }
  673.  
  674.     Be apprised that you *must* use Bourne shell redirection syntax in
  675.     backticks, not csh!  For details on how lucky you are that perl's
  676.     system() and backtick and pipe opens all use Bourne shell, fetch the
  677.     file from convex.com called /pub/csh.whynot -- and you'll be glad that
  678.     perl's shell interface is the Bourne shell.
  679.  
  680.     There's an &open3 routine out there which was merged with &open2 in
  681.     perl5 production. 
  682.  
  683.  
  684. 5.16) Why doesn't open return an error when a pipe open fails?
  685.  
  686.     These statements:
  687.  
  688.     open(TOPIPE, "|bogus_command") || die ...
  689.     open(FROMPIPE, "bogus_command|") || die ...
  690.  
  691.     will not fail just for lack of the bogus_command.  They'll only
  692.     fail if the fork to run them fails, which is seldom the problem.
  693.  
  694.     If you're writing to the TOPIPE, you'll get a SIGPIPE if the child
  695.     exits prematurely or doesn't run.  If you are reading from the
  696.     FROMPIPE, you need to check the close() to see what happened.
  697.  
  698.     If you want an answer sooner than pipe buffering might otherwise
  699.     afford you, you can do something like this:
  700.  
  701.     $kid = open (PIPE, "bogus_command |");   # XXX: check defined($kid)
  702.     (kill 0, $kid) || die "bogus_command failed";
  703.  
  704.     This works fine if bogus_command doesn't have shell metas in it, but
  705.     if it does, the shell may well not have exited before the kill 0.  You
  706.     could always introduce a delay:
  707.  
  708.     $kid = open (PIPE, "bogus_command </dev/null |");
  709.     sleep 1;
  710.     (kill 0, $kid) || die "bogus_command failed";
  711.  
  712.     but this is sometimes undesirable, and in any event does not guarantee
  713.     correct behavior.  But it seems slightly better than nothing.
  714.  
  715.     Similar tricks can be played with writable pipes if you don't wish to
  716.     catch the SIGPIPE.
  717.  
  718.  
  719. 5.17) Why can't my perl program read from STDIN after I gave it ^D (EOF) ?
  720.  
  721.     Because some stdio's set error and eof flags that need clearing.
  722.  
  723.     Try keeping around the seekpointer and go there, like this:
  724.      $where = tell(LOG);
  725.      seek(LOG, $where, 0);
  726.  
  727.     If that doesn't work, try seeking to a different part of the file and
  728.     then back.  If that doesn't work, try seeking to a different part of
  729.     the file, reading something, and then seeking back.  If that doesn't
  730.     work, give up on your stdio package and use sysread.  You can't call
  731.     stdio's clearerr() from Perl, so if you get EINTR from a signal
  732.     handler, you're out of luck.  Best to just use sysread() from the
  733.     start for the tty.
  734.  
  735.  
  736. 5.18) How can I translate tildes in a filename?
  737.  
  738.     Perl doesn't expand tildes -- the shell (ok, some shells) do.
  739.     The classic request is to be able to do something like:
  740.  
  741.     open(FILE, "~/dir1/file1");
  742.     open(FILE, "~tchrist/dir1/file1");
  743.  
  744.     which doesn't work.  (And you don't know it, because you 
  745.     did a system call without an "|| die" clause! :-)
  746.  
  747.     If you *know* you're on a system with the csh, and you *know*
  748.     that Larry hasn't internalized file globbing, then you could
  749.     get away with 
  750.  
  751.     $filename = <~tchrist/dir1/file1>;
  752.  
  753.     but that's pretty iffy.
  754.  
  755.     A better way is to do the translation yourself, as in:
  756.  
  757.     $filename =~ s#^~(\w+)(/.*)?$#(getpwnam($1))[7].$2#e;
  758.  
  759.     More robust and efficient versions that checked for error conditions,
  760.     handed simple ~/blah notation, and cached lookups are all reasonable
  761.     enhancements.
  762.  
  763.  
  764. 5.19) How can I convert my shell script to Perl?
  765.  
  766.     Larry's standard answer is to send it through the shell to perl filter,
  767.     otherwise known at tchrist@perl.com.  Contrary to popular belief, Tom
  768.     Christiansen isn't a real person.  He is actually a highly advanced 
  769.     artificial intelligence experiment written by a graduate student at the
  770.     University of Colorado.  Some of the earlier tasks he was programmed to
  771.     perform included:
  772.  
  773.     * monitor comp.lang.perl and collect statistics on which questions
  774.       were asked with which frequency and to respond to them with stock
  775.       answers.  Tom's programming has since outgrown this paltry task,
  776.       and it has been assigned to an undergraduate student from the
  777.       University of Florida.  After all, we all know that student from
  778.       UF aren't able to do much more than documentation anyway.  ;-)
  779.     * convert shell programs to perl programs
  780.  
  781.     Actually, there is no automatic machine translator.  Even if there
  782.     were, you wouldn't gain a lot, as most of the external programs would 
  783.     still get called.  It's the same problem as blind translation into C:
  784.     you're still apt to be bogged down by exec()s.  You have to analyze
  785.     the dataflow and algorithm and rethink it for optimal speedup.  It's
  786.     not uncommon to see one, two, or even three orders of magnitude of
  787.     speed difference between the brute-force and the recoded approaches.
  788.  
  789.  
  790. 5.20) Can I use Perl to run a telnet or ftp session?
  791.  
  792.     Sure, you can connect directly to them using sockets, or you can run a
  793.     session on a pty.  In either case, Randal's chat2 package, which is
  794.     distributed with the perl source, will come in handly.  It address
  795.     much the same problem space as Don Libes's expect package does.  Two
  796.     examples of using managing an ftp session using chat2 can be found on
  797.     convex.com in /pub/perl/scripts/ftp-chat2.shar .
  798.  
  799.     Caveat lector: chat2 is documented only by example, may not run on
  800.     System V systems, and is subtly machine dependent both in its ideas
  801.     of networking and in pseudottys.
  802.  
  803.     Randal also has code showing an example socket session for handling the
  804.     telnet protocol.  You might nudge him for a copy. 
  805.  
  806.     Gene Spafford* has a nice ftp library package that will help with ftp.
  807.  
  808.  
  809. 5.21) Why do I somestimes get an "Arguments too long" when I use <*>?
  810.  
  811.     As of perl4.036, there is a certain amount of globbing that is passed
  812.     out to the shell and not handled internally.  The following code (which
  813.     will, roughly, emulate "chmod 0644 *")
  814.  
  815.     while (<*>) {
  816.         chmod 0644, $_;
  817.     }
  818.  
  819.     is the equivalent of
  820.  
  821.     open(FOO, "echo * | tr -s ' \t\r\f' '\\012\\012\\012\\012'|");
  822.     while (<FOO>) {
  823.         chop;
  824.         chmod 0644, $_;
  825.     }
  826.  
  827.     Until globbing is built into Perl, you will need to use some form of
  828.     non-globbing work around.
  829.  
  830.     Something like the following will work:
  831.  
  832.     opendir(DIR,'.');
  833.     chmod 0644, grep(/\.c$/, readdir(DIR));
  834.     closedir(DIR);
  835.     
  836.     This example is taken directly from "Programming Perl" page 78.
  837.  
  838.     If you've installed tcsh as /bin/csh, you'll never have this problem.
  839.  
  840. 5.22) How do I do a "tail -f" in Perl?
  841.  
  842.     Larry says that the solution is to put a call to seek in yourself. 
  843.     First try
  844.  
  845.         seek(GWFILE, 0, 1);
  846.  
  847.     If that doesn't work (depends on your stdio implementation), then
  848.     you need something more like this:
  849.  
  850.  
  851.     for (;;) {
  852.     for ($curpos = tell(GWFILE); $_ = <GWFILE>; $curpos = tell(GWFILE)) {
  853.         # search for some stuff and put it into files
  854.     }
  855.     sleep for a while 
  856.     seek(GWFILE, $curpos, 0);
  857.     }
  858.  
  859.  
  860. 5.23) Is there a way to hide perl's command line from programs such as "ps"?
  861.  
  862.     Generally speaking, if you need to do this you're either using poor
  863.     programming practices or are far too paranoid for your own good.  If you
  864.     need to do this to hide a password being entered on the command line,
  865.     recode the program to read the password from a file or to prompt for
  866.     it. (see question 4.24)  Typing a password on the command line is
  867.     inherently insecure as anyone can look over your shoulder to see it.
  868.  
  869.     If you feel you really must overwrite the command line and hide it, you
  870.     can assign to the variable "$0".  For example:
  871.  
  872.         #!/usr/local/bin/perl
  873.         $0 = "Hidden from prying eyes";
  874.  
  875.         open(PS, "ps") || die "Can't PS: $!";
  876.         while (<PS>) {
  877.             next unless m/$$/;
  878.             print
  879.         }
  880.  
  881.     It should be noted that some OSes, like Solaris 2.X, read directly from
  882.     the kernel information, instead of from the program's stack, and hence
  883.     don't allow you to change the command line.
  884.  
  885. Stephen P Potter        spp@vx.com        Varimetrix Corporation
  886. 2350 Commerce Park Drive, Suite 4                Palm Bay, FL 32905
  887. (407) 676-3222                           CAD/CAM/CAE/Software
  888.  
  889.  
  890.