applied patch (via private mail), modulo retrohunks in pod/perlfaq2.pod
authorTom Christiansen <tchrist@perl.com>
Sun, 5 Jul 1998 09:15:22 +0000 (04:15 -0500)
committerGurusamy Sarathy <gsar@cpan.org>
Sun, 5 Jul 1998 21:38:39 +0000 (21:38 +0000)
Subject: Re: docpatch
Message-Id: <199807051515.JAA03644@jhereg.perl.com>

p4raw-id: //depot/perl@1325

13 files changed:
pod/perlfaq.pod
pod/perlfaq1.pod
pod/perlfaq2.pod
pod/perlfaq3.pod
pod/perlfaq4.pod
pod/perlfaq5.pod
pod/perlfaq6.pod
pod/perlfaq7.pod
pod/perlfaq8.pod
pod/perlfaq9.pod
pod/perlfunc.pod
pod/perlipc.pod
pod/perlrun.pod

index 370d9cb..16220a3 100644 (file)
@@ -1,6 +1,6 @@
 =head1 NAME
 
-perlfaq - frequently asked questions about Perl ($Date: 1997/04/24 22:46:06 $)
+perlfaq - frequently asked questions about Perl ($Date: 1998/06/22 15:15:57 $)
 
 =head1 DESCRIPTION
 
@@ -64,8 +64,8 @@ at http://www.perl.com/perl/faq/ .
 =head2 How to contribute to this document
 
 You may mail corrections, additions, and suggestions to
-perlfaq-suggestions@perl.com .  Mail sent to the old perlfaq alias
-will merely cause the FAQ to be sent to you.
+perlfaq-suggestions@perl.com .  This alias should not be 
+used to I<ask> FAQs.  It's for fixing the current FAQ.
 
 =head2 What will happen if you mail your Perl programming problems to the authors
 
@@ -88,30 +88,23 @@ Perl Porters.
 
 =head1 Author and Copyright Information
 
-Copyright (c) 1997 Tom Christiansen and Nathan Torkington.
+Copyright (c) 1997, 1998 Tom Christiansen and Nathan Torkington.
 All rights reserved.
 
-=head2 Noncommercial Reproduction
+=head2 Bundled Distributions
 
-Permission is granted to distribute this document, in part or in full,
-via electronic means or printed copy providing that (1) that all credits
-and copyright notices be retained, (2) that no charges beyond reproduction
-be involved, and (3) that a reasonable attempt be made to use the most
-current version available.
+When included as part of the Standard Version of Perl, or as part of
+its complete documentation whether printed or otherwise, this work
+may be distributed only under the terms of Perl's Artistic License.
+Any distribution of this file or derivatives thereof I<outside>
+of that package require that special arrangements be made with
+copyright holder.
 
-Furthermore, you may include this document in any distribution of the
-full Perl source or binaries, in its verbatim documentation, or on a
-complete dump of the CPAN archive, providing that the three stipulations
-given above continue to be met.
-
-=head2 Commercial Reproduction
-
-Requests for all other distribution rights, including the incorporation
-in part or in full of this text or its code into commercial products
-such as but not limited to books, magazine articles, or CD-ROMs, must
-be made to perlfaq-legal@perl.com.  Any commercial use of any portion
-of this document without prior written authorization by its authors
-will be subject to appropriate action.
+Irrespective of its distribution, all code examples in these files
+are hereby placed into the public domain.  You are permitted and
+encouraged to use this code in your own programs for fun
+or for profit as you see fit.  A simple comment in the code giving
+credit would be courteous but is not required.
 
 =head2 Disclaimer
 
@@ -124,6 +117,11 @@ in respect of this information or its use.
 
 =over 4
 
+=head 22/June/98
+
+Significant changes throughout in preparation for the 5.005
+release.
+
 =item 24/April/97
 
 Style and whitespace changes from Chip, new question on reading one
index 34caab8..ee071e4 100644 (file)
@@ -1,6 +1,6 @@
 =head1 NAME
 
-perlfaq1 - General Questions About Perl ($Revision: 1.12 $, $Date: 1997/04/24 22:43:34 $)
+perlfaq1 - General Questions About Perl ($Revision: 1.14 $, $Date: 1998/06/14 22:15:25 $)
 
 =head1 DESCRIPTION
 
@@ -51,10 +51,10 @@ users the informal support will more than suffice.  See the answer to
 
 You should definitely use version 5.  Version 4 is old, limited, and
 no longer maintained; its last patch (4.036) was in 1992.  The most
-recent production release is 5.004.  Further references to the Perl
+recent production release is 5.004_01.  Further references to the Perl
 language in this document refer to this production release unless
 otherwise specified.  There may be one or more official bug fixes for
-5.004 by the time you read this, and also perhaps some experimental
+5.004_01 by the time you read this, and also perhaps some experimental
 versions on the way to the next release.
 
 =head2 What are perl4 and perl5?
@@ -250,15 +250,13 @@ behind).  Several important bugs were fixed from the 5.000 through
 Copyright (c) 1997, 1998 Tom Christiansen and Nathan Torkington.
 All rights reserved.
 
-When included as part of the Standard Version of Perl, or as part of
-its complete documentation whether printed or otherwise, this work
-may be distributed only under the terms of Perl's Artistic License.
-Any distribution of this file or derivatives thereof I<outside>
-of that package require that special arrangements be made with
-copyright holder.
-
-Irrespective of its distribution, all code examples in this file
-are hereby placed into the public domain.  You are permitted and
-encouraged to use this code in your own programs for fun
-or for profit as you see fit.  A simple comment in the code giving
-credit would be courteous but is not required.
+When included as an integrated part of the Standard Distribution
+of Perl or of its documentation (printed or otherwise), this works is
+covered under Perl's Artistic Licence.  For separate distributions of
+all or part of this FAQ outside of that, see L<perlfaq>.
+
+Irrespective of its distribution, all code examples here are public
+domain.  You are permitted and encouraged to use this code and any
+derivatives thereof in your own programs for fun or for profit as you
+see fit.  A simple comment in the code giving credit to the FAQ would
+be courteous but is not required.
index 4d873c7..a994042 100644 (file)
@@ -1,6 +1,6 @@
 =head1 NAME
 
-perlfaq2 - Obtaining and Learning about Perl ($Revision: 1.16 $, $Date: 1997/04/23 18:04:09 $)
+perlfaq2 - Obtaining and Learning about Perl ($Revision: 1.20 $, $Date: 1998/07/05 15:07:20 $)
 
 =head1 DESCRIPTION
 
@@ -204,7 +204,7 @@ we try to provide in the Llama or its defurred cousin the Gecko, please
 check out the delightful book, I<Perl: The Programmer's Companion>,
 written by Nigel Chapman.
 
-You can order O'Reilly books diretly from O'Reilly & Associates,
+You can order O'Reilly books directly from O'Reilly & Associates,
 1-800-998-9938.  Local/overseas is 1-707-829-0515.  If you can
 locate an O'Reilly order form, you can also fax to 1-707-829-0104.
 See http://www.ora.com/ on the Web.
@@ -280,7 +280,7 @@ send mail to subscriptions@tpj.com.
 
 Beyond this, magazines that frequently carry high-quality articles
 on Perl are I<Web Techniques> (see http://www.webtechniques.com/),
-I<Performance Computing> at www.performance-computing.com, and Usenix's
+I<Performance Computing> (http://www.performance-computing.com/), and Usenix's
 newsletter/magazine to its members, I<login:>, at http://www.usenix.org/.
 Randal's Web Technique's columns are available on the web at
 http://www.stonehenge.com/merlyn/WebTechniques/.
@@ -351,7 +351,7 @@ to join or leave this list.
 =item Perl-Packrats
 
 Discussion related to archiving of perl materials, particularly the
-Comprehensive Perl Archive Network (CPAN). Subscribe by mailing
+Comprehensive Perl Archive Network (CPAN). Subscribe by emailing
 majordomo@cis.ufl.edu:
 
     subscribe perl-packrats
@@ -386,15 +386,15 @@ let perlfaq-suggestions@perl.com know.
 =head2 Perl Training
 
 While some large training companies offer their own courses on
-Perl, you may prefer to contact individuals near and dear to the
-heart of Perl development.  Two well-known members of the Perl
-development team head companies which offer such things are
-Tom Christiansen <perl-classes@perl.com> and Randal Schwartz
-<perl-training-info@stonehenge.com>, plus their respective
-minions, who offer a variety of professional tutorials and
-seminars on Perl.  These courses include large public seminars,
-private corporate training, and fly-ins to Colorado and Oregon.
-See http://www.perl.com/perl/info/training.html for more details.
+Perl, you may prefer to contact individuals near and dear to
+the heart of Perl development.  Two well-known members of the
+Perl development team head companies which offer such things
+are Tom Christiansen <perl-classes@perl.com> and Randal Schwartz
+<perl-training-info@stonehenge.com>, plus their respective minions,
+who offer a variety of professional tutorials and seminars on Perl.
+These courses include large public seminars, private corporate training,
+and fly-ins to Colorado and Oregon.  Contact Tom or Randal for details,
+or see http://www.perl.com/perl/info/training.html on the web.
 
 =head2 Where can I buy a commercial version of Perl?
 
@@ -483,15 +483,13 @@ while L<perlbot> has some excellent tips and tricks.
 Copyright (c) 1997, 1998 Tom Christiansen and Nathan Torkington.
 All rights reserved.
 
-When included as part of the Standard Version of Perl, or as part of
-its complete documentation whether printed or otherwise, this work
-may be distributed only under the terms of Perl's Artistic License.
-Any distribution of this file or derivatives thereof I<outside>
-of that package require that special arrangements be made with
-copyright holder.
-
-Irrespective of its distribution, all code examples in this file
-are hereby placed into the public domain.  You are permitted and
-encouraged to use this code in your own programs for fun
-or for profit as you see fit.  A simple comment in the code giving
-credit would be courteous but is not required.
+When included as an integrated part of the Standard Distribution
+of Perl or of its documentation (printed or otherwise), this works is
+covered under Perl's Artistic Licence.  For separate distributions of
+all or part of this FAQ outside of that, see L<perlfaq>.
+
+Irrespective of its distribution, all code examples here are public
+domain.  You are permitted and encouraged to use this code and any
+derivatives thereof in your own programs for fun or for profit as you
+see fit.  A simple comment in the code giving credit to the FAQ would
+be courteous but is not required.
index 31e669f..62073e8 100644 (file)
@@ -1,6 +1,6 @@
 =head1 NAME
 
-perlfaq3 - Programming Tools ($Revision: 1.22 $, $Date: 1997/04/24 22:43:42 $)
+perlfaq3 - Programming Tools ($Revision: 1.27 $, $Date: 1998/07/05 15:07:20 $)
 
 =head1 DESCRIPTION
 
@@ -71,7 +71,7 @@ The B::Xref module, shipped with the new, alpha-release Perl compiler
 (not the general distribution prior to the 5.005 release), can be used
 to generate cross-reference reports for Perl programs.
 
-    perl -MO=Xref[,OPTIONS] foo.pl
+    perl -MO=Xref[,OPTIONS] scriptname.plx
 
 =head2 Is there a pretty-printer (formatter) for Perl?
 
@@ -226,9 +226,12 @@ No, Perl's garbage collection system takes care of this.
 
 =head2 How can I free an array or hash so my program shrinks?
 
-You can't.  Memory the system allocates to a program will in practice
-never be returned to the system.  That's why long-running programs
-sometimes re-exec themselves.
+You can't.  On most operating systems, memory allocated to a program
+can never be returned to the system.  That's why long-running programs
+sometimes re-exec themselves.  Some operating systems (notably, FreeBSD)
+allegedly reclaim large chunks of memory that is no longer used, but
+it doesn't appear to happen with Perl (yet).  The Mac appears to be the
+only platform that will reliably (albeit, slowly) return memory to the OS.
 
 However, judicious use of my() on your variables will help make sure
 that they go out of scope so that Perl can free up their storage for
@@ -269,6 +272,14 @@ care.
 
 See http://www.perl.com/CPAN/modules/by-category/15_World_Wide_Web_HTML_HTTP_CGI/.
 
+A non-free, commerical product, 'The Velocity Engine for Perl',
+(http://www.binevolve.com/ or http://www.binevolve.com/bine/vep) might
+also be worth looking at.  It will allow you to increase the performance
+of your perl scripts, upto 25 times faster than normal cgi perl by
+running in persistent perl mode, or 4 to 5 times faster without any
+modification to your existing cgi scripts. Fully functional evaluation
+copies are available from the web site.
+
 =head2 How can I hide the source for my Perl program?
 
 Delete it. :-) Seriously, there are a number of (mostly
@@ -523,15 +534,13 @@ information, see L<ExtUtils::MakeMaker>.
 Copyright (c) 1997, 1998 Tom Christiansen and Nathan Torkington.
 All rights reserved.
 
-When included as part of the Standard Version of Perl, or as part of
-its complete documentation whether printed or otherwise, this work
-may be distributed only under the terms of Perl's Artistic License.
-Any distribution of this file or derivatives thereof I<outside>
-of that package require that special arrangements be made with
-copyright holder.
-
-Irrespective of its distribution, all code examples in this file
-are hereby placed into the public domain.  You are permitted and
-encouraged to use this code in your own programs for fun
-or for profit as you see fit.  A simple comment in the code giving
-credit would be courteous but is not required.
+When included as an integrated part of the Standard Distribution
+of Perl or of its documentation (printed or otherwise), this works is
+covered under Perl's Artistic Licence.  For separate distributions of
+all or part of this FAQ outside of that, see L<perlfaq>.
+
+Irrespective of its distribution, all code examples here are public
+domain.  You are permitted and encouraged to use this code and any
+derivatives thereof in your own programs for fun or for profit as you
+see fit.  A simple comment in the code giving credit to the FAQ would
+be courteous but is not required.
index 8c57db3..21daac6 100644 (file)
@@ -1,6 +1,6 @@
 =head1 NAME
 
-perlfaq4 - Data Manipulation ($Revision: 1.19 $, $Date: 1997/04/24 22:43:57 $)
+perlfaq4 - Data Manipulation ($Revision: 1.24 $, $Date: 1998/07/05 15:07:20 $)
 
 =head1 DESCRIPTION
 
@@ -187,11 +187,12 @@ which should help.
 
 Perl is just as Y2K compliant as your pencil--no more, and no less.
 The date and time functions supplied with perl (gmtime and localtime)
-supply adequate information to determine the year well beyond 2000 (2038
-is when trouble strikes).  The year returned by these functions when used
-in an array context is the year minus 1900.  For years between 1910 and
-1999 this I<happens> to be a 2-digit decimal number. To avoid the year
-2000 problem simply do not treat the year as a 2-digit number.  It isn't.
+supply adequate information to determine the year well beyond 2000
+(2038 is when trouble strikes for 32-bit machines).  The year returned
+by these functions when used in an array context is the year minus 1900.
+For years between 1910 and 1999 this I<happens> to be a 2-digit decimal
+number. To avoid the year 2000 problem simply do not treat the year as
+a 2-digit number.  It isn't.
 
 When gmtime() and localtime() are used in scalar context they return
 a timestamp string that contains a fully-expanded year.  For example,
@@ -256,7 +257,7 @@ For that you'll have to write a parser.
 One destructive, inside-out approach that you might try is to pull
 out the smallest nesting parts one at a time:
 
-    while (s/BEGIN(.*?)END//gs) {
+    while (s//BEGIN((?:(?!BEGIN)(?!END).)*)END/gs) {
        # do something with $1
     } 
 
@@ -600,7 +601,7 @@ subsequent line.
         return $_;
     }
 
-This owrks with leading special strings, dynamically determined:
+This works with leading special strings, dynamically determined:
 
     $remember_the_main = fix<<'    MAIN_INTERPRETER_LOOP';
        @@@ int
@@ -659,9 +660,10 @@ ordered and whether you wish to preserve the ordering.
     $prev = 'nonesuch';
     @out = grep($_ ne $prev && ($prev = $_), @in);
 
-This is nice in that it doesn't use much extra memory,
-simulating uniq(1)'s behavior of removing only adjacent
-duplicates.
+This is nice in that it doesn't use much extra memory, simulating
+uniq(1)'s behavior of removing only adjacent duplicates.  It's less
+nice in that it won't work with false values like undef, 0, or "";
+"0 but true" is ok, though.
 
 =item b) If you don't know whether @in is sorted:
 
index 41c46a3..98e706a 100644 (file)
@@ -1,6 +1,6 @@
 =head1 NAME
 
-perlfaq5 - Files and Formats ($Revision: 1.22 $, $Date: 1997/04/24 22:44:02 $)
+perlfaq5 - Files and Formats ($Revision: 1.24 $, $Date: 1998/07/05 15:07:20 $)
 
 =head1 DESCRIPTION
 
@@ -288,6 +288,10 @@ pair to make it easy to sort the hash in insertion order.
         print "$name $. $line";
     }
 
+For passing filehandles to functions, the easiest way is to 
+prefer them with a star, as in func(*STDIN).  See L<perlfaq7/"Passing
+Filehandles"> for details.
+
 If you want to create many, anonymous handles, you should check out the
 Symbol, FileHandle, or IO::Handle (etc.) modules.  Here's the equivalent
 code with Symbol::gensym, which is reasonably light-weight:
@@ -710,7 +714,8 @@ into human-readable form.
 Here's an example:
 
     $write_secs = (stat($file))[9];
-    print "file $file updated at ", scalar(localtime($file)), "\n";
+    printf "file %s updated at %s\n", $file,
+       scalar localtime($write_secs);
 
 If you prefer something more legible, use the File::stat module
 (part of the standard distribution in version 5.004 and later):
@@ -1057,15 +1062,13 @@ request if you doubt its correctness.
 Copyright (c) 1997, 1998 Tom Christiansen and Nathan Torkington.
 All rights reserved.
 
-When included as part of the Standard Version of Perl, or as part of
-its complete documentation whether printed or otherwise, this work
-may be distributed only under the terms of Perl's Artistic License.
-Any distribution of this file or derivatives thereof I<outside>
-of that package require that special arrangements be made with
-copyright holder.
-
-Irrespective of its distribution, all code examples in this file
-are hereby placed into the public domain.  You are permitted and
-encouraged to use this code in your own programs for fun
-or for profit as you see fit.  A simple comment in the code giving
-credit would be courteous but is not required.
+When included as an integrated part of the Standard Distribution
+of Perl or of its documentation (printed or otherwise), this works is
+covered under Perl's Artistic Licence.  For separate distributions of
+all or part of this FAQ outside of that, see L<perlfaq>.
+
+Irrespective of its distribution, all code examples here are public
+domain.  You are permitted and encouraged to use this code and any
+derivatives thereof in your own programs for fun or for profit as you
+see fit.  A simple comment in the code giving credit to the FAQ would
+be courteous but is not required.
index 0e94f9b..053e284 100644 (file)
@@ -1,6 +1,6 @@
 =head1 NAME
 
-perlfaq6 - Regexps ($Revision: 1.17 $, $Date: 1997/04/24 22:44:10 $)
+perlfaq6 - Regexps ($Revision: 1.21 $, $Date: 1998/06/22 04:23:04 $)
 
 =head1 DESCRIPTION
 
index 291ca36..2218c12 100644 (file)
@@ -1,6 +1,6 @@
 =head1 NAME
 
-perlfaq7 - Perl Language Issues ($Revision: 1.18 $, $Date: 1997/04/24 22:44:14 $)
+perlfaq7 - Perl Language Issues ($Revision: 1.21 $, $Date: 1998/06/22 15:20:07 $)
 
 =head1 DESCRIPTION
 
@@ -9,9 +9,14 @@ clearly fit into any of the other sections.
 
 =head2 Can I get a BNF/yacc/RE for the Perl language?
 
-No, in the words of Chaim Frenkel: "Perl's grammar can not be reduced
-to BNF.  The work of parsing perl is distributed between yacc, the
-lexer, smoke and mirrors."
+There is no BNF, but you can paw your way through the yacc grammar in
+perly.y in the source distribution if you're particularly brave.  The
+grammar relies on very smart tokenizing code, so be prepared to
+venture into toke.c as well.
+
+In the words of Chaim Frenkel: "Perl's grammar can not be reduced to BNF.
+The work of parsing perl is distributed between yacc, the lexer, smoke
+and mirrors."
 
 =head2 What are all these $@%* punctuation signs, and how do I know when to use them?
 
@@ -133,6 +138,12 @@ binds more tightly even than unary minus, making C<-2**2> product a
 negative not a positive four.  It is also right-associating, meaning
 that C<2**3**2> is two raised to the ninth power, not eight squared.
 
+Although it has the same precedence as in C, Perl's C<?:> operator
+produces an lvalue.  This assigns $x to either $a or $b, depending
+on the trueness of $maybe:
+
+    ($maybe ? $a : $b) = $x;
+
 =head2 How do I declare/create a structure?
 
 In general, you don't "declare" a structure.  Just use a (probably
@@ -169,7 +180,7 @@ own module.  Make sure to change the names appropriately.
 
        # if using RCS/CVS, this next line may be preferred,
        # but beware two-digit versions.
-       $VERSION = do{my@r=q$Revision: 1.18 $=~/\d+/g;sprintf '%d.'.'%02d'x$#r,@r};
+       $VERSION = do{my@r=q$Revision: 1.21 $=~/\d+/g;sprintf '%d.'.'%02d'x$#r,@r};
 
        @ISA         = qw(Exporter);
        @EXPORT      = qw(&func1 &func2 &func3);
@@ -262,7 +273,7 @@ Here's a classic function-generating function:
     }
 
     $add_sub = add_function_generator();
-    $sum = &$add_sub(4,5);                # $sum is 9 now.
+    $sum = $add_sub->(4,5);                # $sum is 9 now.
 
 The closure works as a I<function template> with some customization
 slots left out to be filled later.  The anonymous subroutine returned
@@ -344,16 +355,37 @@ reference to an existing or anonymous variable or function:
 
 =item Passing Filehandles
 
-To create filehandles you can pass to subroutines, you can use C<*FH>
-or C<\*FH> notation ("typeglobs" - see L<perldata> for more information),
-or create filehandles dynamically using the old FileHandle or the new
-IO::File modules, both part of the standard Perl distribution.
+To pass filehandles to subroutines, use the C<*FH> or C<\*FH> notations.
+These are "typeglobs" - see L<perldata/"Typeglobs and Filehandles">
+and especially L<perlsub/"Pass by Reference"> for more information.
+
+Here's an excerpt:
+
+If you're passing around filehandles, you could usually just use the bare
+typeglob, like *STDOUT, but typeglobs references would be better because
+they'll still work properly under C<use strict 'refs'>.  For example:
 
-    use Fcntl;
-    use IO::File;
-    my $fh = new IO::File $filename, O_WRONLY|O_APPEND;
-               or die "Can't append to $filename: $!";
-    func($fh);
+    splutter(\*STDOUT);
+    sub splutter {
+        my $fh = shift;
+        print $fh "her um well a hmmm\n";
+    }
+
+    $rec = get_rec(\*STDIN);
+    sub get_rec {
+        my $fh = shift;
+        return scalar <$fh>;
+    }
+
+If you're planning on generating new filehandles, you could do this:
+
+    sub openit {
+        my $name = shift;
+        local *FH;
+        return open (FH, $path) ? *FH : undef;
+    }
+    $fh = openit('< /etc/motd');
+    print <$fh>;
 
 =item Passing Regexps
 
@@ -400,7 +432,7 @@ To pass an object method into a subroutine, you can do this:
         }
     }
 
-or you can use a closure to bundle up the object and its method call
+Or you can use a closure to bundle up the object and its method call
 and arguments:
 
     my $whatnot =  sub { $some_obj->obfuscate(@args) };
@@ -452,6 +484,8 @@ could conceivably have several packages in that same file all
 accessing the same private variable, but another file with the same
 package couldn't get to it.
 
+See L<perlsub/"Peristent Private Variables"> for details.
+
 =head2 What's the difference between dynamic and lexical (static) scoping?  Between local() and my()?
 
 C<local($x)> saves away the old value of the global variable C<$x>,
@@ -495,7 +529,8 @@ In summary, local() doesn't make what you think of as private, local
 variables.  It gives a global variable a temporary value.  my() is
 what you're looking for if you want private variables.
 
-See also L<perlsub>, which explains this all in more detail.
+See L<perlsub/"Private Variables via my()"> and L<perlsub/"Temporary
+Values via local()"> for excruciating details.
 
 =head2 How can I access a dynamic variable while a similarly named lexical is in scope?
 
@@ -528,16 +563,16 @@ However, dynamic variables (aka global, local, or package variables)
 are effectively shallowly bound.  Consider this just one more reason
 not to use them.  See the answer to L<"What's a closure?">.
 
-=head2 Why doesn't "local($foo) = <FILE>;" work right?
+=head2 Why doesn't "my($foo) = <FILE>;" work right?
 
-C<local()> gives list context to the right hand side of C<=>.  The
-E<lt>FHE<gt> read operation, like so many of Perl's functions and
-operators, can tell which context it was called in and behaves
-appropriately.  In general, the scalar() function can help.  This
-function does nothing to the data itself (contrary to popular myth)
-but rather tells its argument to behave in whatever its scalar fashion
-is.  If that function doesn't have a defined scalar behavior, this of
-course doesn't help you (such as with sort()).
+C<my()> and C<local()> give list context to the right hand side
+of C<=>.  The E<lt>FHE<gt> read operation, like so many of Perl's
+functions and operators, can tell which context it was called in and
+behaves appropriately.  In general, the scalar() function can help.
+This function does nothing to the data itself (contrary to popular myth)
+but rather tells its argument to behave in whatever its scalar fashion is.
+If that function doesn't have a defined scalar behavior, this of course
+doesn't help you (such as with sort()).
 
 To enforce scalar context in this particular case, however, you need
 merely omit the parentheses:
@@ -576,7 +611,7 @@ the function doesn't get an empty @_, it gets yours!  While not
 strictly speaking a bug (it's documented that way in L<perlsub>), it
 would be hard to consider this a feature in most cases.
 
-When you call your function as C<&foo()>, then you do get a new @_,
+When you call your function as C<&foo()>, then you I<do> get a new @_,
 but prototyping is still circumvented.
 
 Normally, you want to call a function using C<foo()>.  You may only
@@ -595,12 +630,21 @@ regexp matching, overloaded comparisons, ...).  Larry couldn't decide
 how best to do this, so he left it out, even though it's been on the
 wish list since perl1.
 
-Here's a simple example of a switch based on pattern matching.  We'll
-do a multi-way conditional based on the type of reference stored in
-$whatchamacallit:
+The general answer is to write a construct like this:
+
+    for ($variable_to_test) {
+       if    (/pat1/)  { }     # do something
+       elsif (/pat2/)  { }     # do something else
+       elsif (/pat3/)  { }     # do something else
+       else            { }     # default
+    } 
 
-    SWITCH:
-      for (ref $whatchamacallit) {
+Here's a simple example of a switch based on pattern matching, this
+time lined up in a way to make it look more like a switch statement.
+We'll do a multi-way conditional based on the type of reference stored
+in $whatchamacallit:
+
+    SWITCH: for (ref $whatchamacallit) {
 
        /^$/            && die "not a reference";
 
@@ -630,6 +674,41 @@ $whatchamacallit:
 
     }
 
+See C<perlsyn/"Basic BLOCKs and Switch Statements"> for many other 
+examples in this style.
+
+Sometimes you should change the positions of the constant and the variable.
+For example, let's say you wanted to test which of many answers you were
+given, but in a case-insensitive way that also allows abbreviations.
+You can use the following technique if the strings all start with
+different characters, or if you want to arrange the matches so that
+one takes precedence over another, as C<"SEND"> has precedence over
+C<"STOP"> here:
+
+    chomp($answer = <>);
+    if    ("SEND"  =~ /^\Q$answer/i) { print "Action is send\n"  }
+    elsif ("STOP"  =~ /^\Q$answer/i) { print "Action is stop\n"  }
+    elsif ("ABORT" =~ /^\Q$answer/i) { print "Action is abort\n" }
+    elsif ("LIST"  =~ /^\Q$answer/i) { print "Action is list\n"  }
+    elsif ("EDIT"  =~ /^\Q$answer/i) { print "Action is edit\n"  }
+
+A totally different approach is to create a hash of function references.  
+
+    my %commands = (
+        "happy" => \&joy,
+        "sad",  => \&sullen,
+        "done"  => sub { die "See ya!" },
+        "mad"   => \&angry,
+    );
+
+    print "How are you? ";
+    chomp($string = <STDIN>);
+    if ($commands{$string}) {
+        $commands{$string}->();
+    } else {
+        print "No such command: $string\n";
+    } 
+
 =head2 How can I catch accesses to undefined variables/functions/methods?
 
 The AUTOLOAD method, discussed in L<perlsub/"Autoloading"> and
@@ -642,7 +721,7 @@ C<__WARN__> like this:
 
     $SIG{__WARN__} = sub {
 
-       for ( $_[0] ) {
+       for ( $_[0] ) {         # voici un switch statement 
 
            /Use of uninitialized value/  && do {
                # promote warning to a fatal
@@ -672,12 +751,15 @@ C<require>.  If not, make sure to use arrow notation (eg,
 C<Guru-E<gt>find("Samy")>) instead.  Object notation is explained in
 L<perlobj>.
 
+Make sure to read about creating modules in L<perlmod> and
+the perils of indirect objects in L<perlobj/"WARNING">.
+
 =head2 How can I find out my current package?
 
 If you're just a random program, you can do this to find
 out what the currently compiled package is:
 
-    my $packname = ref bless [];
+    my $packname = __PACKAGE__;
 
 But if you're a method and you want to print an error message
 that includes the kind of object you were called on (which is
@@ -711,6 +793,10 @@ Use embedded POD to discard it:
 
     =cut
 
+This can't go just anywhere.  You have to put a pod directive where
+the parser is expecting a new statement, not just in the middle
+of an expression or some other arbitrary yacc grammar production.
+
 =head1 AUTHOR AND COPYRIGHT
 
 Copyright (c) 1997, 1998 Tom Christiansen and Nathan Torkington.
index f4addd8..272dd51 100644 (file)
@@ -1,6 +1,6 @@
 =head1 NAME
 
-perlfaq8 - System Interaction ($Revision: 1.21 $, $Date: 1997/04/24 22:44:19 $)
+perlfaq8 - System Interaction ($Revision: 1.25 $, $Date: 1998/07/05 15:07:20 $)
 
 =head1 DESCRIPTION
 
@@ -15,7 +15,7 @@ contain more detailed information on the vagaries of your perl.
 
 =head2 How do I find out which operating system I'm running under?
 
-The $^O variable ($OSTYPE if you use English) contains the operating
+The $^O variable ($OSNAME if you use English) contains the operating
 system that your perl binary was built for.
 
 =head2 How come exec() doesn't return?
@@ -52,6 +52,162 @@ How you access/control keyboards, screens, and pointing devices
 
 =back
 
+Some of these specific cases are shown below.
+
+=head2 How do I print something out in color?
+
+In general, you don't, because you don't know whether
+the recipient has a color-aware display device.  If you
+know that they have an ANSI terminal that understands
+color, you can use the Term::ANSIColor module from CPAN:
+
+    use Term::ANSIColor;
+    print color("red"), "Stop!\n", color("reset");
+    print color("green"), "Go!\n", color("reset");
+
+Or like this:
+
+    use Term::ANSIColor qw(:constants);
+    print RED, "Stop!\n", RESET;
+    print GREEN, "Go!\n", RESET;
+
+=head2 How do I read just one key without waiting for a return key?
+
+Controlling input buffering is a remarkably system-dependent matter.
+If most systems, you can just use the B<stty> command as shown in
+L<perlfunc/getc>, but as you see, that's already getting you into
+portability snags.  
+
+    open(TTY, "+</dev/tty") or die "no tty: $!";
+    system "stty  cbreak </dev/tty >/dev/tty 2>&1";
+    $key = getc(TTY);          # perhaps this works
+    # OR ELSE
+    sysread(TTY, $key, 1);     # probably this does
+    system "stty -cbreak </dev/tty >/dev/tty 2>&1";
+
+The Term::ReadKey module from CPAN offers an easy-to-use interface that
+should be more efficient than shelling out to B<stty> for each key.
+It even includes limited support for Windows.
+
+    use Term::ReadKey;
+    ReadMode('cbreak');
+    $key = ReadKey(0);
+    ReadMode('normal');
+
+However, that requires that you have a working C compiler and can use it
+to build and install a CPAN module.  Here's a solution using
+the standard POSIX module, which is already on your systems (assuming
+your system supports POSIX).
+
+    use HotKey;
+    $key = readkey();
+
+And here's the HotKey module, which hides the somewhat mystifying calls
+to manipulate the POSIX termios structures.
+
+    # HotKey.pm
+    package HotKey;
+
+    @ISA = qw(Exporter);
+    @EXPORT = qw(cbreak cooked readkey);
+
+    use strict;
+    use POSIX qw(:termios_h);
+    my ($term, $oterm, $echo, $noecho, $fd_stdin);
+
+    $fd_stdin = fileno(STDIN);
+    $term     = POSIX::Termios->new();
+    $term->getattr($fd_stdin);
+    $oterm     = $term->getlflag();
+
+    $echo     = ECHO | ECHOK | ICANON;
+    $noecho   = $oterm & ~$echo;
+
+    sub cbreak {
+        $term->setlflag($noecho);  # ok, so i don't want echo either
+        $term->setcc(VTIME, 1);
+        $term->setattr($fd_stdin, TCSANOW);
+    }
+
+    sub cooked {
+        $term->setlflag($oterm);
+        $term->setcc(VTIME, 0);
+        $term->setattr($fd_stdin, TCSANOW);
+    }
+
+    sub readkey {
+        my $key = '';
+        cbreak();
+        sysread(STDIN, $key, 1);
+        cooked();
+        return $key;
+    }
+
+    END { cooked() }
+
+    1;
+
+=head2 How do I check whether input is ready on the keyboard?
+
+The easiest way to do this is to read a key in nonblocking mode with the
+Term::ReadKey module from CPAN, passing it an argument of -1 to indicate
+not to block:
+
+    use Term::ReadKey;
+
+    ReadMode('cbreak');
+
+    if (defined ($char = ReadKey(-1)) ) {
+        # input was waiting and it was $char
+    } else {
+        # no input was waiting
+    }
+
+    ReadMode('normal');                  # restore normal tty settings
+
+=head2 How do I clear the screen?
+
+If you only have to so infrequently, use C<system>:
+
+    system("clear");
+
+If you have to do this a lot, save the clear string
+so you can print it 100 times without calling a program
+100 times:
+
+    $clear_string = `clear`;
+    print $clear_string;
+
+If you're planning on doing other screen manipulations, like cursor
+positions, etc, you might wish to use Term::Cap module:
+
+    use Term::Cap;
+    $terminal = Term::Cap->Tgetent( {OSPEED => 9600} );
+    $clear_string = $terminal->Tputs('cl');
+
+=head2 How do I get the screen size?
+
+If you have Term::ReadKey module installed from CPAN, 
+you can use it to fetch the width and height in characters
+and in pixels:
+
+    use Term::ReadKey;
+    ($wchar, $hchar, $wpixels, $hpixels) = GetTerminalSize();
+
+This is more portable than the raw C<ioctl>, but not as 
+illustrative:
+
+    require 'sys/ioctl.ph';
+    die "no TIOCGWINSZ " unless defined &TIOCGWINSZ;
+    open(TTY, "+</dev/tty")                     or die "No tty: $!";
+    unless (ioctl(TTY, &TIOCGWINSZ, $winsize='')) {
+        die sprintf "$0: ioctl TIOCGWINSZ (%08x: $!)\n", &TIOCGWINSZ;
+    }
+    ($row, $col, $xpixel, $ypixel) = unpack('S4', $winsize);
+    print "(row,col) = ($row,$col)";
+    print "  (xpixel,ypixel) = ($xpixel,$ypixel)" if $xpixel || $ypixel;
+    print "\n";
+
 =head2 How do I ask the user for a password?
 
 (This question has nothing to do with the web.  See a different
@@ -66,6 +222,11 @@ to the B<stty> program, with varying degrees of portability.
 You can also do this for most systems using the Term::ReadKey module
 from CPAN, which is easier to use and in theory more portable.
 
+    use Term::ReadKey;
+
+    ReadMode('noecho');
+    $password = ReadLine(0);
+
 =head2 How do I read and write the serial port?
 
 This depends on which operating system your program is running on.  In
@@ -112,18 +273,9 @@ next.
 =item flushing output
 
 If you expect characters to get to your device when you print() them,
-you'll want to autoflush that filehandle, as in the older
-
-    use FileHandle;
-    DEV->autoflush(1);
-
-and the newer
-
-    use IO::Handle;
-    DEV->autoflush(1);
-
-You can use select() and the C<$|> variable to control autoflushing
-(see L<perlvar/$|> and L<perlfunc/select>):
+you'll want to autoflush that filehandle.  You can use select()
+and the C<$|> variable to control autoflushing (see L<perlvar/$|>
+and L<perlfunc/select>):
 
     $oldh = select(DEV);
     $| = 1;
@@ -133,6 +285,12 @@ You'll also see code that does this without a temporary variable, as in
 
     select((select(DEV), $| = 1)[0]);
 
+Or if you don't mind pulling in a few thousand lines
+of code just because you're afraid of a little $| variable:
+
+    use IO::Handle;
+    DEV->autoflush(1);
+
 As mentioned in the previous item, this still doesn't work when using
 socket I/O between Unix and Macintosh.  You'll need to hardcode your
 line terminators, in that case.
@@ -148,15 +306,38 @@ L<perlfunc/"select">.
 
 =back
 
+While trying to read from his caller-id box, the notorious Jamie Zawinski
+<jwz@netscape.com>, after much gnashing of teeth and fighting with sysread,
+sysopen, POSIX's tcgetattr business, and various other functions that
+go bump in the night, finally came up with this:
+
+    sub open_modem {
+       use IPC::Open2;
+       my $stty = `/bin/stty -g`;
+       open2( \*MODEM_IN, \*MODEM_OUT, "cu -l$modem_device -s2400 2>&1");
+       # starting cu hoses /dev/tty's stty settings, even when it has
+       # been opened on a pipe...
+       system("/bin/stty $stty");
+       $_ = <MODEM_IN>;
+       chop;
+       if ( !m/^Connected/ ) {
+           print STDERR "$0: cu printed `$_' instead of `Connected'\n";
+       }
+    }
+
+
 =head2 How do I decode encrypted password files?
 
 You spend lots and lots of money on dedicated hardware, but this is
 bound to get you talked about.
 
 Seriously, you can't if they are Unix password files - the Unix
-password system employs one-way encryption.  Programs like Crack can
-forcibly (and intelligently) try to guess passwords, but don't (can't)
-guarantee quick success.
+password system employs one-way encryption.  It's more like hashing than
+encryption.  The best you can check is whether something else hashes to
+the same string.  You can't turn a hash back into the original string.
+Programs like Crack
+can forcibly (and intelligently) try to guess passwords, but don't
+(can't) guarantee quick success.
 
 If you're worried about users selecting bad passwords, you should
 proactively check when they try to change their password (by modifying
@@ -174,7 +355,7 @@ on a Unix-like system:
 
 =over 4
 
-=item STDIN, STDOUT and STDERR are shared
+=item STDIN, STDOUT, and STDERR are shared
 
 Both the main process and the backgrounded one (the "child" process)
 share the same STDIN, STDOUT and STDERR filehandles.  If both try to
@@ -204,9 +385,10 @@ Zombies are not an issue with C<system("prog &")>.
 
 =head2 How do I trap control characters/signals?
 
-You don't actually "trap" a control character.  Instead, that
-character generates a signal, which you then trap.  Signals are
-documented in L<perlipc/"Signals"> and chapter 6 of the Camel.
+You don't actually "trap" a control character.  Instead, that character
+generates a signal which is sent to your terminal's currently
+foregrounded process group, which you then trap in your process.
+Signals are documented in L<perlipc/"Signals"> and chapter 6 of the Camel.
 
 Be warned that very few C libraries are re-entrant.  Therefore, if you
 attempt to print() in a handler that got invoked during another stdio
@@ -235,10 +417,11 @@ blocking flock() in L<perlipc/"Signals"> or chapter 6 of the Camel.
 
 =head2 How do I modify the shadow password file on a Unix system?
 
-If perl was installed correctly, the getpw*() functions described in
-L<perlfunc> provide (read-only) access to the shadow password file.
-To change the file, make a new shadow password file (the format varies
-from system to system - see L<passwd(5)> for specifics) and use
+If perl was installed correctly, and your shadow library was written
+properly, the getpw*() functions described in L<perlfunc> should in
+theory provide (read-only) access to entries in the shadow password
+file.  To change the file, make a new shadow password file (the format
+varies from system to system - see L<passwd(5)> for specifics) and use
 pwd_mkdb(8) to install it (see L<pwd_mkdb(5)> for more details).
 
 =head2 How do I set the time and date?
@@ -254,7 +437,7 @@ probably get away with setting an environment variable:
 
     $ENV{TZ} = "MST7MDT";                 # unixish
     $ENV{'SYS$TIMEZONE_DIFFERENTIAL'}="-5" # vms
-    system "trn comp.lang.perl";
+    system "trn comp.lang.perl.misc";
 
 =head2 How can I sleep() or alarm() for under a second?
 
@@ -303,9 +486,17 @@ then you may be able to do something like this:
 
 Release 5 of Perl added the END block, which can be used to simulate
 atexit().  Each package's END block is called when the program or
-thread ends (see L<perlmod> manpage for more details).  It isn't
-called when untrapped signals kill the program, though, so if you use
-END blocks you should also use
+thread ends (see L<perlmod> manpage for more details).  
+
+For example, you can use this to make sure your filter program
+managed to finish its output without filling up the disk:
+
+    END {
+       close(STDOUT) || die "stdout close failed: $!";
+    } 
+
+The END block isn't called when untrapped signals kill the program, though, so if
+you use END blocks you should also use
 
        use sigtrap qw(die normal-signals);
 
@@ -375,15 +566,21 @@ scripts inherently insecure.  Perl gives you a number of options
 =head2 How can I open a pipe both to and from a command?
 
 The IPC::Open2 module (part of the standard perl distribution) is an
-easy-to-use approach that internally uses pipe(), fork(), and exec()
-to do the job.  Make sure you read the deadlock warnings in its
-documentation, though (see L<IPC::Open2>).
+easy-to-use approach that internally uses pipe(), fork(), and exec() to do
+the job.  Make sure you read the deadlock warnings in its documentation,
+though (see L<IPC::Open2>).  See L<perlipc/"Bidirectional Communication
+with Another Process"> and L<perlipc/"Bidirectional Communication with
+Yourself">
+
+You may also use the IPC::Open3 module (part of the standard perl
+distribution), but be warned that it has a different order of
+arguments from IPC::Open2 (see L<IPC::Open3>).
 
 =head2 Why can't I get the output of a command with system()?
 
 You're confusing the purpose of system() and backticks (``).  system()
 runs a command and returns exit status information (as a 16 bit value:
-the low 8 bits are the signal the process died from, if any, and
+the low 7 bits are the signal the process died from, if any, and
 the high 8 bits are the actual exit value).  Backticks (``) run a
 command and return what it sent to STDOUT.
 
@@ -434,15 +631,51 @@ Note that you I<must> use Bourne shell (sh(1)) redirection syntax in
 backticks, not csh(1)!  Details on why Perl's system() and backtick
 and pipe opens all use the Bourne shell are in
 http://www.perl.com/CPAN/doc/FMTEYEWTK/versus/csh.whynot .
+To capture a command's STDERR and STDOUT together:
 
-You may also use the IPC::Open3 module (part of the standard perl
-distribution), but be warned that it has a different order of
-arguments from IPC::Open2 (see L<IPC::Open3>).
+    $output = `cmd 2>&1`;                       # either with backticks
+    $pid = open(PH, "cmd 2>&1 |");              # or with an open pipe
+    while (<PH>) { }                            #    plus a read
+
+To capture a command's STDOUT but discard its STDERR:
+
+    $output = `cmd 2>/dev/null`;                # either with backticks
+    $pid = open(PH, "cmd 2>/dev/null |");       # or with an open pipe
+    while (<PH>) { }                            #    plus a read
+
+To capture a command's STDERR but discard its STDOUT:
+
+    $output = `cmd 2>&1 1>/dev/null`;           # either with backticks
+    $pid = open(PH, "cmd 2>&1 1>/dev/null |");  # or with an open pipe
+    while (<PH>) { }                            #    plus a read
+
+To exchange a command's STDOUT and STDERR in order to capture the STDERR
+but leave its STDOUT to come out our old STDERR:
+
+    $output = `cmd 3>&1 1>&2 2>&3 3>&-`;        # either with backticks
+    $pid = open(PH, "cmd 3>&1 1>&2 2>&3 3>&-|");# or with an open pipe
+    while (<PH>) { }                            #    plus a read
+
+To read both a command's STDOUT and its STDERR separately, it's easiest
+and safest to redirect them separately to files, and then read from those
+files when the program is done:
+
+    system("program args 1>/tmp/program.stdout 2>/tmp/program.stderr");
+
+Ordering is important in all these examples.  That's because the shell
+processes file descriptor redirections in strictly left to right order.
+
+    system("prog args 1>tmpfile 2>&1");
+    system("prog args 2>&1 1>tmpfile");
+
+The first command sends both standard out and standard error to the
+temporary file.  The second command sends only the old standard output
+there, and the old standard error shows up on the old standard out.
 
 =head2 Why doesn't open() return an error when a pipe open fails?
 
 It does, but probably not how you expect it to.  On systems that
-follow the standard fork()/exec() paradigm (eg, Unix), it works like
+follow the standard fork()/exec() paradigm (such as Unix), it works like
 this: open() causes a fork().  In the parent, open() returns with the
 process ID of the child.  The child exec()s the command to be piped
 to/from.  The parent can't know whether the exec() was successful or
@@ -487,7 +720,7 @@ In most cases, this could and probably should be written as
        or die "cat program failed!";
 
 Which will get the output quickly (as its generated, instead of only
-at the end ) and also check the return value.
+at the end) and also check the return value.
 
 system() also provides direct control over whether shell wildcard
 processing may take place, whereas backticks do not.
@@ -513,6 +746,8 @@ You have to do this:
 
 Just as with system(), no shell escapes happen when you exec() a list.
 
+There are more examples of this L<perlipc/"Safe Pipe Opens">.
+
 =head2 Why can't my script read from STDIN after I gave it EOF (^D on Unix, ^Z on MS-DOS)?
 
 Because some stdio's set error and eof flags that need clearing.  The
@@ -582,9 +817,10 @@ approach will suffice:
 =head2 How can I write expect in Perl?
 
 Once upon a time, there was a library called chat2.pl (part of the
-standard perl distribution), which never really got finished.  These
-days, your best bet is to look at the Comm.pl library available from
-CPAN.
+standard perl distribution), which never really got finished.  If you
+find it somewhere, I<don't use it>.  These days, your best bet is to
+look at the Expect module available from CPAN, which also requires two
+other modules from CPAN, IO::Pty and IO::Stty.
 
 =head2 Is there a way to hide perl's command line from programs such as "ps"?
 
@@ -614,10 +850,6 @@ created after the change.  There is shell magic that may allow you to
 fake it by eval()ing the script's output in your shell; check out the
 comp.unix.questions FAQ for details.
 
-=item VMS
-
-Change to %ENV persist after Perl exits, but directory changes do not.
-
 =back
 
 =head2 How do I close a process's filehandle without waiting for it to complete?
@@ -638,7 +870,8 @@ module for other solutions.
 =item *
 
 Open /dev/tty and use the the TIOCNOTTY ioctl on it.  See L<tty(4)>
-for details.
+for details.  Or better yet, you can just use the POSIX::setsid()
+function, so you don't have to worry about process groups.
 
 =item *
 
@@ -705,12 +938,17 @@ in L<perlfunc/fork>.
 There are a number of excellent interfaces to SQL databases.  See the
 DBD::* modules available from
 http://www.perl.com/CPAN/modules/dbperl/DBD .
+A lot of information on this can be found at 
+http://www.hermetica.com/technologia/perl/DBI/index.html .
 
 =head2 How do I make a system() exit on control-C?
 
 You can't.  You need to imitate the system() call (see L<perlipc> for
 sample code) and then have a signal handler for the INT signal that
-passes the signal on to the subprocess.
+passes the signal on to the subprocess.  Or you can check for it:
+
+    $rc = system($cmd);
+    if ($rc & 127) { die "signal death" } 
 
 =head2 How do I open a file without blocking?
 
@@ -758,9 +996,31 @@ If your version of perl is compiled without dynamic loading, then you
 just need to replace step 3 (B<make>) with B<make perl> and you will
 get a new F<perl> binary with your extension linked in.
 
-See L<ExtUtils::MakeMaker> for more details on building extensions
-and an answer to the question "How do I keep my own module/library
-directory?"
+See L<ExtUtils::MakeMaker> for more details on building extensions.
+See also the next question.
+
+=head2 What's the difference between require and use?
+
+Perl offers several different ways to include code from one file into
+another.  Here are the deltas between the various inclusion constructs:
+
+    1)  do $file is like eval `cat $file`, except the former:
+       1.1: searches @INC.
+       1.2: bequeaths an *unrelated* lexical scope on the eval'ed code.
+
+    2)  require $file is like do $file, except the former:
+       2.1: checks for redundant loading, skipping already loaded files.
+       2.2: raises an exception on failure to find, compile, or execute $file.
+
+    3)  require Module is like require "Module.pm", except the former:
+       3.1: translates each "::" into your system's directory separator.
+       3.2: primes the parser to disambiguate class Module as an indirect object.
+
+    4)  use Module is like require Module, except the former:
+       4.1: loads the module at compile time, not run-time.
+       4.2: imports symbols and semantics from that package to the current one.
+
+In general, you usually want C<use> and a proper Perl module.
 
 =head2 How do I keep my own module/library directory?
 
@@ -796,56 +1056,6 @@ The latter is particularly useful because it knows about machine
 dependent architectures.  The lib.pm pragmatic module was first
 included with the 5.002 release of Perl.
 
-=head1 How do I get one key from the terminal at a time, under POSIX?
-
-    #!/usr/bin/perl -w
-    use strict;
-    $| = 1;
-    for (1..4) {
-        my $got;
-        print "gimme: ";
-        $got = getone();
-        print "--> $got\n";
-    }
-    exit;
-
-    BEGIN {
-        use POSIX qw(:termios_h);
-
-        my ($term, $oterm, $echo, $noecho, $fd_stdin);
-
-        $fd_stdin = fileno(STDIN);
-
-        $term     = POSIX::Termios->new();
-        $term->getattr($fd_stdin);
-        $oterm     = $term->getlflag();
-
-        $echo     = ECHO | ECHOK | ICANON;
-        $noecho   = $oterm & ~$echo;
-
-        sub cbreak {
-            $term->setlflag($noecho);
-            $term->setcc(VTIME, 1);
-            $term->setattr($fd_stdin, TCSANOW);
-        }
-
-        sub cooked {
-            $term->setlflag($oterm);
-            $term->setcc(VTIME, 0);
-            $term->setattr($fd_stdin, TCSANOW);
-        }
-
-        sub getone {
-            my $key = '';
-            cbreak();
-            sysread(STDIN, $key, 1);
-            cooked();
-            return $key;
-        }
-
-    }
-    END { cooked() }
-
 =head1 AUTHOR AND COPYRIGHT
 
 Copyright (c) 1997, 1998 Tom Christiansen and Nathan Torkington.
index deeb650..9927152 100644 (file)
@@ -1,32 +1,79 @@
 =head1 NAME
 
-perlfaq9 - Networking ($Revision: 1.17 $, $Date: 1997/04/24 22:44:29 $)
+perlfaq9 - Networking ($Revision: 1.20 $, $Date: 1998/06/22 18:31:09 $)
 
 =head1 DESCRIPTION
 
 This section deals with questions related to networking, the internet,
 and a few on the web.
 
-=head2 My CGI script runs from the command line but not the browser.  Can you help me fix it?
+=head2 My CGI script runs from the command line but not the browser.   (500 Server Error)
 
-Sure, but you probably can't afford our contracting rates :-)
+If you can demonstrate that you've read the following FAQs and that
+your problem isn't something simple that can be easily answered, you'll
+probably receive a courteous and useful reply to your question if you
+post it on comp.infosystems.www.authoring.cgi (if it's something to do
+with HTTP, HTML, or the CGI protocols).  Questions that appear to be Perl
+questions but are really CGI ones that are posted to comp.lang.perl.misc
+may not be so well received.
 
-Seriously, if you can demonstrate that you've read the following FAQs
-and that your problem isn't something simple that can be easily
-answered, you'll probably receive a courteous and useful reply to your
-question if you post it on comp.infosystems.www.authoring.cgi (if it's
-something to do with HTTP, HTML, or the CGI protocols).  Questions that
-appear to be Perl questions but are really CGI ones that are posted to
-comp.lang.perl.misc may not be so well received.
+The useful FAQs and related documents are:
 
-The useful FAQs are:
+    CGI FAQ
+        http://www.webthing.com/page.cgi/cgifaq
 
-    http://www.perl.com/perl/faq/idiots-guide.html
-    http://www3.pair.com/webthing/docs/cgi/faqs/cgifaq.shtml
-    http://www.perl.com/perl/faq/perl-cgi-faq.html
-    http://www-genome.wi.mit.edu/WWW/faqs/www-security-faq.html
+    Web FAQ
     http://www.boutell.com/faq/
 
+    WWW Security FAQ
+        http://www.w3.org/Security/Faq/
+
+    HTTP Spec
+        http://www.w3.org/pub/WWW/Protocols/HTTP/
+
+    HTML Spec
+        http://www.w3.org/TR/REC-html40/
+        http://www.w3.org/pub/WWW/MarkUp/
+
+    CGI Spec
+        http://www.w3.org/CGI/
+
+    CGI Security FAQ
+        http://www.go2net.com/people/paulp/cgi-security/safe-cgi.txt
+
+=head2 How can I get better error messages from a CGI program?
+
+Use the CGI::Carp module.  It replaces C<warn> and C<die>, plus the
+normal Carp modules C<carp>, C<croak>, and C<confess> functions with
+more verbose and safer versions.  It still sends them to the normal
+server error log.
+
+    use CGI::Carp;
+    warn "This is a complaint";
+    die "But this one is serious";
+
+The following use of CGI::Carp also redirects errors to a file of your choice,
+placed in a BEGIN block to catch compile-time warnings as well:
+
+    BEGIN {
+        use CGI::Carp qw(carpout);
+        open(LOG, ">>/var/local/cgi-logs/mycgi-log")
+            or die "Unable to append to mycgi-log: $!\n";
+        carpout(*LOG);
+    }
+
+You can even arrange for fatal errors to go back to the client browser,
+which is nice for your own debugging, but might confuse the end user.
+
+    use CGI::Carp qw(fatalsToBrowser);
+    die "Bad error here";
+
+Even if the error happens before you get the HTTP header out, the module
+will try to take care of this to avoid the dreaded server 500 errors.
+Normal warnings still go out to the server error log (or wherever
+you've sent them with C<carpout>) with the application name and date
+stamp prepended.
+
 =head2 How do I remove HTML from a string?
 
 The most correct way (albeit not the fastest) is to use HTML::Parse
@@ -49,6 +96,29 @@ program in
 http://www.perl.com/CPAN/authors/Tom_Christiansen/scripts/striphtml.gz
 .
 
+Here are some tricky cases that you should think about when picking
+a solution:
+
+    <IMG SRC = "foo.gif" ALT = "A > B">
+
+    <IMG SRC = "foo.gif" 
+        ALT = "A > B">
+
+    <!-- <A comment> -->
+
+    <script>if (a<b && a>c)</script>
+
+    <# Just data #>
+
+    <![INCLUDE CDATA [ >>>>>>>>>>>> ]]>
+
+If HTML comments include other tags, those solutions would also break
+on text like this:
+
+    <!-- This section commented out.
+        <B>You can't see me!</B>
+    -->
+
 =head2 How do I extract URLs?
 
 A quick but imperfect approach is
@@ -93,11 +163,15 @@ on your system, is this:
 The libwww-perl (LWP) modules from CPAN provide a more powerful way to
 do this.  They work through proxies, and don't require lynx:
 
-    # print HTML from a URL
+    # simplest version
+    use LWP::Simple;
+    $content = get($URL);
+
+    # or print HTML from a URL
     use LWP::Simple;
     getprint "http://www.sn.no/libwww-perl/";
 
-    # print ASCII from HTML from a URL
+    # or print ASCII from HTML from a URL
     use LWP::Simple;
     use HTML::Parse;
     use HTML::FormatText;
@@ -108,7 +182,30 @@ do this.  They work through proxies, and don't require lynx:
     $ascii = HTML::FormatText->new->format(parse_html($html));
     print $ascii;
 
-=head2 how do I decode or create those %-encodings on the web?
+=head2 How do I automate an HTML form submission?
+
+If you're submitting values using the GET method, create a URL and encode
+the form using the C<query_form> method:
+
+    use LWP::Simple;
+    use URI::URL;
+
+    my $url = url('http://www.perl.com/cgi-bin/cpan_mod');
+    $url->query_form(module => 'DB_File', readme => 1);
+    $content = get($url);
+
+If you're using the POST method, create your own user agent and encode
+the content appropriately.
+
+    use HTTP::Request::Common qw(POST);
+    use LWP::UserAgent;
+
+    $ua = LWP::UserAgent->new();
+    my $req = POST 'http://www.perl.com/cgi-bin/cpan_mod',
+                   [ module => 'DB_File', readme => 1 ];
+    $content = $ua->request($req)->as_string;
+
+=head2 How do I decode or create those %-encodings on the web?
 
 Here's an example of decoding:
 
@@ -135,6 +232,14 @@ both:
 Note that relative URLs in these headers can cause strange effects
 because of "optimizations" that servers do.
 
+    $url = "http://www.perl.com/CPAN/";
+    print "Location: $url\n\n";
+    exit;
+
+To be correct to the spec, each of those C<"\n">
+should really each be C<"\015\012">, but unless you're
+stuck on MacOS, you probably won't notice.
+
 =head2 How do I put a password on my web pages?
 
 That depends.  You'll need to read the documentation for your web
@@ -182,44 +287,82 @@ the Mail::Header module from CPAN (part of the MailTools package).
 
 =head2 How do I decode a CGI form?
 
-A lot of people are tempted to code this up themselves, so you've
-probably all seen a lot of code involving C<$ENV{CONTENT_LENGTH}> and
-C<$ENV{QUERY_STRING}>.  It's true that this can work, but there are
-also a lot of versions of this floating around that are quite simply
-broken!
-
-Please do not be tempted to reinvent the wheel.  Instead, use the
-CGI.pm or CGI_Lite.pm (available from CPAN), or if you're trapped in
-the module-free land of perl1 .. perl4, you might look into cgi-lib.pl
-(available from http://www.bio.cam.ac.uk/web/form.html).
+You use a standard module, probably CGI.pm.  Under no circumstances
+should you attempt to do so by hand!
+
+You'll see a lot of CGI programs that blindly read from STDIN the number
+of bytes equal to CONTENT_LENGTH for POSTs, or grab QUERY_STRING for
+decoding GETs.  These programs are very poorly written.  They only work
+sometimes.  They typically forget to check the return value of the read()
+system call, which is a cardinal sin.  They don't handle HEAD requests.
+They don't handle multipart forms used for file uploads.  They don't deal
+with GET/POST combinations where query fields are in more than one place.
+They don't deal with keywords in the query string.
+
+In short, they're bad hacks.  Resist them at all costs.  Please do not be
+tempted to reinvent the wheel.  Instead, use the CGI.pm or CGI_Lite.pm
+(available from CPAN), or if you're trapped in the module-free land
+of perl1 .. perl4, you might look into cgi-lib.pl (available from
+http://www.bio.cam.ac.uk/web/form.html).
+
+Make sure you know whether to use a GET or a POST in your form.
+GETs should only be used for something that doesn't update the server.
+Otherwise you can get mangled databases and repeated feedback mail
+messages.  The fancy word for this is ``idempotency''.  This simply
+means that there should be no difference between making a GET request
+for a particular URL once or multiple times.  This is because the
+HTTP protocol definition says that a GET request may be cached by the
+browser, or server, or an intervening proxy.  POST requests cannot be
+cached, because each request is independent and matters.  Typically,
+POST requests change or depend on state on the server (query or update
+a database, send mail, or purchase a computer).
 
 =head2 How do I check a valid mail address?
 
-You can't.
+You can't, at least, not in real time.  Bummer, eh?
 
-Without sending mail to the address and seeing whether it bounces (and
-even then you face the halting problem), you cannot determine whether
-an mail address is valid.  Even if you apply the mail header
-standard, you can have problems, because there are deliverable
-addresses that aren't RFC-822 (the mail header standard) compliant,
-and addresses that aren't deliverable which are compliant.
+Without sending mail to the address and seeing whether there's a human
+on the other hand to answer you, you cannot determine whether a mail
+address is valid.  Even if you apply the mail header standard, you
+can have problems, because there are deliverable addresses that aren't
+RFC-822 (the mail header standard) compliant, and addresses that aren't
+deliverable which are compliant.
 
-Many are tempted to try to eliminate many frequently-invalid mail
-addresses with a simple regexp, such as
-C</^[\w.-]+\@([\w.-]\.)+\w+$/>.  However, this also throws out many
-valid ones, and says nothing about potential deliverability, so is not
-suggested.  Instead, see
+Many are tempted to try to eliminate many frequently-invalid
+mail addresses with a simple regexp, such as
+C</^[\w.-]+\@([\w.-]\.)+\w+$/>.  It's a very bad idea.  However,
+this also throws out many valid ones, and says nothing about
+potential deliverability, so is not suggested.  Instead, see
 http://www.perl.com/CPAN/authors/Tom_Christiansen/scripts/ckaddr.gz ,
 which actually checks against the full RFC spec (except for nested
 comments), looks for addresses you may not wish to accept mail to
 (say, Bill Clinton or your postmaster), and then makes sure that the
-hostname given can be looked up in DNS.  It's not fast, but it works.
+hostname given can be looked up in the DNS MX records.  It's not fast,
+but it works for what it tries to do.
+
+Our best advice for verifying a person's mail address is to have them
+enter their address twice, just as you normally do to change a password.
+This usually weeds out typos.  If both versions match, send
+mail to that address with a personal message that looks somewhat like:
+
+    Dear someuser@host.com,
+
+    Please confirm the mail address you gave us Wed May  6 09:38:41
+    MDT 1998 by replying to this message.  Include the string
+    "Rumpelstiltskin" in that reply, but spelled in reverse; that is,
+    start with "Nik...".  Once this is done, your confirmed address will
+    be entered into our records.
+
+If you get the message back and they've followed your directions,
+you can be reasonably assured that it's real.
 
-Here's an alternative strategy used by many CGI script authors: Check
-the mail address with a simple regexp (such as the one above).  If
-the regexp matched the address, accept the address.  If the regexp
-didn't match the address, request confirmation from the user that the
-mail address they entered was correct.
+A related strategy that's less open to forgery is to give them a PIN
+(personal ID number).  Record the address and PIN (best that it be a
+random one) for later processing.  In the mail you send, ask them to
+include the PIN in their reply.  But if it bounces, or the message is
+included via a ``vacation'' script, it'll be there anyway.  So it's
+best to ask them to mail back a slight alteration of the PIN, such as
+with the characters reversed, one added or subtracted to each digit, etc.
 
 =head2 How do I decode a MIME/BASE64 string?
 
@@ -257,11 +400,49 @@ It makes a more intelligent guess than the code above, using information
 given when the module was installed, but it could still be incorrect.
 Again, the best way is often just to ask the user.
 
-=head2 How do I send/read mail?
+=head2 How do I send mail?
 
-Sending mail: the Mail::Mailer module from CPAN (part of the MailTools
-package) is UNIX-centric, while Mail::Internet uses Net::SMTP which is
-not UNIX-centric.  Reading mail: use the Mail::Folder module from CPAN
+Use the C<sendmail> program directly:
+
+    open(SENDMAIL, "|/usr/lib/sendmail -oi -t -odq")
+                        or die "Can't fork for sendmail: $!\n";
+    print SENDMAIL <<"EOF";
+    From: User Originating Mail <me\@host>
+    To: Final Destination <you\@otherhost>
+    Subject: A relevant subject line
+
+    Body of the message goes here, in as many lines as you like.
+    EOF
+    close(SENDMAIL)     or warn "sendmail didn't close nicely";
+
+The B<-oi> option prevents sendmail from interpreting a line consisting
+of a single dot as "end of message".  The B<-t> option says to use the
+headers to decide who to send the message to, and B<-odq> says to put
+the message into the queue.  This last option means your message won't
+be immediately delivered, so leave it out if you want immediate
+delivery.
+
+Or use the CPAN module Mail::Mailer:
+
+    use Mail::Mailer;
+
+    $mailer = Mail::Mailer->new();
+    $mailer->open({ From    => $from_address,
+                    To      => $to_address,
+                    Subject => $subject,
+                  })
+        or die "Can't open: $!\n";
+    print $mailer $body;
+    $mailer->close();
+
+The Mail::Internet module uses Net::SMTP which is less Unix-centric than
+Mail::Mailer, but less reliable.  Avoid raw SMTP commands.  There
+are many reasons to use a mail transport agent like sendmail.  These 
+include queueing, MX records, and security.
+
+=head2 How do I read mail?
+
+Use the Mail::Folder module from CPAN
 (part of the MailFolder package) or the Mail::Internet module from
 CPAN (also part of the MailTools package).
 
@@ -282,11 +463,39 @@ CPAN (also part of the MailTools package).
     # send it
     $mail->smtpsend or die;
 
+Often a module is overkill, though.  Here's a mail sorter.
+
+    #!/usr/bin/perl 
+    # bysub1 - simple sort by subject
+    my(@msgs, @sub);
+    my $msgno = -1;
+    $/ = '';                    # paragraph reads
+    while (<>) {
+        if (/^From/m) {
+            /^Subject:\s*(?:Re:\s*)*(.*)/mi;
+            $sub[++$msgno] = lc($1) || '';
+        }
+        $msgs[$msgno] .= $_;
+    } 
+    for my $i (sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msgs)) {
+        print $msgs[$i];
+    }
+
+Or more succinctly, 
+
+    #!/usr/bin/perl -n00
+    # bysub2 - awkish sort-by-subject
+    BEGIN { $msgno = -1 }
+    $sub[++$msgno] = (/^Subject:\s*(?:Re:\s*)*(.*)/mi)[0] if /^From/m;
+    $msg[$msgno] .= $_;
+    END { print @msg[ sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msg) ] }
+
 =head2 How do I find out my hostname/domainname/IP address?
 
-A lot of code has historically cavalierly called the C<`hostname`>
-program.  While sometimes expedient, this isn't very portable.  It's
-one of those tradeoffs of convenience versus portability.
+The normal way to find your own hostname is to call the C<`hostname`>
+program.  While sometimes expedient, this has some problems, such as
+not knowing whether you've got the canonical name or not.  It's one of
+those tradeoffs of convenience versus portability.
 
 The Sys::Hostname module (part of the standard perl distribution) will
 give you the hostname after which you can find out the IP address
index 03e2b9d..2cb03aa 100644 (file)
@@ -3872,9 +3872,9 @@ C<$?> like this:
     $signal_num  = $? & 127;
     $dumped_core = $? & 128;
 
-When the arguments get executed via the system shell, results will
-be subject to its quirks and capabilities.  See L<perlop/"`STRING`">
-and L</exec> for details.
+When the arguments get executed via the system shell, results
+and return codes will be subject to its quirks and capabilities.
+See L<perlop/"`STRING`"> and L</exec> for details.
 
 =item syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET
 
index 09b011e..2348d39 100644 (file)
@@ -506,6 +506,12 @@ and interact() functions.  Find the library (and we hope its
 successor F<IPC::Chat>) at your nearest CPAN archive as detailed
 in the SEE ALSO section below.
 
+The newer Expect.pm module from CPAN also addresses this kind of thing.
+This module requires two other modules from CPAN: IO::Pty and IO::Stty.
+It sets up a pseudo-terminal to interact with programs that insist on
+using talking to the terminal device driver.  If your system is 
+amongst those supported, this may be your best bet.
+
 =head2 Bidirectional Communication with Yourself
 
 If you want, you may make low-level pipe() and fork()
index b0790d7..fa41351 100644 (file)
@@ -117,10 +117,12 @@ distribution for more information).
 =item Win95/NT
 
 The Win95/NT installation, when using the Activeware port of Perl,
-will modify the Registry to associate the .pl extension with the perl
+will modify the Registry to associate the F<.pl> extension with the perl
 interpreter.  If you install another port of Perl, including the one
 in the Win32 directory of the Perl distribution, then you'll have to
-modify the Registry yourself.
+modify the Registry yourself.  Note that this means you can no 
+longer tell the difference between an executable Perl program
+and a Perl library file.
 
 =item Macintosh