Integrate with mainperl.
authorJarkko Hietaniemi <jhi@iki.fi>
Sun, 4 Jul 1999 22:39:23 +0000 (22:39 +0000)
committerJarkko Hietaniemi <jhi@iki.fi>
Sun, 4 Jul 1999 22:39:23 +0000 (22:39 +0000)
p4raw-id: //depot/cfgperl@3576

36 files changed:
Changes
MANIFEST
Porting/makerel
bytecode.pl
eg/cgi/file_upload.cgi
ext/ByteLoader/byterun.h
ext/Data/Dumper/Dumper.pm
ext/Data/Dumper/Dumper.xs
ext/DynaLoader/dl_aix.xs
ext/Thread/Thread/Specific.pm
lib/CGI.pm
lib/CGI/Carp.pm
lib/CGI/Cookie.pm
lib/CGI/Fast.pm
lib/Class/Struct.pm
lib/Dumpvalue.pm
lib/Text/ParseWords.pm
lib/dumpvar.pl
lib/fields.pm
lib/overload.pm
op.c
perl.c
pod/perldelta.pod
pod/perldiag.pod
pod/perlfunc.pod
pod/perltoc.pod
pod/perlxstut.pod
pp_ctl.c
t/io/openpid.t [new file with mode: 0755]
t/lib/cgi-form.t
t/lib/cgi-html.t
t/lib/cgi-request.t
t/pragma/warn/op
win32/perlhost.h [deleted file]
win32/win32.c
win32/win32.h

diff --git a/Changes b/Changes
index 6060b49..0c3c4ab 100644 (file)
--- a/Changes
+++ b/Changes
@@ -79,6 +79,126 @@ Version 5.005_58        Development release working toward 5.006
 ----------------
 
 ____________________________________________________________________________
+[  3565] By: gsar                                  on 1999/07/04  01:26:02
+        Log: newer version of perlxstut from Jeff Okamoto (slightly edited
+             for win32 issues)
+     Branch: perl
+           ! pod/perlxstut.pod
+____________________________________________________________________________
+[  3564] By: gsar                                  on 1999/07/02  03:09:04
+        Log: avoid warnings
+     Branch: perl
+           ! ext/Thread/Thread/Specific.pm lib/fields.pm
+____________________________________________________________________________
+[  3563] By: gsar                                  on 1999/06/28  19:23:47
+        Log: inc version (for CPAN.pm sanity)
+     Branch: perl
+           ! lib/Text/ParseWords.pm
+____________________________________________________________________________
+[  3562] By: gsar                                  on 1999/06/28  19:19:01
+        Log: regen perltoc
+     Branch: perl
+           ! pod/perltoc.pod
+____________________________________________________________________________
+[  3561] By: gsar                                  on 1999/06/28  19:08:41
+        Log: From: Damian Conway <damian@cs.monash.edu.au>
+             Date: Wed, 26 May 1999 00:58:35 -0400
+             Message-Id: <199905260458.AAA06411@defender.perl.org>
+             Subject: [19990526.002] Misc. improvements to Class:Struct
+     Branch: perl
+           ! MANIFEST lib/Class/Struct.pm
+____________________________________________________________________________
+[  3560] By: gsar                                  on 1999/06/28  18:50:52
+        Log: remove bogus PL_optype_size
+     Branch: perl
+           ! bytecode.pl ext/ByteLoader/byterun.h
+____________________________________________________________________________
+[  3559] By: gsar                                  on 1999/06/28  18:22:26
+        Log: upgrade CGI.pm to v2.53 (CGI/{Apache,Switch}.pm NOT deleted)
+     Branch: perl
+           + lib/CGI/Pretty.pm
+          ! eg/cgi/file_upload.cgi lib/CGI.pm lib/CGI/Carp.pm
+          ! lib/CGI/Cookie.pm lib/CGI/Fast.pm t/lib/cgi-form.t
+           ! t/lib/cgi-html.t t/lib/cgi-request.t
+____________________________________________________________________________
+[  3558] By: jhi                                   on 1999/06/28  07:30:21
+        Log: Change Olaf Lebbe's email address.
+     Branch: cfgperl
+           ! README.epoc
+____________________________________________________________________________
+[  3557] By: gsar                                  on 1999/06/28  00:07:33
+        Log: make autogenerated files writable
+     Branch: perl
+           - win32/perlhost.h
+          ! MANIFEST Porting/makerel embed.h embedvar.h ext/B/B/Asmdata.pm
+          ! ext/ByteLoader/byterun.c ext/ByteLoader/byterun.h global.sym
+          ! keywords.h lib/warning.pm objXSUB.h opcode.h pp.sym pp_proto.h
+          ! proto.h regnodes.h warning.h win32/config_H.bc
+           ! win32/config_H.gc win32/config_H.vc
+____________________________________________________________________________
+[  3556] By: jhi                                   on 1999/06/27  19:22:53
+        Log: Update MANIFEST to match #3555.
+     Branch: cfgperl
+           ! MANIFEST
+____________________________________________________________________________
+[  3555] By: jhi                                   on 1999/06/27  19:16:22
+        Log: EPOC port to Psion5.
+             From: Olaf Flebbe <O.Flebbe@science-computing.de>
+             To: Jarkko Hietaniemi <jhi@iki.fi>
+             Cc: perl5-porters@perl.org
+             Subject: Re: Psion5
+             Date: Sun, 27 Jun 1999 20:50:30 +0200 (METDST)
+             Message-ID: <Pine.GHP.4.02.9906272048130.17736-100000@io.science-computing.de>
+     Branch: cfgperl
+          + README.epoc epoc/config.h epoc/epoc.c epoc/epocish.h
+           + epoc/perl.mmp epoc/perl.pkg
+          ! MANIFEST doio.c lib/Term/ReadLine.pm lib/perl5db.pl perl.c
+           ! perl.h sv.c util.c
+____________________________________________________________________________
+[  3554] By: jhi                                   on 1999/06/27  18:50:52
+        Log: Integrate from mainperl.
+     Branch: cfgperl
+          !> (integrate 48 files)
+____________________________________________________________________________
+[  3553] By: gsar                                  on 1999/06/27  14:28:49
+        Log: somewhat untested PERL_OBJECT cleanups (C++isms mostly
+             gone from the public API); PERL_OBJECT builds again on
+             windows
+             
+             TODO: namespace-clean the typedefs in iperlsys.h and
+             elsewhere; remove C++ remnants from public headers
+     Branch: perl
+          ! XSUB.h bytecode.pl cv.h embed.h embed.pl ext/B/B.xs
+          ! ext/ByteLoader/ByteLoader.xs ext/ByteLoader/bytecode.h
+          ! ext/ByteLoader/byterun.c ext/ByteLoader/byterun.h
+          ! ext/DynaLoader/dlutils.c global.sym globals.c iperlsys.h
+          ! lib/ExtUtils/Embed.pm lib/ExtUtils/xsubpp mg.c objXSUB.h
+          ! opcode.h opcode.pl perl.c perl.h pod/perlhist.pod pp_ctl.c
+          ! pp_hot.c proto.h scope.h sv.h toke.c universal.c util.c
+          ! win32/GenCAPI.pl win32/Makefile win32/config.bc
+          ! win32/config.gc win32/config.vc win32/dl_win32.xs
+          ! win32/makedef.pl win32/makefile.mk win32/perllib.c
+          ! win32/runperl.c win32/win32.c win32/win32.h win32/win32iop.h
+           ! win32/win32sck.c
+____________________________________________________________________________
+[  3552] By: gsar                                  on 1999/06/27  13:49:31
+        Log: integrate cfgperl changes into mainline
+     Branch: perl
+         !> dump.c embed.h embed.pl embedvar.h global.sym intrpvar.h mg.c
+         !> objXSUB.h op.c perl.c perl.h perlvars.h pp.c pp_ctl.c
+         !> pp_proto.h pp_sys.c proto.h sv.c t/pragma/locale.t toke.c
+          !> util.c
+____________________________________________________________________________
+[  3551] By: gsar                                  on 1999/06/27  13:31:11
+        Log: fix indents
+     Branch: perl
+           ! op.c
+____________________________________________________________________________
+[  3550] By: gsar                                  on 1999/06/24  22:42:53
+        Log: update Changes
+     Branch: perl
+           ! Changes
+____________________________________________________________________________
 [  3549] By: gsar                                  on 1999/06/24  22:41:17
         Log: avoid race condition in the CAPI extension bootstrap handler
      Branch: perl
index 410edb5..11543e1 100644 (file)
--- a/MANIFEST
+++ b/MANIFEST
@@ -529,6 +529,7 @@ lib/CGI/Apache.pm   Support for Apache's Perl module
 lib/CGI/Carp.pm                Log server errors with helpful context
 lib/CGI/Cookie.pm      Interface to Netscape Cookies
 lib/CGI/Fast.pm                Support for FastCGI (persistent server process)
+lib/CGI/Pretty.pm      Output nicely formatted HTML
 lib/CGI/Push.pm                Support for server push
 lib/CGI/Switch.pm      Simple interface for multiple server types
 lib/CPAN.pm            Interface to Comprehensive Perl Archive Network
@@ -1082,6 +1083,7 @@ t/io/fs.t         See if directory manipulations work
 t/io/inplace.t         See if inplace editing works
 t/io/iprefix.t         See if inplace editing works with prefixes
 t/io/open.t            See if open works
+t/io/openpid.t         See if open works for subprocesses
 t/io/pipe.t            See if secure pipes work
 t/io/print.t           See if print commands work
 t/io/read.t            See if read works
@@ -1411,7 +1413,6 @@ win32/makefile.mk Win32 makefile for DMAKE (BC++, VC++ builds)
 win32/makemain.pl      Win32 port
 win32/makeperldef.pl   Win32 port
 win32/perlglob.c       Win32 port
-win32/perlhost.h       Perl host implementation
 win32/perllib.c                Win32 port
 win32/pod.mak          Win32 port
 win32/runperl.c                Win32 port
index 46f88fb..ea99c67 100644 (file)
@@ -106,6 +106,27 @@ my @exe = qw(
 );
 system("chmod +x @exe");
 
+my @writables = qw(
+    embed.h
+    embedvar.h
+    ext/B/B/Asmdata.pm
+    ext/ByteLoader/byterun.c
+    ext/ByteLoader/byterun.h
+    global.sym
+    keywords.h
+    lib/warning.pm
+    objXSUB.h
+    opcode.h
+    pp.sym
+    pp_proto.h
+    regnodes.h
+    warning.h
+    win32/config_H.bc
+    win32/config_h.gc
+    win32/config_H.vc
+);
+system("chmod +w @writables");
+
 print "Adding CRs to DOSish files...\n";
 my @crlf = qw(
     djgpp/configure.bat
index e12acbb..030d1ea 100644 (file)
@@ -232,20 +232,6 @@ for ($i = 0; $i < @optype - 1; $i++) {
     printf BYTERUN_H "    OPt_%s,\t\t/* %d */\n", $optype[$i], $i;
 }
 printf BYTERUN_H "    OPt_%s\t\t/* %d */\n};\n\n", $optype[$i], $i;
-print BYTERUN_H <<'EOT';
-EXT int PL_optype_size[]
-#ifdef DOINIT
-= {
-EOT
-for ($i = 0; $i < @optype - 1; $i++) {
-    printf BYTERUN_H "    sizeof(%s),\n", $optype[$i], $i;
-}
-printf BYTERUN_H "    sizeof(%s)\n}\n", $optype[$i], $i;
-print BYTERUN_H <<'EOT';
-#endif /* DOINIT */
-;
-
-EOT
 
 print BYTERUN_H <<'EOT';
 EXT void byterun(pTHXo_ struct bytestream bs);
index 38f8547..3037de7 100644 (file)
@@ -12,7 +12,7 @@ print strong("Version "),$CGI::VERSION,p;
 print h1("File Upload Example"),
     'This example demonstrates how to prompt the remote user to
     select a remote file for uploading. ',
-    strong("This feature only works with Netscape 2.0 browsers."),
+    strong("This feature only works with Netscape 2.0 or greater, or IE 4.0 or greater."),
     p,
     'Select the ',cite('browser'),' button to choose a text file
     to upload.  When you press the submit button, this script
index 3a0381f..6bc03af 100644 (file)
@@ -154,25 +154,6 @@ enum {
     OPt_COP            /* 11 */
 };
 
-EXT int PL_optype_size[]
-#ifdef DOINIT
-= {
-    sizeof(OP),
-    sizeof(UNOP),
-    sizeof(BINOP),
-    sizeof(LOGOP),
-    sizeof(CONDOP),
-    sizeof(LISTOP),
-    sizeof(PMOP),
-    sizeof(SVOP),
-    sizeof(GVOP),
-    sizeof(PVOP),
-    sizeof(LOOP),
-    sizeof(COP)
-}
-#endif /* DOINIT */
-;
-
 EXT void byterun(pTHXo_ struct bytestream bs);
 
 #define INIT_SPECIALSV_LIST STMT_START { \
index d653af3..3828d7b 100644 (file)
@@ -259,14 +259,22 @@ sub _dump {
       }
     }
 
+    if ($realpack) {
+      if ($realpack eq 'Regexp') {
+       $out = "$val";
+       $out =~ s,/,\\/,g;
+       return "qr/$out/";
+      }
+      else {          # we have a blessed ref
+       $out = $s->{'bless'} . '( ';
+       $blesspad = $s->{apad};
+       $s->{apad} .= '       ' if ($s->{indent} >= 2);
+      }
+    }
+
     $s->{level}++;
     $ipad = $s->{xpad} x $s->{level};
 
-    if ($realpack) {          # we have a blessed ref
-      $out = $s->{'bless'} . '( ';
-      $blesspad = $s->{apad};
-      $s->{apad} .= '       ' if ($s->{indent} >= 2);
-    }
     
     if ($realtype eq 'SCALAR') {
       if ($realpack) {
index e0ca403..27d128b 100644 (file)
@@ -251,22 +251,40 @@ DD_dump(pTHX_ SV *val, char *name, STRLEN namelen, SV *retval, HV *seenhv,
                SvREFCNT_dec(seenentry);
            }
        }
-       
-       (*levelp)++;
-       ipad = sv_x(aTHX_ Nullsv, SvPVX(xpad), SvCUR(xpad), *levelp);
 
-       if (realpack) {   /* we have a blessed ref */
-           STRLEN blesslen;
-           char *blessstr = SvPV(bless, blesslen);
-           sv_catpvn(retval, blessstr, blesslen);
-           sv_catpvn(retval, "( ", 2);
-           if (indent >= 2) {
-               blesspad = apad;
-               apad = newSVsv(apad);
-               sv_x(aTHX_ apad, " ", 1, blesslen+2);
+       if (realpack) {
+           if (*realpack == 'R' && strEQ(realpack, "Regexp")) {
+               STRLEN rlen;
+               char *rval = SvPV(val, rlen);
+               char *slash = strchr(rval, '/');
+               sv_catpvn(retval, "qr/", 3);
+               while (slash) {
+                   sv_catpvn(retval, rval, slash-rval);
+                   sv_catpvn(retval, "\\/", 2);
+                   rlen -= slash-rval+1;
+                   rval = slash+1;
+                   slash = strchr(rval, '/');
+               }
+               sv_catpvn(retval, rval, rlen);
+               sv_catpvn(retval, "/", 1);
+               return 1;
+           }
+           else {                              /* we have a blessed ref */
+               STRLEN blesslen;
+               char *blessstr = SvPV(bless, blesslen);
+               sv_catpvn(retval, blessstr, blesslen);
+               sv_catpvn(retval, "( ", 2);
+               if (indent >= 2) {
+                   blesspad = apad;
+                   apad = newSVsv(apad);
+                   sv_x(aTHX_ apad, " ", 1, blesslen+2);
+               }
            }
        }
 
+       (*levelp)++;
+       ipad = sv_x(aTHX_ Nullsv, SvPVX(xpad), SvCUR(xpad), *levelp);
+
        if (realtype <= SVt_PVBM) {                          /* scalar ref */
            SV *namesv = newSVpvn("${", 2);
            sv_catpvn(namesv, name, namelen);
index 2e7cd4a..69fb7a7 100644 (file)
@@ -77,19 +77,18 @@ typedef struct Module {
  * We keep a list of all loaded modules to be able to call the fini
  * handlers at atexit() time.
  */
-static ModulePtr modList;
+static ModulePtr modList;              /* XXX threadead */
 
 /*
  * The last error from one of the dl* routines is kept in static
  * variables here. Each error is returned only once to the caller.
  */
-static char errbuf[BUFSIZ];
-static int errvalid;
+static char errbuf[BUFSIZ];            /* XXX threadead */
+static int errvalid;                   /* XXX threadead */
 
 static void caterr(char *);
 static int readExports(ModulePtr);
 static void terminate(void);
-static void *findMain(void);
 
 static char *strerror_failed   = "(strerror failed)";
 static char *strerror_r_failed = "(strerror_r failed)";
@@ -155,16 +154,14 @@ char *strerrorcpy(char *str, int err) {
 void *dlopen(char *path, int mode)
 {
        register ModulePtr mp;
-       static void *mainModule;
+       static int inited;                      /* XXX threadead */
 
        /*
         * Upon the first call register a terminate handler that will
-        * close all libraries. Also get a reference to the main module
-        * for use with loadbind.
+        * close all libraries.
         */
-       if (!mainModule) {
-               if ((mainModule = findMain()) == NULL)
-                       return NULL;
+       if (!inited) {
+               inited++;
                atexit(terminate);
        }
        /*
@@ -222,7 +219,12 @@ void *dlopen(char *path, int mode)
        mp->refCnt = 1;
        mp->next = modList;
        modList = mp;
-       if (loadbind(0, mainModule, mp->entry) == -1) {
+       /*
+        * Assume anonymous exports come from the module this dlopen
+        * is linked into, that holds true as long as dlopen and all
+        * of the perl core are in the same shared object.
+        */
+       if (loadbind(0, (void *)dlopen, mp->entry) == -1) {
                dlclose(mp);
                errvalid++;
                strcpy(errbuf, "loadbind: ");
@@ -526,52 +528,6 @@ static int readExports(ModulePtr mp)
        return 0;
 }
 
-/*
- * Find the main modules entry point. This is used as export pointer
- * for loadbind() to be able to resolve references to the main part.
- */
-static void * findMain(void)
-{
-       struct ld_info *lp;
-       char *buf;
-       int size = 4*1024;
-       int i;
-       void *ret;
-
-       if ((buf = safemalloc(size)) == NULL) {
-               errvalid++;
-               strcpy(errbuf, "findMain: ");
-               strerrorcat(errbuf, errno);
-               return NULL;
-       }
-       while ((i = loadquery(L_GETINFO, buf, size)) == -1 && errno == ENOMEM) {
-               safefree(buf);
-               size += 4*1024;
-               if ((buf = safemalloc(size)) == NULL) {
-                       errvalid++;
-                       strcpy(errbuf, "findMain: ");
-                       strerrorcat(errbuf, errno);
-                       return NULL;
-               }
-       }
-       if (i == -1) {
-               errvalid++;
-               strcpy(errbuf, "findMain: ");
-               strerrorcat(errbuf, errno);
-               safefree(buf);
-               return NULL;
-       }
-       /*
-        * The first entry is the main module. The entry point
-        * returned by load() does actually point to the data
-        * segment origin.
-        */
-       lp = (struct ld_info *)buf;
-       ret = lp->ldinfo_dataorg;
-       safefree(buf);
-       return ret;
-}
-
 /* dl_dlopen.xs
  * 
  * Platform:   SunOS/Solaris, possibly others which use dlopen.
index 9c8a66a..46b9b60 100644 (file)
@@ -18,7 +18,7 @@ C<key_create> returns a unique thread-specific key.
 sub import {
     use attrs qw(locked method);
     require fields;
-    fields->import(@_);
+    fields::->import(@_);
 }      
 
 sub key_create {
index f5615f2..b131926 100644 (file)
@@ -17,8 +17,8 @@ require 5.004;
 # The most recent version and complete docs are available at:
 #   http://stein.cshl.org/WWW/software/CGI/
 
-$CGI::revision = '$Id: CGI.pm,v 1.5 1998/12/06 10:19:48 lstein Exp $';
-$CGI::VERSION='2.46';
+$CGI::revision = '$Id: CGI.pm,v 1.18 1999/06/09 14:52:45 lstein Exp $';
+$CGI::VERSION='2.53';
 
 # HARD-CODED LOCATION FOR FILE UPLOAD TEMPORARY FILES.
 # UNCOMMENT THIS ONLY IF YOU KNOW WHAT YOU'RE DOING.
@@ -58,6 +58,9 @@ sub initialize_globals {
     # Change this to 1 to disable uploads entirely:
     $DISABLE_UPLOADS = 0;
 
+    # Automatically determined -- don't change
+    $EBCDIC = 0;
+
     # Change this to 1 to suppress redundant HTTP headers
     $HEADERS_ONCE = 0;
 
@@ -89,9 +92,11 @@ unless ($OS) {
     }
 }
 if ($OS=~/Win/i) {
-    $OS = 'WINDOWS';
+  $OS = 'WINDOWS';
 } elsif ($OS=~/vms/i) {
-    $OS = 'VMS';
+  $OS = 'VMS';
+} elsif ($OS=~/dos/i) {
+  $OS = 'DOS';
 } elsif ($OS=~/^MacOS$/i) {
     $OS = 'MACINTOSH';
 } elsif ($OS=~/os2/i) {
@@ -101,7 +106,7 @@ if ($OS=~/Win/i) {
 }
 
 # Some OS logic.  Binary mode enabled on DOS, NT and VMS
-$needs_binmode = $OS=~/^(WINDOWS|VMS|OS2)/;
+$needs_binmode = $OS=~/^(WINDOWS|DOS|OS2|MSWin)/;
 
 # This is the default class for the CGI object to use when all else fails.
 $DefaultClass = 'CGI' unless defined $CGI::DefaultClass;
@@ -112,7 +117,7 @@ $AutoloadClass = $DefaultClass unless defined $CGI::AutoloadClass;
 # The path separator is a slash, backslash or semicolon, depending
 # on the paltform.
 $SL = {
-    UNIX=>'/', OS2=>'\\', WINDOWS=>'\\', MACINTOSH=>':', VMS=>'/'
+    UNIX=>'/', OS2=>'\\', WINDOWS=>'\\', DOS=>'\\', MACINTOSH=>':', VMS=>'/'
     }->{$OS};
 
 # This no longer seems to be necessary
@@ -123,7 +128,7 @@ $IIS++ if defined($ENV{'SERVER_SOFTWARE'}) && $ENV{'SERVER_SOFTWARE'}=~/IIS/;
 # Turn on special checking for Doug MacEachern's modperl
 if (exists $ENV{'GATEWAY_INTERFACE'} 
     && 
-    ($MOD_PERL = $ENV{'GATEWAY_INTERFACE'} =~ /^CGI-Perl/))
+    ($MOD_PERL = $ENV{'GATEWAY_INTERFACE'} =~ /^CGI-Perl\//))
 {
     $| = 1;
     require Apache;
@@ -139,11 +144,32 @@ $PERLEX++ if defined($ENV{'GATEWAY_INTERFACE'}) && $ENV{'GATEWAY_INTERFACE'} =~
 # really annoying.
 $EBCDIC = "\t" ne "\011";
 if ($OS eq 'VMS') {
-    $CRLF = "\n";
+  $CRLF = "\n";
 } elsif ($EBCDIC) {
-    $CRLF= "\r\n";
+  $CRLF= "\r\n";
 } else {
-    $CRLF = "\015\012";
+  $CRLF = "\015\012";
+}
+
+if ($EBCDIC) {
+@A2E = (
+  0,  1,  2,  3, 55, 45, 46, 47, 22,  5, 21, 11, 12, 13, 14, 15,
+ 16, 17, 18, 19, 60, 61, 50, 38, 24, 25, 63, 39, 28, 29, 30, 31,
+ 64, 90,127,123, 91,108, 80,125, 77, 93, 92, 78,107, 96, 75, 97,
+240,241,242,243,244,245,246,247,248,249,122, 94, 76,126,110,111,
+124,193,194,195,196,197,198,199,200,201,209,210,211,212,213,214,
+215,216,217,226,227,228,229,230,231,232,233,173,224,189, 95,109,
+121,129,130,131,132,133,134,135,136,137,145,146,147,148,149,150,
+151,152,153,162,163,164,165,166,167,168,169,192, 79,208,161,  7,
+ 32, 33, 34, 35, 36, 37,  6, 23, 40, 41, 42, 43, 44,  9, 10, 27,
+ 48, 49, 26, 51, 52, 53, 54,  8, 56, 57, 58, 59,  4, 20, 62,255,
+ 65,170, 74,177,159,178,106,181,187,180,154,138,176,202,175,188,
+144,143,234,250,190,160,182,179,157,218,155,139,183,184,185,171,
+100,101, 98,102, 99,103,158,104,116,113,114,115,120,117,118,119,
+172,105,237,238,235,239,236,191,128,253,254,251,252,186,174, 89,
+ 68, 69, 66, 70, 67, 71,156, 72, 84, 81, 82, 83, 88, 85, 86, 87,
+140, 73,205,206,203,207,204,225,112,221,222,219,220,141,142,223
+      );
 }
 
 if ($needs_binmode) {
@@ -164,15 +190,16 @@ if ($needs_binmode) {
                          submit reset defaults radio_group popup_menu button autoEscape
                          scrolling_list image_button start_form end_form startform endform
                          start_multipart_form end_multipart_form isindex tmpFileName uploadInfo URL_ENCODED MULTIPART/],
-               ':cgi'=>[qw/param path_info path_translated url self_url script_name cookie Dump
-                        raw_cookie request_method query_string Accept user_agent remote_host 
+               ':cgi'=>[qw/param upload path_info path_translated url self_url script_name cookie Dump
+                        raw_cookie request_method query_string Accept user_agent remote_host content_type
                         remote_addr referer server_name server_software server_port server_protocol
                         virtual_host remote_ident auth_type http use_named_parameters 
                         save_parameters restore_parameters param_fetch
-                        remote_user user_name header redirect import_names put Delete Delete_all url_param/],
+                        remote_user user_name header redirect import_names put 
+                        Delete Delete_all url_param cgi_error/],
                ':ssl' => [qw/https/],
                ':imagemap' => [qw/Area Map/],
-               ':cgi-lib' => [qw/ReadParse PrintHeader HtmlTop HtmlBot SplitParam/],
+               ':cgi-lib' => [qw/ReadParse PrintHeader HtmlTop HtmlBot SplitParam Vars/],
                ':html' => [qw/:html2 :html3 :netscape/],
                ':standard' => [qw/:html2 :html3 :form :cgi/],
                ':push' => [qw/multipart_init multipart_start multipart_end/],
@@ -337,12 +364,17 @@ sub init {
 
     $meth=$ENV{'REQUEST_METHOD'} if defined($ENV{'REQUEST_METHOD'});
     $content_length = defined($ENV{'CONTENT_LENGTH'}) ? $ENV{'CONTENT_LENGTH'} : 0;
-    die "Client attempted to POST $content_length bytes, but POSTs are limited to $POST_MAX"
-       if ($POST_MAX > 0) && ($content_length > $POST_MAX);
+
     $fh = to_filehandle($initializer) if $initializer;
 
   METHOD: {
 
+      # avoid unreasonably large postings
+      if (($POST_MAX > 0) && ($content_length > $POST_MAX)) {
+         $self->cgi_error("413 Request entity too large");
+         last METHOD;
+      }
+
       # Process multipart postings, but only if the initializer is
       # not defined.
       if ($meth eq 'POST'
@@ -394,7 +426,11 @@ sub init {
       # If method is GET or HEAD, fetch the query from
       # the environment.
       if ($meth=~/^(GET|HEAD)$/) {
-         $query_string = $ENV{'QUERY_STRING'} if defined $ENV{'QUERY_STRING'};
+         if ($MOD_PERL) {
+             $query_string = Apache->request->args;
+         } else {
+             $query_string = $ENV{'QUERY_STRING'} if defined $ENV{'QUERY_STRING'};
+         }
          last METHOD;
       }
 
@@ -473,14 +509,25 @@ sub print {
     CORE::print(@_);
 }
 
+# get/set last cgi_error
+sub cgi_error {
+    my ($self,$err) = self_or_default(@_);
+    $self->{'.cgi_error'} = $err if defined $err;
+    return $self->{'.cgi_error'};
+}
+
 # unescape URL-encoded data
 sub unescape {
-    shift() if ref($_[0]);
-    my $todecode = shift;
-    return undef unless defined($todecode);
-    $todecode =~ tr/+/ /;       # pluses become spaces
-    $todecode =~ s/%([0-9a-fA-F]{2})/pack("c",hex($1))/ge;
-    return $todecode;
+  shift() if ref($_[0]) || $_[0] eq $DefaultClass;
+  my $todecode = shift;
+  return undef unless defined($todecode);
+  $todecode =~ tr/+/ /;       # pluses become spaces
+    if ($EBCDIC) {
+      $todecode =~ s/%([0-9a-fA-F]{2})/pack("c",$A2E[hex($1)])/ge;
+    } else {
+      $todecode =~ s/%([0-9a-fA-F]{2})/pack("c",hex($1))/ge;
+    }
+  return $todecode;
 }
 
 # URL-encode data
@@ -488,7 +535,8 @@ sub escape {
     shift() if ref($_[0]) || $_[0] eq $DefaultClass;
     my $toencode = shift;
     return undef unless defined($toencode);
-    $toencode=~s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
+    $toencode=~s/ /+/g;
+    $toencode=~s/([^a-zA-Z0-9_.+-])/uc sprintf("%%%02x",ord($1))/eg;
     return $toencode;
 }
 
@@ -536,10 +584,10 @@ sub binmode {
 
 sub _make_tag_func {
     my ($self,$tagname) = @_;
-    my $func = qq#
+    my $func = qq(
        sub $tagname { 
            shift if \$_[0] && 
-               (!ref(\$_[0]) && \$_[0] eq \$CGI::DefaultClass) ||
+#              (!ref(\$_[0]) && \$_[0] eq \$CGI::DefaultClass) ||
                    (ref(\$_[0]) &&
                     (substr(ref(\$_[0]),0,3) eq 'CGI' ||
                    UNIVERSAL::isa(\$_[0],'CGI')));
@@ -549,7 +597,7 @@ sub _make_tag_func {
                my(\@attr) = make_attributes( '',shift() );
                \$attr = " \@attr" if \@attr;
            }
-       #;
+       );
     if ($tagname=~/start_(\w+)/i) {
        $func .= qq! return "<\U$1\E\$attr>";} !;
     } elsif ($tagname=~/end_(\w+)/i) {
@@ -650,7 +698,7 @@ sub _compile {
           die $@;
        }
     }       
-    delete($sub->{$func_name});  #free storage
+    CORE::delete($sub->{$func_name});  #free storage
     return "$pack\:\:$func_name";
 }
 
@@ -746,8 +794,8 @@ END_OF_FUNC
 ####
 sub delete {
     my($self,$name) = self_or_default(@_);
-    delete $self->{$name};
-    delete $self->{'.fieldnames'}->{$name};
+    CORE::delete $self->{$name};
+    CORE::delete $self->{'.fieldnames'}->{$name};
     @{$self->{'.parameters'}}=grep($_ ne $name,$self->param());
     return wantarray ? () : undef;
 }
@@ -762,7 +810,7 @@ sub import_names {
     my($self,$namespace,$delete) = self_or_default(@_);
     $namespace = 'Q' unless defined($namespace);
     die "Can't import names into \"main\"\n" if \%{"${namespace}::"} == \%::;
-    if ($delete || $MOD_PERL) {
+    if ($delete || $MOD_PERL || exists $ENV{'FCGI_ROLE'}) {
        # can anyone find an easier way to do this?
        foreach (keys %{"${namespace}::"}) {
            local *symbol = "${namespace}::${_}";
@@ -801,6 +849,17 @@ END_OF_FUNC
 
 # These are some tie() interfaces for compatibility
 # with Steve Brenner's cgi-lib.pl routines
+'Vars' => <<'END_OF_FUNC',
+sub Vars {
+    my %in;
+    tie(%in,CGI);
+    return %in if wantarray;
+    return \%in;
+}
+END_OF_FUNC
+
+# These are some tie() interfaces for compatibility
+# with Steve Brenner's cgi-lib.pl routines
 'ReadParse' => <<'END_OF_FUNC',
 sub ReadParse {
     local(*in);
@@ -1031,6 +1090,7 @@ sub dump {
        push(@result,"<UL>");
        foreach $value ($self->param($param)) {
            $value = $self->escapeHTML($value);
+            $value =~ s/\n/<BR>\n/g;
            push(@result,"<LI>$value");
        }
        push(@result,"</UL>");
@@ -1065,7 +1125,7 @@ sub save {
        my($escaped_param) = escape($param);
        my($value);
        foreach $value ($self->param($param)) {
-           print $filehandle "$escaped_param=",escape($value),"\n";
+           print $filehandle "$escaped_param=",escape("$value"),"\n";
        }
     }
     print $filehandle "=\n";    # end of record
@@ -1327,7 +1387,7 @@ sub _style {
                             '-foo'=>'bar',     # a trick to allow the '-' to be omitted
                             ref($style) eq 'ARRAY' ? @$style : %$style);
        $type = $stype if $stype;
-       push(@result,qq/<LINK REL="stylesheet" HREF="$src">/) if $src;
+       push(@result,qq/<LINK REL="stylesheet" TYPE="$type" HREF="$src">/) if $src;
        push(@result,style({'type'=>$type},"<!--\n$code\n-->")) if $code;
     } else {
        push(@result,style({'type'=>$type},"<!--\n$style\n-->"));
@@ -1348,7 +1408,7 @@ sub _script {
            ($src,$code,$language) =
                $self->rearrange([SRC,CODE,LANGUAGE],
                                 '-foo'=>'bar', # a trick to allow the '-' to be omitted
-                                ref($style) eq 'ARRAY' ? @$script : %$script);
+                                ref($script) eq 'ARRAY' ? @$script : %$script);
            
        } else {
            ($src,$code,$language) = ('',$script,'JavaScript');
@@ -1360,7 +1420,7 @@ sub _script {
            if $code && $language=~/javascript/i;
        $code = "<!-- Hide script\n$code\n\# End script hiding -->"
            if $code && $language=~/perl/i;
-       push(@result,script({@satts},$code));
+       push(@result,script({@satts},$code || ''));
     }
     @result;
 }
@@ -1727,9 +1787,7 @@ sub checkbox {
     $the_label = $self->escapeHTML($the_label);
     my($other) = @other ? " @other" : '';
     $self->register_parameter($name);
-    return <<END;
-<INPUT TYPE="checkbox" NAME="$name" VALUE="$value"$checked$other>$the_label
-END
+    return qq{<INPUT TYPE="checkbox" NAME="$name" VALUE="$value"$checked$other>$the_label};
 }
 END_OF_FUNC
 
@@ -1800,8 +1858,7 @@ END_OF_FUNC
 # Escape HTML -- used internally
 'escapeHTML' => <<'END_OF_FUNC',
 sub escapeHTML {
-    my($self,$toencode) = @_;
-    $toencode = $self unless ref($self);
+    my ($self,$toencode) = self_or_default(@_);
     return undef unless defined($toencode);
     return $toencode if ref($self) && $self->{'dontescape'};
 
@@ -2135,6 +2192,19 @@ sub url {
     my $url;
     $full++ if !($relative || $absolute);
 
+    my $path = $self->path_info;
+    my $script_name;
+    if (exists($ENV{REQUEST_URI})) {
+        my $index;
+       $script_name = $ENV{REQUEST_URI};
+        # strip query string
+        substr($script_name,$index) = '' if ($index = index($script_name,'?')) >= 0;
+        # and path
+        substr($script_name,$index) = '' if $path and ($index = rindex($script_name,$path)) >= 0;
+    } else {
+       $script_name = $self->script_name;
+    }
+
     if ($full) {
        my $protocol = $self->protocol();
        $url = "$protocol://";
@@ -2148,13 +2218,13 @@ sub url {
                unless (lc($protocol) eq 'http' && $port == 80)
                    || (lc($protocol) eq 'https' && $port == 443);
        }
-       $url .= $self->script_name;
+       $url .= $script_name;
     } elsif ($relative) {
-       ($url) = $self->script_name =~ m!([^/]+)$!;
+       ($url) = $script_name =~ m!([^/]+)$!;
     } elsif ($absolute) {
-       $url = $self->script_name;
+       $url = $script_name;
     }
-    $url .= $self->path_info if $path_info and $self->path_info;
+    $url .= $path if $path_info and defined $path;
     $url .= "?" . $self->query_string if $query and $self->query_string;
     return $url;
 }
@@ -2236,6 +2306,8 @@ sub expire_calc {
     my($offset);
     if (!$time || (lc($time) eq 'now')) {
         $offset = 0;
+    } elsif ($time=~/^\d+/) {
+        return $time;
     } elsif ($time=~/^([+-]?(?:\d+|\d*\.\d*))([mhdMy]?)/) {
         $offset = ($mult{$2} || 1)*$1;
     } else {
@@ -2247,7 +2319,7 @@ END_OF_FUNC
 
 # This internal routine creates date strings suitable for use in
 # cookies and HTTP headers.  (They differ, unfortunately.)
-# Thanks to Fisher Mark for this.
+# Thanks to Mark Fisher for this.
 'expires' => <<'END_OF_FUNC',
 sub expires {
     my($time,$format) = @_;
@@ -2330,6 +2402,15 @@ sub request_method {
 }
 END_OF_FUNC
 
+#### Method: content_type
+# Returns the content_type string
+####
+'content_type' => <<'END_OF_FUNC',
+sub content_type {
+    return $ENV{'CONTENT_TYPE'};
+}
+END_OF_FUNC
+
 #### Method: path_translated
 # Return the physical path information provided
 # by the URL (if any)
@@ -2353,6 +2434,7 @@ sub query_string {
        my($eparam) = escape($param);
        foreach $value ($self->param($param)) {
            $value = escape($value);
+            next unless defined $value;
            push(@pairs,"$eparam=$value");
        }
     }
@@ -2556,6 +2638,7 @@ END_OF_FUNC
 sub http {
     my ($self,$parameter) = self_or_CGI(@_);
     return $ENV{$parameter} if $parameter=~/^HTTP/;
+    $parameter =~ tr/-/_/;
     return $ENV{"HTTP_\U$parameter\E"} if $parameter;
     my(@p);
     foreach (keys %ENV) {
@@ -2574,6 +2657,7 @@ sub https {
     my ($self,$parameter) = self_or_CGI(@_);
     return $ENV{HTTPS} unless $parameter;
     return $ENV{$parameter} if $parameter=~/^HTTPS/;
+    $parameter =~ tr/-/_/;
     return $ENV{"HTTPS_\U$parameter\E"} if $parameter;
     my(@p);
     foreach (keys %ENV) {
@@ -2754,7 +2838,11 @@ sub read_multipart {
     my $filenumber = 0;
     while (!$buffer->eof) {
        %header = $buffer->readHeader;
-       die "Malformed multipart POST\n" unless %header;
+
+       unless (%header) {
+           $self->cgi_error("400 Bad request (malformed multipart POST)");
+           return;
+       }
 
        my($param)= $header{'Content-Disposition'}=~/ name="?([^\";]*)"?/;
 
@@ -2784,13 +2872,16 @@ sub read_multipart {
              last UPLOADS;
          }
 
-         $tmpfile = new TempFile;
-         $tmp = $tmpfile->as_string;
-         
-         $filehandle = Fh->new($filename,$tmp,$PRIVATE_TEMPFILES);
-
+         # choose a relatively unpredictable tmpfile sequence number
+          my $seqno = unpack("%16C*",join('',localtime,values %ENV));
+          for (my $cnt=10;$cnt>0;$cnt--) {
+           next unless $tmpfile = new TempFile($seqno);
+           $tmp = $tmpfile->as_string;
+           last if $filehandle = Fh->new($filename,$tmp,$PRIVATE_TEMPFILES);
+            $seqno += int rand(100);
+          }
+          die "CGI open of tmpfile: $!\n" unless $filehandle;
          $CGI::DefaultClass->binmode($filehandle) if $CGI::needs_binmode;
-         chmod 0600,$tmp;    # only the owner can tamper with it
 
          my ($data);
          local($\) = '';
@@ -2814,6 +2905,16 @@ sub read_multipart {
 }
 END_OF_FUNC
 
+'upload' =><<'END_OF_FUNC',
+sub upload {
+    my($self,$param_name) = self_or_default(@_);
+    my $param = $self->param($param_name);
+    return unless $param;
+    return unless ref($param) && fileno($param);
+    return $param;
+}
+END_OF_FUNC
+
 'tmpFileName' => <<'END_OF_FUNC',
 sub tmpFileName {
     my($self,$filename) = self_or_default(@_);
@@ -2906,10 +3007,9 @@ sub new {
     require Fcntl unless defined &Fcntl::O_RDWR;
     ++$FH;
     my $ref = \*{'Fh::' . quotemeta($name)}; 
-    sysopen($ref,$file,Fcntl::O_RDWR()|Fcntl::O_CREAT()|Fcntl::O_EXCL()) 
-       || die "CGI open of $file: $!\n";
+    sysopen($ref,$file,Fcntl::O_RDWR()|Fcntl::O_CREAT()|Fcntl::O_EXCL(),0600) || return;
     unlink($file) if $delete;
-    delete $Fh::{$FH};
+    CORE::delete $Fh::{$FH};
     return bless $ref,$pack;
 }
 END_OF_FUNC
@@ -2976,7 +3076,7 @@ sub new {
 
        # BUG: IE 3.01 on the Macintosh uses just the boundary -- not
        # the two extra hyphens.  We do a special case here on the user-agent!!!!
-       $boundary = "--$boundary" unless CGI::user_agent('MSIE 3\.0[12];  ?Mac');
+       $boundary = "--$boundary" unless CGI::user_agent('MSIE\s+3\.0[12];\s*Mac');
 
     } else { # otherwise we find it ourselves
        my($old);
@@ -3175,15 +3275,25 @@ $MAC = $CGI::OS eq 'MACINTOSH';
 my ($vol) = $MAC ? MacPerl::Volumes() =~ /:(.*)/ : "";
 unless ($TMPDIRECTORY) {
     @TEMP=("${SL}usr${SL}tmp","${SL}var${SL}tmp",
-          "C:${SL}temp","${SL}tmp","${SL}temp","${vol}${SL}Temporary Items",
+          "C:${SL}temp","${SL}tmp","${SL}temp",
+          "${vol}${SL}Temporary Items",
           "${SL}WWW_ROOT");
+    unshift(@TEMP,$ENV{'TMPDIR'}) if exists $ENV{'TMPDIR'};
+
+    #
+    #    unshift(@TEMP,(getpwuid($<))[7].'/tmp') if $CGI::OS eq 'UNIX';
+    # Rob: getpwuid() is unfortunately UNIX specific. On brain dead OS'es this
+    #    : can generate a 'getpwuid() not implemented' exception, even though
+    #    : it's never called.  Found under DOS/Win with the DJGPP perl port.
+    #    : Refer to getpwuid() only at run-time if we're fortunate and have  UNIX.
+    unshift(@TEMP,(eval {(getpwuid($<))[7]}).'/tmp') if $CGI::OS eq 'UNIX';
+
     foreach (@TEMP) {
        do {$TMPDIRECTORY = $_; last} if -d $_ && -w _;
     }
 }
 
 $TMPDIRECTORY  = $MAC ? "" : "." unless $TMPDIRECTORY;
-$SEQUENCE=0;
 $MAXTRIES = 5000;
 
 # cute feature, but overload implementation broke it
@@ -3199,14 +3309,15 @@ $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
 
 'new' => <<'END_OF_FUNC',
 sub new {
-    my($package) = @_;
-    my $directory;
-    my $i;
-    for ($i = 0; $i < $MAXTRIES; $i++) {
-       $directory = sprintf("${TMPDIRECTORY}${SL}CGItemp%d%04d",${$},++$SEQUENCE);
-       last if ! -f $directory;
+    my($package,$sequence) = @_;
+    my $filename;
+    for (my $i = 0; $i < $MAXTRIES; $i++) {
+       last if ! -f ($filename = sprintf("${TMPDIRECTORY}${SL}CGItemp%d",$sequence++));
     }
-    return bless \$directory;
+    # untaint the darn thing
+    return unless $filename =~ m!^([a-zA-Z0-9_ '":/\\]+)$!;
+    $filename = $1;
+    return bless \$filename;
 }
 END_OF_FUNC
 
@@ -3240,7 +3351,6 @@ if ($^W) {
     $MultipartBuffer::CRLF;
     $MultipartBuffer::TIMEOUT;
     $MultipartBuffer::INITIAL_FILLUNIT;
-    $TempFile::SEQUENCE;
 EOF
     ;
 }
@@ -3322,7 +3432,7 @@ script and restore it later.
 For example, using the object oriented style, here is how you create
 a simple "Hello World" HTML page:
 
-   #!/usr/local/bin/perl
+   #!/usr/local/bin/perl -w
    use CGI;                             # load CGI routines
    $q = new CGI;                        # create new CGI object
    print $q->header,                    # create the HTTP header
@@ -3640,6 +3750,36 @@ can manipulate in any way you like.
 
 You can also use a named argument style using the B<-name> argument.
 
+=head2 FETCHING THE PARAMETER LIST AS A HASH:
+
+    $params = $q->Vars;
+    print $params->{'address'};
+    @foo = split("\0",$params->{'foo'});
+    %params = $q->Vars;
+
+    use CGI ':cgi-lib';
+    $params = Vars;
+
+Many people want to fetch the entire parameter list as a hash in which
+the keys are the names of the CGI parameters, and the values are the
+parameters' values.  The Vars() method does this.  Called in a scalar
+context, it returns the parameter list as a tied hash reference.
+Changing a key changes the value of the parameter in the underlying
+CGI parameter list.  Called in an array context, it returns the
+parameter list as an ordinary hash.  This allows you to read the
+contents of the parameter list, but not to change it.
+
+When using this, the thing you must watch out for are multivalued CGI
+parameters.  Because a hash cannot distinguish between scalar and
+array context, multivalued parameters will be returned as a packed
+string, separated by the "\0" (null) character.  You must split this
+packed string in order to get at the individual values.  This is the
+convention introduced long ago by Steve Brenner in his cgi-lib.pl
+module for Perl version 4.
+
+If you wish to use Vars() as a function, import the I<:cgi-lib> set of
+function calls (also see the section on CGI-LIB compatibility).
+
 =head2 SAVING THE STATE OF THE SCRIPT TO A FILE:
 
     $query->save(FILEHANDLE)
@@ -3687,13 +3827,36 @@ The file format used for save/restore is identical to that used by the
 Whitehead Genome Center's data exchange format "Boulderio", and can be
 manipulated and even databased using Boulderio utilities.  See
        
-  http://www.genome.wi.mit.edu/genome_software/other/boulder.html
+  http://stein.cshl.org/boulder/
 
 for further details.
 
 If you wish to use this method from the function-oriented (non-OO)
 interface, the exported name for this method is B<save_parameters()>.
 
+=head2 RETRIEVING CGI ERRORS
+
+Errors can occur while processing user input, particularly when
+processing uploaded files.  When these errors occur, CGI will stop
+processing and return an empty parameter list.  You can test for
+the existence and nature of errors using the I<cgi_error()> function.
+The error messages are formatted as HTTP status codes. You can either
+incorporate the error text into an HTML page, or use it as the value
+of the HTTP status:
+
+    my $error = $q->cgi_error;
+    if ($error) {
+       print $q->header(-status=>$error),
+             $q->start_html('Problems'),
+              $q->h2('Request not processed'),
+             $q->strong($error);
+        exit 0;
+    }
+
+When using the function-oriented interface (see the next section),
+errors may only occur the first time you call I<param()>. Be ready
+for this!
+
 =head2 USING THE FUNCTION-ORIENTED INTERFACE
 
 To use the function-oriented interface, you must specify which CGI.pm
@@ -3754,7 +3917,7 @@ Import "standard" features, 'html2', 'html3', 'form' and 'cgi'.
 =item B<:all>
 
 Import all the available methods.  For the full list, see the CGI.pm
-code, where the variable %TAGS is defined.
+code, where the variable %EXPORT_TAGS is defined.
 
 =back
 
@@ -3907,15 +4070,35 @@ See the section on debugging for more details.
 
 =item -private_tempfiles
 
-CGI.pm can process uploaded file. Ordinarily it spools the
-uploaded file to a temporary directory, then deletes the file
-when done.  However, this opens the risk of eavesdropping as
-described in the file upload section.
-Another CGI script author could peek at this data during the
-upload, even if it is confidential information. On Unix systems,
-the -private_tempfiles pragma will cause the temporary file to be unlinked as soon
-as it is opened and before any data is written into it,
-eliminating the risk of eavesdropping.
+CGI.pm can process uploaded file. Ordinarily it spools the uploaded
+file to a temporary directory, then deletes the file when done.
+However, this opens the risk of eavesdropping as described in the file
+upload section.  Another CGI script author could peek at this data
+during the upload, even if it is confidential information. On Unix
+systems, the -private_tempfiles pragma will cause the temporary file
+to be unlinked as soon as it is opened and before any data is written
+into it, reducing, but not eliminating the risk of eavesdropping
+(there is still a potential race condition).  To make life harder for
+the attacker, the program chooses tempfile names by calculating a 32
+bit checksum of the incoming HTTP headers.
+
+To ensure that the temporary file cannot be read by other CGI scripts,
+use suEXEC or a CGI wrapper program to run your script.  The temporary
+file is created with mode 0600 (neither world nor group readable).
+
+The temporary directory is selected using the following algorithm:
+
+    1. if the current user (e.g. "nobody") has a directory named
+    "tmp" in its home directory, use that (Unix systems only).
+
+    2. if the environment variable TMPDIR exists, use the location
+    indicated.
+
+    3. Otherwise try the locations /usr/tmp, /var/tmp, C:\temp,
+    /tmp, /temp, ::Temporary Items, and \WWW_ROOT.
+
+Each of these locations is checked that it is a directory and is
+writable.  If not, the algorithm tries the next choice.
 
 =back
 
@@ -4135,17 +4318,17 @@ You can place other arbitrary HTML elements to the <HEAD> section with the
 B<-head> tag.  For example, to place the rarely-used <LINK> element in the
 head section, use this:
 
-    print $q->start_html(-head=>Link({-rel=>'next',
-                                 -href=>'http://www.capricorn.com/s2.html'}));
+    print start_html(-head=>Link({-rel=>'next',
+                    -href=>'http://www.capricorn.com/s2.html'}));
 
 To incorporate multiple HTML elements into the <HEAD> section, just pass an
 array reference:
 
-    print $q->start_html(-head=>[ 
-                              Link({-rel=>'next',
-                                   -href=>'http://www.capricorn.com/s2.html'}),
-                             Link({-rel=>'previous',
-                                   -href=>'http://www.capricorn.com/s1.html'})
+    print start_html(-head=>[ 
+                             Link({-rel=>'next',
+                                  -href=>'http://www.capricorn.com/s2.html'}),
+                            Link({-rel=>'previous',
+                                  -href=>'http://www.capricorn.com/s1.html'})
                             ]
                     );
 
@@ -4205,8 +4388,8 @@ one or more of -language, -src, or -code:
                         );
 
     print $q->(-title=>'The Riddle of the Sphinx',
-              -script=>{-language=>'PERLSCRIPT'},
-                        -code=>'print "hello world!\n;"'
+              -script=>{-language=>'PERLSCRIPT',
+                        -code=>'print "hello world!\n;"'}
               );
 
 
@@ -4215,19 +4398,19 @@ header.  Just pass the list of script sections as an array reference.
 this allows you to specify different source files for different dialects
 of JavaScript.  Example:     
 
-     print $q-&gt;start_html(-title=&gt;'The Riddle of the Sphinx',
-                          -script=&gt;[
-                                    { -language =&gt; 'JavaScript1.0',
-                                      -src      =&gt; '/javascript/utilities10.js'
+     print $q->start_html(-title=>'The Riddle of the Sphinx',
+                          -script=>[
+                                    { -language => 'JavaScript1.0',
+                                      -src      => '/javascript/utilities10.js'
                                     },
-                                    { -language =&gt; 'JavaScript1.1',
-                                      -src      =&gt; '/javascript/utilities11.js'
+                                    { -language => 'JavaScript1.1',
+                                      -src      => '/javascript/utilities11.js'
                                     },
-                                    { -language =&gt; 'JavaScript1.2',
-                                      -src      =&gt; '/javascript/utilities12.js'
+                                    { -language => 'JavaScript1.2',
+                                      -src      => '/javascript/utilities12.js'
                                     },
-                                    { -language =&gt; 'JavaScript28.2',
-                                      -src      =&gt; '/javascript/utilities219.js'
+                                    { -language => 'JavaScript28.2',
+                                      -src      => '/javascript/utilities219.js'
                                     }
                                  ]
                              );
@@ -4382,7 +4565,7 @@ This example shows how to use the HTML methods:
    print $q->blockquote(
                     "Many years ago on the island of",
                     $q->a({href=>"http://crete.org/"},"Crete"),
-                    "there lived a minotaur named",
+                    "there lived a Minotaur named",
                     $q->strong("Fred."),
                    ),
        $q->hr;
@@ -4820,23 +5003,16 @@ field will accept (-maxlength).
 =back
 
 When the form is processed, you can retrieve the entered filename
-by calling param().
+by calling param():
 
        $filename = $query->param('uploaded_file');
 
-In Netscape Navigator 2.0, the filename that gets returned is the full
-local filename on the B<remote user's> machine.  If the remote user is
-on a Unix machine, the filename will follow Unix conventions:
-
-       /path/to/the/file
-
-On an MS-DOS/Windows and OS/2 machines, the filename will follow DOS conventions:
-
-       C:\PATH\TO\THE\FILE.MSW
-
-On a Macintosh machine, the filename will follow Mac conventions:
-
-       HD 40:Desktop Folder:Sort Through:Reminders
+Different browsers will return slightly different things for the
+name.  Some browsers return the filename only.  Others return the full
+path to the file, using the path conventions of the user's machine.
+Regardless, the name returned is always the name of the file on the
+I<user's> machine, and is unrelated to the name of the temporary file
+that CGI.pm creates during upload spooling (see below).
 
 The filename returned is also a file handle.  You can read the contents
 of the file using standard Perl file reading calls:
@@ -4852,6 +5028,25 @@ of the file using standard Perl file reading calls:
           print OUTFILE $buffer;
        }
 
+However, there are problems with the dual nature of the upload fields.
+If you C<use strict>, then Perl will complain when you try to use a
+string as a filehandle.  You can get around this by placing the file
+reading code in a block containing the C<no strict> pragma.  More
+seriously, it is possible for the remote user to type garbage into the
+upload field, in which case what you get from param() is not a
+filehandle at all, but a string.
+
+To be safe, use the I<upload()> function (new in version 2.47).  When
+called with the name of an upload field, I<upload()> returns a
+filehandle, or undef if the parameter is not a valid filehandle.
+
+     $fh = $query->upload('uploaded_file');
+     while (<$fh>) {
+          print;
+     }
+
+This is the recommended idiom.
+
 When a file is uploaded the browser usually sends along some
 information along with it in the format of headers.  The information
 usually includes the MIME content type.  Future browsers may send
@@ -4867,7 +5062,25 @@ an associative array containing all the document headers.
 
 If you are using a machine that recognizes "text" and "binary" data
 modes, be sure to understand when and how to use them (see the Camel book).  
-Otherwise you may find that binary files are corrupted during file uploads.
+Otherwise you may find that binary files are corrupted during file
+uploads.
+
+There are occasionally problems involving parsing the uploaded file.
+This usually happens when the user presses "Stop" before the upload is
+finished.  In this case, CGI.pm will return undef for the name of the
+uploaded file and set I<cgi_error()> to the string "400 Bad request
+(malformed multipart POST)".  This error message is designed so that
+you can incorporate it into a status code to be sent to the browser.
+Example:
+
+   $file = $query->upload('uploaded_file');
+   if (!$file && $query->cgi_error) {
+      print $query->header(-status->$query->cgi_error);
+      exit 0;
+   }
+
+You are free to create a custom HTML page to complain about the error,
+if you wish.
 
 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur>,
 B<-onMouseOver>, B<-onMouseOut> and B<-onSelect> parameters are
@@ -5838,6 +6051,32 @@ Newer browsers do not report the user name for privacy reasons!
 Returns the method used to access your script, usually
 one of 'POST', 'GET' or 'HEAD'.
 
+=item B<content_type()>
+
+Returns the content_type of data submitted in a POST, generally 
+multipart/form-data or application/x-www-form-urlencoded
+
+=item B<http()>
+
+Called with no arguments returns the list of HTTP environment
+variables, including such things as HTTP_USER_AGENT,
+HTTP_ACCEPT_LANGUAGE, and HTTP_ACCEPT_CHARSET, corresponding to the
+like-named HTTP header fields in the request.  Called with the name of
+an HTTP header field, returns its value.  Capitalization and the use
+of hyphens versus underscores are not significant.
+
+For example, all three of these examples are equivalent:
+
+   $requested_language = $q->http('Accept-language');
+   $requested_language = $q->http('Accept_language');
+   $requested_language = $q->http('HTTP_ACCEPT_LANGUAGE');
+
+=item B<https()>
+
+The same as I<http()>, but operates on the HTTPS environment variables
+present when the SSL protocol is in effect.  Can be used to determine
+whether SSL is turned on.
+
 =back
 
 =head1 USING NPH SCRIPTS
@@ -6014,18 +6253,31 @@ initialize_globals().
 
 =back
 
-Since an attempt to send a POST larger than $POST_MAX bytes
-will cause a fatal error, you might want to use CGI::Carp to echo the
-fatal error message to the browser window as shown in the example
-above.  Otherwise the remote user will see only a generic "Internal
-Server" error message.  See the L<CGI::Carp> manual page for more
-details.
+An attempt to send a POST larger than $POST_MAX bytes will cause
+I<param()> to return an empty CGI parameter list.  You can test for
+this event by checking I<cgi_error()>, either after you create the CGI
+object or, if you are using the function-oriented interface, call
+<param()> for the first time.  If the POST was intercepted, then
+cgi_error() will return the message "413 POST too large".
+
+This error message is actually defined by the HTTP protocol, and is
+designed to be returned to the browser as the CGI script's status
+ code.  For example:
+
+   $uploaded_file = param('upload');
+   if (!$uploaded_file && cgi_error()) {
+      print header(-status=>cgi_error());
+      exit 0;
+   }
+
+However it isn't clear that any browser currently knows what to do
+with this status code.  It might be better just to create an
+HTML page that warns the user of the problem.
 
 =head1 COMPATIBILITY WITH CGI-LIB.PL
 
-To make it easier to port existing programs that use cgi-lib.pl
-the compatibility routine "ReadParse" is provided.  Porting is
-simple:
+To make it easier to port existing programs that use cgi-lib.pl the
+compatibility routine "ReadParse" is provided.  Porting is simple:
 
 OLD VERSION
     require "cgi-lib.pl";
index dfae1a6..8425fa0 100644 (file)
@@ -192,9 +192,16 @@ use Carp;
 @EXPORT = qw(confess croak carp);
 @EXPORT_OK = qw(carpout fatalsToBrowser wrap set_message cluck);
 
+BEGIN {
+  $] >= 5.005
+    ? eval q#sub ineval { $^S }#
+      : eval q#sub ineval { _longmess() =~ /eval [\{\']/m }#;
+  $@ and die;
+}
+
 $main::SIG{__WARN__}=\&CGI::Carp::warn;
 $main::SIG{__DIE__}=\&CGI::Carp::die;
-$CGI::Carp::VERSION = '1.13';
+$CGI::Carp::VERSION = '1.14';
 $CGI::Carp::CUSTOM_MSG = undef;
 
 # fancy import routine detects and handles 'errorWrap' specially.
@@ -251,14 +258,15 @@ sub _longmess {
 }
 
 sub die {
-    my $message = shift;
-    my $time = scalar(localtime);
-    my($file,$line,$id) = id(1);
-    $message .= " at $file line $line." unless $message=~/\n$/;
-    &fatalsToBrowser($message) if $WRAP && _longmess() !~ /eval [{\']/m;
-    my $stamp = stamp;
-    $message=~s/^/$stamp/gm;
-    realdie $message;
+  realdie @_ if ineval;
+  my $message = shift;
+  my $time = scalar(localtime);
+  my($file,$line,$id) = id(1);
+  $message .= " at $file line $line." unless $message=~/\n$/;
+  &fatalsToBrowser($message) if $WRAP;
+  my $stamp = stamp;
+  $message=~s/^/$stamp/gm;
+  realdie $message;
 }
 
 sub set_message {
index 204d67b..433df49 100644 (file)
@@ -7,17 +7,13 @@ package CGI::Cookie;
 # documentation in manual or html file format (these utilities are part of the
 # Perl 5 distribution).
 
-# Copyright 1995,1996, Lincoln D. Stein.  All rights reserved.
+# Copyright 1995-1999, Lincoln D. Stein.  All rights reserved.
 # It may be used and modified freely, but I do request that this copyright
 # notice remain attached to the file.  You may modify this module as you 
 # wish, but if you redistribute a modified version, please attach a note
 # listing the modifications you have made.
 
-# The most recent version and complete docs are available at:
-#   http://www.genome.wi.mit.edu/ftp/pub/software/WWW/cgi_docs.html
-#   ftp://ftp-genome.wi.mit.edu/pub/software/WWW/
-
-$CGI::Cookie::VERSION='1.06';
+$CGI::Cookie::VERSION='1.10';
 
 use CGI;
 use overload '""' => \&as_string,
@@ -100,8 +96,9 @@ sub new {
        'value'=>[@values],
        },$class;
 
-    # IE requires the path to be present for some reason.
-    ($path = $ENV{'SCRIPT_NAME'})=~s![^/]+$!! unless $path;
+    # IE requires the path and domain to be present for some reason.
+    $path   ||= CGI::url(-absolute=>1);
+    $domain ||= CGI::virtual_host();
 
     $self->path($path) if defined $path;
     $self->domain($domain) if defined $domain;
@@ -251,10 +248,10 @@ cookie originated from.
 If you provide a cookie path attribute, the browser will check it
 against your script's URL before returning the cookie.  For example,
 if you specify the path "/cgi-bin", then the cookie will be returned
-to each of the scripts "/cgi-bin/tally.pl", "/cgi-bin/order.pl",
-and "/cgi-bin/customer_service/complain.pl", but not to the script
-"/cgi-private/site_admin.pl".  By default, path is set to "/", which
-causes the cookie to be sent to any CGI script on your site.
+to each of the scripts "/cgi-bin/tally.pl", "/cgi-bin/order.pl", and
+"/cgi-bin/customer_service/complain.pl", but not to the script
+"/cgi-private/site_admin.pl".  By default, the path is set to the
+directory that contains your script.
 
 =item B<4. secure flag>
 
index a39fe05..968bb1f 100644 (file)
@@ -16,7 +16,7 @@ package CGI::Fast;
 # The most recent version and complete docs are available at:
 #   http://www.genome.wi.mit.edu/ftp/pub/software/WWW/cgi_docs.html
 #   ftp://ftp-genome.wi.mit.edu/pub/software/WWW/
-$CGI::Fast::VERSION='1.01';
+$CGI::Fast::VERSION='1.02';
 
 use CGI;
 use FCGI;
index 8fddfbf..d8327bc 100644 (file)
@@ -5,7 +5,7 @@ package Class::Struct;
 require 5.002;
 
 use strict;
-use vars qw(@ISA @EXPORT);
+use vars qw(@ISA @EXPORT $VERSION);
 
 use Carp;
 
@@ -13,6 +13,8 @@ require Exporter;
 @ISA = qw(Exporter);
 @EXPORT = qw(struct);
 
+$VERSION = '0.58';
+
 ## Tested on 5.002 and 5.003 without class membership tests:
 my $CHECK_CLASS_MEMBERSHIP = ($] >= 5.003_95);
 
@@ -98,6 +100,7 @@ sub struct {
     my $out = '';
 
     $out = "{\n  package $class;\n  use Carp;\n  sub new {\n";
+    $out .= "    my (\$class, \%init) = \@_;\n";
 
     my $cnt = 0;
     my $idx = 0;
@@ -115,7 +118,7 @@ sub struct {
         $type = $decls[$idx+1];
         push( @methods, $name );
         if( $base_type eq 'HASH' ){
-            $elem = "{'$name'}";
+            $elem = "{'${class}::$name'}";
         }
         elsif( $base_type eq 'ARRAY' ){
             $elem = "[$cnt]";
@@ -126,19 +129,27 @@ sub struct {
             $refs{$name}++;
             $type = $1;
         }
+        my $init = "defined(\$init{'$name'}) ? \$init{'$name'} :";
         if( $type eq '@' ){
-            $out .= "    \$r->$elem = [];$cmt\n";
+            $out .= "    croak 'Initializer for $name must be array reference'\n"; 
+            $out .= "        if defined(\$init{'$name'}) && ref(\$init{'$name'}) ne 'ARRAY';\n";
+            $out .= "    \$r->$elem = $init [];$cmt\n"; 
             $arrays{$name}++;
         }
         elsif( $type eq '%' ){
-            $out .= "    \$r->$elem = {};$cmt\n";
+            $out .= "    croak 'Initializer for $name must be hash reference'\n";
+            $out .= "        if defined(\$init{'$name'}) && ref(\$init{'$name'}) ne 'HASH';\n";
+            $out .= "    \$r->$elem = $init {};$cmt\n";
             $hashes{$name}++;
         }
         elsif ( $type eq '$') {
-            $out .= "    \$r->$elem = undef;$cmt\n";
+            $out .= "    \$r->$elem = $init undef;$cmt\n";
         }
         elsif( $type =~ /^\w+(?:::\w+)*$/ ){
-            $out .= "    \$r->$elem = '${type}'->new();$cmt\n";
+            $init = "defined(\$init{'$name'}) ? \%{\$init{'$name'}} : ()";
+            $out .= "    croak 'Initializer for $name must be hash reference'\n";
+            $out .= "        if defined(\$init{'$name'}) && ref(\$init{'$name'}) ne 'HASH';\n";
+            $out .= "    \$r->$elem = '${type}'->new($init);$cmt\n";
             $classes{$name} = $type;
             $got_class = 1;
         }
@@ -147,7 +158,7 @@ sub struct {
         }
         $idx += 2;
     }
-    $out .= "    bless \$r;\n  }\n";
+    $out .= "    bless \$r, \$class;\n  }\n";
 
     # Create accessor methods.
 
@@ -171,16 +182,16 @@ sub struct {
                 ++$cnt;
             }
             elsif( $base_type eq 'HASH' ){
-                $elem = "{'$name'}";
+                $elem = "{'${class}::$name'}";
             }
             if( defined $arrays{$name} ){
                 $out .= "    my \$i;\n";
-                $out .= "    \@_ ? (\$i = shift) : return $pre\$r->$elem$pst;\n";
+                $out .= "    \@_ ? (\$i = shift) : return \$r->$elem;\n"; 
                 $sel = "->[\$i]";
             }
             elsif( defined $hashes{$name} ){
                 $out .= "    my \$i;\n";
-                $out .= "    \@_ ? (\$i = shift) : return $pre\$r->$elem$pst;\n";
+                $out .= "    \@_ ? (\$i = shift) : return \$r->$elem;\n"; 
                 $sel = "->{\$i}";
             }
             elsif( defined $classes{$name} ){
@@ -297,6 +308,11 @@ flexible.
 The class created by C<struct> must not be a subclass of another
 class other than C<UNIVERSAL>.
 
+It can, however, be used as a superclass for other classes. To facilitate
+this, the generated constructor method uses a two-argument blessing.
+Furthermore, if the class is hash-based, the key of each element is
+prefixed with the class name (see I<Perl Cookbook>, Recipe 13.12).
+
 A function named C<new> must not be explicitly defined in a class
 created by C<struct>.
 
@@ -323,7 +339,8 @@ on the declared type of the element.
 
 =item Scalar (C<'$'> or C<'*$'>)
 
-The element is a scalar, and is initialized to C<undef>.
+The element is a scalar, and by default is initialized to C<undef>
+(but see L<Initializing with new>).
 
 The accessor's argument, if any, is assigned to the element.
 
@@ -333,10 +350,11 @@ to the element is returned.
 
 =item Array (C<'@'> or C<'*@'>)
 
-The element is an array, initialized to C<()>.
+The element is an array, initialized by default to C<()>.
 
 With no argument, the accessor returns a reference to the
-element's whole array.
+element's whole array (whether or not the element was
+specified as C<'@'> or C<'*@').
 
 With one or two arguments, the first argument is an index
 specifying one element of the array; the second argument, if
@@ -347,10 +365,11 @@ returned.
 
 =item Hash (C<'%'> or C<'*%'>)
 
-The element is a hash, initialized to C<()>.
+The element is a hash, initialized by default to C<()>.
 
 With no argument, the accessor returns a reference to the
-element's whole hash.
+element's whole hash (whether or not the element was
+specified as C<'%'> or C<'*%').
 
 With one or two arguments, the first argument is a key specifying
 one element of the hash; the second argument, if present, is
@@ -374,6 +393,23 @@ starts with a C<'*'>, a reference to the element itself is returned.
 
 =back
 
+=head2 Initializing with C<new>
+
+C<struct> always creates a constructor called C<new>. That constructor
+may take a list of initializers for the various elements of the new
+struct. 
+
+Each initializer is a pair of values: I<element name>C< =E<gt> >I<value>.
+The initializer value for a scalar element is just a scalar value. The 
+initializer for an array element is an array reference. The initializer
+for a hash is a hash reference.
+
+The initializer for a class element is also a hash reference, and the
+contents of that hash are passed to the element's own constructor.
+
+See Example 3 below for an example of initialization.
+
+
 =head1 EXAMPLES
 
 =over
@@ -399,8 +435,8 @@ type C<timeval>.
 
         # create an object:
     my $t = new rusage;
-       # $t->ru_utime and $t->ru_stime are objects of type timeval.
 
+        # $t->ru_utime and $t->ru_stime are objects of type timeval.
         # set $t->ru_utime to 100.0 sec and $t->ru_stime to 5.0 sec.
     $t->ru_utime->tv_secs(100);
     $t->ru_utime->tv_usecs(0);
@@ -418,10 +454,10 @@ accessor accordingly.
     package MyObj;
     use Class::Struct;
 
-               # declare the struct
+    # declare the struct
     struct ( 'MyObj', { count => '$', stuff => '%' } );
 
-               # override the default accessor method for 'count'
+    # override the default accessor method for 'count'
     sub count {
         my $self = shift;
         if ( @_ ) {
@@ -443,10 +479,67 @@ accessor accordingly.
     print "\$x->count(-5) = ", $x->count(-5), "\n";
                             # dies due to negative argument!
 
+=item Example 3
+
+The constructor of a generated class can be passed a list
+of I<element>=>I<value> pairs, with which to initialize the struct.
+If no initializer is specified for a particular element, its default
+initialization is performed instead. Initializers for non-existent
+elements are silently ignored.
+
+Note that the initializer for a nested struct is specified
+as an anonymous hash of initializers, which is passed on to the nested
+struct's constructor.
+
+
+    use Class::Struct;
+
+    struct Breed =>
+    {
+        name  => '$',
+        cross => '$',
+    };
+
+    struct Cat =>
+    [
+        name     => '$',
+        kittens  => '@',
+        markings => '%',
+        breed    => 'Breed',
+    ];
+
+
+    my $cat = Cat->new( name     => 'Socks',
+                        kittens  => ['Monica', 'Kenneth'],
+                        markings => { socks=>1, blaze=>"white" },
+                        breed    => { name=>'short-hair', cross=>1 },
+                      );
+
+    print "Once a cat called ", $cat->name, "\n";
+    print "(which was a ", $cat->breed->name, ")\n";
+    print "had two kittens: ", join(' and ', @{$cat->kittens}), "\n";
+
 
 =head1 Author and Modification History
 
 
+Modified by Damian Conway, 1999-03-05, v0.58.
+
+    Added handling of hash-like arg list to class ctor.
+
+    Changed to two-argument blessing in ctor to support
+    derivation from created classes.
+
+    Added classname prefixes to keys in hash-based classes
+    (refer to "Perl Cookbook", Recipe 13.12 for rationale).
+
+    Corrected behaviour of accessors for '*@' and '*%' struct
+    elements.  Package now implements documented behaviour when
+    returning a reference to an entire hash or array element.
+    Previously these were returned as a reference to a reference
+    to the element.
+
+
 Renamed to C<Class::Struct> and modified by Jim Miner, 1997-04-02.
 
     members() function removed.
index 5bcd58f..9c596ff 100644 (file)
@@ -181,6 +181,13 @@ sub unwrap {
     }
   }
 
+  if (ref $v eq 'Regexp') {
+    my $re = "$v";
+    $re =~ s,/,\\/,g;
+    print "$sp-> qr/$re/\n";
+    return;
+  }
+
   if ( UNIVERSAL::isa($v, 'HASH') ) {
     my @sortKeys = sort keys(%$v) ;
     my $more;
index 065c2f7..ada9d70 100644 (file)
@@ -1,7 +1,7 @@
 package Text::ParseWords;
 
 use vars qw($VERSION @ISA @EXPORT $PERL_SINGLE_QUOTE);
-$VERSION = "3.1";
+$VERSION = "3.2";
 
 require 5.000;
 
index 32d4692..fb0bb23 100644 (file)
@@ -143,6 +143,13 @@ sub unwrap {
       } 
     }
 
+    if (ref $v eq 'Regexp') {
+      my $re = "$v";
+      $re =~ s,/,\\/,g;
+      print "$sp-> qr/$re/\n";
+      return;
+    }
+
     if ( UNIVERSAL::isa($v, 'HASH') ) { 
        @sortKeys = sort keys(%$v) ;
        undef $more ; 
index 54602a6..f54f639 100644 (file)
@@ -111,7 +111,7 @@ sub inherit  # called by base.pm
 {
     my($derived, $base) = @_;
 
-    if (defined %{"$derived\::FIELDS"}) {
+    if (keys %{"$derived\::FIELDS"}) {
         require Carp;
          Carp::croak("Inherited %FIELDS can't override existing %FIELDS");
     } else {
@@ -132,7 +132,7 @@ sub _dump  # sometimes useful for debugging
 {
    for my $pkg (sort keys %attr) {
       print "\n$pkg";
-      if (defined @{"$pkg\::ISA"}) {
+      if (@{"$pkg\::ISA"}) {
          print " (", join(", ", @{"$pkg\::ISA"}), ")";
       }
       print "\n";
index bcb56c3..c46be83 100644 (file)
@@ -87,7 +87,7 @@ sub AddrRef {
 }
 
 sub StrVal {
-  (OverloadedStringify($_[0])) ?
+  (OverloadedStringify($_[0]) or ref($_[0]) eq 'Regexp') ?
     (AddrRef(shift)) :
     "$_[0]";
 }
diff --git a/op.c b/op.c
index 3d07000..f0cd15f 100644 (file)
--- a/op.c
+++ b/op.c
@@ -4999,14 +4999,14 @@ Perl_ck_defined(pTHX_ OP *o)            /* 19990527 MJD */
        case OP_PADAV:
        case OP_AASSIGN:                /* Is this a good idea? */
            Perl_warner(aTHX_ WARN_DEPRECATED,
-                       "defined(@array) is deprecated (and not really meaningful)");
+                       "defined(@array) is deprecated");
            Perl_warner(aTHX_ WARN_DEPRECATED,
                        "(Maybe you should just omit the defined()?)\n");
        break;
        case OP_RV2HV:
        case OP_PADHV:
            Perl_warner(aTHX_ WARN_DEPRECATED,
-                       "defined(%hash) is deprecated (and not really meaningful)");
+                       "defined(%hash) is deprecated");
            Perl_warner(aTHX_ WARN_DEPRECATED,
                        "(Maybe you should just omit the defined()?)\n");
            break;
diff --git a/perl.c b/perl.c
index cb3abdd..a869678 100644 (file)
--- a/perl.c
+++ b/perl.c
@@ -1088,6 +1088,8 @@ S_run_body(pTHX_ va_list args)
        CALLRUNOPS(aTHX);
     }
 
+    my_exit(0);
+    /* NOTREACHED */
     return NULL;
 }
 
index c172985..3b43f28 100644 (file)
@@ -477,13 +477,13 @@ by Perl.
 (W) You used the C<open(FH, "| command")> or C<open(FH, "command |")>
 construction, but the command was missing or blank.
 
-=item defined(@array) is deprecated (and not really meaningful)
+=item defined(@array) is deprecated
 
 (D) defined() is not usually useful on arrays because it checks for an
 undefined I<scalar> value.  If you want to see if the array is empty,
 just use C<if (@array) { # not empty }> for example.  
 
-=item defined(%hash) is deprecated (and not really meaningful)
+=item defined(%hash) is deprecated
 
 (D) defined() is not usually useful on hashes because it checks for an
 undefined I<scalar> value.  If you want to see if the hash is empty,
index 0084f9c..d7b9024 100644 (file)
@@ -1105,13 +1105,13 @@ times more than it has returned.  This probably indicates an infinite
 recursion, unless you're writing strange benchmark programs, in which
 case it indicates something else.
 
-=item defined(@array) is deprecated (and not really meaningful)
+=item defined(@array) is deprecated
 
 (D) defined() is not usually useful on arrays because it checks for an
 undefined I<scalar> value.  If you want to see if the array is empty,
 just use C<if (@array) { # not empty }> for example.  
 
-=item defined(%hash) is deprecated (and not really meaningful)
+=item defined(%hash) is deprecated
 
 (D) defined() is not usually useful on hashes because it checks for an
 undefined I<scalar> value.  If you want to see if the hash is empty,
index 0ac2810..6b0fd9d 100644 (file)
@@ -881,10 +881,17 @@ doesn't I<necessarily> indicate an exceptional condition: C<pop>
 returns C<undef> when its argument is an empty array, I<or> when the
 element to return happens to be C<undef>.
 
-You may also use C<defined> to check whether a subroutine exists, by
-saying C<defined &func> without parentheses.  On the other hand, use
-of C<defined> upon aggregates (hashes and arrays) is not guaranteed to
-produce intuitive results, and should probably be avoided.
+You may also use C<defined(&func)> to check whether subroutine C<&func>
+has ever been defined.  The return value is unaffected by any forward
+declarations of C<&foo>.
+
+Use of C<defined> on aggregates (hashes and arrays) is deprecated.  It
+used to report whether memory for that aggregate has ever been
+allocated.  This behavior may disappear in future versions of Perl.
+You should instead use a simple test for size:
+
+    if (@an_array) { print "has array elements\n" }
+    if (%a_hash)   { print "has hash members\n"   }
 
 When used on a hash element, it tells you whether the value is defined,
 not whether the key exists in the hash.  Use L</exists> for the latter
@@ -914,14 +921,6 @@ should use C<defined> only when you're questioning the integrity of what
 you're trying to do.  At other times, a simple comparison to C<0> or C<""> is
 what you want.
 
-Use of C<defined> on aggregates (hashes and arrays) is deprecated.  It
-used to report whether memory for that aggregate has ever been
-allocated.  This behavior may disappear in future versions of Perl.
-You should instead use a simple test for size:
-
-    if (@an_array) { print "has array elements\n" }
-    if (%a_hash)   { print "has hash members\n"   }
-
 See also L</undef>, L</exists>, L</ref>.
 
 =item delete EXPR
index b17a889..ca5b055 100644 (file)
@@ -1176,7 +1176,9 @@ perlopentut.pod, perlreftut.pod, perltootc.pod
 =item New Diagnostics
 
 /%s/: Unrecognized escape \\%c passed through, Unrecognized escape \\%c
-passed through, Missing command in piped open
+passed through, Missing command in piped open, defined(@array) is
+deprecated (and not really meaningful), defined(%hash) is deprecated (and
+not really meaningful)
 
 =item Obsolete Diagnostics
 
@@ -2527,7 +2529,7 @@ LIMIT specified
 
 =item DESCRIPTION
 
-Not all Perl programs have to be portable, The vast majority of Perl I<is>
+Not all Perl programs have to be portable, Nearly all of Perl already I<is>
 portable
 
 =item ISSUES
@@ -2647,12 +2649,10 @@ wait, waitpid PID,FLAGS
 
 =item CHANGES
 
-v1.42, 22 May 1999Added notes about tests, sprintf/printf, and epoch
-offsets.
-=item v1.41, 19 May 1999, v1.40, 11 April 1999, v1.39, 11 February 1999,
-v1.38, 31 December 1998, v1.37, 19 December 1998, v1.36, 9 September 1998,
-v1.35, 13 August 1998, v1.33, 06 August 1998, v1.32, 05 August 1998, v1.30,
-03 August 1998, v1.23, 10 July 1998
+v1.43, 24 May 1999, v1.42, 22 May 1999, v1.41, 19 May 1999, v1.40, 11 April
+1999, v1.39, 11 February 1999, v1.38, 31 December 1998, v1.37, 19 December
+1998, v1.36, 9 September 1998, v1.35, 13 August 1998, v1.33, 06 August
+1998, v1.32, 05 August 1998, v1.30, 03 August 1998, v1.23, 10 July 1998
 
 =item AUTHORS / CONTRIBUTORS
 
@@ -3214,6 +3214,14 @@ method, locked
 
 =item AUTHOR
 
+=head2 caller - inherit pragmatic attributes from the context of the caller
+
+=item SYNOPSIS
+
+=item DESCRIPTION
+
+encoding
+
 =head2 constant - Perl pragma to declare constants
 
 =item SYNOPSIS
@@ -3674,8 +3682,7 @@ label, stash, filegv, cop_seq, arybase, line
 main_cv, init_av, main_root, main_start, comppadlist, sv_undef, sv_yes,
 sv_no, amagic_generation, walkoptree(OP, METHOD), walkoptree_debug(DEBUG),
 walksymtable(SYMREF, METHOD, RECURSE), svref_2object(SV), ppname(OPNUM),
-hash(STR), cast_I32(I), minus_c, cstring(STR), class(OBJ), threadsv_names,
-byteload_fh(FILEHANDLE)
+hash(STR), cast_I32(I), minus_c, cstring(STR), class(OBJ), threadsv_names
 
 =item AUTHOR
 
@@ -3980,8 +3987,12 @@ B<-On>, B<-D>, B<-Do>, B<-Db>, B<-Da>, B<-DC>, B<-S>, B<-m>
 
 =item DIRECT ACCESS TO THE PARAMETER LIST:
 
+=item FETCHING THE PARAMETER LIST AS A HASH:
+
 =item SAVING THE STATE OF THE SCRIPT TO A FILE:
 
+=item RETRIEVING CGI ERRORS
+
 =item USING THE FUNCTION-ORIENTED INTERFACE
 
 B<:cgi>, B<:form>, B<:html2>, B<:html3>, B<:netscape>, B<:html>,
@@ -4131,7 +4142,7 @@ B<path_translated()>, B<remote_host()>, B<script_name()>Return the script
 name as a partial URL, for self-refering
 scripts, B<referer()>, B<auth_type ()>, B<server_name ()>, B<virtual_host
 ()>, B<server_software ()>, B<remote_user ()>, B<user_name ()>,
-B<request_method()>
+B<request_method()>, B<content_type()>, B<http()>, B<https()>
 
 =item USING NPH SCRIPTS
 
@@ -4416,11 +4427,13 @@ module
 Scalar (C<'$'> or C<'*$'>), Array (C<'@'> or C<'*@'>), Hash (C<'%'> or
 C<'*%'>), Class (C<'Class_Name'> or C<'*Class_Name'>)
 
+=item Initializing with C<new>
+
 =back
 
 =item EXAMPLES
 
-Example 1, Example 2
+Example 1, Example 2, Example 3
 
 =item Author and Modification History
 
index 69a1a25..4200140 100644 (file)
@@ -1,6 +1,6 @@
 =head1 NAME
 
-perlXStut - Tutorial for XSUBs
+perlXStut - Tutorial for writing XSUBs
 
 =head1 DESCRIPTION
 
@@ -10,61 +10,35 @@ L<perlxs>.
 
 This tutorial starts with very simple examples and becomes more complex,
 with each new example adding new features.  Certain concepts may not be
-completely explained until later in the tutorial to ease the
-reader slowly into building extensions.
+completely explained until later in the tutorial in order to slowly ease
+the reader into building extensions.
 
-=head2 VERSION CAVEAT
+This tutorial was written from a Unix point of view.  Where I know them
+to be otherwise different for other platforms (e.g. Win32), I will list
+them.  If you find something that was missed, please let me know.
 
-This tutorial tries hard to keep up with the latest development versions
-of Perl.  This often means that it is sometimes in advance of the latest
-released version of Perl, and that certain features described here might
-not work on earlier versions.  This section will keep track of when various
-features were added to Perl 5.
-
-=over 4
-
-=item *
-
-In versions of Perl 5.002 prior to the gamma version, the test script
-in Example 1 will not function properly.  You need to change the "use
-lib" line to read:
-
-       use lib './blib';
-
-=item *
-
-In versions of Perl 5.002 prior to version beta 3, the line in the .xs file
-about "PROTOTYPES: DISABLE" will cause a compiler error.  Simply remove that
-line from the file.
-
-=item *
-
-In versions of Perl 5.002 prior to version 5.002b1h, the test.pl file was not
-automatically created by h2xs.  This means that you cannot say "make test"
-to run the test script.  You will need to add the following line before the
-"use extension" statement:
+=head1 SPECIAL NOTES
 
-       use lib './blib';
-
-=item *
-
-In versions 5.000 and 5.001, instead of using the above line, you will need
-to use the following line:
+=head2 make
 
-       BEGIN { unshift(@INC, "./blib") }
+This tutorial assumes that the make program that Perl is configured to
+use is called C<make>.  Instead of running "make" in the examples that
+follow, you may have to substitute whatever make program Perl has been
+configured to use.  Running "perl -V:make" should tell you what it is.
 
-=item *
-
-This document assumes that the executable named "perl" is Perl version 5.
-Some systems may have installed Perl version 5 as "perl5".
+=head2 Version caveat
 
-=back
+This tutorial tries hard to keep up with the latest development versions
+of Perl.  This often means that it is sometimes in advance of the latest
+released version of Perl, and that certain features described here might
+not work on earlier versions.  See the section on "Troubleshooting
+these Examples" for more information.
 
-=head2 DYNAMIC VERSUS STATIC
+=head2 Dynamic Loading versus Static Loading
 
 It is commonly thought that if a system does not have the capability to
-load a library dynamically, you cannot build XSUBs.  This is incorrect.
-You I<can> build them, but you must link the XSUB's subroutines with the
+dynamically load a library, you cannot build XSUBs.  This is incorrect.
+You I<can> build them, but you must link the XSUBs subroutines with the
 rest of Perl, creating a new executable.  This situation is similar to
 Perl 4.
 
@@ -75,25 +49,30 @@ executable with that static library linked in.
 
 Should you wish to build a statically-linked executable on a system which
 can dynamically load libraries, you may, in all the following examples,
-where the command "make" with no arguments is executed, run the command
-"make perl" instead.
+where the command "C<make>" with no arguments is executed, run the command
+"C<make perl>" instead.
 
 If you have generated such a statically-linked executable by choice, then
-instead of saying "make test", you should say "make test_static".  On systems
-that cannot build dynamically-loadable libraries at all, simply saying "make
-test" is sufficient.
+instead of saying "C<make test>", you should say "C<make test_static>".
+On systems that cannot build dynamically-loadable libraries at all, simply
+saying "C<make test>" is sufficient.
+
+=head1 TUTORIAL
+
+Now let's go on with the show!
 
 =head2 EXAMPLE 1
 
 Our first extension will be very simple.  When we call the routine in the
 extension, it will print out a well-known message and return.
 
-Run C<h2xs -A -n Mytest>.  This creates a directory named Mytest, possibly under
-ext/ if that directory exists in the current working directory.  Several files
-will be created in the Mytest dir, including MANIFEST, Makefile.PL, Mytest.pm,
-Mytest.xs, test.pl, and Changes.
+Run "C<h2xs -A -n Mytest>".  This creates a directory named Mytest,
+possibly under ext/ if that directory exists in the current working
+directory.  Several files will be created in the Mytest dir, including
+MANIFEST, Makefile.PL, Mytest.pm, Mytest.xs, test.pl, and Changes.
 
-The MANIFEST file contains the names of all the files created.
+The MANIFEST file contains the names of all the files just created in the
+Mytest directory.
 
 The file Makefile.PL should look something like this:
 
@@ -101,17 +80,20 @@ The file Makefile.PL should look something like this:
        # See lib/ExtUtils/MakeMaker.pm for details of how to influence
        # the contents of the Makefile that is written.
        WriteMakefile(
-           'NAME'      => 'Mytest',
-           'VERSION_FROM' => 'Mytest.pm', # finds $VERSION
-           'LIBS'      => [''],   # e.g., '-lm'
-           'DEFINE'    => '',     # e.g., '-DHAVE_SOMETHING'
-           'INC'       => '',     # e.g., '-I/usr/include/other'
+           NAME         => 'Mytest',
+           VERSION_FROM => 'Mytest.pm', # finds $VERSION
+           LIBS         => [''],   # e.g., '-lm'
+           DEFINE       => '',     # e.g., '-DHAVE_SOMETHING'
+           INC          => '',     # e.g., '-I/usr/include/other'
        );
 
 The file Mytest.pm should start with something like this:
 
        package Mytest;
 
+       use strict;
+       use vars qw($VERSION @ISA @EXPORT);
+
        require Exporter;
        require DynaLoader;
 
@@ -134,19 +116,14 @@ The file Mytest.pm should start with something like this:
        __END__
        # Below is the stub of documentation for your module. You better edit it!
 
-And the Mytest.xs file should look something like this:
+The rest of the .pm file contains sample code for providing documentation for
+the extension.
+
+Finally, the Mytest.xs file should look something like this:
 
-       #ifdef __cplusplus
-       extern "C" {
-       #endif
        #include "EXTERN.h"
        #include "perl.h"
        #include "XSUB.h"
-       #ifdef __cplusplus
-       }
-       #endif
-
-       PROTOTYPES: DISABLE
 
        MODULE = Mytest         PACKAGE = Mytest
 
@@ -154,10 +131,14 @@ Let's edit the .xs file by adding this to the end of the file:
 
        void
        hello()
-               CODE:
+           CODE:
                printf("Hello, world!\n");
 
-Now we'll run "perl Makefile.PL".  This will create a real Makefile,
+It is okay for the lines starting at the "CODE:" line to not be indented.
+However, for readability purposes, it is suggested that you indent CODE:
+one level and the lines following one more level.
+
+Now we'll run "C<perl Makefile.PL>".  This will create a real Makefile,
 which make needs.  Its output looks something like:
 
        % perl Makefile.PL
@@ -166,12 +147,14 @@ which make needs.  Its output looks something like:
        Writing Makefile for Mytest
        %
 
-Now, running make will produce output that looks something like this
-(some long lines shortened for clarity):
+Now, running make will produce output that looks something like this (some
+long lines have been shortened for clarity and some extraneous lines have
+been deleted):
 
        % make
        umask 0 && cp Mytest.pm ./blib/Mytest.pm
        perl xsubpp -typemap typemap Mytest.xs >Mytest.tc && mv Mytest.tc Mytest.c
+       Please specify prototyping behavior for Mytest.xs (see perlxs manual)
        cc -c Mytest.c
        Running Mkbootstrap for Mytest ()
        chmod 644 Mytest.bs
@@ -179,55 +162,65 @@ Now, running make will produce output that looks something like this
        chmod 755 ./blib/PA-RISC1.1/auto/Mytest/Mytest.sl
        cp Mytest.bs ./blib/PA-RISC1.1/auto/Mytest/Mytest.bs
        chmod 644 ./blib/PA-RISC1.1/auto/Mytest/Mytest.bs
+       Manifying ./blib/man3/Mytest.3
+       %
+
+You can safely ignore the line about "prototyping behavior".
+
+If you are on a Win32 system, and the build process fails with linker
+errors for functions in the C library, check if your Perl is configured
+to use PerlCRT (running "perl -V:libc" should show you if this is the
+case).  If Perl is configured to use PerlCRT, you have to make sure
+PerlCRT.lib is copied to the same location that msvcrt.lib lives in,
+so that the compiler can find it on its own.  msvcrt.lib is usually
+found in the Visual C compiler's lib directory (e.g. C:/DevStudio/VC/lib).
 
-Now, although there is already a test.pl template ready for us, for this
-example only, we'll create a special test script.  Create a file called hello
+Perl has its own special way of easily writing test scripts, but for this
+example only, we'll create our own test script.  Create a file called hello
 that looks like this:
 
        #! /opt/perl5/bin/perl
-
+       
        use ExtUtils::testlib;
-
+       
        use Mytest;
-
+       
        Mytest::hello();
 
-Now we run the script and we should see the following output:
+Now we make the script executable (C<chmod -x hello>), run the script
+and we should see the following output:
 
-       % perl hello
+       % ./hello
        Hello, world!
        %
 
 =head2 EXAMPLE 2
 
-Now let's add to our extension a subroutine that will take a single argument
-and return 1 if the argument is even, 0 if the argument is odd.
+Now let's add to our extension a subroutine that will take a single numeric
+argument as input and return 0 if the number is even or 1 if the number
+is odd.
 
 Add the following to the end of Mytest.xs:
 
        int
        is_even(input)
                int     input
-               CODE:
+           CODE:
                RETVAL = (input % 2 == 0);
-               OUTPUT:
+           OUTPUT:
                RETVAL
 
-There does not need to be white space at the start of the "int input" line,
-but it is useful for improving readability.  The semi-colon at the end of
-that line is also optional.
-
-Any white space may be between the "int" and "input".  It is also okay for
-the four lines starting at the "CODE:" line to not be indented.  However,
-for readability purposes, it is suggested that you indent them 8 spaces
-(or one normal tab stop).
+There does not need to be white space at the start of the "C<int input>"
+line, but it is useful for improving readability.  Placing a semi-colon at
+the end of that line is also optional.  Any amount and kind of white space
+may be placed between the "C<int>" and "C<input>".
 
-Now rerun make to rebuild our new shared library.
+Now re-run make to rebuild our new shared library.
 
 Now perform the same steps as before, generating a Makefile from the
 Makefile.PL file, and running make.
 
-To test that our extension works, we now need to look at the
+In order to test that our extension works, we now need to look at the
 file test.pl.  This file is set up to imitate the same kind of testing
 structure that Perl itself has.  Within the test script, you perform a
 number of tests to confirm the behavior of the extension, printing "ok"
@@ -239,11 +232,11 @@ to the end of the file:
        print &Mytest::is_even(1) == 0 ? "ok 3" : "not ok 3", "\n";
        print &Mytest::is_even(2) == 1 ? "ok 4" : "not ok 4", "\n";
 
-We will be calling the test script through the command "make test".  You
+We will be calling the test script through the command "C<make test>".  You
 should see output that looks something like this:
 
        % make test
-       PERL_DL_NONLAZY=1 /opt/perl5.002b2/bin/perl (lots of -I arguments) test.pl
+       PERL_DL_NONLAZY=1 /opt/perl5.004/bin/perl (lots of -I arguments) test.pl
        1..4
        ok 1
        ok 2
@@ -251,7 +244,7 @@ should see output that looks something like this:
        ok 4
        %
 
-=head2 WHAT HAS GONE ON?
+=head2 What has gone on?
 
 The program h2xs is the starting point for creating extensions.  In later
 examples we'll see how we can use h2xs to read header files and generate
@@ -261,71 +254,72 @@ h2xs creates a number of files in the extension directory.  The file
 Makefile.PL is a perl script which will generate a true Makefile to build
 the extension.  We'll take a closer look at it later.
 
-The files E<lt>extensionE<gt>.pm and E<lt>extensionE<gt>.xs contain the meat
-of the extension.
-The .xs file holds the C routines that make up the extension.  The .pm file
-contains routines that tell Perl how to load your extension.
-
-Generating and invoking the Makefile created a directory blib (which stands
-for "build library") in the current working directory.  This directory will
-contain the shared library that we will build.  Once we have tested it, we
-can install it into its final location.
-
-Invoking the test script via "make test" did something very important.  It
-invoked perl with all those C<-I> arguments so that it could find the various
-files that are part of the extension.
-
-It is I<very> important that while you are still testing extensions that
-you use "make test".  If you try to run the test script all by itself, you
-will get a fatal error.
-
-Another reason it is important to use "make test" to run your test script
-is that if you are testing an upgrade to an already-existing version, using
-"make test" insures that you use your new extension, not the already-existing
-version.
+The .pm and .xs files contain the meat of the extension.  The .xs file holds
+the C routines that make up the extension.  The .pm file contains routines
+that tell Perl how to load your extension.
+
+Generating the Makefile and running C<make> created a directory called blib
+(which stands for "build library") in the current working directory.  This
+directory will contain the shared library that we will build.  Once we have
+tested it, we can install it into its final location.
+
+Invoking the test script via "C<make test>" did something very important.
+It invoked perl with all those C<-I> arguments so that it could find the
+various files that are part of the extension.  It is I<very> important that
+while you are still testing extensions that you use "C<make test>".  If you
+try to run the test script all by itself, you will get a fatal error.
+Another reason it is important to use "C<make test>" to run your test
+script is that if you are testing an upgrade to an already-existing version,
+using "C<make test>" insures that you will test your new extension, not the
+already-existing version.
 
 When Perl sees a C<use extension;>, it searches for a file with the same name
-as the use'd extension that has a .pm suffix.  If that file cannot be found,
+as the C<use>'d extension that has a .pm suffix.  If that file cannot be found,
 Perl dies with a fatal error.  The default search path is contained in the
-@INC array.
+C<@INC> array.
 
 In our case, Mytest.pm tells perl that it will need the Exporter and Dynamic
-Loader extensions.  It then sets the @ISA and @EXPORT arrays and the $VERSION
-scalar; finally it tells perl to bootstrap the module.  Perl will call its
-dynamic loader routine (if there is one) and load the shared library.
+Loader extensions.  It then sets the C<@ISA> and C<@EXPORT> arrays and the
+C<$VERSION> scalar; finally it tells perl to bootstrap the module.  Perl
+will call its dynamic loader routine (if there is one) and load the shared
+library.
 
-The two arrays that are set in the .pm file are very important.  The @ISA
+The two arrays C<@ISA> and C<@EXPORT> are very important.  The C<@ISA>
 array contains a list of other packages in which to search for methods (or
-subroutines) that do not exist in the current package.  The @EXPORT array
-tells Perl which of the extension's routines should be placed into the
-calling package's namespace.
+subroutines) that do not exist in the current package.  This is usually
+only important for object-oriented extensions (which we will talk about
+much later), and so usually doesn't need to be modified.
 
-It's important to select what to export carefully.  Do NOT export method names
-and do NOT export anything else I<by default> without a good reason.
+The C<@EXPORT> array tells Perl which of the extension's variables and
+subroutines should be placed into the calling package's namespace.  Because
+you don't know if the user has already used your variable and subroutine
+names, it's vitally important to carefully select what to export.  Do I<not>
+export method or variable names I<by default> without a good reason.
 
 As a general rule, if the module is trying to be object-oriented then don't
-export anything.  If it's just a collection of functions then you can export
-any of the functions via another array, called @EXPORT_OK.
+export anything.  If it's just a collection of functions and variables, then
+you can export them via another array, called C<@EXPORT_OK>.  This array
+does not automatically place its subroutine and variable names into the
+namespace unless the user specifically requests that this be done.
 
 See L<perlmod> for more information.
 
-The $VERSION variable is used to ensure that the .pm file and the shared
+The C<$VERSION> variable is used to ensure that the .pm file and the shared
 library are "in sync" with each other.  Any time you make changes to
 the .pm or .xs files, you should increment the value of this variable.
 
-=head2 WRITING GOOD TEST SCRIPTS
+=head2 Writing good test scripts
 
 The importance of writing good test scripts cannot be overemphasized.  You
 should closely follow the "ok/not ok" style that Perl itself uses, so that
 it is very easy and unambiguous to determine the outcome of each test case.
 When you find and fix a bug, make sure you add a test case for it.
 
-By running "make test", you ensure that your test.pl script runs and uses
+By running "C<make test>", you ensure that your test.pl script runs and uses
 the correct version of your extension.  If you have many test cases, you
-might want to copy Perl's test style.  Create a directory named "t", and
-ensure all your test files end with the suffix ".t".  The Makefile will
-properly run all these test files.
-
+might want to copy Perl's test style.  Create a directory named "t" in the
+extension's directory and append the suffix ".t" to the names of your test
+files.  When you run "C<make test>", all of these test files will be executed.
 
 =head2 EXAMPLE 3
 
@@ -337,7 +331,7 @@ Add the following to the end of Mytest.xs:
        void
        round(arg)
                double  arg
-               CODE:
+           CODE:
                if (arg > 0.0) {
                        arg = floor(arg + 0.5);
                } else if (arg < 0.0) {
@@ -345,14 +339,14 @@ Add the following to the end of Mytest.xs:
                } else {
                        arg = 0.0;
                }
-               OUTPUT:
+           OUTPUT:
                arg
 
 Edit the Makefile.PL file so that the corresponding line looks like this:
 
        'LIBS'      => ['-lm'],   # e.g., '-lm'
 
-Generate the Makefile and run make.  Change the BEGIN block to print out
+Generate the Makefile and run make.  Change the BEGIN block to print
 "1..9" and add the following to test.pl:
 
        $i = -1.5; &Mytest::round($i); print $i == -2.0 ? "ok 5" : "not ok 5", "\n";
@@ -361,58 +355,70 @@ Generate the Makefile and run make.  Change the BEGIN block to print out
        $i = 0.5; &Mytest::round($i); print $i == 1.0 ? "ok 8" : "not ok 8", "\n";
        $i = 1.2; &Mytest::round($i); print $i == 1.0 ? "ok 9" : "not ok 9", "\n";
 
-Running "make test" should now print out that all nine tests are okay.
+Running "C<make test>" should now print out that all nine tests are okay.
 
-You might be wondering if you can round a constant.  To see what happens, add
-the following line to test.pl temporarily:
+Notice that in these new test cases, the argument passed to round was a
+scalar variable.  You might be wondering if you can round a constant or
+literal.  To see what happens, temporarily add the following line to test.pl:
 
        &Mytest::round(3);
 
-Run "make test" and notice that Perl dies with a fatal error.  Perl won't let
-you change the value of constants!
+Run "C<make test>" and notice that Perl dies with a fatal error.  Perl won't
+let you change the value of constants!
 
-=head2 WHAT'S NEW HERE?
+=head2 What's new here?
 
-Two things are new here.  First, we've made some changes to Makefile.PL.
-In this case, we've specified an extra library to link in, the math library
-libm.  We'll talk later about how to write XSUBs that can call every routine
-in a library.
+=over 4
 
-Second, the value of the function is being passed back not as the function's
-return value, but through the same variable that was passed into the function.
+=item *
 
-=head2 INPUT AND OUTPUT PARAMETERS
+We've made some changes to Makefile.PL.  In this case, we've specified an
+extra library to be linked into the extension's shared library, the math
+library libm in this case.  We'll talk later about how to write XSUBs that
+can call every routine in a library.
 
-You specify the parameters that will be passed into the XSUB just after you
-declare the function return value and name.  Each parameter line starts with
-optional white space, and may have an optional terminating semicolon.
+=item *
+
+The value of the function is not being passed back as the function's return
+value, but by changing the value of the variable that was passed into the
+function.  You might have guessed that when you saw that the return value
+of round is of type "void".
+
+=back
+
+=head2 Input and Output Parameters
 
-The list of output parameters occurs after the OUTPUT: directive.  The use
-of RETVAL tells Perl that you wish to send this value back as the return
-value of the XSUB function.  In Example 3, the value we wanted returned was
-contained in the same variable we passed in, so we listed it (and not RETVAL)
-in the OUTPUT: section.
+You specify the parameters that will be passed into the XSUB on the line(s)
+after you declare the function's return value and name.  Each input parameter
+line starts with optional white space, and may have an optional terminating
+semicolon.
 
-=head2 THE XSUBPP COMPILER
+The list of output parameters occurs at the very end of the function, just
+before after the OUTPUT: directive.  The use of RETVAL tells Perl that you
+wish to send this value back as the return value of the XSUB function.  In
+Example 3, we wanted the "return value" placed in the original variable
+which we passed in, so we listed it (and not RETVAL) in the OUTPUT: section.
 
-The compiler xsubpp takes the XS code in the .xs file and converts it into
+=head2 The XSUBPP Program
+
+The xsubpp program takes the XS code in the .xs file and translates it into
 C code, placing it in a file whose suffix is .c.  The C code created makes
 heavy use of the C functions within Perl.
 
-=head2 THE TYPEMAP FILE
+=head2 The TYPEMAP file
 
-The xsubpp compiler uses rules to convert from Perl's data types (scalar,
-array, etc.) to C's data types (int, char *, etc.).  These rules are stored
+The xsubpp program uses rules to convert from Perl's data types (scalar,
+array, etc.) to C's data types (int, char, etc.).  These rules are stored
 in the typemap file ($PERLLIB/ExtUtils/typemap).  This file is split into
 three parts.
 
-The first part attempts to map various C data types to a coded flag, which
-has some correspondence with the various Perl types.  The second part contains
-C code which xsubpp uses for input parameters.  The third part contains C
-code which xsubpp uses for output parameters.  We'll talk more about the
-C code later.
+The first section maps various C data types to a name, which corresponds
+somewhat with the various Perl types.  The second section contains C code
+which xsubpp uses to handle input parameters.  The third section contains
+C code which xsubpp uses to handle output parameters.
 
-Let's now take a look at a portion of the .c file created for our extension.
+Let's take a look at a portion of the .c file created for our extension.
+The file name is Mytest.c:
 
        XS(XS_Mytest_round)
        {
@@ -428,13 +434,13 @@ Let's now take a look at a portion of the .c file created for our extension.
                } else {
                        arg = 0.0;
                }
-               sv_setnv(ST(0), (double)arg);           /* XXXXX */
+               sv_setnv(ST(0), (double)arg);   /* XXXXX */
            }
            XSRETURN(1);
        }
 
-Notice the two lines marked with "XXXXX".  If you check the first section of
-the typemap file, you'll see that doubles are of type T_DOUBLE.  In the
+Notice the two lines commented with "XXXXX".  If you check the first section
+of the typemap file, you'll see that doubles are of type T_DOUBLE.  In the
 INPUT section, an argument that is T_DOUBLE is assigned to the variable
 arg by calling the routine SvNV on something, then casting it to double,
 then assigned to the variable arg.  Similarly, in the OUTPUT section,
@@ -443,17 +449,19 @@ be passed back to the calling subroutine.  These two functions are explained
 in L<perlguts>; we'll talk more later about what that "ST(0)" means in the
 section on the argument stack.
 
-=head2 WARNING
+=head2 Warning about Output Arguments
 
 In general, it's not a good idea to write extensions that modify their input
-parameters, as in Example 3.  However, to accommodate better calling
-pre-existing C routines, which often do modify their input parameters,
-this behavior is tolerated.  The next example will show how to do this.
+parameters, as in Example 3.  Instead, you should probably return multiple
+values in an array and let the caller handle them (we'll do this in a later
+example).  However, in order to better accomodate calling pre-existing C
+routines, which often do modify their input parameters, this behavior is
+tolerated.
 
 =head2 EXAMPLE 4
 
 In this example, we'll now begin to write XSUBs that will interact with
-predefined C libraries.  To begin with, we will build a small library of
+pre-defined C libraries.  To begin with, we will build a small library of
 our own, then let h2xs write our .pm and .xs files for us.
 
 Create a new directory called Mytest2 at the same level as the directory
@@ -475,12 +483,9 @@ Also create a file mylib.c that looks like this:
 
        #include <stdlib.h>
        #include "./mylib.h"
-
+       
        double
-       foo(a, b, c)
-       int             a;
-       long            b;
-       const char *    c;
+       foo(int a, long b, const char *c)
        {
                return (a + b + atof(c) + TESTVAL);
        }
@@ -490,9 +495,9 @@ And finally create a file Makefile.PL that looks like this:
        use ExtUtils::MakeMaker;
        $Verbose = 1;
        WriteMakefile(
-           NAME      => 'Mytest2::mylib',
-           SKIP      => [qw(all static static_lib dynamic dynamic_lib)],
-           clean     => {'FILES' => 'libmylib$(LIB_EXT)'},
+           NAME   => 'Mytest2::mylib',
+           SKIP   => [qw(all static static_lib dynamic dynamic_lib)],
+           clean  => {'FILES' => 'libmylib$(LIBEEXT)'},
        );
 
 
@@ -500,6 +505,8 @@ And finally create a file Makefile.PL that looks like this:
                '
        all :: static
 
+       pure_all :: static
+
        static ::       libmylib$(LIB_EXT)
 
        libmylib$(LIB_EXT): $(O_FILES)
@@ -509,6 +516,11 @@ And finally create a file Makefile.PL that looks like this:
        ';
        }
 
+Make sure you use a tab and not spaces on the lines beginning with "$(AR)"
+and "$(RANLIB)".  Make will not function properly if you use spaces.
+It has also been reported that the "cr" argument to $(AR) is unnecessary
+on Win32 systems.
+
 We will now create the main top-level Mytest2 files.  Change to the directory
 above Mytest2 and run the following command:
 
@@ -519,24 +531,29 @@ Our files are stored in Mytest2/mylib, and will be untouched.
 
 The normal Makefile.PL that h2xs generates doesn't know about the mylib
 directory.  We need to tell it that there is a subdirectory and that we
-will be generating a library in it.  Let's add the following key-value
-pair to the WriteMakefile call:
+will be generating a library in it.  Let's add the argument MYEXTLIB to
+the WriteMakefile call so that it looks like this:
 
-       'MYEXTLIB' => 'mylib/libmylib$(LIB_EXT)',
+       WriteMakefile(
+           'NAME'      => 'Mytest2',
+           'VERSION_FROM' => 'Mytest2.pm', # finds $VERSION
+           'LIBS'      => [''],   # e.g., '-lm'
+           'DEFINE'    => '',     # e.g., '-DHAVE_SOMETHING'
+           'INC'       => '',     # e.g., '-I/usr/include/other'
+           'MYEXTLIB' => 'mylib/libmylib$(LIB_EXT)',
+       );
 
-and a new replacement subroutine too:
+and then at the end add a subroutine (which will override the pre-existing
+subroutine).  Remember to use a tab character to indent the line beginning
+with "cd"!
 
        sub MY::postamble {
        '
        $(MYEXTLIB): mylib/Makefile
-               cd mylib && $(MAKE) $(PASTHRU)
+               cd mylib && $(MAKE) $(PASSTHRU)
        ';
        }
 
-(Note: Most makes will require that there be a tab character that indents
-the line C<cd mylib && $(MAKE) $(PASTHRU)>, similarly for the Makefile in the
-subdirectory.)
-
 Let's also fix the MANIFEST file so that it accurately reflects the contents
 of our extension.  The single line that says "mylib" should be replaced by
 the following three lines:
@@ -546,7 +563,7 @@ the following three lines:
        mylib/mylib.h
 
 To keep our namespace nice and unpolluted, edit the .pm file and change
-the lines setting @EXPORT to @EXPORT_OK (there are two: one in the line
+the variable C<@EXPORT> to C<@EXPORT_OK> (there are two: one in the line
 beginning "use vars" and one setting the array itself).  Finally, in the
 .xs file, edit the #include line to read:
 
@@ -559,17 +576,17 @@ And also add the following function definition to the end of the .xs file:
                int             a
                long            b
                const char *    c
-               OUTPUT:
+           OUTPUT:
                RETVAL
 
 Now we also need to create a typemap file because the default Perl doesn't
-currently support the const char * type.  Create a file called typemap and
-place the following in it:
+currently support the const char * type.  Create a file called typemap in
+the Mytest2 directory and place the following in it:
 
        const char *    T_PV
 
 Now run perl on the top-level Makefile.PL.  Notice that it also created a
-Makefile in the mylib directory.  Run make and see that it does cd into
+Makefile in the mylib directory.  Run make and watch that it does cd into
 the mylib directory and run make in there as well.
 
 Now edit the test.pl script and change the BEGIN block to print "1..4",
@@ -579,13 +596,13 @@ and add the following lines to the end of the script:
        print &Mytest2::foo(1, 2, "0.0") == 7 ? "ok 3\n" : "not ok 3\n";
        print abs(&Mytest2::foo(0, 0, "-3.4") - 0.6) <= 0.01 ? "ok 4\n" : "not ok 4\n";
 
-(When dealing with floating-point comparisons, it is often useful not to check
-for equality, but rather the difference being below a certain epsilon factor,
-0.01 in this case)
+(When dealing with floating-point comparisons, it is best to not check for
+equality, but rather that the difference between the expected and actual
+result is below a certain amount (called epsilon) which is 0.01 in this case)
 
-Run "make test" and all should be well.
+Run "C<make test>" and all should be well.
 
-=head2 WHAT HAS HAPPENED HERE?
+=head2 What has happened here?
 
 Unlike previous examples, we've now run h2xs on a real include file.  This
 has caused some extra goodies to appear in both the .pm and .xs files.
@@ -594,59 +611,62 @@ has caused some extra goodies to appear in both the .pm and .xs files.
 
 =item *
 
-In the .xs file, there's now a #include declaration with the full path to
-the mylib.h header file.
+In the .xs file, there's now a #include directive with the absolute path to
+the mylib.h header file.  We changed this to a relative path so that we
+could move the extension directory if we wanted to.
 
 =item *
 
 There's now some new C code that's been added to the .xs file.  The purpose
 of the C<constant> routine is to make the values that are #define'd in the
-header file available to the Perl script (in this case, by calling
-C<&main::TESTVAL>).  There's also some XS code to allow calls to the
+header file accessible by the Perl script (by calling either C<TESTVAL> or
+C<&Mytest2::TESTVAL>).  There's also some XS code to allow calls to the
 C<constant> routine.
 
 =item *
 
-The .pm file has exported the name TESTVAL in the @EXPORT array.  This
-could lead to name clashes.  A good rule of thumb is that if the #define
-is going to be used by only the C routines themselves, and not by the user,
-they should be removed from the @EXPORT array.  Alternately, if you don't
-mind using the "fully qualified name" of a variable, you could remove most
-or all of the items in the @EXPORT array.
+The .pm file originally exported the name C<TESTVAL> in the C<@EXPORT> array.
+This could lead to name clashes.  A good rule of thumb is that if the #define
+is only going to be used by the C routines themselves, and not by the user,
+they should be removed from the C<@EXPORT> array.  Alternately, if you don't
+mind using the "fully qualified name" of a variable, you could move most
+or all of the items from the C<@EXPORT> array into the C<@EXPORT_OK> array.
 
 =item *
 
-If our include file contained #include directives, these would not be
-processed at all by h2xs.  There is no good solution to this right now.
+If our include file had contained #include directives, these would not have
+been processed by h2xs.  There is no good solution to this right now.
 
-=back
+=item *
 
 We've also told Perl about the library that we built in the mylib
-subdirectory.  That required the addition of only the MYEXTLIB variable
+subdirectory.  That required only the addition of the C<MYEXTLIB> variable
 to the WriteMakefile call and the replacement of the postamble subroutine
 to cd into the subdirectory and run make.  The Makefile.PL for the
 library is a bit more complicated, but not excessively so.  Again we
 replaced the postamble subroutine to insert our own code.  This code
-specified simply that the library to be created here was a static
-archive (as opposed to a dynamically loadable library) and provided the
+simply specified that the library to be created here was a static archive
+library (as opposed to a dynamically loadable library) and provided the
 commands to build it.
 
-=head2 SPECIFYING ARGUMENTS TO XSUBPP
+=back
+
+=head2 More about XSUBPP
 
 With the completion of Example 4, we now have an easy way to simulate some
 real-life libraries whose interfaces may not be the cleanest in the world.
 We shall now continue with a discussion of the arguments passed to the
 xsubpp compiler.
 
-When you specify arguments in the .xs file, you are really passing three
-pieces of information for each one listed.  The first piece is the order
-of that argument relative to the others (first, second, etc).  The second
-is the type of argument, and consists of the type declaration of the
-argument (e.g., int, char*, etc).  The third piece is the exact way in
-which the argument should be used in the call to the library function
-from this XSUB.  This would mean whether or not to place a "&" before
-the argument or not, meaning the argument expects to be passed the address
-of the specified data type.
+When you specify arguments to routines in the .xs file, you are really
+passing three pieces of information for each argument listed.  The first
+piece is the order of that argument relative to the others (first, second,
+etc).  The second is the type of argument, and consists of the type
+declaration of the argument (e.g., int, char*, etc).  The third piece is
+the exact way in which the argument should be used in the call to the
+library function from this XSUB.  This would mean whether or not to place
+a "&" before the argument or not, meaning the argument expects to be
+passed the address of the specified data type.
 
 There is a difference between the two arguments in this hypothetical function:
 
@@ -663,7 +683,7 @@ actual call to the function foo that xsubpp generates would look like this:
 
        foo(&a, b);
 
-Xsubpp will identically parse the following function argument lists:
+Xsubpp will parse the following function argument lists identically:
 
        char    &a
        char&a
@@ -672,40 +692,55 @@ Xsubpp will identically parse the following function argument lists:
 However, to help ease understanding, it is suggested that you place a "&"
 next to the variable name and away from the variable type), and place a
 "*" near the variable type, but away from the variable name (as in the
-complete example above).  By doing so, it is easy to understand exactly
-what will be passed to the C function -- it will be whatever is in the
-"last column".
+call to foo above).  By doing so, it is easy to understand exactly what
+will be passed to the C function -- it will be whatever is in the "last
+column".
 
 You should take great pains to try to pass the function the type of variable
 it wants, when possible.  It will save you a lot of trouble in the long run.
 
-=head2 THE ARGUMENT STACK
+=head2 The Argument Stack
 
 If we look at any of the C code generated by any of the examples except
 example 1, you will notice a number of references to ST(n), where n is
-usually 0.  The "ST" is actually a macro that points to the n'th argument
-on the argument stack.  ST(0) is thus the first argument passed to the
-XSUB, ST(1) is the second argument, and so on.
+usually 0.  "ST" is actually a macro that points to the n'th argument
+on the argument stack.  ST(0) is thus the first argument on the stack and
+therefore the first argument passed to the XSUB, ST(1) is the second
+argument, and so on.
 
 When you list the arguments to the XSUB in the .xs file, that tells xsubpp
 which argument corresponds to which of the argument stack (i.e., the first
 one listed is the first argument, and so on).  You invite disaster if you
 do not list them in the same order as the function expects them.
 
-=head2 EXTENDING YOUR EXTENSION
+The actual values on the argument stack are pointers to the values passed
+in.  When an argument is listed as being an OUTPUT value, its corresponding
+value on the stack (i.e., ST(0) if it was the first argument) is changed.
+You can verify this by looking at the C code generated for Example 3.
+The code for the round() XSUB routine contains lines that look like this:
+
+       double  arg = (double)SvNV(ST(0));
+       /* Round the contents of the variable arg */
+       sv_setnv(ST(0), (double)arg);
+
+The arg variable is initially set by taking the value from ST(0), then is
+stored back into ST(0) at the end of the routine.
+
+=head2 Extending your Extension
 
 Sometimes you might want to provide some extra methods or subroutines
 to assist in making the interface between Perl and your extension simpler
 or easier to understand.  These routines should live in the .pm file.
 Whether they are automatically loaded when the extension itself is loaded
-or loaded only when called depends on where in the .pm file the subroutine
-definition is placed.
+or only loaded when called depends on where in the .pm file the subroutine
+definition is placed.  You can also consult L<Autoloader> for an alternate
+way to store and load your extra subroutines.
 
-=head2 DOCUMENTING YOUR EXTENSION
+=head2 Documenting your Extension
 
 There is absolutely no excuse for not documenting your extension.
 Documentation belongs in the .pm file.  This file will be fed to pod2man,
-and the embedded documentation will be converted to the manpage format,
+and the embedded documentation will be converted to the man page format,
 then placed in the blib directory.  It will be copied to Perl's man
 page directory when the extension is installed.
 
@@ -715,19 +750,180 @@ as the comment inside the .pm file explains.
 
 See L<perlpod> for more information about the pod format.
 
-=head2 INSTALLING YOUR EXTENSION
+=head2 Installing your Extension
 
 Once your extension is complete and passes all its tests, installing it
-is quite simple: you simply run "make install".  You will either need
+is quite simple: you simply run "make install".  You will either need 
 to have write permission into the directories where Perl is installed,
 or ask your system administrator to run the make for you.
 
-=head2 SEE ALSO
+Alternately, you can specify the exact directory to place the extension's
+files by placing a "PREFIX=/destination/directory" after the make install.
+(or in between the make and install if you have a brain-dead version of make).
+This can be very useful if you are building an extension that will eventually
+be distributed to multiple systems.  You can then just archive the files in
+the destination directory and distribute them to your destination systems.
+
+=head2 EXAMPLE 5
+
+In this example, we'll do some more work with the argument stack.  The
+previous examples have all returned only a single value.  We'll now
+create an extension that returns an array.
+
+This extension is very Unix-oriented (struct statfs and the statfs system
+call).  If you are not running on a Unix system, you can substitute for
+statfs any other function that returns multiple values, you can hard-code
+values to be returned to the caller (although this will be a bit harder
+to test the error case), or you can simply not do this example.  If you
+change the XSUB, be sure to fix the test cases to match the changes.
+
+Return to the Mytest directory and add the following code to the end of
+Mytest.xs:
+
+       void
+       statfs(path)
+               char *  path
+           PREINIT:
+               int i;
+               struct statfs buf;
+
+           PPCODE:
+               i = statfs(path, &buf);
+               if (i == 0) {
+                       XPUSHs(sv_2mortal(newSVnv(buf.f_bavail)));
+                       XPUSHs(sv_2mortal(newSVnv(buf.f_bfree)));
+                       XPUSHs(sv_2mortal(newSVnv(buf.f_blocks)));
+                       XPUSHs(sv_2mortal(newSVnv(buf.f_bsize)));
+                       XPUSHs(sv_2mortal(newSVnv(buf.f_ffree)));
+                       XPUSHs(sv_2mortal(newSVnv(buf.f_files)));
+                       XPUSHs(sv_2mortal(newSVnv(buf.f_type)));
+                       XPUSHs(sv_2mortal(newSVnv(buf.f_fsid[0])));
+                       XPUSHs(sv_2mortal(newSVnv(buf.f_fsid[1])));
+               } else {
+                       XPUSHs(sv_2mortal(newSVnv(errno)));
+               }
+
+You'll also need to add the following code to the top of the .xs file, just
+after the include of "XSUB.h":
+
+       #include <sys/vfs.h>
+
+Also add the following code segment to test.pl while incrementing the "1..9"
+string in the BEGIN block to "1..11":
+
+       @a = &Mytest::statfs("/blech");
+       print ((scalar(@a) == 1 && $a[0] == 2) ? "ok 10\n" : "not ok 10\n");
+       @a = &Mytest::statfs("/");
+       print scalar(@a) == 9 ? "ok 11\n" : "not ok 11\n";
+
+=head2 New Things in this Example
+
+This example added quite a few new concepts.  We'll take them one at a time.
+
+=over 4
+
+=item *
+
+The PREINIT: directive contains code that will be placed immediately after
+variable declaration and before the argument stack is decoded.  Some compilers
+cannot handle variable declarations at arbitrary locations inside a function,
+so this is usually the best way to declare local variables needed by the XSUB.
+
+=item *
+
+This routine also returns a different number of arguments depending on the
+success or failure of the call to statfs.  If there is an error, the error
+number is returned as a single-element array.  If the call is successful,
+then a 9-element array is returned.  Since only one argument is passed into
+this function, we need room on the stack to hold the 9 values which may be
+returned.
+
+We do this by using the PPCODE: directive, rather than the CODE: directive.
+This tells xsubpp that we will be managing the return values that will be
+put on the argument stack by ourselves.
+
+=item *
+
+When we want to place values to be returned to the caller onto the stack,
+we use the series of macros that begin with "XPUSH".  There are five
+different versions, for placing integers, unsigned integers, doubles,
+strings, and Perl scalars on the stack.  In our example, we placed a
+Perl scalar onto the stack.
+
+The XPUSH* macros will automatically extend the return stack to prevent
+it from being overrun.  You push values onto the stack in the order you
+want them seen by the calling program.
+
+=item *
+
+The values pushed onto the return stack of the XSUB are actually mortal SV's.
+They are made mortal so that once the values are copied by the calling
+program, the SV's that held the returned values can be deallocated.
+If they were not mortal, then they would continue to exist after the XSUB
+routine returned, but would not be accessible.  This is a memory leak.
+
+=back
+
+=head2 EXAMPLE 6 (Coming Soon)
+
+Passing in and returning references to arrays and/or hashes
+
+=head2 EXAMPLE 7 (Coming Soon)
+
+XPUSH args AND set RETVAL AND assign return value to array
+
+=head2 EXAMPLE 8 (Coming Soon)
+
+Setting $!
+
+=head2 EXAMPLE 9 (Coming Soon)
+
+Getting fd's from filehandles
+
+=head2 Troubleshooting these Examples
+
+As mentioned at the top of this document, if you are having problems with
+these example extensions, you might see if any of these help you.
+
+=over 4
+
+=item *
+
+In versions of 5.002 prior to the gamma version, the test script in Example
+1 will not function properly.  You need to change the "use lib" line to
+read:
+
+       use lib './blib';
+
+=item *
+
+In versions of 5.002 prior to version 5.002b1h, the test.pl file was not
+automatically created by h2xs.  This means that you cannot say "make test"
+to run the test script.  You will need to add the following line before the
+"use extension" statement:
+
+       use lib './blib';
+
+=item *
+
+In versions 5.000 and 5.001, instead of using the above line, you will need
+to use the following line:
+
+       BEGIN { unshift(@INC, "./blib") }
+
+=item *
+
+This document assumes that the executable named "perl" is Perl version 5.  
+Some systems may have installed Perl version 5 as "perl5".
+
+=back
+
+=head1 See also
 
 For more information, consult L<perlguts>, L<perlxs>, L<perlmod>,
 and L<perlpod>.
 
-=head2 Author
+=head1 Author
 
 Jeff Okamoto <F<okamoto@corp.hp.com>>
 
@@ -736,4 +932,4 @@ and Tim Bunce.
 
 =head2 Last Changed
 
-1996/7/10
+1999/5/25
index 9b5c932..64e695b 100644 (file)
--- a/pp_ctl.c
+++ b/pp_ctl.c
@@ -2817,7 +2817,7 @@ S_doopen_pmc(pTHX_ const char *name, const char *mode)
     STRLEN namelen = strlen(name);
     PerlIO *fp;
 
-    if (namelen > 3 && strcmp(name + namelen - 3, ".pm") == 0) {
+    if (namelen > 3 && strEQ(name + namelen - 3, ".pm")) {
        SV *pmcsv = Perl_newSVpvf(aTHX_ "%s%c", name, 'c');
        char *pmc = SvPV_nolen(pmcsv);
        Stat_t pmstat;
diff --git a/t/io/openpid.t b/t/io/openpid.t
new file mode 100755 (executable)
index 0000000..2d3ac9f
--- /dev/null
@@ -0,0 +1,78 @@
+
+#!./perl
+
+#####################################################################
+#
+# Test for process id return value from open
+# Ronald Schmidt (The Software Path) RonaldWS@software-path.com
+#
+#####################################################################
+
+BEGIN {
+    chdir 't' if -d 't';
+    unshift @INC, '../lib';
+}
+
+
+use FileHandle;
+autoflush STDOUT 1;
+$SIG{PIPE} = 'IGNORE';
+
+print "1..10\n";
+
+$perl = "$^X -I../lib";
+
+#
+# commands run 4 perl programs.  Two of these programs write a
+# short message to STDOUT and exit.  Two of these programs
+# read from STDIN.  One reader never exits and must be killed.
+# the other reader reads one line, waits a few seconds and then
+# exits to test the waitpid function.
+#
+$cmd1 = qq/$perl -e "use FileHandle; autoflush STDOUT 1; / .
+        qq/print qq[first process\\n]; sleep 30;"/;
+$cmd2 = qq/$perl -e "use FileHandle; autoflush STDOUT 1; / .
+        qq/print qq[second process\\n]; sleep 30;"/;
+$cmd3 = qq/$perl -e "print <>;"/; # hangs waiting for end of STDIN
+$cmd4 = qq/$perl -e "print scalar <>;"/;
+
+#warn "#$cmd1\n#$cmd2\n#$cmd3\n#$cmd4\n";
+
+# start the processes
+$pid1 = open(FH1, "$cmd1 |") or print "not ";
+print "ok 1\n";
+$pid2 = open(FH2, "$cmd2 |") or print "not ";
+print "ok 2\n";
+$pid3 = open(FH3, "| $cmd3") or print "not ";
+print "ok 3\n";
+$pid4 = open(FH4, "| $cmd4") or print "not ";
+print "ok 4\n";
+
+print "# pids were $pid1, $pid2, $pid3, $pid4\n";
+
+# get message from first process and kill it
+chomp($from_pid1 = scalar(<FH1>));
+print "# child1 returned [$from_pid1]\nnot "
+    unless $from_pid1 eq 'first process';
+print "ok 5\n";
+$kill_cnt = kill STOP, $pid1;
+print "not " unless $kill_cnt == 1;
+print "ok 6\n";
+
+# get message from second process and kill second process and reader process
+chomp($from_pid2 = scalar(<FH2>));
+print "# child2 returned [$from_pid2]\nnot "
+    unless $from_pid2 eq 'second process';
+print "ok 7\n";
+$kill_cnt = kill STOP, $pid2, $pid3;
+print "not " unless $kill_cnt == 2;
+print "ok 8\n";
+
+# send one expected line of text to child process and then wait for it
+autoflush FH4 1;
+print FH4 "ok 9\n";
+print "# waiting for process $pid4 to exit\n";
+$reap_pid = waitpid $pid4, 0;
+print "# reaped pid $reap_pid != $pid4\nnot "
+    unless $reap_pid == $pid4;
+print "ok 10\n";
index 83217a2..e3cba5f 100755 (executable)
@@ -44,16 +44,16 @@ test(6,textfield(-name=>'weather') eq qq(<INPUT TYPE="text" NAME="weather" VALUE
 test(7,textfield(-name=>'weather',-value=>'nice') eq qq(<INPUT TYPE="text" NAME="weather" VALUE="dull">),"textfield({-name,-value})");
 test(8,textfield(-name=>'weather',-value=>'nice',-override=>1) eq qq(<INPUT TYPE="text" NAME="weather" VALUE="nice">),
      "textfield({-name,-value,-override})");
-test(9,checkbox(-name=>'weather',-value=>'nice') eq qq(<INPUT TYPE="checkbox" NAME="weather" VALUE="nice">weather\n),
+test(9,checkbox(-name=>'weather',-value=>'nice') eq qq(<INPUT TYPE="checkbox" NAME="weather" VALUE="nice">weather),
      "checkbox()");
 test(10,checkbox(-name=>'weather',-value=>'nice',-label=>'forecast') eq 
-     qq(<INPUT TYPE="checkbox" NAME="weather" VALUE="nice">forecast\n),
+     qq(<INPUT TYPE="checkbox" NAME="weather" VALUE="nice">forecast),
      "checkbox()");
 test(11,checkbox(-name=>'weather',-value=>'nice',-label=>'forecast',-checked=>1,-override=>1) eq 
-     qq(<INPUT TYPE="checkbox" NAME="weather" VALUE="nice" CHECKED>forecast\n),
+     qq(<INPUT TYPE="checkbox" NAME="weather" VALUE="nice" CHECKED>forecast),
      "checkbox()");
 test(12,checkbox(-name=>'weather',-value=>'dull',-label=>'forecast') eq 
-     qq(<INPUT TYPE="checkbox" NAME="weather" VALUE="dull" CHECKED>forecast\n),
+     qq(<INPUT TYPE="checkbox" NAME="weather" VALUE="dull" CHECKED>forecast),
      "checkbox()");
 
 test(13,radio_group(-name=>'game') eq 
index 3fe41d1..d4c9c1b 100755 (executable)
@@ -10,9 +10,6 @@ BEGIN {
 }
 
 BEGIN {$| = 1; print "1..20\n"; }
-BEGIN {$eol = "\n"   if $^O eq 'VMS';
-       $eol = "\r\n" if $Config{ebcdic} eq 'define';
-       $eol = "\cM\cJ" unless defined $eol; }
 END {print "not ok 1\n" unless $loaded;}
 use CGI (':standard','-no_debug','*h3','start_table');
 $loaded = 1;
@@ -40,10 +37,10 @@ test(7,h1({-align=>'CENTER'},['fred','agnes']) eq
     local($") = '-'; 
     test(8,h1('fred','agnes','maura') eq '<H1>fred-agnes-maura</H1>',"open/close tag \$\" interpolation");
 }
-test(9,header() eq "Content-Type: text/html${eol}${eol}","header()");
-test(10,header(-type=>'image/gif') eq "Content-Type: image/gif${eol}${eol}","header()");
-test(11,header(-type=>'image/gif',-status=>'500 Sucks') eq "Status: 500 Sucks${eol}Content-Type: image/gif${eol}${eol}","header()");
-test(12,header(-nph=>1) eq "HTTP/1.0 200 OK${eol}Content-Type: text/html${eol}${eol}","header()");
+test(9,header() eq "Content-Type: text/html\015\012\015\012","header()");
+test(10,header(-type=>'image/gif') eq "Content-Type: image/gif\015\012\015\012","header()");
+test(11,header(-type=>'image/gif',-status=>'500 Sucks') eq "Status: 500 Sucks\015\012Content-Type: image/gif\015\012\015\012","header()");
+test(12,header(-nph=>1) eq "HTTP/1.0 200 OK\015\012Content-Type: text/html\015\012\015\012","header()");
 test(13,start_html() ."\n" eq <<END,"start_html()");
 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
 <HTML><HEAD><TITLE>Untitled Document</TITLE>
@@ -63,8 +60,8 @@ test(15,start_html(-Title=>'The world of foo') ."\n" eq <<END,"start_html()");
 END
     ;
 test(16,($cookie=cookie(-name=>'fred',-value=>['chocolate','chip'],-path=>'/')) eq 
-     'fred=chocolate&chip; path=/',"cookie()");
-test(17,header(-Cookie=>$cookie) =~ m!^Set-Cookie: fred=chocolate&chip\; path=/${eol}Date:.*${eol}Content-Type: text/html${eol}${eol}!s,
+     'fred=chocolate&chip; domain=localhost; path=/',"cookie()");
+test(17,header(-Cookie=>$cookie) =~ m!^Set-Cookie: fred=chocolate&chip\; domain=localhost; path=/\015\012Date:.*\015\012Content-Type: text/html\015\012\015\012!s,
      "header(-cookie)");
 test(18,start_h3 eq '<H3>');
 test(19,end_h3 eq '</H3>');
index 2a6f3fb..9e8cdc2 100755 (executable)
@@ -25,15 +25,16 @@ sub test {
 }
 
 # Set up a CGI environment
-$ENV{REQUEST_METHOD}='GET';
-$ENV{QUERY_STRING}  ='game=chess&game=checkers&weather=dull';
-$ENV{PATH_INFO}     ='/somewhere/else';
-$ENV{PATH_TRANSLATED} ='/usr/local/somewhere/else';
-$ENV{SCRIPT_NAME}   ='/cgi-bin/foo.cgi';
+$ENV{REQUEST_METHOD}  = 'GET';
+$ENV{QUERY_STRING}    = 'game=chess&game=checkers&weather=dull';
+$ENV{PATH_INFO}       = '/somewhere/else';
+$ENV{PATH_TRANSLATED} = '/usr/local/somewhere/else';
+$ENV{SCRIPT_NAME}     = '/cgi-bin/foo.cgi';
 $ENV{SERVER_PROTOCOL} = 'HTTP/1.0';
-$ENV{SERVER_PORT} = 8080;
-$ENV{SERVER_NAME} = 'the.good.ship.lollypop.com';
-$ENV{HTTP_LOVE} = 'true';
+$ENV{SERVER_PORT}     = 8080;
+$ENV{SERVER_NAME}     = 'the.good.ship.lollypop.com';
+$ENV{REQUEST_URI}     = "$ENV{SCRIPT_NAME}$ENV{PATH_INFO}?$ENV{QUERY_STRING}";
+$ENV{HTTP_LOVE}       = 'true';
 
 $q = new CGI;
 test(2,$q,"CGI::new()");
index c72534a..a07a837 100644 (file)
      (Maybe you meant system() when you said exec()?
        exec "true" ; my $a
 
-     defined(@array) is deprecated (and not really meaningful)
+     defined(@array) is deprecated
      (Maybe you should just omit the defined()?)
        defined @a ;
        my @a ; defined @a ;
        defined (@a = (1,2,3)) ;
 
-     defined(%hash) is deprecated (and not really meaningful)
+     defined(%hash) is deprecated
      (Maybe you should just omit the defined()?)
        defined %h ;
        my %h ; defined %h ;
@@ -558,33 +558,33 @@ Statement unlikely to be reached at - line 4.
 use warning 'deprecated' ;
 defined(@a);
 EXPECT
-defined(@array) is deprecated (and not really meaningful) at - line 3.
+defined(@array) is deprecated at - line 3.
 (Maybe you should just omit the defined()?)
 ########
 # op.c
 use warning 'deprecated' ;
 my @a; defined(@a);
 EXPECT
-defined(@array) is deprecated (and not really meaningful) at - line 3.
+defined(@array) is deprecated at - line 3.
 (Maybe you should just omit the defined()?)
 ########
 # op.c
 use warning 'deprecated' ;
 defined(@a = (1,2,3));
 EXPECT
-defined(@array) is deprecated (and not really meaningful) at - line 3.
+defined(@array) is deprecated at - line 3.
 (Maybe you should just omit the defined()?)
 ########
 # op.c
 use warning 'deprecated' ;
 defined(%h);
 EXPECT
-defined(%hash) is deprecated (and not really meaningful) at - line 3.
+defined(%hash) is deprecated at - line 3.
 (Maybe you should just omit the defined()?)
 ########
 # op.c
 use warning 'deprecated' ;
 my %h; defined(%h);
 EXPECT
-defined(%hash) is deprecated (and not really meaningful) at - line 3.
+defined(%hash) is deprecated at - line 3.
 (Maybe you should just omit the defined()?)
diff --git a/win32/perlhost.h b/win32/perlhost.h
deleted file mode 100644 (file)
index a645328..0000000
+++ /dev/null
@@ -1,953 +0,0 @@
-
-#include "iperlsys.h"
-
-extern CPerlObj *pPerl;
-
-#define CALLFUNC0RET(x)\
-    int ret = x;\
-    if (ret < 0)\
-       err = errno;\
-    return ret;
-
-#define PROCESS_AND_RETURN  \
-    if (errno)             \
-       err = errno;        \
-    return r
-
-#define CALLFUNCRET(x)\
-    int ret = x;\
-    if (ret)\
-       err = errno;\
-    return ret;
-
-#define CALLFUNCERR(x)\
-    int ret = x;\
-    if (errno)\
-       err = errno;\
-    return ret;
-
-#define LCALLFUNCERR(x)\
-    long ret = x;\
-    if (errno)\
-       err = errno;\
-    return ret;
-
-class CPerlDir : public IPerlDir
-{
-public:
-    CPerlDir() {};
-    virtual int Makedir(const char *dirname, int mode, int &err)
-    {
-       CALLFUNC0RET(win32_mkdir(dirname, mode));
-    };
-    virtual int Chdir(const char *dirname, int &err)
-    {
-       CALLFUNC0RET(win32_chdir(dirname));
-    };
-    virtual int Rmdir(const char *dirname, int &err)
-    {
-       CALLFUNC0RET(win32_rmdir(dirname));
-    };
-    virtual int Close(DIR *dirp, int &err)
-    {
-       return win32_closedir(dirp);
-    };
-    virtual DIR *Open(char *filename, int &err)
-    {
-       return win32_opendir(filename);
-    };
-    virtual struct direct *Read(DIR *dirp, int &err)
-    {
-       return win32_readdir(dirp);
-    };
-    virtual void Rewind(DIR *dirp, int &err)
-    {
-       win32_rewinddir(dirp);
-    };
-    virtual void Seek(DIR *dirp, long loc, int &err)
-    {
-       win32_seekdir(dirp, loc);
-    };
-    virtual long Tell(DIR *dirp, int &err)
-    {
-       return win32_telldir(dirp);
-    };
-};
-
-
-extern char *          g_win32_get_privlib(char *pl);
-extern char *          g_win32_get_sitelib(char *pl);
-
-class CPerlEnv : public IPerlEnv
-{
-public:
-    CPerlEnv() {};
-    virtual char *Getenv(const char *varname, int &err)
-    {
-       return win32_getenv(varname);
-    };
-    virtual int Putenv(const char *envstring, int &err)
-    {
-       return win32_putenv(envstring);
-    };
-    virtual char* LibPath(char *pl)
-    {
-       return g_win32_get_privlib(pl);
-    };
-    virtual char* SiteLibPath(char *pl)
-    {
-       return g_win32_get_sitelib(pl);
-    };
-    virtual int Uname(struct utsname *name, int &err)
-    {
-       return win32_uname(name);
-    };
-    virtual char *Getenv_len(const char *varname, unsigned long *len, int &err)
-    {
-       char *e = win32_getenv(varname);
-       if (e)
-           *len = strlen(e);
-       return e;
-    };
-};
-
-class CPerlSock : public IPerlSock
-{
-public:
-    CPerlSock() {};
-    virtual u_long Htonl(u_long hostlong)
-    {
-       return win32_htonl(hostlong);
-    };
-    virtual u_short Htons(u_short hostshort)
-    {
-       return win32_htons(hostshort);
-    };
-    virtual u_long Ntohl(u_long netlong)
-    {
-       return win32_ntohl(netlong);
-    };
-    virtual u_short Ntohs(u_short netshort)
-    {
-       return win32_ntohs(netshort);
-    }
-
-    virtual SOCKET Accept(SOCKET s, struct sockaddr* addr, int* addrlen, int &err)
-    {
-       SOCKET r = win32_accept(s, addr, addrlen);
-       PROCESS_AND_RETURN;
-    };
-    virtual int Bind(SOCKET s, const struct sockaddr* name, int namelen, int &err)
-    {
-       int r = win32_bind(s, name, namelen);
-       PROCESS_AND_RETURN;
-    };
-    virtual int Connect(SOCKET s, const struct sockaddr* name, int namelen, int &err)
-    {
-       int r = win32_connect(s, name, namelen);
-       PROCESS_AND_RETURN;
-    };
-    virtual void Endhostent(int &err)
-    {
-       win32_endhostent();
-    };
-    virtual void Endnetent(int &err)
-    {
-       win32_endnetent();
-    };
-    virtual void Endprotoent(int &err)
-    {
-       win32_endprotoent();
-    };
-    virtual void Endservent(int &err)
-    {
-       win32_endservent();
-    };
-    virtual struct hostent* Gethostbyaddr(const char* addr, int len, int type, int &err)
-    {
-       struct hostent *r = win32_gethostbyaddr(addr, len, type);
-       PROCESS_AND_RETURN;
-    };
-    virtual struct hostent* Gethostbyname(const char* name, int &err)
-    {
-       struct hostent *r = win32_gethostbyname(name);
-       PROCESS_AND_RETURN;
-    };
-    virtual struct hostent* Gethostent(int &err)
-    {
-        croak("gethostent not implemented!\n");
-       return NULL;
-    };
-    virtual int Gethostname(char* name, int namelen, int &err)
-    {
-       int r = win32_gethostname(name, namelen);
-       PROCESS_AND_RETURN;
-    };
-    virtual struct netent *Getnetbyaddr(long net, int type, int &err)
-    {
-       struct netent *r = win32_getnetbyaddr(net, type);
-       PROCESS_AND_RETURN;
-    };
-    virtual struct netent *Getnetbyname(const char *name, int &err)
-    {
-       struct netent *r = win32_getnetbyname((char*)name);
-       PROCESS_AND_RETURN;
-    };
-    virtual struct netent *Getnetent(int &err)
-    {
-       struct netent *r = win32_getnetent();
-       PROCESS_AND_RETURN;
-    };
-    virtual int Getpeername(SOCKET s, struct sockaddr* name, int* namelen, int &err)
-    {
-       int r = win32_getpeername(s, name, namelen);
-       PROCESS_AND_RETURN;
-    };
-    virtual struct protoent* Getprotobyname(const char* name, int &err)
-    {
-       struct protoent *r = win32_getprotobyname(name);
-       PROCESS_AND_RETURN;
-    };
-    virtual struct protoent* Getprotobynumber(int number, int &err)
-    {
-       struct protoent *r = win32_getprotobynumber(number);
-       PROCESS_AND_RETURN;
-    };
-    virtual struct protoent* Getprotoent(int &err)
-    {
-       struct protoent *r = win32_getprotoent();
-       PROCESS_AND_RETURN;
-    };
-    virtual struct servent* Getservbyname(const char* name, const char* proto, int &err)
-    {
-       struct servent *r = win32_getservbyname(name, proto);
-       PROCESS_AND_RETURN;
-    };
-    virtual struct servent* Getservbyport(int port, const char* proto, int &err)
-    {
-       struct servent *r = win32_getservbyport(port, proto);
-       PROCESS_AND_RETURN;
-    };
-    virtual struct servent* Getservent(int &err)
-    {
-       struct servent *r = win32_getservent();
-       PROCESS_AND_RETURN;
-    };
-    virtual int Getsockname(SOCKET s, struct sockaddr* name, int* namelen, int &err)
-    {
-       int r = win32_getsockname(s, name, namelen);
-       PROCESS_AND_RETURN;
-    };
-    virtual int Getsockopt(SOCKET s, int level, int optname, char* optval, int* optlen, int &err)
-    {
-       int r = win32_getsockopt(s, level, optname, optval, optlen);
-       PROCESS_AND_RETURN;
-    };
-    virtual unsigned long InetAddr(const char* cp, int &err)
-    {
-       unsigned long r = win32_inet_addr(cp);
-       PROCESS_AND_RETURN;
-    };
-    virtual char* InetNtoa(struct in_addr in, int &err)
-    {
-       char *r = win32_inet_ntoa(in);
-       PROCESS_AND_RETURN;
-    };
-    virtual int Listen(SOCKET s, int backlog, int &err)
-    {
-       int r = win32_listen(s, backlog);
-       PROCESS_AND_RETURN;
-    };
-    virtual int Recv(SOCKET s, char* buffer, int len, int flags, int &err)
-    {
-       int r = win32_recv(s, buffer, len, flags);
-       PROCESS_AND_RETURN;
-    };
-    virtual int Recvfrom(SOCKET s, char* buffer, int len, int flags, struct sockaddr* from, int* fromlen, int &err)
-    {
-       int r = win32_recvfrom(s, buffer, len, flags, from, fromlen);
-       PROCESS_AND_RETURN;
-    };
-    virtual int Select(int nfds, char* readfds, char* writefds, char* exceptfds, const struct timeval* timeout, int &err)
-    {
-       int r = win32_select(nfds, (Perl_fd_set*)readfds, (Perl_fd_set*)writefds, (Perl_fd_set*)exceptfds, timeout);
-       PROCESS_AND_RETURN;
-    };
-    virtual int Send(SOCKET s, const char* buffer, int len, int flags, int &err)
-    {
-       int r = win32_send(s, buffer, len, flags);
-       PROCESS_AND_RETURN;
-    };
-    virtual int Sendto(SOCKET s, const char* buffer, int len, int flags, const struct sockaddr* to, int tolen, int &err)
-    {
-       int r = win32_sendto(s, buffer, len, flags, to, tolen);
-       PROCESS_AND_RETURN;
-    };
-    virtual void Sethostent(int stayopen, int &err)
-    {
-       win32_sethostent(stayopen);
-    };
-    virtual void Setnetent(int stayopen, int &err)
-    {
-       win32_setnetent(stayopen);
-    };
-    virtual void Setprotoent(int stayopen, int &err)
-    {
-       win32_setprotoent(stayopen);
-    };
-    virtual void Setservent(int stayopen, int &err)
-    {
-       win32_setservent(stayopen);
-    };
-    virtual int Setsockopt(SOCKET s, int level, int optname, const char* optval, int optlen, int &err)
-    {
-       int r = win32_setsockopt(s, level, optname, optval, optlen);
-       PROCESS_AND_RETURN;
-    };
-    virtual int Shutdown(SOCKET s, int how, int &err)
-    {
-       int r = win32_shutdown(s, how);
-       PROCESS_AND_RETURN;
-    };
-    virtual SOCKET Socket(int af, int type, int protocol, int &err)
-    {
-       SOCKET r = win32_socket(af, type, protocol);
-       PROCESS_AND_RETURN;
-    };
-    virtual int Socketpair(int domain, int type, int protocol, int* fds, int &err)
-    {
-        croak("socketpair not implemented!\n");
-       return 0;
-    };
-    virtual int Closesocket(SOCKET s, int& err)
-    {
-       int r = win32_closesocket(s);
-       PROCESS_AND_RETURN;
-    };
-    virtual int Ioctlsocket(SOCKET s, long cmd, u_long *argp, int& err)
-    {
-       int r = win32_ioctlsocket(s, cmd, argp);
-       PROCESS_AND_RETURN;
-    };
-};
-
-class CPerlLIO : public IPerlLIO
-{
-public:
-    CPerlLIO() {};
-    virtual int Access(const char *path, int mode, int &err)
-    {
-       CALLFUNCRET(access(path, mode))
-    };
-    virtual int Chmod(const char *filename, int pmode, int &err)
-    {
-       CALLFUNCRET(chmod(filename, pmode))
-    };
-    virtual int Chown(const char *filename, uid_t owner, gid_t group, int &err)
-    {
-       CALLFUNCERR(chown(filename, owner, group))
-    };
-    virtual int Chsize(int handle, long size, int &err)
-    {
-       CALLFUNCRET(chsize(handle, size))
-    };
-    virtual int Close(int handle, int &err)
-    {
-       CALLFUNCRET(win32_close(handle))
-    };
-    virtual int Dup(int handle, int &err)
-    {
-       CALLFUNCERR(win32_dup(handle))
-    };
-    virtual int Dup2(int handle1, int handle2, int &err)
-    {
-       CALLFUNCERR(win32_dup2(handle1, handle2))
-    };
-    virtual int Flock(int fd, int oper, int &err)
-    {
-       CALLFUNCERR(win32_flock(fd, oper))
-    };
-    virtual int FileStat(int handle, struct stat *buffer, int &err)
-    {
-       CALLFUNCERR(fstat(handle, buffer))
-    };
-    virtual int IOCtl(int i, unsigned int u, char *data, int &err)
-    {
-       CALLFUNCERR(win32_ioctlsocket((SOCKET)i, (long)u, (u_long*)data))
-    };
-    virtual int Isatty(int fd, int &err)
-    {
-       return isatty(fd);
-    };
-    virtual long Lseek(int handle, long offset, int origin, int &err)
-    {
-       LCALLFUNCERR(win32_lseek(handle, offset, origin))
-    };
-    virtual int Lstat(const char *path, struct stat *buffer, int &err)
-    {
-       return NameStat(path, buffer, err);
-    };
-    virtual char *Mktemp(char *Template, int &err)
-    {
-       return mktemp(Template);
-    };
-    virtual int Open(const char *filename, int oflag, int &err)
-    {
-       CALLFUNCERR(win32_open(filename, oflag))
-    };
-    virtual int Open(const char *filename, int oflag, int pmode, int &err)
-    {
-       int ret;
-       if(stricmp(filename, "/dev/null") == 0)
-           ret = open("NUL", oflag, pmode);
-       else
-           ret = open(filename, oflag, pmode);
-
-       if(errno)
-           err = errno;
-       return ret;
-    };
-    virtual int Read(int handle, void *buffer, unsigned int count, int &err)
-    {
-       CALLFUNCERR(win32_read(handle, buffer, count))
-    };
-    virtual int Rename(const char *OldFileName, const char *newname, int &err)
-    {
-       CALLFUNCRET(win32_rename(OldFileName, newname))
-    };
-    virtual int Setmode(int handle, int mode, int &err)
-    {
-       CALLFUNCRET(win32_setmode(handle, mode))
-    };
-    virtual int NameStat(const char *path, struct stat *buffer, int &err)
-    {
-       return win32_stat(path, buffer);
-    };
-    virtual char *Tmpnam(char *string, int &err)
-    {
-       return tmpnam(string);
-    };
-    virtual int Umask(int pmode, int &err)
-    {
-       return umask(pmode);
-    };
-    virtual int Unlink(const char *filename, int &err)
-    {
-       chmod(filename, S_IREAD | S_IWRITE);
-       CALLFUNCRET(unlink(filename))
-    };
-    virtual int Utime(char *filename, struct utimbuf *times, int &err)
-    {
-       CALLFUNCRET(win32_utime(filename, times))
-    };
-    virtual int Write(int handle, const void *buffer, unsigned int count, int &err)
-    {
-       CALLFUNCERR(win32_write(handle, buffer, count))
-    };
-};
-
-class CPerlMem : public IPerlMem
-{
-public:
-    CPerlMem() {};
-    virtual void* Malloc(size_t size)
-    {
-       return win32_malloc(size);
-    };
-    virtual void* Realloc(void* ptr, size_t size)
-    {
-       return win32_realloc(ptr, size);
-    };
-    virtual void Free(void* ptr)
-    {
-       win32_free(ptr);
-    };
-};
-
-#define EXECF_EXEC 1
-#define EXECF_SPAWN 2
-
-extern char *          g_getlogin(void);
-extern int             do_spawn2(char *cmd, int exectype);
-extern int             g_do_aspawn(void *vreally, void **vmark, void **vsp);
-
-class CPerlProc : public IPerlProc
-{
-public:
-    CPerlProc() {};
-    virtual void Abort(void)
-    {
-       win32_abort();
-    };
-    virtual char * Crypt(const char* clear, const char* salt)
-    {
-       return win32_crypt(clear, salt);
-    };
-    virtual void Exit(int status)
-    {
-       exit(status);
-    };
-    virtual void _Exit(int status)
-    {
-       _exit(status);
-    };
-    virtual int Execl(const char *cmdname, const char *arg0, const char *arg1, const char *arg2, const char *arg3)
-    {
-       return execl(cmdname, arg0, arg1, arg2, arg3);
-    };
-    virtual int Execv(const char *cmdname, const char *const *argv)
-    {
-       return win32_execvp(cmdname, argv);
-    };
-    virtual int Execvp(const char *cmdname, const char *const *argv)
-    {
-       return win32_execvp(cmdname, argv);
-    };
-    virtual uid_t Getuid(void)
-    {
-       return getuid();
-    };
-    virtual uid_t Geteuid(void)
-    {
-       return geteuid();
-    };
-    virtual gid_t Getgid(void)
-    {
-       return getgid();
-    };
-    virtual gid_t Getegid(void)
-    {
-       return getegid();
-    };
-    virtual char *Getlogin(void)
-    {
-       return g_getlogin();
-    };
-    virtual int Kill(int pid, int sig)
-    {
-       return win32_kill(pid, sig);
-    };
-    virtual int Killpg(int pid, int sig)
-    {
-       croak("killpg not implemented!\n");
-       return 0;
-    };
-    virtual int PauseProc(void)
-    {
-       return win32_sleep((32767L << 16) + 32767);
-    };
-    virtual PerlIO* Popen(const char *command, const char *mode)
-    {
-       win32_fflush(stdout);
-       win32_fflush(stderr);
-       return (PerlIO*)win32_popen(command, mode);
-    };
-    virtual int Pclose(PerlIO *stream)
-    {
-       return win32_pclose((FILE*)stream);
-    };
-    virtual int Pipe(int *phandles)
-    {
-       return win32_pipe(phandles, 512, O_BINARY);
-    };
-    virtual int Setuid(uid_t u)
-    {
-       return setuid(u);
-    };
-    virtual int Setgid(gid_t g)
-    {
-       return setgid(g);
-    };
-    virtual int Sleep(unsigned int s)
-    {
-       return win32_sleep(s);
-    };
-    virtual int Times(struct tms *timebuf)
-    {
-       return win32_times(timebuf);
-    };
-    virtual int Wait(int *status)
-    {
-       return win32_wait(status);
-    };
-    virtual int Waitpid(int pid, int *status, int flags)
-    {
-       return win32_waitpid(pid, status, flags);
-    };
-    virtual Sighandler_t Signal(int sig, Sighandler_t subcode)
-    {
-       return 0;
-    };
-    virtual void GetSysMsg(char*& sMsg, DWORD& dwLen, DWORD dwErr)
-    {
-       dwLen = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
-                         |FORMAT_MESSAGE_IGNORE_INSERTS
-                         |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
-                          dwErr, 0, (char *)&sMsg, 1, NULL);
-       if (0 < dwLen) {
-           while (0 < dwLen  &&  isSPACE(sMsg[--dwLen]))
-               ;
-           if ('.' != sMsg[dwLen])
-               dwLen++;
-           sMsg[dwLen]= '\0';
-       }
-       if (0 == dwLen) {
-           sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
-           if (sMsg)
-               dwLen = sprintf(sMsg,
-                           "Unknown error #0x%lX (lookup 0x%lX)",
-                           dwErr, GetLastError());
-       }
-    };
-    virtual void FreeBuf(char* sMsg)
-    {
-       LocalFree(sMsg);
-    };
-    virtual BOOL DoCmd(char *cmd)
-    {
-       do_spawn2(cmd, EXECF_EXEC);
-        return FALSE;
-    };
-    virtual int Spawn(char* cmds)
-    {
-       return do_spawn2(cmds, EXECF_SPAWN);
-    };
-    virtual int Spawnvp(int mode, const char *cmdname, const char *const *argv)
-    {
-       return win32_spawnvp(mode, cmdname, argv);
-    };
-    virtual int ASpawn(void *vreally, void **vmark, void **vsp)
-    {
-       return g_do_aspawn(vreally, vmark, vsp);
-    };
-};
-
-
-class CPerlStdIO : public IPerlStdIO
-{
-public:
-    CPerlStdIO() {};
-    virtual PerlIO* Stdin(void)
-    {
-       return (PerlIO*)win32_stdin();
-    };
-    virtual PerlIO* Stdout(void)
-    {
-       return (PerlIO*)win32_stdout();
-    };
-    virtual PerlIO* Stderr(void)
-    {
-       return (PerlIO*)win32_stderr();
-    };
-    virtual PerlIO* Open(const char *path, const char *mode, int &err)
-    {
-       PerlIO*pf = (PerlIO*)win32_fopen(path, mode);
-       if(errno)
-           err = errno;
-       return pf;
-    };
-    virtual int Close(PerlIO* pf, int &err)
-    {
-       CALLFUNCERR(win32_fclose(((FILE*)pf)))
-    };
-    virtual int Eof(PerlIO* pf, int &err)
-    {
-       CALLFUNCERR(win32_feof((FILE*)pf))
-    };
-    virtual int Error(PerlIO* pf, int &err)
-    {
-       CALLFUNCERR(win32_ferror((FILE*)pf))
-    };
-    virtual void Clearerr(PerlIO* pf, int &err)
-    {
-       win32_clearerr((FILE*)pf);
-    };
-    virtual int Getc(PerlIO* pf, int &err)
-    {
-       CALLFUNCERR(win32_getc((FILE*)pf))
-    };
-    virtual char* GetBase(PerlIO* pf, int &err)
-    {
-#ifdef FILE_base
-       FILE *f = (FILE*)pf;
-       return FILE_base(f);
-#else
-       return Nullch;
-#endif
-    };
-    virtual int GetBufsiz(PerlIO* pf, int &err)
-    {
-#ifdef FILE_bufsiz
-       FILE *f = (FILE*)pf;
-       return FILE_bufsiz(f);
-#else
-       return (-1);
-#endif
-    };
-    virtual int GetCnt(PerlIO* pf, int &err)
-    {
-#ifdef USE_STDIO_PTR
-       FILE *f = (FILE*)pf;
-       return FILE_cnt(f);
-#else
-       return (-1);
-#endif
-    };
-    virtual char* GetPtr(PerlIO* pf, int &err)
-    {
-#ifdef USE_STDIO_PTR
-       FILE *f = (FILE*)pf;
-       return FILE_ptr(f);
-#else
-       return Nullch;
-#endif
-    };
-    virtual char* Gets(PerlIO* pf, char* s, int n, int& err)
-    {
-       char* ret = win32_fgets(s, n, (FILE*)pf);
-       if(errno)
-           err = errno;
-       return ret;
-    };
-    virtual int Putc(PerlIO* pf, int c, int &err)
-    {
-       CALLFUNCERR(win32_fputc(c, (FILE*)pf))
-    };
-    virtual int Puts(PerlIO* pf, const char *s, int &err)
-    {
-       CALLFUNCERR(win32_fputs(s, (FILE*)pf))
-    };
-    virtual int Flush(PerlIO* pf, int &err)
-    {
-       CALLFUNCERR(win32_fflush((FILE*)pf))
-    };
-    virtual int Ungetc(PerlIO* pf,int c, int &err)
-    {
-       CALLFUNCERR(win32_ungetc(c, (FILE*)pf))
-    };
-    virtual int Fileno(PerlIO* pf, int &err)
-    {
-       CALLFUNCERR(win32_fileno((FILE*)pf))
-    };
-    virtual PerlIO* Fdopen(int fd, const char *mode, int &err)
-    {
-       PerlIO* pf = (PerlIO*)win32_fdopen(fd, mode);
-       if(errno)
-           err = errno;
-       return pf;
-    };
-    virtual PerlIO* Reopen(const char*path, const char*mode, PerlIO* pf, int &err)
-    {
-       PerlIO* newPf = (PerlIO*)win32_freopen(path, mode, (FILE*)pf);
-       if(errno)
-           err = errno;
-       return newPf;
-    };
-    virtual SSize_t Read(PerlIO* pf, void *buffer, Size_t size, int &err)
-    {
-       SSize_t i = win32_fread(buffer, 1, size, (FILE*)pf);
-       if(errno)
-           err = errno;
-       return i;
-    };
-    virtual SSize_t Write(PerlIO* pf, const void *buffer, Size_t size, int &err)
-    {
-       SSize_t i = win32_fwrite(buffer, 1, size, (FILE*)pf);
-       if(errno)
-           err = errno;
-       return i;
-    };
-    virtual void SetBuf(PerlIO* pf, char* buffer, int &err)
-    {
-       win32_setbuf((FILE*)pf, buffer);
-    };
-    virtual int SetVBuf(PerlIO* pf, char* buffer, int type, Size_t size, int &err)
-    {
-       int i = win32_setvbuf((FILE*)pf, buffer, type, size);
-       if(errno)
-           err = errno;
-       return i;
-    };
-    virtual void SetCnt(PerlIO* pf, int n, int &err)
-    {
-#ifdef STDIO_CNT_LVALUE
-       FILE *f = (FILE*)pf;
-       FILE_cnt(f) = n;
-#endif
-    };
-    virtual void SetPtrCnt(PerlIO* pf, char * ptr, int n, int& err)
-    {
-#ifdef STDIO_PTR_LVALUE
-       FILE *f = (FILE*)pf;
-       FILE_ptr(f) = ptr;
-       FILE_cnt(f) = n;
-#endif
-    };
-    virtual void Setlinebuf(PerlIO* pf, int &err)
-    {
-       win32_setvbuf((FILE*)pf, NULL, _IOLBF, 0);
-    };
-    virtual int Printf(PerlIO* pf, int &err, const char *format,...)
-    {
-       va_list(arglist);
-       va_start(arglist, format);
-       int i = win32_vfprintf((FILE*)pf, format, arglist);
-       if(errno)
-           err = errno;
-       return i;
-    };
-    virtual int Vprintf(PerlIO* pf, int &err, const char *format, va_list arglist)
-    {
-       int i = win32_vfprintf((FILE*)pf, format, arglist);
-       if(errno)
-           err = errno;
-       return i;
-    };
-    virtual long Tell(PerlIO* pf, int &err)
-    {
-       long l = win32_ftell((FILE*)pf);
-       if(errno)
-           err = errno;
-       return l;
-    };
-    virtual int Seek(PerlIO* pf, off_t offset, int origin, int &err)
-    {
-       int i = win32_fseek((FILE*)pf, offset, origin);
-       if(errno)
-           err = errno;
-       return i;
-    };
-    virtual void Rewind(PerlIO* pf, int &err)
-    {
-       win32_rewind((FILE*)pf);
-    };
-    virtual PerlIO* Tmpfile(int &err)
-    {
-       PerlIO* pf = (PerlIO*)win32_tmpfile();
-       if(errno)
-           err = errno;
-       return pf;
-    };
-    virtual int Getpos(PerlIO* pf, Fpos_t *p, int &err)
-    {
-       int i = win32_fgetpos((FILE*)pf, p);
-       if(errno)
-           err = errno;
-       return i;
-    };
-    virtual int Setpos(PerlIO* pf, const Fpos_t *p, int &err)
-    {
-       int i = win32_fsetpos((FILE*)pf, p);
-       if(errno)
-           err = errno;
-       return i;
-    };
-    virtual void Init(int &err)
-    {
-    };
-    virtual void InitOSExtras(void* p)
-    {
-       Perl_init_os_extras();
-    };
-    virtual int OpenOSfhandle(long osfhandle, int flags)
-    {
-       return win32_open_osfhandle(osfhandle, flags);
-    }
-    virtual int GetOSfhandle(int filenum)
-    {
-       return win32_get_osfhandle(filenum);
-    }
-};
-
-class CPerlHost
-{
-public:
-    CPerlHost() { pPerl = NULL; };
-    inline BOOL PerlCreate(void)
-    {
-       try
-       {
-           pPerl = perl_alloc(&perlMem, &perlEnv, &perlStdIO, &perlLIO,
-                              &perlDir, &perlSock, &perlProc);
-           if(pPerl != NULL)
-           {
-               try
-               {
-                   perl_construct();
-               }
-               catch(...)
-               {
-                   win32_fprintf(stderr, "%s\n",
-                                 "Error: Unable to construct data structures");
-                   perl_free();
-                   pPerl = NULL;
-               }
-           }
-       }
-       catch(...)
-       {
-           win32_fprintf(stderr, "%s\n", "Error: Unable to allocate memory");
-           pPerl = NULL;
-       }
-       return (pPerl != NULL);
-    };
-    inline int PerlParse(void (*xs_init)(CPerlObj*), int argc, char** argv, char** env)
-    {
-       int retVal;
-       try
-       {
-           retVal = perl_parse(xs_init, argc, argv, env);
-       }
-       catch(int x)
-       {
-           // this is where exit() should arrive
-           retVal = x;
-       }
-       catch(...)
-       {
-           win32_fprintf(stderr, "Error: Parse exception\n");
-           retVal = -1;
-       }
-       *win32_errno() = 0;
-       return retVal;
-    };
-    inline int PerlRun(void)
-    {
-       int retVal;
-       try
-       {
-           retVal = perl_run();
-       }
-       catch(int x)
-       {
-           // this is where exit() should arrive
-           retVal = x;
-       }
-       catch(...)
-       {
-           win32_fprintf(stderr, "Error: Runtime exception\n");
-           retVal = -1;
-       }
-       return retVal;
-    };
-    inline void PerlDestroy(void)
-    {
-       try
-       {
-           perl_destruct();
-           perl_free();
-       }
-       catch(...)
-       {
-       }
-    };
-
-protected:
-    CPerlDir   perlDir;
-    CPerlEnv   perlEnv;
-    CPerlLIO   perlLIO;
-    CPerlMem   perlMem;
-    CPerlProc  perlProc;
-    CPerlSock  perlSock;
-    CPerlStdIO perlStdIO;
-};
index 2df9c7c..a8ba54d 100644 (file)
@@ -1439,15 +1439,11 @@ win32_uname(struct utsname *name)
        char *arch;
        GetSystemInfo(&info);
 
-#ifdef __MINGW32__
-       switch (info.DUMMYUNIONNAME.DUMMYSTRUCTNAME.wProcessorArchitecture) {
-#else
-#ifdef __BORLANDC__
+#if defined(__BORLANDC__) || defined(__MINGW32__)
        switch (info.u.s.wProcessorArchitecture) {
 #else
        switch (info.wProcessorArchitecture) {
 #endif
-#endif
        case PROCESSOR_ARCHITECTURE_INTEL:
            arch = "x86"; break;
        case PROCESSOR_ARCHITECTURE_MIPS:
@@ -2126,6 +2122,9 @@ win32_popen(const char *command, const char *mode)
        win32_close(oldfd);
 
        sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
+
+       /* set process id so that it can be returned by perl's open() */
+       PL_forkprocess = childpid;
     }
 
     /* we have an fd, return a file stream */
index ee25b5a..75e3c61 100644 (file)
@@ -23,7 +23,7 @@
 #endif
 
 #ifdef __GNUC__
-// typedef long long __int64;
+typedef long long __int64;
 #  define Win32_Winsock
 /* GCC does not do __declspec() - render it a nop 
  * and turn on options to avoid importing data