home *** CD-ROM | disk | FTP | other *** search
/ ftp.pasteur.org/FAQ/ / ftp-pasteur-org-FAQ.zip / FAQ / perl-faq / part5 < prev   
Encoding:
Internet Message Format  |  1996-01-31  |  40.6 KB

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