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