This is Info file pm.info, produced by Makeinfo-1.55 from the input file
bigpm.texi.


File: pm.info,  Node: Module List,  Next: (perl.info)Function Index,  Up: (perl.info)Top

Module List
***********

This is it!  The list of the installed (documented) modules on sampras, as
of Fri Nov  8 21:40:30 PST 1996.

Texinfo source for this file was generated by krishna running pod2texi.pl.
This info file itself was created 8 November 1996.

* Menu:


* Agent:: supplies agentspace methods for perl5.
* Alias:: declare symbolic aliases for perl data
* AnyDBM_File:: provide framework for multiple DBMs
* Apache:: Perl interface to the Apache server API
* Apache/AccessLimitNum:: Limit user access by number of requests
* Apache/Authen:: Perl Apache authentication handlers
* Apache/AuthzAge:: Authorize based on age
* Apache/CGI:: Make things work with CGI.pm against Perl-Apache API
* Apache/Debug:: Utilities for debugging embedded perl code
* Apache/MsqlProxy:: Translate URI's into mSQL database queries
* Apache/Options:: OPT_* defines from httpd_core.h
* Apache/Registry:: Run (mostly) unaltered CGI scripts through mod_perl_fast
* Apache/SSI:: Implement Server Side Includes in Perl
* Apache/TieHandle:: tie stdio to Apache's i/o methods
* Archie:: Perl module to make Archie queries via Prospero requests
* AtExit:: Register a subroutine to be invoked at program-exit time.
* AutoLoader:: load functions only on demand
* AutoSplit:: split a package for autoloading
* B/Xref:: Generates cross reference reports for Perl programs
* BSD/Resource:: BSD process resource limit and priority functions
* Benchmark:: benchmark running times of code
* BitCount:: count number of "1" bits in string
* C/Scan:: scan C language files for easily recognized constructs.
* CGI:: Simple Common Gateway Interface Class
* CGI/Base:: HTTP Daemon Common Gateway Interface (CGI) Base Class
* CGI/BasePlus:: HTTP CGI Base Class with Handling of Multipart Forms
* CGI/Carp:: CGI routines for writing to the HTTPD (or other) error log
* CGI/Fast:: CGI Interface for Fast CGI
* CGI/Form:: Build Smart HTML Forms on Top of the CGI:: Modules
* CGI/Imagemap:: imagemap behavior for CGI programs
* CGI/MiniSvr:: Adds to CGI::Base the ability for a CGI script to become a mini http server.
* CGI/Out:: buffer output when building CGI programs
* CGI/Request:: Parse client request via a CGI interface
* CGI/Response:: Respond to CGI requests
* CGI/Switch:: Try more than one constructors and return the first object available
* CGI/Wrap:: buffer output when building CGI programs
* CGI/XA:: Clone of CGI.pm with less backwards compatibility and less namespace pollution
* CPAN:: query, download and build perl modules from CPAN sites
* Carp:: warn of errors (from perspective of caller)
* Color:: implements color functions and names
* Compress/Zlib:: Interface to zlib compression library
* Config:: access Perl configuration information
* ConfigFile:: Perl module to read and write Windows-like config files
* Convert/UU:: Perl module for uuencode and uudecode
* Crypt/DES:: Perl interface to DES block cipher
* Crypt/IDEA:: Perl interface to IDEA block cipher
* Cwd:: get pathname of current working directory
* DB_File:: Perl5 access to Berkeley DB
* DCE/Login:: Perl extension for interfacing to the DCE login API
* DCE/Registry:: Perl interface to DCE Registry API
* DCE/Status:: Make sense of DCE status codes
* DCE/UUID:: Misc UUID functions
* DCE/login_base:: Constants from sec_login_*.h
* DCE/rgybase:: Constants from dce/rgybase.h
* Data/Dumper:: stringified perl data structures, suitable for both printing and eval
* Data/Flow:: Perl extension for simple-minded recipe-controlled build of data.
* Date/DateCalc:: Date Calculations
* Date/Format:: Date formating subroutines
* Date/Manip:: date manipulation routines
* Date/Parse:: Parse date strings into time values
* Des:: Des extension module for Perl
* Devel/CoreStack:: try to generate a stack dump from a core file
* Devel/DProf:: a Perl code profiler
* Devel/Peek:: A data debugging tool for the XS programmer
* Devel/SelfStubber:: generate stubs for a SelfLoading module
* Devel/Symdump:: dump symbol names or the symbol table
* Devel/TraceFuncs:: trace function calls as they happen.
* DirHandle:: supply object methods for directory handles
* DynaLoader:: Dynamically load C libraries into Perl code
* English:: use nice English (or awk) names for ugly punctuation variables
* Env:: perl module that imports environment variables
* EventServer:: the all singing, all dancing server. Handles i/o driven clients, timer driven clients, and interrupt driven clients, all at the same time. Allows user defined events also. If there are any more types of clients, please tell me.
* Exporter:: Implements default import method for modules
* ExtUtils/Embed:: Utilities for embedding Perl in C/C++ applications
* ExtUtils/Install:: install files from here to there
* ExtUtils/Liblist:: determine libraries to use and how to use them
* ExtUtils/MM_OS2:: methods to override UN*X behaviour in ExtUtils::MakeMaker
* ExtUtils/MM_Unix:: methods used by ExtUtils::MakeMaker
* ExtUtils/MM_VMS:: methods to override UN*X behaviour in ExtUtils::MakeMaker
* ExtUtils/MakeMaker:: create an extension Makefile
* ExtUtils/Manifest:: utilities to write and check a MANIFEST file
* ExtUtils/Miniperl:: write the C code for perlmain.c
* ExtUtils/Mkbootstrap:: make a bootstrap file for use by DynaLoader
* ExtUtils/Mksymlists:: write linker options files for dynamic extension
* ExtUtils/testlib:: add blib/* directories to @INC
* Fatal:: replace functions with equivalents which succeed or die
* Fcntl:: load the C Fcntl.h defines
* File/Basename:: parse file specifications
* File/BasicFlock:: file locking with flock
* File/CheckTree:: run many filetest checks on a tree
* File/Cmp:: compare files
* File/Copy:: Copy files or filehandles
* File/CounterFile:: Persistent counter class
* File/Find:: traverse a file tree
* File/Flock:: file locking with flock
* File/Listing:: parse directory listing
* File/Path:: create or remove a series of directories
* File/PathConvert:: make an canonicalized absolute path name
* File/Recurse:: Recurse over files, performing some function.
* File/Slurp:: single call read & write file routines; read directories
* File/Tools:: This module is a wrapper for the various File moudles.
* FileCache:: keep more files open than the system permits
* FileHandle:: supply object methods for filehandles
* Filter/Util/Call:: Perl Source Filter Utility Module
* Filter/Util/Exec:: exec source filter
* Filter/cpp:: cpp source filter
* Filter/decrypt:: template for a decrypt source filter
* Filter/exec:: exec source filter
* Filter/sh:: sh source filter
* Filter/tee:: tee source filter
* FindBin:: Locate directory of original perl script
* Font/AFM:: Interface to Adobe Font Metrics files
* GD:: Interface to Gd Graphics Library
* GDBM_File:: Perl5 access to the gdbm library.
* Getopt/Long:: extended processing of command line options
* Getopt/Mixed:: getopt processing with both long and short options
* Getopt/Regex:: MISSING SHORT DESCRIPTION
* Getopt/Std:: Process single-character switches with switch clustering
* HTML/AsSubs:: functions that construct a HTML syntax tree
* HTML/Element:: Class for objects that represent HTML elements
* HTML/Entities:: Expand HTML entities in a string
* HTML/FormatPS:: Format HTML as postscript
* HTML/FormatText:: Format HTML as text
* HTML/Formatter:: Base class for HTML formatters
* HTML/HeadParser:: Parse <HEAD> section of a HTML document
* HTML/LinkExtor:: Extract links from an HTML document
* HTML/Parse:: Parse HTML text
* HTML/Parser:: SGML parser class
* HTML/QuickCheck:: a simple and fast HTML syntax checking package for perl 4 and perl 5
* HTML/Stream:: HTML output stream class, and some markup utilities
* HTML/TreeBuilder:: Parser that builds a HTML syntax tree
* HTTP/Daemon:: a simple http server class
* HTTP/Date:: date conversion routines
* HTTP/Headers:: Class encapsulating HTTP Message headers
* HTTP/Message:: Class encapsulating HTTP messages
* HTTP/Negotiate:: choose a variant of a document to serve (HTTP content negotiation)
* HTTP/Request:: Class encapsulating HTTP Requests
* HTTP/Response:: Class encapsulating HTTP Responses
* HTTP/Status:: HTTP Status code processing
* HTTPD/Authen:: HTTP server authentication class
* HTTPD/GroupAdmin:: Management of HTTP server group databases
* HTTPD/UserAdmin:: Management of HTTP server user databases
* I18N/Collate:: compare 8-bit scalar data according to the current locale
* IO:: load various IO modules
* IO/File:: supply object methods for filehandles
* IO/Handle:: supply object methods for I/O handles
* IO/Pipe:: supply object methods for pipes
* IO/Seekable:: supply seek based methods for I/O objects
* IO/Select:: OO interface to the select system call
* IO/Socket:: Object interface to socket communications
* IPC/Open2:: open a process for both reading and writing
* IPC/Open3:: open a process for reading, writing, and error handling
* Image/Size:: read the dimensions of an image in several popular formats
* IniConf:: A Module for reading .ini-style configuration files
* LWP:: Library for WWW access in Perl
* LWP/Debug:: debug routines for the libwww-perl library
* LWP/IO:: Low level I/O capability
* LWP/MediaTypes:: guess media type for a file or a URL.
* LWP/MemberMixin:: Member access mixin class
* LWP/Protocol:: Base class for LWP protocols
* LWP/RobotUA:: A class for Web Robots
* LWP/Simple:: Procedural LWP interface
* LWP/Socket:: TCP/IP socket interface
* LWP/TkIO:: Tk I/O routines for the LWP library
* LWP/UserAgent:: A WWW UserAgent class
* Log/Topics:: control flow of logging messages
* Logfile:: Perl extension for generating reports from logfiles
* MD5:: Perl interface to the RSA Data Security Inc. MD5 Message-Digest Algorithm
* MIME/Base64:: Encode string using base64 encoding
* MIME/Body:: the body of a MIME message
* MIME/Decoder:: an object for decoding the body part of a MIME stream
* MIME/Entity:: class for parsed-and-decoded MIME message
* MIME/Field/ConTraEnc:: a "Content-transfer-encoding" field
* MIME/Field/ContDisp:: a "Content-disposition" field
* MIME/Field/ContType:: a "Content-type" field
* MIME/Field/ParamVal:: subclass of Mail::Field, for structured MIME fields
* MIME/Head:: MIME message header (a subclass of Mail::Header)
* MIME/IO:: a small package for turning things into IO handles
* MIME/Latin1:: translate ISO-8859-1 into 7-bit approximations
* MIME/OLD/ParserUtil:: MIME-parser configuration
* MIME/Parser:: split MIME mail into decoded components
* MIME/ParserBase:: abstract class for parsing MIME mail
* MIME/QuotedPrint:: Encode string using quoted-printable encoding
* MIME/ToolUtils:: MIME-tools kit configuration and utilities
* MLDBM:: store multi-level hash structure in single level tied hash
* Mail/Address:: Parse mail addresses
* Mail/Cap:: Parse mailcap files
* Mail/Field:: Base class for manipulation of mail header fields
* Mail/Folder:: A folder-independant interface to email folders.
* Mail/Folder/Emaul:: An Emaul folder interface for Mail::Folder.
* Mail/Folder/Mbox:: A Unix mbox interface for Mail::Folder.
* Mail/Header:: manipulate mail RFC822 compliant headers
* Mail/Internet:: manipulate Internet format (RFC 822) mail messages
* Mail/MIME:: manipulate MIME (RFC 1521) mail messages
* Mail/Mailer:: Simple interface to electronic mailing mechanisms
* Mail/POP3Client:: Perl 5 module to talk to a POP3 (RFC1081) server
* Mail/Send:: Simple electronic mail interface
* Mail/Util:: mail utility functions
* Make:: module for processing makefiles
* Math/Amoeba:: MISSING SHORT DESCRIPTION
* Math/Approx:: Math::Approx
* Math/BigFloat:: Arbitrary length float math package
* Math/BigInt:: Arbitrary size integer math package
* Math/BigInteger:: Arbitrary length integer extension module for Perl
* Math/Brent:: MISSING SHORT DESCRIPTION
* Math/Complex:: complex numbers and associated mathematical functions
* Math/DVector:: Fast, compact vectors using arrays of double.
* Math/Derivative:: MISSING SHORT DESCRIPTION
* Math/Fortran:: MISSING SHORT DESCRIPTION
* Math/Matrix:: Multiply and invert Matrices
* Math/PRSG:: Perl interface to pseudo random sequence generator function.
* Math/Spline:: MISSING SHORT DESCRIPTION
* Math/Trig:: MISSING SHORT DESCRIPTION
* Math/TrulyRandom:: Perl interface to a truly random number generator function
* Math/VecStat:: MISSING SHORT DESCRIPTION
* Mmap:: uses mmap to map in a file as a perl variable
* Msql/RDBMS:: Relational Database Management System for Msql
* NDBM_File:: Tied access to ndbm files
* NNML/Server:: a minimal NNTP server
* Net/Cmd:: Network Command class (as used by FTP, SMTP etc)
* Net/Domain:: Attempt to evaluate the current host's internet name and domain
* Net/DummyInetd:: A dummy Inetd server
* Net/FTP:: FTP Client class
* Net/NIS:: Interface to Sun's Network Information Service
* Net/NISPlus/Table:: MISSING SHORT DESCRIPTION
* Net/NISTable:: Object Interface to Sun's Network Information Service
* Net/NNTP:: NNTP Client class
* Net/Netrc:: OO interface to users netrc file
* Net/POP3:: Post Office Protocol 3 Client class (RFC1081)
* Net/Ping:: check a host for upness
* Net/SMTP:: Simple Mail transfer Protocol Client
* Net/SNPP:: Simple Network Pager Protocol Client
* Net/SSLeay:: Perl extension for using Eric Young's implementation of SSL
* Net/Socket:: TEMPORARY Socket filedescriptor class, so Net::FTP still works while IO::Socket is having a re-fit <GBARR>
* Net/Telnet:: Defines constants for the telnet protocol
* Net/Time:: time and daytime network client interface
* News/NNTPClient:: Perl 5 module to talk to NNTP (RFC977) server
* News/Newsrc:: manage newsrc files
* ODBM_File:: Tied access to odbm files
* OS2/Attrib:: Get or set OS/2 file attributes
* OS2/SoftInstaller:: Perl extension for generation of daughter packages for IBM's Software Installer.
* Opcode:: Disable named opcodes when compiling perl code
* PDL:: Perl Data Language extension module
* PGP:: perl module to work with PGP messages
* POSIX:: Perl interface to IEEE Std 1003.1
* Parext:: Parity (odd/even) handling functions
* Pari:: Perl interface to PARI.
* Parity:: Parity (mark/space) handling functions
* Penguin/Easy:: provides easy access to Penguin module.
* Pg:: Perl extension for Postgres95
* Pod/Parse:: Parse the pod (Plain Old Documentation) portion of a file
* Pod/Parser:: base class for creating pod filters and translators
* Pod/Select:: function to extract selected sections of pod documentation
* Pod/Text:: convert POD data to formatted ASCII text
* Pod/Usage:: print a usage message using a script's embedded pod documentation
* Pod/foo:: MISSING SHORT DESCRIPTION
* Pod/newrun:: how to execute the Perl interpreter
* Pod/newvar:: Perl predefined variables
* Pod/newvar2:: Perl predefined variables
* Pod/test:: MISSING SHORT DESCRIPTION
* Proc/Forkfunc:: fork off a function
* Proc/Simple:: launch and control background processes
* Religion:: Generate tracebacks and create and install die() and  warn() handlers.
* Remedy/Ar:: Interface to Remedy's Action Request (Version 1.2)
* Resources:: handling application defaults in Perl.
* SDBM_File:: Tied access to sdbm files
* SHA:: Perl interface to the NIST Secure Hash Algorithm
* Safe:: Compile and execute code in restricted compartments
* Search/Base:: provide framework for multiple searches
* Search/Dict:: search for key in dictionary file
* SelectSaver:: save and restore selected file handle
* SelfLoader:: load functions only on demand
* Set/IntSpan:: Manages sets of integers
* Shell:: run shell commands transparently within perl
* Socket:: load the C socket.h defines and structure manipulators
* Sort/Versions:: a perl 5 module for sorting of revision-like numbers
* Sprite:: Perl 5.0 module to manipulate text delimited databases.
* Statistics/ChiSquare:: How random is your data?
* Statistics/LTU:: An implementation of Linear Threshold Units
* Storable:: persistency for perl data structures
* String/Scanf:: emulate the sscanf() of the C stdio library
* Sx:: front-end to all the Athena and Xlib garbage for Perl GUI progamming
* Sybase/BCP:: Simple front end to the Sybase BCP API
* Sybase/Login:: A highly configurable Login widget for Sybperl and Perl/Tk
* Symbol:: manipulate Perl symbols and their names
* Sys/Hostname:: Try every conceivable way to get hostname
* Sys/Syslog:: Perl interface to the UNIX syslog(3) calls
* SysV:: MISSING SHORT DESCRIPTION
* SyslogScan/ByGroup:: Organizes a Summary of mail statistics into Groups of related e-mail users
* SyslogScan/Delivery:: encapsulates a logged, successful delivery of mail from a sender to a list of recipients.
* SyslogScan/DeliveryIterator:: scans a syslog file for "deliveries", successful transfers of mail to mailboxes or to other machines.
* SyslogScan/SendmailLine:: Enhances basic SyslogEntry parsing by understanding sendmail to/from message syntax.
* SyslogScan/SendmailLineFrom:: encapsulates a 'From:' line in a syslog file
* SyslogScan/SendmailLineTo:: encapsulates a 'To:' line in a syslog file
* SyslogScan/SendmailUtil:: utilities for sendmail packages.
* SyslogScan/Summary:: encapsulates a tally of how many bytes people have sent and received through sendmail
* SyslogScan/SyslogEntry:: parses generic lines in syslog files.
* SyslogScan/Usage:: encapsulates the total volumes of mail broadcast, sent, and received through sendmail by a single user or group.
* SyslogScan/WhereIs:: return full path of syslog file where mail messages are logged
* Tcl:: Tcl extension module for Perl
* Tcl/Tk:: MISSING SHORT DESCRIPTION
* Term/Cap:: Perl termcap interface
* Term/Complete:: Perl word completion module
* Term/ReadKey:: A perl module for simple terminal control
* Term/ReadLine:: Perl interface to various `readline' packages. If no real package is found, substitutes stubs instead of basic functions.
* Test/Harness:: run perl standard test scripts with statistics
* Text/Abbrev:: create an abbreviation table from a list
* Text/English:: Porter's stemming algorithm
* Text/German:: German grundform reduction
* Text/ParseWords:: parse text into an array of tokens
* Text/Soundex:: Implementation of the Soundex Algorithm as Described by Knuth
* Text/Tabs:: expand and unexpand tabs per the unix expand(1) and unexpand(1)
* Text/Template:: Expand template text with embedded Perl
* Text/Wrap:: line wrapping to form simple paragraphs
* Tie/Dir:: class definition for reading directories via a tied hash
* Tie/Hash:: base class definitions for tied hashes
* Tie/Scalar:: base class definitions for tied scalars
* Tie/SubstrHash:: Fixed-table-size, fixed-key-length hashing
* Tie/Watch:: place watchpoints on Perl variables.
* Time/CTime:: format times ala POSIX asctime
* Time/DaysInMonth:: simply report the number of days in a month
* Time/HiRes:: Perl extension for ualarm, usleep, and gettimeofday
* Time/JulianDay:: Julian calendar manipulations
* Time/Local:: efficiently compute time from local and GMT time
* Time/ParseDate:: date parsing both relative and absolute
* Time/Timezone:: miscellaneous timezone manipulations routines
* Time/Zone:: miscellaneous timezone manipulations routines
* Tk/FileDialog:: A highly configurable File Dialog widget for Perl/Tk.
* Tk/SelFile:: a widget for choosing a file to read or write
* Tk/WaitBox:: An Object Oriented Wait Dialog for Perl/Tk, of the Please Wait variety.
* UNIVERSAL:: base class for ALL classes (blessed references)
* URI/Escape:: Escape unsafe characters
* URI/URL:: Uniform Resource Locators (absolute and relative)
* VRML:: implements VRML primitives and extensions
* VRML/VRML1:: implements VRML methods with the VRML 1.x standard
* VRML/VRML1/Standard:: implements nodes the VRML 1.x standard
* WWW/RobotRules:: Parse robots.txt files
* WWW/RobotRules/AnyDBM_File:: Persistent RobotRules
* WWW/Search:: Virtual base class for WWW searches
* WWW/Search/AltaVista:: class for searching Alta Vista
* WWW/SearchResult:: class for results returned from WWW::Search
* Xbase:: Perl Module to Read Xbase DBF Files and Foxpro IDX indexes
* diagnostics:: Perl compiler pragma to force verbose warning diagnostics
* gettext:: message handling functions
* integer:: Perl pragma to compute arithmetic in integer instead of double
* iodbc:: Perl extension for the iODBC API
* less:: perl pragma to request less of something from the compiler
* lib:: manipulate @INC at compile time
* lwpcook:: libwww-perl cookbook
* ops:: Perl pragma to restrict unsafe operations when compiling
* overload:: Package for overloading perl operations
* ptkFAQ:: ptkFAQ
* sigtrap:: Perl pragma to enable simple signal handling
* strict:: Perl pragma to restrict unsafe constructs
* subs:: Perl pragma to predeclare sub names
* vars:: Perl pragma to predeclare global variable names


File: pm.info,  Node: Agent,  Next: Alias,  Up: Module List

supplies agentspace methods for perl5.
**************************************

NAME
====

Agent - supplies agentspace methods for perl5.

SYNOPSIS
========

     use Agent;

DESCRIPTION
===========

`Agent::new' creates `Agent' objects,  variables can be stored and
retrieved within the `Agent''s agentspace with the `Agent::add',
`Agent::write', and `Agent::read' methods.  When the `Agent' needs to be
transported,  it can be packed completely via the `Agent::sleep' method.
Once it gets wherever it's going,  use `Agent::wake' to turn it back into
an object.  To set the importance (priority level) of the agentspace,  use
the `Agent::setpriority' method.  You can set the level of priority to
three different values:  `Urgent',  Normal,  and `Low'.  This will
eventully define how much precedence the agentspace will have on a remote
machine,  if lots of other agents are also running.  The `Agent::addcode'
method allows you to add some form of code to the agent.  It does not
matter what language the code is written in,  except when a remote machine
runs it, the particular remote machine must be able to read and parse that
language.

Agent 2.91 `should' be backwardly compatible with the first release of
Agent,  even though Agentspace has had data compartments replaced and
added.

`Agent::new'
============

     $my_agent = new Agent;

     Agent::new creates Agentspace objects.

`Agent::add'
============

     $my_agent->add ( Name => 'A_Variable',  Value => 'Untyped_value' );

     Agent::add allows you to declare new variables inside the Agentspace.

`Agent::write'
==============

     $my_agent->write ( Name => 'An_Existing_Variable', Value => 'New_Value' );

     Agent::write lets you re-write (Modify) existing Agentspace variables.

`Agent::read'
=============

     $my_value = $my_agent->read ( Name => 'A Variable' );
     
     Agent::read lets you read variables out of the Agentspace.

`Agent::addcode'
================

     $my_agent->addcode ( Code => 'any_code' );

     Agent::addcode lets you add information into the Codespace of the Agent.

`Agent::setpriority'
====================

     $my_agent->setpriority ( Level => 'Normal' );

     Agent::setpriority allows you to set the execution priority level of the
     Agentspace agent.  It has three levels: C<Urgent>, C<Normal>,  and C<Low>.
     All agents start with priority level set at normal.

`Agent::sleep'
==============

     $my_var = $my_agent->sleep();

     Agent::sleep returns a packed agentspace variable.  The contents of
     this variable could then be transported in many ways.

`Agent::wake'
=============

     wake $my_agent Agent => $sleeping_agent;

     Agent::wake is used to unpack agentspace created with packself.

`Agent::contents'
=================

     $my_agent_vars = $my_agent->var_contents();
     $my_agent_code = $my_agent->code_contents();
     $my_agent_level = $my_agent->getlevel();

     Agent::contents returns the contents of the various compartments within
     the agentspace.

HISTORY
=======

Agent 1.0   	General idea and bad implementation. `Undistibuted!'
Agent 2.0	Better implementation.	`Undistributed!' Agent 2.9	Decent
implementation. `First Distribtion!' Agent 2.91	Decent
implementation, works with                 Agentspace2 compartments.
`Distributed'

AUTHOR
======

     Agent/Agentspace code written by James Duncan <jduncan@hawk.igs.net>

CREDITS
=======

     Thanks go out to Steve Purkis <spurkis@hawk.igs.net> and everyone who
     has submitted oo modules to CPAN.


File: pm.info,  Node: Alias,  Next: AnyDBM_File,  Prev: Agent,  Up: Module List

declare symbolic aliases for perl data
**************************************

NAME
====

alias - declare symbolic aliases for perl data

attr  - auto-declare hash attributes for convenient access

const - define compile-time scalar constants

SYNOPSIS
========

     use Alias qw(alias const attr);
     alias TEN => $ten, Ten => \$ten, Ten => \&ten,
           Ten => \@ten, Ten => \%ten, TeN => \*ten;
     {
        local @Ten;
        my $ten = [1..10];
        alias Ten => $ten;   # local @Ten
     }

     const pi => 3.14, ten => 10;

     package Foo;
     use Alias;
     sub new { bless {foo => 1, bar => [2, 3]}, $_[0] }
     sub method {
        my $s = attr shift;
        # $foo, @bar are now local aliases for $_[0]{foo}, @{$_[0]{bar}} etc.
     }

DESCRIPTION
===========

Provides general mechanisms for aliasing perl data for convenient access.

Functions
---------

alias
     Given a list of alias-symbol => value pairs, declares aliases in the
     caller's namespace. If the value supplied is a reference, the alias
     is created for the underlying value instead of the reference itself
     (since no one will use this package to alias references-they are
     automatically "aliased" on assignment).  This allows the user to
     alias all of Perl's basic types.

     If the value supplied is a scalar compile-time constant, the aliases
     become read-only. Any attempt to write to them will fail with a run
     time error.

     Aliases can be dynamically scoped by pre-declaring the target symbol
     as a local.  Using attr for is this purpose is more convenient, and
     recommended.

attr
     Given a hash reference, aliases the values of the hash to the names
     that correspond to the keys.  It always returns the supplied value.
     The aliases are local to the enclosing block. If any of the values
     are references, they are available as their dereferenced types.  Thus
     the action is similar to saying:

          alias %{$_[0]}

     but, in addition, also localizes the aliases.

     This can be used for convenient access to hash values and hash-based
     object attributes.

     Note that this makes available the semantics of local subroutines and
     methods.  That makes for some nifty possibilities.  You could make
     truly private methods by putting anonymous subs within an object.
     These subs would be available within methods where you will use attr,
     and will not be visible to the outside world as normal methods.  You
     could forbid recursion in methods by always putting an empty sub in
     the object hash with the same key as the method name. This would be
     useful where a method has to run code from other modules, but cannot
     be certain whether that module will call it back again.

const
     This is simply a function alias for alias, described above.  Provided
     on demand at use time, since it reads better for constant
     declarations.  Note that hashes and arrays cannot be so constrained.

Exports
-------

alias
attr
EXAMPLES
========

     use Alias qw(alias const attr);
     $ten = 10;
     alias TEN => $ten, Ten => \$ten, Ten => \&ten,
     	  Ten => \@ten, Ten => \%ten;
     alias TeN => \*ten;  # same as *TeN = *ten

     # aliasing basic types
     $ten = 20;
     print "$TEN|$Ten|$ten\n";
     sub ten { print "10\n"; }
     @ten = (1..10);
     %ten = (a..j);
     &Ten;
     print @Ten, "|", %Ten, "\n";

     # dynamically scoped aliases
     @DYNAMIC = qw(m n o);
     {
        my $tmp = [ qw(a b c d) ];
        local @DYNAMIC;
        alias DYNAMIC => $tmp, PERM => $tmp;
        $DYNAMIC[2] = 'zzz';
        print @$tmp, "|", @DYNAMIC, "|", @PERM, "\n";
        @DYNAMIC = qw(p q r);
        print @$tmp, "|", @DYNAMIC, "|", @PERM, "\n";
     }
     print @DYNAMIC, "|", @PERM, "\n";

     # named closures
     my($lex) = 'abcd';
     $closure = sub { print $lex, "\n" };
     alias NAMEDCLOSURE => \&$closure;
     NAMEDCLOSURE();
     $lex = 'pqrs';
     NAMEDCLOSURE();

     # hash/object attributes
     package Foo;
     use Alias;
     sub new {
       bless
     	{ foo => 1,
           bar => [2,3],
           buz => { a => 4},
           privmeth => sub { "private" },
           easymeth => sub { die "to recurse or to die, is the question" },
         }, $_[0];
     }

     sub easymeth {
       my $s = attr shift;    # localizes $foo, @bar, %buz etc with values
       eval { $s->easymeth }; # should fail
       print $@ if $@;
       print join '|', $foo, @bar, %buz, $s->privmeth, "\n";
     }

     $foo = 6;
     @bar = (7,8);
     %buz = (b => 9);
     Foo->new->easymeth;
     print join '|', $foo, @bar, %buz, "\n";

     # this should fail at run-time
     eval { Foo->new->privmeth };
     print $@ if $@;

     # and this too
     const _TEN_ => 10;
     $_TEN_ = 20;

NOTES
=====

It is worth repeating that the aliases created by alias and const will be
created in the caller's namespace.  If that namespace happens to be
localized, the aliases created will be local to that block.  attr
localizes the aliases for you.

Aliases cannot be lexical, since, by necessity, they live on the symbol
table.

Lexicals can be aliased. Note that this provides a means of reversing the
action of anonymous type generators `\', `[]' and `{}'.  This allows you
to anonymously construct data or code and give it a symbol-table presence
when you choose.

Any occurrence of `::' or `'' in names will be treated as package
qualifiers, and the value will be aliased in that namespace.

Remember that aliases are very much like references, only you don't have
to de-reference them as often.  Which means you won't have to pound on the
dollars so much.

You can make named closures with this scheme.

It is possible to alias packages, but that might be construed as abuse.

Using this module will dramatically reduce noise characters in
object-oriented perl code.

BUGS
====

`use strict;' is not very usable, since we depend so much on the symbol
table.

Tied variables cannot be aliased properly, yet.

VERSION
=======

Version 2.1       6 April 1996

AUTHOR
======

Gurusamy Sarathy                gsar@umich.edu

Copyright (c) 1995 Gurusamy Sarathy. All rights reserved.  This program is
free software; you can redistribute it and/or modify it under the same
terms as Perl itself.

SEE ALSO
========

perl(1)


File: pm.info,  Node: AnyDBM_File,  Next: Apache,  Prev: Alias,  Up: Module List

provide framework for multiple DBMs
***********************************

NAME
====

AnyDBM_File - provide framework for multiple DBMs

NDBM_File, ODBM_File, SDBM_File, GDBM_File - various DBM implementations

SYNOPSIS
========

     use AnyDBM_File;

DESCRIPTION
===========

This module is a "pure virtual base class"-it has nothing of its own.
It's just there to inherit from one of the various DBM packages.  It
prefers ndbm for compatibility reasons with Perl 4, then Berkeley DB (See
*Note DB_File: DB_File,), GDBM, SDBM (which is always there-it comes with
Perl), and finally ODBM.   This way old programs that used to use NDBM via
dbmopen() can still do so, but new ones can reorder @ISA:

     @AnyDBM_File::ISA = qw(DB_File GDBM_File NDBM_File);

Note, however, that an explicit use overrides the specified order:

     use GDBM_File;
     @AnyDBM_File::ISA = qw(DB_File GDBM_File NDBM_File);

will only find GDBM_File.

Having multiple DBM implementations makes it trivial to copy database
formats:

     use POSIX; use NDBM_File; use DB_File;
     tie %newhash,  'DB_File', $new_filename, O_CREAT|O_RDWR;
     tie %oldhash,  'NDBM_File', $old_filename, 1, 0;
     %newhash = %oldhash;

DBM Comparisons
---------------

Here's a partial table of features the different packages offer:

     odbm    ndbm    sdbm    gdbm    bsd-db
     			 ----	 ----    ----    ----    ------
      Linkage comes w/ perl   yes     yes     yes     yes     yes
      Src comes w/ perl       no      no      yes     no      no
      Comes w/ many unix os   yes     yes[0]  no      no      no
      Builds ok on !unix      ?       ?       yes     yes     ?
      Code Size               ?       ?       small   big     big
      Database Size           ?       ?       small   big?    ok[1]
      Speed                   ?       ?       slow    ok      fast
      FTPable                 no      no      yes     yes     yes
      Easy to build          N/A     N/A      yes     yes     ok[2]
      Size limits             1k      4k      1k[3]   none    none
      Byte-order independent  no      no      no      no      yes
      Licensing restrictions  ?       ?       no      yes     no

[0]
     on mixed universe machines, may be in the bsd compat library, which
     is often shunned.

[1]
     Can be trimmed if you compile for one access method.

[2]
     See *Note DB_File: DB_File,.  Requires symbolic links.

[3]
     By default, but can be redefined.

SEE ALSO
========

dbm(3), ndbm(3), DB_File(3)


File: pm.info,  Node: Apache,  Next: Apache/AccessLimitNum,  Prev: AnyDBM_File,  Up: Module List

Perl interface to the Apache server API
***************************************

NAME
====

Apache - Perl interface to the Apache server API

SYNOPSIS
========

     require Apache;

DESCRIPTION
===========

This module provides a Perl interface the Apache API.  It's here mainly
for *mod_perl*, but may be used for other Apache modules that wish to
embed a Perl interpreter.  We suggest that you also consult the
description of the Apache C API at http://www.apache.org/docs/.

THE REQUEST OBJECT
==================

The request object holds all the information that the server needs to
service a request.  Apache *Perl*Handler*s will be given a reference to the
request object as parameter and may choose update or use it in various
ways.  Most of the methods described below obtain information from or
updates the request object.  The perl version of the request object will
be blessed into the *Apache* package, it is really a `request_rec *' in
disguise.

Apache->request
     The Apache->request method will create a request object and return a
     reference to it.

$r->main
     If the current request is a sub-request, this method returns a blessed
     reference to the main request structure.

$r->is_main
     Returns true if the current request object is for the main request.

CLIENT REQUEST PARAMETERS
=========================

First we will take a look at various methods that can be used to retrieve
the request parameters sent from the client.  In the following examples,
*$r* is a request object blessed into the *Apache* class, obtained by a
handler's first parameter or *Apache->request*

$r->method( [$meth] )
     The $r->method method will return the request method.  It will be a
     string such as "GET", "HEAD" or "POST".  Passing an argument will set
     the method, mainly used for internal redirects.

$r->method_number( [$num] )
     The $r->method_number method will return the request method number.
     Each number corresponds to a string representation such as "GET",
     "HEAD" or "POST".  Passing an argument will set the method_number,
     mainly used for internal redirects and testing authorization
     restriction masks.

$r->proxyreq
     Returns true if the request is proxy http.  Mainly used during the
     filename translation stage of the request, which may be handled by a
     `PerlTransHandler'.

$r->protocol
     The $r->protocol method will return a string identifying the protocol
     that the client speaks.  Typical values will be "HTTP/1.0" or
     "HTTP/1.1".

$r->uri( [$uri] )
     The $r->uri method will return the requested URI, optionally changing
     it with the first argument.

$r->filename( [$filename] )
     The $r->filename method will return the result of the *URI ->
     filename* translation, optionally changing it with the first argument
     if you happen to be doing the translation.

$r->path_info( [$path_info] )
     The $r->path_info method will return what's left in the path after the
     *URI -> filename* translation, optionally changing it with the first
     argument if you happen to be doing the translation.

$r->args
     The $r->args method will return the contents of the URI's *query
     string*.  When called in a scalar context, the entire string is
     returned.  When called in a list context, a list of parsed *key* =>
     value pairs are returned, i.e. it can be used like this:

          $query = $req->args;
          %in    = $req->args;

$r->headers_in
     The $r->headers_in method will return a %hash of client request
     headers.  This can be used to initialize a perl hash, or one could use
     the $r->header_in() method (described below) to retrieve a specific
     header value directly.

$r->header_in( $header_name )
     Return the value of a client header.  Can be used like this:

          $ct = $req->header_in("Content-type");

$r->content
     The $r->content method will return the entity body read from the
     client, but only if the request content type is
     `application/x-www-form-urlencoded'.  When called in a scalar
     context, the entire string is returned.  When called in a list
     context, a list of parsed *key* => value pairs are returned.  *NOTE*:
     you can only ask for this once, as the entire body is read from the
     client.

$r->read_client_block($buf, $bytes_to_read)
     Read from the entity body sent by the client.  Example of use:

          $r->read_client_block($buf, $r->header_in('Content-length'));

$r->read($buf, $bytes_to_read)
     Friendly alias for $r->read_client_block()

$r->get_remote_host
     Lookup the client's DNS hostname.  Might return undef if the hostname
     is not known.

More information about the client can be obtained from the
*Apache::Connection* object, as described below.

$c = $r->connection
     The $r->connection method will return a reference to the request
     connection object (blessed into the *Apache::Connection* package).
     This is really a `conn_rec*' in disguise.  The following methods can
     be used on the connection object:

     $c->remote_host

     $c->remote_ip

     $c->remote_logname

     $c->user; #Returns the remote username if authenticated.

     $c->auth_type; #Returns the authentication scheme used, if any.

     $c->close; #Calling this method will close down the connection to the
     client

SERVER CONFIGURATION INFORMATION
================================

The following methods are used to obtain information from server
configuration and access control files.

$r->dir_config( $key )
     Returns the value of a per-directory variable specified by the
     `PerlSetVar' directive.

          #<Location /foo/bar>
          #SetPerlVar  Key  Value
          #</Location>

          my $val = $r->dir_config('Key');

$r->requires
     Returns an array reference of hash references, containing information
     related to the require directive.  This is normally used for access
     control, see *Note Apache/AuthzAge: Apache/AuthzAge, for an example.

$r->allow_options
$r->is_perlaliased
     The $r->allow_options and $r->is_perlaliased methods can be used for
     checking if it's ok to run a perl script.  The *Apache::Options*
     module provide the constants to check against.

          if(!($r->allow_options & OPT_EXECCGI) && !$r->is_perlaliased) {
              $r->log_reason("Options ExecCGI is off in this directory",
          		    $filename);

$s = $r->server
     Return a reference to the server info object (blessed into the
     *Apache::Server* package).  This is really a `server_rec*' in
     disguise.  The following methods can be used on the server object:

     $s->server_admin; Returns the mail address of the person responsible
     for this server.

     $s->server_hostname; Returns the hostname used by this server.

     $s->port; Returns the port that this servers listens too.

SETTING UP THE RESPONSE
=======================

The following methods are used to set up and return the response back to
the client.  This typically involves setting up $r->status(), the various
content attributes and optionally some additional $r->out_headers() before
calling $r->send_http_header() which will actually send the headers to the
client.  After this a typical application will call the $r->write_client()
method to send the response content to the client.

$r->basic_http_header
     Send the response line (status) along with *Server:* and *Date:*
     headers.

$r->send_http_header
     Send the response line and all headers to the client.  (This method
     will actually call $r->basic_http_header first).

     This method will create headers from the $r->content_xxx() and
     $r->no_cache() attributes (described below) and then append the
     headers defined by $r->header_out (or $r->err_header_out if status
     indicates an error).

$r->get_basic_auth_pw
     If the current request is protected by Basic authentication, this
     method will return 0, otherwise -1.  The second return value will be
     the decoded password sent by the client.

          ($ret, $sent_pw) = $r->get_basic_auth_pw;

$r->note_basic_auth_failure
     Prior to requiring Basic authentication from the client, this method
     will set the outgoing HTTP headers asking the client to authenticate
     for the realm defined by the configuration directive `AuthName'.

$r->handler( [$meth] )
     Set the handler for a request.  Normally set by the configuration
     directive `AddHandler'.

     $r->handler( "perl-script" );

$r->content_type( [$newval] )
     Get or set the content type being sent to the client.  Content types
     are strings like "text/plain", "text/html" or "image/gif".  This
     corresponds to the "Content-Type" header in the HTTP protocol.
     Example of usage is:

          $previous_type = $r->content_type;
          $r->content_type("text/plain");

$r->content_encoding( [$newval] )
     Get or set the content encoding.  Content encodings are string like
     "gzip" or "compress".  This correspond to the "Content-Encoding"
     header in the HTTP protocol.

$r->content_language( [$newval] )
     Get or set the content language.  The content language corresponds to
     the "Content-Language" HTTP header and is a string like "en" or "no".

$r->status( $integer )
     Get or set the reply status for the client request.  The
     *Apache::Constants* module provide mnemonic names for the status
     codes.

$r->status_line( $string )
     Get or set the response status line.  The status line is a string like
     "HTTP/1.0 200 OK" and it will take precedence over the value specified
     using the $r->status() described above.

$r->header_out( $header, $value )
     Change the value of a response header, or create a new one.  You
     should not define any "Content-XXX" headers by calling this method,
     because these headers use their own specific methods.  Example of use:

          $req->header_out("WWW-Authenticate" => "Basic");

$r->err_header_out( $header, $value )
     Change the value of an error response header, or create a new one.
     These headers are used if the status indicates an error.

          $req->err_headers_out("Warning" => "Bad luck");

$r->no_cache( $boolean )
     This is a flag that indicates that the data being returned is volatile
     and the client should be told not to cache it.

$r->write_client( @list_of_data )
     Send data to the client.  Unless you know what you are doing, you
     should only call this method after you have called
     $r->send_http_header.

$r->print()
     Friendly alias for $r->write_client()

$r->send_fd( $filehandle )
     Send the contents of a file to the client.  Can for instance be used
     like this:

          open(FILE, $r->filename) || return 404;
          $r->send_fd(FILE);
          close(FILE);

$r->internal_redirect_handler( $newplace )
     Redirect to a location in the server's namespace without telling the
     client. For instance:

          $r->internal_redirect_handler("/home/sweet/home.html");

CGI SUPPORT
===========

We also provide some methods that make it easier to support the CGI type
of interface.

$r->cgi_env
     Return a %hash that can be used to set up a standard CGI environment.
     Typical usage would be:

          %ENV = $req->cgi_env

     *NOTE:* The $ENV{GATEWAY_INTERFACE} is set to `'CGI-Perl/1.1'' so you
     can say:

          if($ENV{GATEWAY_INTERFACE} =~ /^CGI-Perl/) {
              #do mod_perl stuff
          }
          else {
             #do normal CGI stuff
          }

$r->send_cgi_header()
     Take action on certain headers including *Status:*, *Location:* and
     *Content-type:* just as mod_cgi does, then calls
     $r->send_http_header().  Example of use:

          $req->send_cgi_header("
          Location: /foo/bar
          Content-type: text/html
          
          ");

ERROR LOGGING
=============

The following methods can be used to log errors.

$r->log_reason($message, $file)
     The request failed, why??  Write a message to the server's errorlog.

          $r->log_reason("Because I felt like it", $r->filename);

$r->log_error($message)
     Uh, oh.  Write a message to the server's errorlog.

          $r->log_error("Some text that goes in the error_log");

UTILITY FUNCTIONS
=================

Apache::unescape_url($string)
     Handy function for unescapes.

SEE ALSO
========

perl(1), Apache::Constants(3), Apache::Registry(3), Apache::CGI(3),
Apache::Debug(3), Apache::Options(3)

AUTHORS
=======

Gisle Aas <aas@sn.no> and Doug MacEachern <dougm@osf.org>


File: pm.info,  Node: Apache/AccessLimitNum,  Next: Apache/Authen,  Prev: Apache,  Up: Module List

Limit user access by number of requests
***************************************

NAME
====

Apache::AccessLimitNum - Limit user access by number of requests

SYNOPSIS
========

     #server config file

     PerlModule Apache::AccessLimitNum

     #access control directives

     #use any authentication module
     AuthName SomeRealm
     Auth[DBM]UserFile /path/to/password/file
     
     PerlAccessHandler Apache::AccessLimitNum::handler
     PerlSetVar        AccessLimitNum  100
     PerlSetVar        AccessLimitFile /path/to/limit/file

     <Limit GET>
     require valid-user #or some such
     </Limit>

DESCRIPTION
===========

Decide if an authenticated user has exceeded an access limit for the
requested realm, if so, forbid access.

*AccessLimitFile* is a dbm file consisting of *username* = number value
pairs.  This file must be writeable by httpd server process.

SEE ALSO
========

Apache(3)

AUTHOR
======

Doug MacEachern <dougm@osf.org>


File: pm.info,  Node: Apache/Authen,  Next: Apache/AuthzAge,  Prev: Apache/AccessLimitNum,  Up: Module List

Perl Apache authentication handlers
***********************************

NAME
====

Apache::Authen - Perl Apache authentication handlers

SYNOPSIS
========

     #httpd.conf or srm.conf

     PerlModule Apache::Authen

     #.htaccess
     AuthName DBI
     AuthType Basic

     #authenticate via DBI
     PerlAuthenHandler Apache::DBIAuthen::handler

     PerlSetVar AuthDBIDB     dbname
     PerlSetVar AuthDBIUser   username
     PerlSetVar AuthDBIAuth   password
     PerlSetVar AuthDBIDriver Oracle
     #DBI->connect(qw(AuthDBIDB AuthDBIUser AuthDBIAuth AuthDBIDriver))

     PerlSetVar AuthDBIUserTable www_users
     PerlSetVar AuthDBINameField user
     PerlSetVar AuthDBIPasswordField password

<Limit GET POST> require valid-user </Limit>

DESCRIPTION
===========

With the PerlAuthenHandler set, you may define a subroutine handler to
preform the authentication check.  This module provides some building
blocks and some full-fledged handlers.

HANDLERS
========

Apache::AuthenDBI::handler
     This handler authenticates against a database such as Oracle, DB2,
     Sybase, and others supported by the DBI module.  For supported
     drivers see: http://www.hermetica.com/technologia/DBI

     This handler users *Note HTTPD/UserAdmin: HTTPD/UserAdmin, to lookup
     the username and password.  This may change.

SEE ALSO
========

Apache(3), HTTPD::UserAdmin(3), DBI(3)

AUTHOR
======

Doug MacEachern <dougm@osf.org>


File: pm.info,  Node: Apache/AuthzAge,  Next: Apache/CGI,  Prev: Apache/Authen,  Up: Module List

Authorize based on age
**********************

NAME
====

Apache::AuthzAge - Authorize based on age

SYNOPSIS
========

     #server config file

     PerlModule Apache::AuthzAge

     #access control directives

     #use standard authentication modules
     AuthName SomeRealm
     Auth[DBM]UserFile /path/to/password/file
     
     PerlAuthzHandler Apache::AuthzAge::handler
     PerlSetVar       UserAgeFile  /path/to/dbm_file

     #user must be at least 21
     <Limit GET>
     require age 21
     </Limit>

DESCRIPTION
===========

Decide if an authenticated user is authorized to complete a request based
on age.

*UserAgeFile* is a dbm file consisting of *username* = *age* value pairs.

SEE ALSO
========

Apache(3)

AUTHOR
======

Doug MacEachern <dougm@osf.org>


File: pm.info,  Node: Apache/CGI,  Next: Apache/Debug,  Prev: Apache/AuthzAge,  Up: Module List

Make things work with CGI.pm against Perl-Apache API
****************************************************

NAME
====

Apache::CGI - Make things work with CGI.pm against Perl-Apache API

SYNOPSIS
========

     require Apache::CGI;

     my $q = new Apache::CGI;

     $q->print($q->header);

     #do things just like you do with CGI.pm

DESCRIPTION
===========

When using the Perl-Apache API, your applications are faster, but the
enviroment is different than CGI.  This module attempts to set-up that
environment as best it can.

SEE ALSO
========

perl(1), Apache(3), CGI(3)

AUTHOR
======

Doug MacEachern <dougm@osf.org>, hacked over by Andreas König
<a.koenig@mind.de>


File: pm.info,  Node: Apache/Debug,  Next: Apache/MsqlProxy,  Prev: Apache/CGI,  Up: Module List

Utilities for debugging embedded perl code
******************************************

NAME
====

Apache::Debug - Utilities for debugging embedded perl code

SYNOPSIS
========

     require Apache::Debug;

     Apache::Debug::dump(Apache->request, 500, "Uh Oh!");

DESCRIPTION
===========

This module sends what may be helpful debugging info to the client rather
that the error log.


File: pm.info,  Node: Apache/MsqlProxy,  Next: Apache/Options,  Prev: Apache/Debug,  Up: Module List

Translate URI's into mSQL database queries
******************************************

NAME
====

Apache::MsqlProxy - Translate URI's into mSQL database queries

SYNOPSIS
========

     #httpd.conf or srm.conf
     PerlTransHandler Apache::MsqlProxy::translate
     PerlHandler      Apache::MsqlProxy::handler
     PerlModule       Apache::MsqlProxy

Configure your browser's HTTP proxy to point at the host running Apache
configured with this module:

     http://hostname.domain/

When connecting to the server via normal HTTP (not proxy), URLs are not
translated.

URL's are translated as follows:

     http://hostname/database_name/table_name

Connect to hostname via TCP, select database *database_name*, query table
<table_name> with:

     SELECT * from table_name

     http://hostname/database_name/table_name?login_name=dougm

Same as above with query:

     SELECT login_name from table where login_name=dougm

     http://hostname/database_name/table_name/*?login_name=dougm

Same as above with query:

     SELECT * from table where login_name=dougm

Of course,

     http:///database_name/table_name

A null hostname connects via UNIX socket

     http://hostname:9876/database_name/table_name

Connect via TCP to hostname and port 9876

DESCRIPTION
===========

This module is meant as an example to show how one can use Apache +
mod_perl to handle HTTP proxy requests, or simply translating a URL.

It may not be very useful other than as an example, but feel free to
change that.

SEE ALSO
========

Apache(3), Msql(3)

AUTHOR
======

Doug MacEachern <dougm@osf.org>


File: pm.info,  Node: Apache/Options,  Next: Apache/Registry,  Prev: Apache/MsqlProxy,  Up: Module List

OPT_* defines from httpd_core.h
*******************************

NAME
====

Apache::Options - OPT_* defines from httpd_core.h

DESCRIPTION
===========

The *Apache::Options* module will export the following bitmask constants:

     OPT_NONE
     OPT_INDEXES
     OPT_INCLUDES
     OPT_SYMLINKS
     OPT_EXECCGI
     OPT_UNSET
     OPT_INCNOEXEC
     OPT_SYM_OWNER
     OPT_MULTI
     OPT_ALL

These constants can be used to check the return value from
Apache->request->allow_options() method.

This module is simply a stub which imports from `Apache::Constants' in
this node, just as if you had said `use Apache::Constants ':options';'.

SEE ALSO
========

*Note Apache: Apache,, `Apache::Constants' in this node


File: pm.info,  Node: Apache/Registry,  Next: Apache/SSI,  Prev: Apache/Options,  Up: Module List

Run (mostly) unaltered CGI scripts through mod_perl_fast
********************************************************

NAME
====

Apache::Registry - Run (mostly) unaltered CGI scripts through mod_perl_fast

SYNOPSIS
========

     #in srm.conf

     PerlAlias /perl/ /perl/apache/scripts/ #optional
     PerlModule Apache::Registry
     
     AddHandler perl-script .fpl
     
     #in access.conf
     <Directory /perl/apache/scripts>
     PerlHandler Apache::Regsistry::handler
     ...
     </Directory>

DESCRIPTION
===========

URIs in the form of:  http://www.host.com/perl/file.fpl

Will be compiled as the body of a perl subroutine and executed.  Each
server process or 'child' will compile the subroutine once and store it in
memory until the file is updated on the disk.

The file looks much like a "normal" script, but it is compiled or 'evaled'
into a subroutine.

Here's an example:

     my $r = Apache->request;
     $r->content_type("text/html");
     $r->send_http_header;
     $r->print("Hi There!");

Apache::Registry::handler will preform the same checks as mod_cgi before
running the script.

SEE ALSO
========

perl(1), Apache(3)

AUTHORS
=======

Andreas Koenig <andreas.koenig@franz.ww.tu-berlin.de> and Doug MacEachern
<dougm@osf.org>


File: pm.info,  Node: Apache/SSI,  Next: Apache/TieHandle,  Prev: Apache/Registry,  Up: Module List

Implement Server Side Includes in Perl
**************************************

NAME
====

Apache::SSI - Implement Server Side Includes in Perl

SYNOPSIS
========

wherever you choose: AddType text/x-perl-server-parsed-html .phtml

add this to srm.conf: PerlScript Apache::SSI

in access.conf or .htaccess say: PerlResponse Apache::SSI::handler

You may wish to subclass Apache::SSI for your own extentions

     package MySSI;
     require Apache::SSI;
     @ISA = qw(Apache::SSI);

     #embedded syntax:
     #<!--#something cmd=doit -->
     sub something {
        my($self, $attr) = @_;
        my $cmd = $attr->{cmd};
        ...
        return $a_string;
     }

DESCRIPTION
===========

Apache::SSI implements the functionality of mod_include for handling
server-parsed html documents.  Each "command" or element is handled by an
Apache::SSI method of the same name.  attribute=value pairs are parsed and
passed to the method in an anonymous hash.

This module supports the same directives as mod_include, see it's
documentation for commands and syntax.

In addition, Apache::SSI supports the following directives:

perlsub
     This directive calls a perl subroutine:

          Hello user from <!--#perlsub sub=remote_host -->

CAVEATS
=======

This module is not complete, it does not provide the full functionality of
mod_include.

There is no support for xssi directives.

SEE ALSO
========

mod_include, mod_perl_fast, HTML::TreeBuilder(3), perl(1), Apache(3)

AUTHOR
======

Doug MacEachern <dougm@osf.org>


File: pm.info,  Node: Apache/TieHandle,  Next: Archie,  Prev: Apache/SSI,  Up: Module List

tie stdio to Apache's i/o methods
*********************************

NAME
====

Apache::TieHandle - tie stdio to Apache's i/o methods

SYNOPSIS
========

     use Apache::TieHandle ();

     tie *STDOUT => 'Apache::TieHash';

     print "Content-type: text/html\n\n" .
          "Ah, just like CGI\n";

DESCRIPTION
===========

This module tie's stdio filehandles to Apache's i/o methods.

*** NOTE *** This is experimental, you must apply Sven Verdoolaege's patch
'pp_hot.patch' for it to work

AUTHOR
======

Well, Doug MacEachern wrote it, but it wouldn't be possible without the
efforts of Larry Wall and the fearless perl5-porters who implemented tie'd
filehandles...


File: pm.info,  Node: Archie,  Next: AtExit,  Prev: Apache/TieHandle,  Up: Module List

Perl module to make Archie queries via Prospero requests
********************************************************

NAME
====

Archie - Perl module to make Archie queries via Prospero requests

DESCRIPTION
===========

The Archie module finds files available via anonymous ftp by making
requests to an Archie server.  The package communicates with the Archie
server via the Prospero protocol, which is layered on the Asynchronous
Reliable Delivery Protocol, which is layered on UDP.

The usual entry point is Archie::archie_request, which takes arguments
similar to the Unix archie command-line client, and returns an array of
hash references which point to the returned data.

The routine Archie::archie_cancel cancels the request on the server; this
stops the server from sending packets to a canceled client process.

This release is $Revision: 1.5 $.

EXAMPLE
=======

     use Archie;
     
     $SIG{'INT'} = 'sig_handler';
     
     [...]
     @responses = Archie::archie_request($server,$match,$order,
                                         $max_hits,$niceness,$user,
                                         $timeout,@searchterms);
     if ($Archie::ArchieErr) {
         print "Error: $Archie::ArchieErr\n";
     }
     else {
         foreach $response (@responses) {
             print "name: $response->{'name'}\n";
             print "   host: $response->{'host'}\n";
             print "   type: $response->{'type'}\n";
             print "   dir: $response->{'dir'}\n";
             print "   size: $response->{'size'}\n";
             print "   mode: $response->{'mode'}\n";
             print "   lastmod: $response->{'lastmod'}\n";
         }
     }
     
     sub sig_handler {
         my($sig) = @_;
         &Archie::archie_cancel();
         exit;
     }

NOTES
=====

The Prospero parser is incomplete and only really deals with standard
Archie responses - this should be generalized.

The archie service was conceived and implemented by Alan Emtage, Peter
Deutsch, and Bill Heelan.  The entire Internet is in their debt.

The Prospero system was created by Clifford Neuman <bcn@isi.edu>; write to
<info-prospero@isi.edu> for more information on the protocol and its use.

SEE ALSO
========

The archie man pages.

Information about Prospero and ARDP is available from ftp.isi.edu.

AUTHOR
======

Greg Bossert <bossert@noc.rutgers.edu


File: pm.info,  Node: AtExit,  Next: AutoLoader,  Prev: Archie,  Up: Module List

Register a subroutine to be invoked at program-exit time.
*********************************************************

NAME
====

atexit - Register a subroutine to be invoked at program-exit time.

rmexit - Unregister a subroutine that was registered with atexit.

SYNOPSIS
========

     use AtExit;
     
     sub cleanup {
         my @args = @_;
         print "cleanup() executing: args = @args\n";
     }
     
     $_ = atexit(\&cleanup, "This call was registered first");
     print "first call to atexit() returned $_\n";

     $_ = atexit("cleanup", "This call was registered second");
     print "second call to atexit() returned $_\n";

     $_ = atexit("cleanup", "This call should've been unregistered by rmexit");
     rmexit($_)  ||  warn "couldnt' unregister exit-sub $_!";

     END {
         print "*** Now performing program-exit processing ***\n";
     }

DESCRIPTION
===========

The *AtExit* module provides ANSI-C style exit processing modeled after
the `atexit()' function in the standard C library (see `atexit(3C)' in
this node).  Various exit processing routines may be registered by calling
`atexit()' and passing it the desired subroutine along with any desired
arguments. Then, at program-exit time, the subroutines registered with
`atexit()' are invoked with their given arguments in the reverse order of
registration (last one registered is invoked first).  Registering the same
subroutine more than once will cause that subroutine to be invoked once
for each registration.

The `atexit()' function exported by *AtExit* should be passed a subroutine
name or reference, optionally followed by the list of arguments with which
to invoke it at program-exit time.  Anonymous subroutine references passed
to `atexit()' act as "closures" (which are described in *Note Perlref:
(perl.info)perlref,).  If a subroutine *name* is specified (as opposed to
a subroutine reference) then, unless the subroutine name has an explicit
package prefix, it is assumed to be the name of a subroutine in the
caller's current package.  A reference to the specified subroutine is
obtained, and, if invocation arguments were specified, it is "wrapped up"
in a closure which invokes the subroutine with the specified arguments.
The resulting subroutine reference is prepended to the front of the
`@AtExit::EXIT_SUBS' list of exit-handling subroutines and the reference
is then returned to the caller (just in case you might want to unregister
it later using `rmexit()'). If the given subroutine could *not* be
registered, then the value zero is returned.

The `rmexit()' function exported by *AtExit* should be passed one or more
subroutine references, each of which was returned by a previous call to
`atexit()'. For each argument given, `rmexit()' will look for it in the
`@AtExit::EXIT_SUBS' list of exit-handling subroutines and remove the
first such match from the list. The value returned will be the number of
subroutines that were successfully unregistered.

At program-exit time, the `END{}' block in the *AtExit* module iterates
over the subroutine references in the `@AtExit::EXIT_SUBS' array and
invokes each one in turn (each subroutine is removed from the front of the
queue immediately before it is invoked).  Note that the subroutines in
this queue are invoked in first-to-last order (the reverse order in which
they were registered with `atexit()').

Invoking `atexit()' and `rmexit()' during program-exit
------------------------------------------------------

The variable `$AtExit::IGNORE_WHEN_EXITING' specifies how calls to
`atexit()' will be handled if they occur during the time that subroutines
registered with `atexit()' are being invoked.  By default, this variable
is set to a non-zero value, which causes `atexit()' to *ignore* any calls
made to it during this time (a value of zero will be returned). This
behavior is consistent with that of the standard C library function of the
same name. If desired however, the user may enable the registration of
subroutines by `atexit()' during this time by setting
`$AtExit::IGNORE_WHEN_EXITING' to zero or to the empty string. Just
remember that any subroutines registered with `atexit()' during
program-exit time will be placed at the *front* of the queue of
yet-to-be-invoked exit-processing subroutines.

Regardless of when it is invoked, `rmexit()' will *always* attempt to
unregister the given subroutines (even when called during program-exit
processing). Keep in mind however that if it is invoked during program-exit
processing then it will *fail* to unregister any exit-processing
subroutines that have *already been invoked* by the `END{}' block in the
*AtExit* module (since those subroutine calls have already been removed
from the `@AtExit::EXIT_SUBS' list).

The variable `$AtExit::EXITING' may be examined to determine if routines
registered using `atexit()' are currently in the process of being invoked.
It will be non-zero if they are and zero otherwise.

NOTES
=====

The usual Perl way of doing exit processing is through the use of `END{}'
blocks (see `"Package Constructors and Destructors"', *Note Perlmod:
(perl.info)perlmod,).  The *AtExit* module implements its exit processing
with an `END{}' block that invokes all the subroutines registered by
`atexit()' in the array `@AtExit::EXIT_SUBS'.  If any other `END{}' block
processing is specified in the user's code or in any other packages it
uses, then the order in which the exit processing takes place is subject
to Perl's rules for the order in which `END{}' blocks are processed. This
may affect when subroutines registered with `atexit()' are invoked with
respect to other exit processing that is to be performed. In particular,
if `atexit()' is invoked from within an `END{}' block that executes
*after* the `END{}' block in the *AtExit* module, then the corresponding
subroutine that was registered will never be invoked by the *AtExit*
module's exit-processing code.

`END{}' block processing order
------------------------------

`END{}' blocks, including those in other packages, get called in the
reverse order in which they appear in the code. (`atexit()' subroutines
get called in the reverse order in which they are registered.) If a
package gets read via "use", it will act as if the `END{}' block was
defined at that particular part of the "main" code.  Packages read via
"require" will be executed after the code of "main" has been parsed and
will be seen last so will execute first (they get executed in the context
of the package in which they exist).

It is important to note that `END{}' blocks only get called on normal
termination (which includes calls to `die()' or `Carp::croak()'). They do
*not* get called when the program terminates *abnormally* (due to a signal
for example) unless special arrangements have been made by the programmer
(e.g. using a signal handler - see `"%SIG{expr}"', *Note Perlvar:
(perl.info)perlvar,).

SEE ALSO
========

`atexit(3C)' in this node describes the `atexit()' function for the
standard C library (the actual Unix manual section in which it appears may
differ from platform to platform - try sections 3C, 3, 2C, and 2).  Further
information on anonymous subroutines ("closures") may be found in *Note
Perlref: (perl.info)perlref,.  For more information on `END{}' blocks, see
`"Package Constructors and Destructors"', *Note Perlmod:
(perl.info)perlmod,.  See `"%SIG{expr}"', *Note Perlvar:
(perl.info)perlvar, for handling abnormal program termination.

AUTHOR
======

Andrew Langmead <aml@world.std.com> (initial draft).

Brad Appleton <Brad_Appleton-GBDA001@email.mot.com> (final version).


File: pm.info,  Node: AutoLoader,  Next: AutoSplit,  Prev: AtExit,  Up: Module List

load functions only on demand
*****************************

NAME
====

AutoLoader - load functions only on demand

SYNOPSIS
========

     package FOOBAR;
     use Exporter;
     use AutoLoader;
     @ISA = qw(Exporter AutoLoader);

DESCRIPTION
===========

This module tells its users that functions in the FOOBAR package are to be
autoloaded from `auto/$AUTOLOAD.al'.  See `"Autoloading"', *Note Perlsub:
(perl.info)perlsub, and `"Autoloading"', *Note AutoSplit: AutoSplit,.

__END__
-------

The module using the autoloader should have the special marker __END__
prior to the actual subroutine declarations. All code that is before the
marker will be loaded and compiled when the module is used. At the marker,
perl will cease reading and parsing. See also the AutoSplit module, a
utility that automatically splits a module into a collection of files for
autoloading.

When a subroutine not yet in memory is called, the AUTOLOAD function
attempts to locate it in a directory relative to the location of the module
file itself. As an example, assume `POSIX.pm' is located in
`/usr/local/lib/perl5/POSIX.pm'. The autoloader will look for perl
subroutines for this package in `/usr/local/lib/perl5/auto/POSIX/*.al'.
The `.al' file is named using the subroutine name, sans package.

Loading Stubs
-------------

The AutoLoader module provide a special import() method that will load the
stubs (from `autosplit.ix' file) of the calling module.  These stubs are
needed to make inheritance work correctly for class modules.

Modules that inherit from AutoLoader should always ensure that they
override the AutoLoader->import() method.  If the module inherit from
Exporter like shown in the *synopis* section this is already taken care
of.  For class methods an empty import() would do nicely:

     package MyClass;
     use AutoLoader;        # load stubs
     @ISA=qw(AutoLoader);
     sub import {}          # hide AutoLoader::import

You can also set up autoloading by importing the AUTOLOAD function instead
of inheriting from AutoLoader:

     package MyClass;
     use AutoLoader;        # load stubs
     *AUTOLOAD = \&AutoLoader::AUTOLOAD;

Package Lexicals
----------------

Package lexicals declared with my in the main block of a package using the
AutoLoader will not be visible to auto-loaded functions, due to the fact
that the given scope ends at the __END__ marker. A module using such
variables as package globals will not work properly under the AutoLoader.

The vars pragma (see `"vars"', *Note Perlmod: (perl.info)perlmod,) may be
used in such situations as an alternative to explicitly qualifying all
globals with the package namespace. Variables pre-declared with this
pragma will be visible to any autoloaded routines (but will not be
invisible outside the package, unfortunately).

AutoLoader vs. SelfLoader
-------------------------

The AutoLoader is a counterpart to the SelfLoader module. Both delay the
loading of subroutines, but the SelfLoader accomplishes the goal via the
`__DATA__' marker rather than __END__. While this avoids the use of a
hierarchy of disk files and the associated open/close for each routine
loaded, the SelfLoader suffers a disadvantage in the one-time parsing of
the lines after `__DATA__', after which routines are cached. SelfLoader
can also handle multiple packages in a file.

AutoLoader only reads code as it is requested, and in many cases should be
faster, but requires a machanism like AutoSplit be used to create the
individual files.  The ExtUtils::MakeMaker will invoke AutoSplit
automatically if the AutoLoader is used in a module source file.

CAVEAT
======

On systems with restrictions on file name length, the file corresponding
to a subroutine may have a shorter name that the routine itself. This can
lead to conflicting file names. The AutoSplit package warns of these
potential conflicts when used to split a module.

Calling foo($1) for the autoloaded function foo() might not work as
expected, because the AUTOLOAD function of AutoLoader clobbers the regexp
variables.  Invoking it as foo("$1") avoids this problem.


File: pm.info,  Node: AutoSplit,  Next: B/Xref,  Prev: AutoLoader,  Up: Module List

split a package for autoloading
*******************************

NAME
====

AutoSplit - split a package for autoloading

SYNOPSIS
========

     perl -e 'use AutoSplit; autosplit_lib_modules(@ARGV)' ...

     use AutoSplit; autosplit($file, $dir, $keep, $check, $modtime);

for perl versions 5.002 and later:

     perl -MAutoSplit -e 'autosplit($ARGV[0], $ARGV[1], $k, $chk, $modtime)' ...

DESCRIPTION
===========

This function will split up your program into files that the AutoLoader
module can handle. It is used by both the standard perl libraries and by
the MakeMaker utility, to automatically configure libraries for
autoloading.

The `autosplit' interface splits the specified file into a hierarchy
rooted at the directory `$dir'. It creates directories as needed to reflect
class hierarchy, and creates the file `autosplit.ix'. This file acts as
both forward declaration of all package routines, and as timestamp for the
last update of the hierarchy.

The remaining three arguments to `autosplit' govern other options to the
autosplitter. If the third argument, *$keep*, is false, then any
pre-existing `.al' files in the autoload directory are removed if they are
no longer part of the module (obsoleted functions). The fourth argument,
*$check*, instructs `autosplit' to check the module currently being split
to ensure that it does include a use specification for the AutoLoader
module, and skips the module if AutoLoader is not detected. Lastly, the
*$modtime* argument specifies that `autosplit' is to check the
modification time of the module against that of the `autosplit.ix' file,
and only split the module if it is newer.

Typical use of AutoSplit in the perl MakeMaker utility is via the
command-line with:

     perl -e 'use AutoSplit; autosplit($ARGV[0], $ARGV[1], 0, 1, 1)'

Defined as a Make macro, it is invoked with file and directory arguments;
`autosplit' will split the specified file into the specified directory and
delete obsolete `.al' files, after checking first that the module does use
the AutoLoader, and ensuring that the module is not already currently split
in its current form (the modtime test).

The `autosplit_lib_modules' form is used in the building of perl. It takes
as input a list of files (modules) that are assumed to reside in a
directory *lib* relative to the current directory. Each file is sent to the
autosplitter one at a time, to be split into the directory *lib/auto*.

In both usages of the autosplitter, only subroutines defined following the
perl special marker __END__ are split out into separate files. Some
routines may be placed prior to this marker to force their immediate
loading and parsing.

CAVEATS
=======

Currently, AutoSplit cannot handle multiple package specifications within
one file.

DIAGNOSTICS
===========

AutoSplit will inform the user if it is necessary to create the top-level
directory specified in the invocation. It is preferred that the script or
installation process that invokes AutoSplit have created the full directory
path ahead of time. This warning may indicate that the module is being
split into an incorrect path.

AutoSplit will warn the user of all subroutines whose name causes potential
file naming conflicts on machines with drastically limited (8 characters or
less) file name length. Since the subroutine name is used as the file name,
these warnings can aid in portability to such systems.

Warnings are issued and the file skipped if AutoSplit cannot locate either
the __END__ marker or a "package Name;"-style specification.

AutoSplit will also emit general diagnostics for inability to create
directories or files.


File: pm.info,  Node: B/Xref,  Next: BSD/Resource,  Prev: AutoSplit,  Up: Module List

Generates cross reference reports for Perl programs
***************************************************

NAME
====

B::Xref - Generates cross reference reports for Perl programs

SYNOPSIS
========

perl -MO=Xref[,OPTIONS] foo.pl

DESCRIPTION
===========

The B::Xref module is used to generate a cross reference listing of all
definitions and uses of variables, subroutines and formats in a Perl
program.  It is implemented as a backend for the Perl compiler.

The report generated is in the following format:

     File filename1
       Subroutine subname1
     	Package package1
     	  object1        C<line numbers>
     	  object2        C<line numbers>
     	  ...
     	Package package2
     	...

Each *File* section reports on a single file. Each Subroutine section
reports on a single subroutine apart from the special cases
"(definitions)" and "(main)". These report, respectively, on subroutine
definitions found by the initial symbol table walk and on the main part of
the program or module external to all subroutines.

The report is then grouped by the Package of each variable, subroutine or
format with the special case "(lexicals)" meaning lexical variables. Each
*object* name (implicitly qualified by its containing Package) includes
its type character(s) at the beginning where possible. Lexical variables
are easier to track and even included dereferencing information where
possible.

The `line numbers' are a comma separated list of line numbers (some
preceded by code letters) where that object is used in some way.  Simple
uses aren't preceded by a code letter. Introductions (such as where a
lexical is first defined with my) are indicated with the letter "i".
Subroutine and method calls are indicated by the character "&".
Subroutine definitions are indicated by "s" and format definitions by "f".

OPTIONS
=======

Option words are separated by commas (not whitespace) and follow the usual
conventions of compiler backend options.

`-oFILENAME'
     Directs output to `FILENAME' instead of standard output.

-r
     Raw output. Instead of producing a human-readable report, outputs a
     line in machine-readable form for each definition/use of a
     variable/sub/format.

`-D[tO]'
     (Internal) debug options, probably only useful if -r included.  The t
     option prints the object on the top of the stack as it's being
     tracked. The O option prints each operator as it's being processed in
     the execution order of the program.

BUGS
====

Non-lexical variables are quite difficult to track through a program.
Sometimes the type of a non-lexical variable's use is impossible to
determine. Introductions of non-lexical non-scalars don't seem to be
reported properly.

AUTHOR
======

Malcolm Beattie, mbeattie@sable.ox.ac.uk.


File: pm.info,  Node: BSD/Resource,  Next: Benchmark,  Prev: B/Xref,  Up: Module List

BSD process resource limit and priority functions
*************************************************

NAME
====

BSD::Resource - BSD process resource limit and priority functions

SYNOPSIS
========

     use BSD::Resource;

     ($usertime, $systemtime,
      $maxrss, $ixrss, $idrss, $isrss, $minflt, $majflt, $nswap,
      $inblock, $oublock, $msgsnd, $msgrcv,
      $nsignals, $nvcsw, $nivcsw) = getrusage($ru_who);

     ($nowsoft, $nowhard) = getrlimit($resource);

     $nowpriority = getpriority($which, $pr_ywho);

     $success = setrlimit($resource, $newsoft, $newhard);

     $success = setpriority($which, $who, $priority);

DESCRIPTION
===========

getrusage
---------

For a detailed description about the values returned by getrusage() please
consult your usual C programming documentation about getrusage() and also
the header file `sys/resource.h'.  The $ru_who argument is either
RUSAGE_SELF (the current process) or RUSAGE_CHILDREN (all the child
processes of the current process).  On some (very few) systems (those
supporting both getrusage() and the POSIX threads) there is also
RUSAGE_THREAD. The BSD::Resource supports the _THREAD flag if it is
present but understands nothing about the POSIX threads themselves.

Note 1: officially HP-UX 9 does not support getrusage() at all but for the
time being, it does seem to.

Note 2: Solaris claims in `sys/rusage.h' that the `ixrss' and the `isrss'
fields are always zero.

getrlimit
---------

Processes have soft and hard resource limits.  At soft limit they receive
a signal (XCPU or XFSZ, normally) they can trap and handle and at hard
limit they will be ruthlessly killed by the KILL signal.  The $resource
argument can be one of

     RLIMIT_CPU RLIMIT_FSIZE
     RLIMIT_DATA RLIMIT_STACK RLIMIT_CORE RLIMIT_RSS
     RLIMIT_NOFILE RLIMIT_OPEN_MAX
     RLIMIT_AS RLIMIT_VMEM

The last two pairs (NO_FILE, OPEN_MAX) and (AS, VMEM) mean the same, the
former being the BSD names and the latter SVR4 names.  Two
meta-resource-symbols might exist

     RLIM_NLIMITS
     RLIM_INFINITY

NLIMITS being the number of possible (but not necessarily fully supported)
resource limits, INFINITY being useful in setrlimit().

NOTE: the level of 'support' for a resource varies. Not all the systems

     a) even recognise all those limits
     b) really track the consumption of a resource
     c) care (send those signals) if a resource limit get exceeded

Again, please consult your usual C programming documentation.

One notable exception: officially HP-UX 9 does not support getrlimit() at
all but for the time being, it does seem to.

getpriority
-----------

The priorities returned by getpriority() are [PRIO_MIN,PRIO_MAX].  The
$which argument can be any of PRIO_PROCESS (a process) PRIO_USER (a user),
or PRIO_PGRP (a process group). The $pr_who argument tells which
process/user/process group, 0 signifying the current one.

setrlimit
---------

A normal user process can only lower its resource limits.  Soft or hard
limit RLIM_INFINITY means as much as possible, the real limits are
normally buried inside the kernel.

setpriority
-----------

The priorities handled by setpriority() are [PRIO_MIN,PRIO_MAX].  A normal
user process can only lower its priority (make it more positive).

EXAMPLES
========

     # the user and system times so far by the process itself

     ($usertime, $systemtime) = getrusage(RUSAGE_SELF);

     # get the current priority level of this process

     $currprio = getpriority(PRIO_PROCESS, 0);

VERSION
=======

v1.0, $Id: Resource.pm,v 1.6 1995/12/18 08:32:00 jhi Exp $

AUTHOR
======

Jarkko Hietaniemi, `Jarkko.Hietaniemi@hut.fi'


File: pm.info,  Node: Benchmark,  Next: BitCount,  Prev: BSD/Resource,  Up: Module List

benchmark running times of code
*******************************

NAME
====

Benchmark - benchmark running times of code

timethis - run a chunk of code several times

timethese - run several chunks of code several times

timeit - run a chunk of code and see how long it goes

SYNOPSIS
========

     timethis ($count, "code");

     timethese($count, {
     	'Name1' => '...code1...',
     	'Name2' => '...code2...',
     });

     $t = timeit($count, '...other code...')
     print "$count loops of other code took:",timestr($t),"\n";

DESCRIPTION
===========

The Benchmark module encapsulates a number of routines to help you figure
out how long it takes to execute some code.

Methods
-------

new
     Returns the current time.   Example:

          use Benchmark;
          $t0 = new Benchmark;
          # ... your code here ...
          $t1 = new Benchmark;
          $td = timediff($t1, $t0);
          print "the code took:",timestr($td),"\n";

debug
     Enables or disable debugging by setting the `$Benchmark::Debug' flag:

          debug Benchmark 1;
          $t = timeit(10, ' 5 ** $Global ');
          debug Benchmark 0;

Standard Exports
----------------

The following routines will be exported into your namespace if you use the
Benchmark module:

timeit(COUNT, CODE)
     Arguments: COUNT is the number of time to run the loop, and the
     second is the code to run.  CODE may be a string containing the code,
     a reference to the function to run, or a reference to a hash
     containing keys which are names and values which are more CODE specs.

     Side-effects: prints out noise to standard out.

     Returns: a Benchmark object.

timethis
timethese
timediff
timestr
Optional Exports
----------------

The following routines will be exported into your namespace if you
specifically ask that they be imported:

clearcache

clearallcache

disablecache

enablecache

NOTES
=====

The data is stored as a list of values from the time and times functions:

     ($real, $user, $system, $children_user, $children_system)

in seconds for the whole loop (not divided by the number of rounds).

The timing is done using time(3) and times(3).

Code is executed in the caller's package.

Enable debugging by:

     $Benchmark::debug = 1;

The time of the null loop (a loop with the same number of rounds but empty
loop body) is subtracted from the time of the real loop.

The null loop times are cached, the key being the number of rounds. The
caching can be controlled using calls like these:

     clearcache($key);
     clearallcache();

     disablecache();
     enablecache();

INHERITANCE
===========

Benchmark inherits from no other class, except of course for Exporter.

CAVEATS
=======

The real time timing is done using time(2) and the granularity is
therefore only one second.

Short tests may produce negative figures because perl can appear to take
longer to execute the empty loop than a short test; try:

     timethis(100,'1');

The system time of the null loop might be slightly more than the system
time of the loop with the actual code and therefore the difference might
end up being < 0.

More documentation is needed :-( especially for styles and formats.

AUTHORS
=======

Jarkko Hietaniemi <`Jarkko.Hietaniemi@hut.fi'>, Tim Bunce
<`Tim.Bunce@ig.co.uk'>

MODIFICATION HISTORY
====================

September 8th, 1994; by Tim Bunce.


File: pm.info,  Node: BitCount,  Next: C/Scan,  Prev: Benchmark,  Up: Module List

count number of "1" bits in string
**********************************

NAME
====

String::BitCount, BitCount showBitCount - count number of "1" bits in
string

SYNOPSIS
========

     use String::BitCount;

DESCRIPTION
===========

BitCount LIST
     Joins the elements of LIST into a single string and returns the the
     number of bits in this string.

showBitCount LIST
     Copies the elements of LIST to a new list and converts the new
     elements to strings of digits showing the number of set bits in the
     original byte.  In array context returns the new list.  In scalar
     context joins the elements of the new list into a single string and
     returns the string.

AUTHOR
======

Winfried Koenig <win@in.rhein-main.de>

     Copyright (c) 1995 Winfried Koenig. All rights reserved.
     This program is free software; you can redistribute it
     and/or modify it under the same terms as Perl itself.


File: pm.info,  Node: C/Scan,  Next: CGI,  Prev: BitCount,  Up: Module List

scan C language files for easily recognized constructs.
*******************************************************

NAME
====

C::Scan - scan C language files for easily recognized constructs.

SYNOPSIS
========

     $c = new C::Scan 'filename' => $filename, 'filename_filter' => $filter,
                      'add_cppflags' => $addflags;
     $c->set('includeDirs' => [$Config::Config{shrpdir}]);
     
     my $fdec = $c->get('parsed_fdecls');

DESCRIPTION
===========

*This description is *VERY* incomplete.*

This module uses `Data::Flow' interface, thus one uses it in the following
fashion:

     $c = new C::Scan(attr1 => $value1, attr2 => $value2);
     $c->set( attr3 => $value3 );

     $value4 = $c->get('attr4');

Attributes are depending on some other attributes. The only *required*
attribute, i.e., the attribute which *should* be set, is `filename', which
denotes which file to parse.

All other attributes are either optional, or would be calculated basing on
values of required and optional attributes.

Output attributes
-----------------

`includes'
     Value: reference to a list of included files.

`defines_args'
     Value: reference to hash of macros with arguments. The values are
     references to an array of length 2, the first element is a reference
     to the list of arguments, the second one being the expansion.
     Newlines are not unescaped, thus

          #define C(x,y) E\
                         F

     will finish with `("C" => [ ["x", "y"], "E\nF"])'.

`defines_no_args'
     Value: reference to hash of macros without arguments.  Newlines are
     not escaped, thus

          #define A B

     will finish with `("A" => "B")'.

`fdecls'
     Value: reference to list of declarations of functions.

`inlines'
     Value: reference to list of definitions of functions.

`parsed_fdecls'
     Value: reference to list of parsed declarations of functions.

     A parsed declaration is a reference to a list of `(rt, nm, args, ft,
     mod)'. Here `rt' is return type of a function, `nm' is the name,
     `args' is the list of arguments, `ft' is the full text of the
     declaration, and mod is the modifier (which is always undef).

     Each entry in the list `args' is of the same form `(ty, nm, args, ft,
     mod)', here `ty' is the type of an argument, `nm' is the name (a
     generated one if missing in the declaration), `args' is undef, and
     mod is the string of array modifiers.

`typedef_hash'
     Value: a reference to a hash which contains known `typedef's as keys.

`typedef_texts'
     Value: a reference to a list which contains known expansions of
     `typedef's.

`typedefs_maybe'
     Value: a reference to a list of `typedef'ed names. (Syncronized with
     `typedef_texts').

`vdecls'
     Value: a reference to a list of `extern' variable declarations.


File: pm.info,  Node: CGI,  Next: CGI/Base,  Prev: C/Scan,  Up: Module List

Simple Common Gateway Interface Class
*************************************

NAME
====

CGI - Simple Common Gateway Interface Class

ABSTRACT
========

This perl library uses perl5 objects to make it easy to create Web
fill-out forms and parse their contents.  This package defines CGI
objects, entities that contain the values of the current query string and
other state variables.  Using a CGI object's methods, you can examine
keywords and parameters passed to your script, and create forms whose
initial values are taken from the current query (thereby preserving state
information).

The current version of CGI.pm is available at

     http://www-genome.wi.mit.edu/ftp/pub/software/WWW/cgi_docs.html
     ftp://ftp-genome.wi.mit.edu/pub/software/WWW/

INSTALLATION:
=============

To install this package, just change to the directory in which this file
is found and type the following:

     perl Makefile.PL
     make
     make install

This will copy CGI.pm to your perl library directory for use by all perl
scripts.  You probably must be root to do this.   Now you can load the CGI
routines in your Perl scripts with the line:

     use CGI;

If you don't have sufficient privileges to install CGI.pm in the Perl
library directory, you can put CGI.pm into some convenient spot, such as
your home directory, or in cgi-bin itself and prefix all Perl scripts that
call it with something along the lines of the following preamble:

     BEGIN {
     	unshift(@INC,'/home/davis/lib');
     }
     use CGI;

The CGI distribution also comes with a cute module called *Note CGI/Carp:
CGI/Carp,.  It redefines the die(), warn(), confess() and croak() error
routines so that they write nicely formatted error messages into the
server's error log (or to the output stream of your choice).  This avoids
long hours of groping through the error and access logs, trying to figure
out which CGI script is generating  error messages.  If you choose, you
can even have fatal error messages echoed to the browser to avoid the
annoying and uninformative "Server Error" message.

DESCRIPTION
===========

CREATING A NEW QUERY OBJECT:
----------------------------

     $query = new CGI;

This will parse the input (from both POST and GET methods) and store it
into a perl5 object called $query.

CREATING A NEW QUERY OBJECT FROM AN INPUT FILE
----------------------------------------------

     $query = new CGI(INPUTFILE);

If you provide a file handle to the new() method, it will read parameters
from the file (or STDIN, or whatever).  The file can be in any of the
forms describing below under debugging (i.e. a series of newline delimited
TAG=VALUE pairs will work).  Conveniently, this type of file is created by
the save() method (see below).  Multiple records can be saved and restored.

Perl purists will be pleased to know that this syntax accepts references
to file handles, or even references to filehandle globs, which is the
"official" way to pass a filehandle:

     $query = new CGI(\*STDIN);

You can also initialize the query object from an associative array
reference:

     $query = new CGI( {'dinosaur'=>'barney',
     		       'song'=>'I love you',
     		       'friends'=>[qw/Jessica George Nancy/]}
                     );

or from a properly formatted, URL-escaped query string:

     $query = new CGI('dinosaur=barney&color=purple');

To create an empty query, initialize it from an empty string or hash:

     $empty_query = new CGI("");
                  -or-
             $empty_query = new CGI({});

FETCHING A LIST OF KEYWORDS FROM THE QUERY:
-------------------------------------------

     @keywords = $query->keywords

If the script was invoked as the result of an <ISINDEX> search, the parsed
keywords can be obtained as an array using the keywords() method.

FETCHING THE NAMES OF ALL THE PARAMETERS PASSED TO YOUR SCRIPT:
---------------------------------------------------------------

     @names = $query->param

If the script was invoked with a parameter list (e.g.
"name1=value1&name2=value2&name3=value3"), the param() method will return
the parameter names as a list.  If the script was invoked as an <ISINDEX>
script, there will be a single parameter named 'keywords'.

NOTE: As of version 1.5, the array of parameter names returned will be in
the same order as they were submitted by the browser.  Usually this order
is the same as the order in which the parameters are defined in the form
(however, this isn't part of the spec, and so isn't guaranteed).

FETCHING THE VALUE OR VALUES OF A SINGLE NAMED PARAMETER:
---------------------------------------------------------

     @values = $query->param('foo');

     -or-

     $value = $query->param('foo');

Pass the param() method a single argument to fetch the value of the named
parameter. If the parameter is multivalued (e.g. from multiple selections
in a scrolling list), you can ask to receive an array.  Otherwise the
method will return a single value.

SETTING THE VALUE(S) OF A NAMED PARAMETER:
------------------------------------------

     $query->param('foo','an','array','of','values');

This sets the value for the named parameter 'foo' to an array of values.
This is one way to change the value of a field AFTER the script has been
invoked once before.  (Another way is with the -override parameter
accepted by all methods that generate form elements.)

param() also recognizes a named parameter style of calling described in
more detail later:

     $query->param(-name=>'foo',-values=>['an','array','of','values']);

     -or-

     $query->param(-name=>'foo',-value=>'the value');

APPENDING ADDITIONAL VALUES TO A NAMED PARAMETER:
-------------------------------------------------

     $query->append(-name=>;'foo',-values=>['yet','more','values']);

This adds a value or list of values to the named parameter.  The values
are appended to the end of the parameter if it already exists.  Otherwise
the parameter is created.  Note that this method only recognizes the named
argument calling syntax.

IMPORTING ALL PARAMETERS INTO A NAMESPACE:
------------------------------------------

     $query->import_names('R');

This creates a series of variables in the 'R' namespace.  For example,
$R::foo, @R:foo.  For keyword lists, a variable @R::keywords will appear.
If no namespace is given, this method will assume 'Q'.  WARNING:  don't
import anything into 'main'; this is a major security risk!!!!

In older versions, this method was called import().  As of version 2.20,
this name has been removed completely to avoid conflict with the built-in
Perl module import operator.

DELETING A PARAMETER COMPLETELY:
--------------------------------

     $query->delete('foo');

This completely clears a parameter.  It sometimes useful for resetting
parameters that you don't want passed down between script invocations.

DELETING ALL PARAMETERS:
------------------------

$query->delete_all();

This clears the CGI object completely.  It might be useful to ensure that
all the defaults are taken when you create a fill-out form.

SAVING THE STATE OF THE FORM TO A FILE:
---------------------------------------

     $query->save(FILEHANDLE)

This will write the current state of the form to the provided filehandle.
You can read it back in by providing a filehandle to the new() method.
Note that the filehandle can be a file, a pipe, or whatever!

The format of the saved file is:

     NAME1=VALUE1
     NAME1=VALUE1'
     NAME2=VALUE2
     NAME3=VALUE3
     =

Both name and value are URL escaped.  Multi-valued CGI parameters are
represented as repeated names.  A session record is delimited by a single
= symbol.  You can write out multiple records and read them back in with
several calls to new.  You can do this across several sessions by opening
the file in append mode, allowing you to create primitive guest books, or
to keep a history of users' queries.  Here's a short example of creating
multiple session records:

     use CGI;

     open (OUT,">>test.out") || die;
     $records = 5;
     foreach (0..$records) {
         my $q = new CGI;
         $q->param(-name=>'counter',-value=>$_);
         $q->save(OUT);
     }
     close OUT;

     # reopen for reading
     open (IN,"test.out") || die;
     while (!eof(IN)) {
         my $q = new CGI(IN);
         print $q->param('counter'),"\n";
     }

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

for further details.

CREATING A SELF-REFERENCING URL THAT PRESERVES STATE INFORMATION:
-----------------------------------------------------------------

     $myself = $query->self_url;
     print "<A HREF=$myself>I'm talking to myself.</A>";

self_url() will return a URL, that, when selected, will reinvoke this
script with all its state information intact.  This is most useful when
you want to jump around within the document using internal anchors but you
don't want to disrupt the current contents of the form(s).  Something like
this will do the trick.

     $myself = $query->self_url;
     print "<A HREF=$myself#table1>See table 1</A>";
     print "<A HREF=$myself#table2>See table 2</A>";
     print "<A HREF=$myself#yourself>See for yourself</A>";

If you don't want to get the whole query string, call the method url() to
return just the URL for the script:

     $myself = $query->url;
     print "<A HREF=$myself>No query string in this baby!</A>\n";

You can also retrieve the unprocessed query string with query_string():

     $the_string = $query->query_string;

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:

OLD VERSION     require "cgi-lib.pl";     &ReadParse;     print "The value
of the antique is $in{antique}.\n";

NEW VERSION     use CGI;     CGI::ReadParse     print "The value of the
antique is $in{antique}.\n";

CGI.pm's ReadParse() routine creates a tied variable named %in, which can
be accessed to obtain the query variables.  Like ReadParse, you can also
provide your own variable.  Infrequently used features of ReadParse, such
as the creation of @in and $in variables, are not supported.

Once you use ReadParse, you can retrieve the query object itself this way:

     $q = $in{CGI};
     print $q->textfield(-name=>'wow',
                         -value=>'does this really work?');

This allows you to start using the more interesting features of CGI.pm
without rewriting your old scripts from scratch.

CALLING CGI FUNCTIONS THAT TAKE MULTIPLE ARGUMENTS
--------------------------------------------------

In versions of CGI.pm prior to 2.0, it could get difficult to remember the
proper order of arguments in CGI function calls that accepted five or six
different arguments.  As of 2.0, there's a better way to pass arguments to
the various CGI functions.  In this style, you pass a series of
name=>argument pairs, like this:

     $field = $query->radio_group(-name=>'OS',
                                  -values=>[Unix,Windows,Macintosh],
                                  -default=>'Unix');

The advantages of this style are that you don't have to remember the exact
order of the arguments, and if you leave out a parameter, in most cases it
will default to some reasonable value.  If you provide a parameter that
the method doesn't recognize, it will usually do something useful with it,
such as incorporating it into the HTML form tag.  For example if Netscape
decides next week to add a new JUSTIFICATION parameter to the text field
tags, you can start using the feature without waiting for a new version of
CGI.pm:

     $field = $query->textfield(-name=>'State',
                                -default=>'gaseous',
                                -justification=>'RIGHT');

This will result in an HTML tag that looks like this:

     <INPUT TYPE="textfield" NAME="State" VALUE="gaseous"
                    JUSTIFICATION="RIGHT">

Parameter names are case insensitive: you can use -name, or -Name or
-NAME.  You don't have to use the hyphen if you don't want to.  After
creating a CGI object, call the *use_named_parameters()* method with a
nonzero value.  This will tell CGI.pm that you intend to use named
parameters exclusively:

     $query = new CGI;
     $query->use_named_parameters(1);
     $field = $query->radio_group('name'=>'OS',
                                  'values'=>['Unix','Windows','Macintosh'],
                                  'default'=>'Unix');

Actually, CGI.pm only looks for a hyphen in the first parameter.  So you
can leave it off subsequent parameters if you like.  Something to be wary
of is the potential that a string constant like "values" will collide with
a keyword (and in fact it does!) While Perl usually figures out when
you're referring to a function and when you're referring to a string, you
probably should put quotation marks around all string constants just to
play it safe.

CREATING THE HTTP HEADER:
-------------------------

     print $query->header;

     -or-

     print $query->header('image/gif');

     -or-

     print $query->header('text/html','204 No response');

     -or-

     print $query->header(-type=>'image/gif',
     			     -status=>'402 Payment required',
     			     -expires=>'+3d',
     			     -cookie=>$cookie,
     			     -Cost=>'$2.00');

header() returns the Content-type: header.  You can provide your own MIME
type if you choose, otherwise it defaults to text/html.  An optional
second parameter specifies the status code and a human-readable message.
For example, you can specify 204, "No response" to create a script that
tells the browser to do nothing at all.  If you want to add additional
fields to the header, just tack them on to the end:

     print $query->header('text/html','200 OK','Content-Length: 3002');

The last example shows the named argument style for passing arguments to
the CGI methods using named parameters.  Recognized parameters are
*-type*, *-status*, *-expires*, and *-cookie*.  Any other parameters will
be stripped of their initial hyphens and turned into header fields,
allowing you to specify any HTTP header you desire.

Most browsers will not cache the output from CGI scripts.  Every time the
browser reloads the page, the script is invoked anew.  You can change this
behavior with the *-expires* parameter.  When you specify an absolute or
relative expiration interval with this parameter, some browsers and proxy
servers will cache the script's output until the indicated expiration
date.  The following forms are all valid for the -expires field:

     +30s                              30 seconds from now
     +10m                              ten minutes from now
     +1h	                          one hour from now
             -1d                               yesterday (i.e. "ASAP!")
     now                               immediately
     +3M                               in three months
             +10y                              in ten years time
     Thursday, 25-Apr-96 00:40:33 GMT  at the indicated time & date

(CGI::expires() is the static function call used internally that turns
relative time intervals into HTTP dates.  You can call it directly if you
wish.)

The *-cookie* parameter generates a header that tells the browser to
provide a "magic cookie" during all subsequent transactions with your
script.  Netscape cookies have a special format that includes interesting
attributes such as expiration time.  Use the cookie() method to create and
retrieve session cookies.

As of version 1.56, all HTTP headers produced by CGI.pm contain the
Pragma: no-cache instruction.  However, as of version 1.57, this is turned
OFF by default because it causes Netscape 2.0 and higher to produce an
annoying warning message every time the "back" button is hit.  Turn it on
again with the method cache().

GENERATING A REDIRECTION INSTRUCTION
------------------------------------

     print $query->redirect('http://somewhere.else/in/movie/land');

redirects the browser elsewhere.  If you use redirection like this, you
should *not* print out a header as well.  As of version 2.0, we produce
both the unofficial Location: header and the official URI: header.  This
should satisfy most servers and browsers.

One hint I can offer is that relative links may not work correctly when
when you generate a redirection to another document on your site.  This is
due to a well-intentioned optimization that some servers use.  The
solution to this is to use the full URL (including the http: part) of the
document you are redirecting to.

CREATING THE HTML HEADER:
-------------------------

     print $query->start_html(-title=>'Secrets of the Pyramids',
                              -author=>'fred@capricorn.org',
                              -base=>'true',
     			    -meta=>{'keywords'=>'pharaoh secret mummy',
                                      'copyright'=>'copyright 1996 King Tut'},
                              -BGCOLOR=>'blue');

     -or-

     print $query->start_html('Secrets of the Pyramids',
                              'fred@capricorn.org','true',
                              'BGCOLOR="blue"');

This will return a canned HTML header and the opening <BODY> tag.  All
parameters are optional.   In the named parameter form, recognized
parameters are -title, -author and -base (see below for the explanation).
Any additional parameters you provide, such as the Netscape unofficial
BGCOLOR attribute, are added to the <BODY> tag.

The argument *-xbase* allows you to provide an HREF for the <BASE> tag
different from the current location, as in

     -xbase=>"http://home.mcom.com/"

All relative links will be interpreted relative to this tag.

You add arbitrary meta information to the header with the *-meta*
argument.  This argument expects a reference to an associative array
containing name/value pairs of meta information.  These will be turned
into a series of header <META> tags that look something like this:

     <META NAME="keywords" CONTENT="pharaoh secret mummy">
     <META NAME="description" CONTENT="copyright 1996 King Tut">

There is no support for the HTTP-EQUIV type of <META> tag.  This is
because you can modify the HTTP header directly with the *header()* method.

JAVASCRIPTING: The *-script*, *-onLoad* and *-onUnload* parameters are
used to add Netscape JavaScript calls to your pages.  *-script* should
point to a block of text containing JavaScript function definitions.  This
block will be placed within a <SCRIPT> block inside the HTML (not HTTP)
header.  The block is placed in the header in order to give your page a
fighting chance of having all its JavaScript functions in place even if
the user presses the stop button before the page has loaded completely.
CGI.pm attempts to format the script in such a way that JavaScript-naive
browsers will not choke on the code: unfortunately there are some
browsers, such as Chimera for Unix, that get confused by it nevertheless.

The *-onLoad* and *-onUnload* parameters point to fragments of JavaScript
code to execute when the page is respectively opened and closed by the
browser.  Usually these parameters are calls to functions defined in the
*-script* field:

     $query = new CGI;
     print $query->header;
     $JSCRIPT=<<END;
     // Ask a silly question
     function riddle_me_this() {
        var r = prompt("What walks on four legs in the morning, " +
                      "two legs in the afternoon, " +
                      "and three legs in the evening?");
        response(r);
     }
     // Get a silly answer
     function response(answer) {
        if (answer == "man")
           alert("Right you are!");
        else
           alert("Wrong!  Guess again.");
     }
     END
     print $query->start_html(-title=>'The Riddle of the Sphinx',
                              -script=>$JSCRIPT);

See

     http://home.netscape.com/eng/mozilla/2.0/handbook/javascript/

for more information about JavaScript.

The old-style positional parameters are as follows:

Parameters:

     The title


     The author's e-mail address (will create a <LINK REV="MADE"> tag if
     present


     A 'true' flag if you want to include a <BASE> tag in the header.  This
     helps resolve relative addresses to absolute ones when the document
     is moved, but makes the document hierarchy non-portable.  Use with
     care!

5, 6...
     Any other parameters you want to include in the <BODY> tag.  This is
     a good place to put Netscape extensions, such as colors and wallpaper
     patterns.

ENDING THE HTML DOCUMENT:
-------------------------

     print $query->end_html

This ends an HTML document by printing the </BODY></HTML> tags.

CREATING FORMS:
===============

*General note*  The various form-creating methods all return strings to
the caller, containing the tag or tags that will create the requested form
element.  You are responsible for actually printing out these strings.
It's set up this way so that you can place formatting tags around the form
elements.

*Another note* The default values that you specify for the forms are only
used the *first* time the script is invoked (when there is no query
string).  On subsequent invocations of the script (when there is a query
string), the former values are used even if they are blank.

If you want to change the value of a field from its previous value, you
have two choices:

(1) call the param() method to set it.

(2) use the -override (alias -force) parameter (a new feature in version
2.15).  This forces the default value to be used, regardless of the
previous value:

     print $query->textfield(-name=>'field_name',
                             -default=>'starting value',
                             -override=>1,
                             -size=>50,
                             -maxlength=>80);

*Yet another note* By default, the text and labels of form elements are
escaped according to HTML rules.  This means that you can safely use
"<CLICK ME>" as the label for a button.  However, it also interferes with
your ability to incorporate special HTML character sequences, such as
&Aacute;, into your fields.  If you wish to turn off automatic escaping,
call the autoEscape() method with a false value immediately after creating
the CGI object:

     $query = new CGI;
     $query->autoEscape(undef);

CREATING AN ISINDEX TAG
-----------------------

     print $query->isindex(-action=>$action);

     -or-

     print $query->isindex($action);

Prints out an <ISINDEX> tag.  Not very exciting.  The parameter -action
specifies the URL of the script to process the query.  The default is to
process the query with the current script.

STARTING AND ENDING A FORM
--------------------------

     print $query->startform(-method=>$method,
     	                    -action=>$action,
     	                    -encoding=>$encoding);
       <... various form stuff ...>
     print $query->endform;

     -or-

     print $query->startform($method,$action,$encoding);
       <... various form stuff ...>
     print $query->endform;

startform() will return a <FORM> tag with the optional method, action and
form encoding that you specify.  The defaults are:

method: POST     action: this script     encoding:
application/x-www-form-urlencoded

endform() returns the closing </FORM> tag.

Startform()'s encoding method tells the browser how to package the various
fields of the form before sending the form to the server.  Two values are
possible:

*application/x-www-form-urlencoded*
     This is the older type of encoding used by all browsers prior to
     Netscape 2.0.  It is compatible with many CGI scripts and is suitable
     for short fields containing text data.  For your convenience, CGI.pm
     stores the name of this encoding type in *$CGI::URL_ENCODED*.

*multipart/form-data*
     This is the newer type of encoding introduced by Netscape 2.0.  It is
     suitable for forms that contain very large fields or that are
     intended for transferring binary data.  Most importantly, it enables
     the "file upload" feature of Netscape 2.0 forms.  For your
     convenience, CGI.pm stores the name of this encoding type in
     *$CGI::MULTIPART*

     Forms that use this type of encoding are not easily interpreted by
     CGI scripts unless they use CGI.pm or another library designed to
     handle them.

For compatibility, the startform() method uses the older form of encoding
by default.  If you want to use the newer form of encoding by default, you
can call *start_multipart_form()* instead of *startform()*.

JAVASCRIPTING: The *-name* and *-onSubmit* parameters are provided for use
with JavaScript.  The -name parameter gives the form a name so that it can
be identified and manipulated by JavaScript functions.  -onSubmit should
point to a JavaScript function that will be executed just before the form
is submitted to your server.  You can use this opportunity to check the
contents of the form for consistency and completeness.  If you find
something wrong, you can put up an alert box or maybe fix things up
yourself.  You can abort the submission by returning false from this
function.

Usually the bulk of JavaScript functions are defined in a <SCRIPT> block
in the HTML header and -onSubmit points to one of these function call.
See start_html() for details.

CREATING A TEXT FIELD
---------------------

     print $query->textfield(-name=>'field_name',
     	                    -default=>'starting value',
     	                    -size=>50,
     	                    -maxlength=>80);
     	-or-

     print $query->textfield('field_name','starting value',50,80);

textfield() will return a text input field.

Parameters

     The first parameter is the required name for the field (-name).


     The optional second parameter is the default starting value for the
     field contents (-default).


     The optional third parameter is the size of the field in
     characters (-size).


     The optional fourth parameter is the maximum number of characters the
          field will accept (-maxlength).

As with all these methods, the field will be initialized with its previous
contents from earlier invocations of the script.  When the form is
processed, the value of the text field can be retrieved with:

     $value = $query->param('foo');

If you want to reset it from its initial value after the script has been
called once, you can do so like this:

     $query->param('foo',"I'm taking over this value!");

NEW AS OF VERSION 2.15: If you don't want the field to take on its previous
value, you can force its current value by using the -override (alias
-force) parameter:

     print $query->textfield(-name=>'field_name',
     	                    -default=>'starting value',
     			    -override=>1,
     	                    -size=>50,
     	                    -maxlength=>80);

JAVASCRIPTING: You can also provide *-onChange*, *-onFocus*, *-onBlur* and
*-onSelect* parameters to register JavaScript event handlers.  The
onChange handler will be called whenever the user changes the contents of
the text field.  You can do text validation if you like.  onFocus and
onBlur are called respectively when the insertion point moves into and out
of the text field.  onSelect is called when the user changes the portion
of the text that is selected.

CREATING A BIG TEXT FIELD
-------------------------

     print $query->textarea(-name=>'foo',
     	 		  -default=>'starting value',
     	                  -rows=>10,
     	                  -columns=>50);

     -or

     print $query->textarea('foo','starting value',10,50);

textarea() is just like textfield, but it allows you to specify rows and
columns for a multiline text entry box.  You can provide a starting value
for the field, which can be long and contain multiple lines.

JAVASCRIPTING: The *-onChange*, *-onFocus*, *-onBlur* and *-onSelect*
parameters are recognized.  See textfield().

CREATING A PASSWORD FIELD
-------------------------

     print $query->password_field(-name=>'secret',
     				-value=>'starting value',
     				-size=>50,
     				-maxlength=>80);
     	-or-

     print $query->password_field('secret','starting value',50,80);

password_field() is identical to textfield(), except that its contents
will be starred out on the web page.

JAVASCRIPTING: The *-onChange*, *-onFocus*, *-onBlur* and *-onSelect*
parameters are recognized.  See textfield().

CREATING A FILE UPLOAD FIELD
----------------------------

     print $query->filefield(-name=>'uploaded_file',
     	                    -default=>'starting value',
     	                    -size=>50,
     	 		    -maxlength=>80);
     	-or-

     print $query->filefield('uploaded_file','starting value',50,80);

filefield() will return a file upload field for Netscape 2.0 browsers.  In
order to take full advantage of this *you must use the new multipart
encoding scheme* for the form.  You can do this either by calling
*startform()* with an encoding type of *$CGI::MULTIPART*, or by calling
the new method *start_multipart_form()* instead of vanilla *startform()*.

Parameters

     The first parameter is the required name for the field (-name).


     The optional second parameter is the starting value for the field
     contents to be used as the default file name (-default).

     The beta2 version of Netscape 2.0 currently doesn't pay any attention
     to this field, and so the starting value will always be blank.  Worse,
     the field loses its "sticky" behavior and forgets its previous
     contents.  The starting value field is called for in the HTML
     specification, however, and possibly later versions of Netscape will
     honor it.


     The optional third parameter is the size of the field in characters
     (-size).


     The optional fourth parameter is the maximum number of characters the
     field will accept (-maxlength).

When the form is processed, you can retrieve the entered filename by
calling param().

     $filename = $query->param('uploaded_file');

In Netscape Beta 1, the filename that gets returned is the full local
filename on the *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 machine, 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

In Netscape Beta 2, only the last part of the file path (the filename
itself) is returned.  I don't know what the release behavior will be.

The filename returned is also a file handle.  You can read the contents of
the file using standard Perl file reading calls:

     # Read a text file and print it out
     while (<$filename>) {
        print;
             }

     # Copy a binary file to somewhere safe
     open (OUTFILE,">>/usr/local/web/users/feedback");
     	while ($bytesread=read($filename,$buffer,1024)) {
     	   print OUTFILE $buffer;
     }

JAVASCRIPTING: The *-onChange*, *-onFocus*, *-onBlur* and *-onSelect*
parameters are recognized.  See textfield() for details.

CREATING A POPUP MENU
---------------------

     print $query->popup_menu('menu_name',
                              ['eenie','meenie','minie'],
                              'meenie');

     -or-

     %labels = ('eenie'=>'your first choice',
                'meenie'=>'your second choice',
                'minie'=>'your third choice');
     print $query->popup_menu('menu_name',
                              ['eenie','meenie','minie'],
                              'meenie',\%labels);

     -or (named parameter style)-

     print $query->popup_menu(-name=>'menu_name',
     			    -values=>['eenie','meenie','minie'],
     	                    -default=>'meenie',
     	                    -labels=>\%labels);

popup_menu() creates a menu.

  1. The required first argument is the menu's name (-name).

  2. The required second argument (-values) is an array *reference*
     containing the list of menu items in the menu.  You can pass the
     method an anonymous array, as shown in the example, or a reference to
     a named array, such as "\@foo".

  3. The optional third parameter (-default) is the name of the default
     menu choice.  If not specified, the first item will be the default.
     The values of the previous choice will be maintained across queries.

  4. The optional fourth parameter (-labels) is provided for people who
     want to use different values for the user-visible label inside the
     popup menu nd the value returned to your script.  It's a pointer to an
     associative array relating menu values to user-visible labels.  If you
     leave this parameter blank, the menu values will be displayed by
     default.  (You can also leave a label undefined if you want to).

     When the form is processed, the selected value of the popup menu can
be retrieved using:

     $popup_menu_value = $query->param('menu_name');

JAVASCRIPTING: popup_menu() recognizes the following event handlers:
*-onChange*, *-onFocus*, and *-onBlur*.  See the textfield() section for
details on when these handlers are called.

CREATING A SCROLLING LIST
-------------------------

     print $query->scrolling_list('list_name',
                                  ['eenie','meenie','minie','moe'],
                                  ['eenie','moe'],5,'true');
        -or-

     print $query->scrolling_list('list_name',
                                  ['eenie','meenie','minie','moe'],
                                  ['eenie','moe'],5,'true',
                                  \%labels);

     -or-

     print $query->scrolling_list(-name=>'list_name',
                                  -values=>['eenie','meenie','minie','moe'],
                                  -default=>['eenie','moe'],
     	                        -size=>5,
     	                        -multiple=>'true',
                                  -labels=>\%labels);

scrolling_list() creates a scrolling list.

Parameters:

     The first and second arguments are the list name (-name) and values
     (-values).  As in the popup menu, the second argument should be an
     array reference.


     The optional third argument (-default) can be either a reference to a
     list containing the values to be selected by default, or can be a
     single value to select.  If this argument is missing or undefined,
     then nothing is selected when the list first appears.  In the named
     parameter version, you can use the synonym "-defaults" for this
     parameter.


     The optional fourth argument is the size of the list (-size).


     The optional fifth argument can be set to true to allow multiple
     simultaneous selections (-multiple).  Otherwise only one selection
     will be allowed at a time.


     The optional sixth argument is a pointer to an associative array
     containing long user-visible labels for the list items (-labels).  If
     not provided, the values will be displayed.

     When this form is processed, all selected list items will be returned
     as a list under the parameter name 'list_name'.  The values of the
     selected items can be retrieved with:

          @selected = $query->param('list_name');

JAVASCRIPTING: scrolling_list() recognizes the following event handlers:
*-onChange*, *-onFocus*, and *-onBlur*.  See textfield() for the
description of when these handlers are called.

CREATING A GROUP OF RELATED CHECKBOXES
--------------------------------------

     print $query->checkbox_group(-name=>'group_name',
                                  -values=>['eenie','meenie','minie','moe'],
                                  -default=>['eenie','moe'],
     	                        -linebreak=>'true',
     	                        -labels=>\%labels);

     print $query->checkbox_group('group_name',
                                  ['eenie','meenie','minie','moe'],
                                  ['eenie','moe'],'true',\%labels);

     HTML3-COMPATIBLE BROWSERS ONLY:

     print $query->checkbox_group(-name=>'group_name',
                                  -values=>['eenie','meenie','minie','moe'],
     	                        -rows=2,-columns=>2);

checkbox_group() creates a list of checkboxes that are related by the same
name.

Parameters:

     The first and second arguments are the checkbox name and values,
     respectively (-name and -values).  As in the popup menu, the second
     argument should be an array reference.  These values are used for the
     user-readable labels printed next to the checkboxes as well as for the
     values passed to your script in the query string.


     The optional third argument (-default) can be either a reference to a
     list containing the values to be checked by default, or can be a
     single value to checked.  If this argument is missing or undefined,
     then nothing is selected when the list first appears.


     The optional fourth argument (-linebreak) can be set to true to place
     line breaks between the checkboxes so that they appear as a vertical
     list.  Otherwise, they will be strung together on a horizontal line.


     The optional fifth argument is a pointer to an associative array
     relating the checkbox values to the user-visible labels that will will
     be printed next to them (-labels).  If not provided, the values will
     be used as the default.


     *HTML3-compatible browsers* (such as Netscape) can take advantage of
     the optional parameters *-rows*, and *-columns*.  These parameters
     cause checkbox_group() to return an HTML3 compatible table containing
     the checkbox group formatted with the specified number of rows and
     columns.  You can provide just the -columns parameter if you wish;
     checkbox_group will calculate the correct number of rows for you.

     To include row and column headings in the returned table, you can use
     the *-rowheader* and *-colheader* parameters.  Both of these accept a
     pointer to an array of headings to use.  The headings are just
     decorative.  They don't reorganize the interpretation of the
     checkboxes - they're still a single named unit.

When the form is processed, all checked boxes will be returned as a list
under the parameter name 'group_name'.  The values of the "on" checkboxes
can be retrieved with:

     @turned_on = $query->param('group_name');

The value returned by checkbox_group() is actually an array of button
elements.  You can capture them and use them within tables, lists, or in
other creative ways:

     @h = $query->checkbox_group(-name=>'group_name',-values=>\@values);
     &use_in_creative_way(@h);

JAVASCRIPTING: checkbox_group() recognizes the *-onClick* parameter.  This
specifies a JavaScript code fragment or function call to be executed every
time the user clicks on any of the buttons in the group.  You can retrieve
the identity of the particular button clicked on using the "this" variable.

CREATING A STANDALONE CHECKBOX
------------------------------

     print $query->checkbox(-name=>'checkbox_name',
     			   -checked=>'checked',
     		           -value=>'ON',
     		           -label=>'CLICK ME');

     -or-

     print $query->checkbox('checkbox_name','checked','ON','CLICK ME');

checkbox() is used to create an isolated checkbox that isn't logically
related to any others.

Parameters:

     The first parameter is the required name for the checkbox (-name).  It
     will also be used for the user-readable label printed next to the
     checkbox.


     The optional second parameter (-checked) specifies that the checkbox
     is turned on by default.  Synonyms are -selected and -on.


     The optional third parameter (-value) specifies the value of the
     checkbox when it is checked.  If not provided, the word "on" is
     assumed.


     The optional fourth parameter (-label) is the user-readable label to
     be attached to the checkbox.  If not provided, the checkbox name is
     used.

The value of the checkbox can be retrieved using:

     $turned_on = $query->param('checkbox_name');

JAVASCRIPTING: checkbox() recognizes the *-onClick* parameter.  See
checkbox_group() for further details.

CREATING A RADIO BUTTON GROUP
-----------------------------

     print $query->radio_group(-name=>'group_name',
     			     -values=>['eenie','meenie','minie'],
                               -default=>'meenie',
     			     -linebreak=>'true',
     			     -labels=>\%labels);

     -or-

     print $query->radio_group('group_name',['eenie','meenie','minie'],
                                            'meenie','true',\%labels);

     HTML3-COMPATIBLE BROWSERS ONLY:

     print $query->radio_group(-name=>'group_name',
                               -values=>['eenie','meenie','minie','moe'],
     	                     -rows=2,-columns=>2);

radio_group() creates a set of logically-related radio buttons (turning
one member of the group on turns the others off)

Parameters:

     The first argument is the name of the group and is required (-name).


     The second argument (-values) is the list of values for the radio
     buttons.  The values and the labels that appear on the page are
     identical.  Pass an array *reference* in the second argument, either
     using an anonymous array, as shown, or by referencing a named array as
     in "\@foo".


     The optional third parameter (-default) is the name of the default
     button to turn on. If not specified, the first item will be the
     default.  You can provide a nonexistent button name, such as "-" to
     start up with no buttons selected.


     The optional fourth parameter (-linebreak) can be set to 'true' to put
     line breaks between the buttons, creating a vertical list.


     The optional fifth parameter (-labels) is a pointer to an associative
     array relating the radio button values to user-visible labels to be
     used in the display.  If not provided, the values themselves are
     displayed.


     *HTML3-compatible browsers* (such as Netscape) can take advantage of
     the optional parameters *-rows*, and *-columns*.  These parameters
     cause radio_group() to return an HTML3 compatible table containing
     the radio group formatted with the specified number of rows and
     columns.  You can provide just the -columns parameter if you wish;
     radio_group will calculate the correct number of rows for you.

     To include row and column headings in the returned table, you can use
     the *-rowheader* and *-colheader* parameters.  Both of these accept a
     pointer to an array of headings to use.  The headings are just
     decorative.  They don't reorganize the interpetation of the radio
     buttons - they're still a single named unit.

When the form is processed, the selected radio button can be retrieved
using:

     $which_radio_button = $query->param('group_name');

The value returned by radio_group() is actually an array of button
elements.  You can capture them and use them within tables, lists, or in
other creative ways:

     @h = $query->radio_group(-name=>'group_name',-values=>\@values);
     &use_in_creative_way(@h);

CREATING A SUBMIT BUTTON
------------------------

     print $query->submit(-name=>'button_name',
     		        -value=>'value');

     -or-

     print $query->submit('button_name','value');

submit() will create the query submission button.  Every form should have
one of these.

Parameters:

     The first argument (-name) is optional.  You can give the button a
     name if you have several submission buttons in your form and you want
     to distinguish between them.  The name will also be used as the
     user-visible label.  Be aware that a few older browsers don't deal
     with this correctly and *never* send back a value from a button.


     The second argument (-value) is also optional.  This gives the button
     a value that will be passed to your script in the query string.

You can figure out which button was pressed by using different values for
each one:

     $which_one = $query->param('button_name');

JAVASCRIPTING: radio_group() recognizes the *-onClick* parameter.  See
checkbox_group() for further details.

CREATING A RESET BUTTON
-----------------------

     print $query->reset

reset() creates the "reset" button.  Note that it restores the form to its
value from the last time the script was called, NOT necessarily to the
defaults.

CREATING A DEFAULT BUTTON
-------------------------

     print $query->defaults('button_label')

defaults() creates a button that, when invoked, will cause the form to be
completely reset to its defaults, wiping out all the changes the user ever
made.

CREATING A HIDDEN FIELD
-----------------------

     print $query->hidden(-name=>'hidden_name',
                          -default=>['value1','value2'...]);

     -or-

     print $query->hidden('hidden_name','value1','value2'...);

hidden() produces a text field that can't be seen by the user.  It is
useful for passing state variable information from one invocation of the
script to the next.

Parameters:

     The first argument is required and specifies the name of this field
     (-name).


     The second argument is also required and specifies its value
     (-default).  In the named parameter style of calling, you can provide
     a single value here or a reference to a whole list

Fetch the value of a hidden field this way:

     $hidden_value = $query->param('hidden_name');

Note, that just like all the other form elements, the value of a hidden
field is "sticky".  If you want to replace a hidden field with some other
values after the script has been called once you'll have to do it manually:

     $query->param('hidden_name','new','values','here');

CREATING A CLICKABLE IMAGE BUTTON
---------------------------------

     print $query->image_button(-name=>'button_name',
     			        -src=>'/source/URL',
     			        -align=>'MIDDLE');

     -or-

     print $query->image_button('button_name','/source/URL','MIDDLE');

image_button() produces a clickable image.  When it's clicked on the
position of the click is returned to your script as "button_name.x" and
"button_name.y", where "button_name" is the name you've assigned to it.

JAVASCRIPTING: image_button() recognizes the *-onClick* parameter.  See
checkbox_group() for further details.

Parameters:

     The first argument (-name) is required and specifies the name of this
     field.


     The second argument (-src) is also required and specifies the URL

The third option (-align, optional) is an alignment type, and may be TOP, BOTTOM or MIDDLE
Fetch the value of the button this way:      $x =
$query->param('button_name.x');      $y = $query->param('button_name.y');

CREATING A JAVASCRIPT ACTION BUTTON
-----------------------------------

     print $query->button(-name=>'button_name',
                          -value=>'user visible label',
                          -onClick=>"do_something()");

     -or-

     print $query->button('button_name',"do_something()");

button() produces a button that is compatible with Netscape 2.0's
JavaScript.  When it's pressed the fragment of JavaScript code pointed to
by the *-onClick* parameter will be executed.  On non-Netscape browsers
this form element will probably not even display.

NETSCAPE COOKIES
================

Netscape browsers versions 1.1 and higher support a so-called "cookie"
designed to help maintain state within a browser session.  CGI.pm has
several methods that support cookies.

A cookie is a name=value pair much like the named parameters in a CGI
query string.  CGI scripts create one or more cookies and send them to the
browser in the HTTP header.  The browser maintains a list of cookies that
belong to a particular Web server, and returns them to the CGI script
during subsequent interactions.

In addition to the required name=value pair, each cookie has several
optional attributes:

  1. an expiration time This is a time/date string (in a special GMT
     format) that indicates when a cookie expires.  The cookie will be
     saved and returned to your script until this expiration date is
     reached if the user exits Netscape and restarts it.  If an expiration
     date isn't specified, the cookie will remain active until the user
     quits Netscape.

  2. a domain This is a partial or complete domain name for which the
     cookie is valid.  The browser will return the cookie to any host that
     matches the partial domain name.  For example, if you specify a
     domain name of ".capricorn.com", then Netscape will return the cookie
     to Web servers running on any of the machines "www.capricorn.com",
     "www2.capricorn.com", "feckless.capricorn.com", etc.  Domain names
     must contain at least two periods to prevent attempts to match on top
     level domains like ".edu".  If no domain is specified, then the
     browser will only return the cookie to servers on the host the cookie
     originated from.

  3. a path 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.

  4. a "secure" flag If the "secure" attribute is set, the cookie will
     only be sent to your script if the CGI request is occurring on a
     secure channel, such as SSL.

     The interface to Netscape cookies is the *cookie()* method:

     $cookie = $query->cookie(-name=>'sessionID',
     			     -value=>'xyzzy',
     			     -expires=>'+1h',
     			     -path=>'/cgi-bin/database',
     			     -domain=>'.capricorn.org',
     			     -secure=>1);
     print $query->header(-cookie=>$cookie);

*cookie()* creates a new cookie.  Its parameters include:

*-name*
     The name of the cookie (required).  This can be any string at all.
     Although Netscape limits its cookie names to non-whitespace
     alphanumeric characters, CGI.pm removes this restriction by escaping
     and unescaping cookies behind the scenes.

*-value*
     The value of the cookie.  This can be any scalar value, array
     reference, or even associative array reference.  For example, you can
     store an entire associative array into a cookie this way:

          $cookie=$query->cookie(-name=>'family information',
                                         -value=>\%childrens_ages);

*-path*
     The optional partial path for which this cookie will be valid, as
     described above.

*-domain*
     The optional partial domain for which this cookie will be valid, as
     described above.

*-expires*
     The optional expiration date for this cookie.  The format is as
     described in the section on the *header()* method:

          "+1h"  one hour from now

*-secure*
     If set to true, this cookie will only be used within a secure SSL
     session.

The cookie created by cookie() must be incorporated into the HTTP header
within the string returned by the header() method:

     print $query->header(-cookie=>$my_cookie);

To create multiple cookies, give header() an array reference:

     $cookie1 = $query->cookie(-name=>'riddle_name',
                                       -value=>"The Sphynx's Question");
             $cookie2 = $query->cookie(-name=>'answers',
                                       -value=>\%answers);
             print $query->header(-cookie=>[$cookie1,$cookie2]);

To retrieve a cookie, request it by name by calling cookie() method
without the *-value* parameter:

     use CGI;
     $query = new CGI;
     %answers = $query->cookie(-name=>'answers');
     # $query->cookie('answers') will work too!

The cookie and CGI namespaces are separate.  If you have a parameter named
'answers' and a cookie named 'answers', the values retrieved by param()
and cookie() are independent of each other.  However, it's simple to turn
a CGI parameter into a cookie, and vice-versa:

     # turn a CGI parameter into a cookie
     $c=$q->cookie(-name=>'answers',-value=>[$q->param('answers')]);
     # vice-versa
     $q->param(-name=>'answers',-value=>[$q->cookie('answers')]);

See the *cookie.cgi* example script for some ideas on how to use cookies
effectively.

*NOTE:* There appear to be some (undocumented) restrictions on Netscape
cookies.  In Netscape 2.01, at least, I haven't been able to set more than
three cookies at a time.  There may also be limits on the length of
cookies.  If you need to store a lot of information, it's probably better
to create a unique session ID, store it in a cookie, and use the session
ID to locate an external file/database saved on the server's side of the
connection.

WORKING WITH NETSCAPE FRAMES
============================

It's possible for CGI.pm scripts to write into several browser panels and
windows using Netscape's frame mechanism.  There are three techniques for
defining new frames programmatically:

  1. Create a <Frameset> document After writing out the HTTP header,
     instead of creating a standard HTML document using the start_html()
     call, create a <FRAMESET> document that defines the frames on the
     page.  Specify your script(s) (with appropriate parameters) as the
     SRC for each of the frames.

     There is no specific support for creating <FRAMESET> sections in
     CGI.pm, but the HTML is very simple to write.  See the frame
     documentation in Netscape's home pages for details

          http://home.netscape.com/assist/net_sites/frames.html

  2. Specify the destination for the document in the HTTP header You may
     provide a *-target* parameter to the header() method:

     print $q->header(-target=>'ResultsWindow');

     This will tell Netscape to load the output of your script into the
     frame named "ResultsWindow".  If a frame of that name doesn't already
     exist, Netscape will pop up a new window and load your script's
     document into that.  There are a number of magic names that you can
     use for targets.  See the frame documents on Netscape's home pages
     for details.

  3. Specify the destination for the document in the <FORM> tag You can
     specify the frame to load in the FORM tag itself.  With CGI.pm it
     looks like this:

          print $q->startform(-target=>'ResultsWindow');

     When your script is reinvoked by the form, its output will be loaded
     into the frame named "ResultsWindow".  If one doesn't already exist a
     new window will be created.

     The script "frameset.cgi" in the examples directory shows one way to
create pages in which the fill-out form and the response live in
side-by-side frames.

DEBUGGING
=========

If you are running the script from the command line or in the perl
debugger, you can pass the script a list of keywords or parameter=value
pairs on the command line or from standard input (you don't have to worry
about tricking your script into reading from environment variables).  You
can pass keywords like this:

     your_script.pl keyword1 keyword2 keyword3

or this:

     your_script.pl keyword1+keyword2+keyword3

or this:

     your_script.pl name1=value1 name2=value2

or this:

     your_script.pl name1=value1&name2=value2

or even as newline-delimited parameters on standard input.

When debugging, you can use quotes and backslashes to escape characters in
the familiar shell manner, letting you place spaces and other funny
characters in your parameter=value pairs:

     your_script.pl "name1='I am a long value'" "name2=two\ words"

DUMPING OUT ALL THE NAME/VALUE PAIRS
------------------------------------

The dump() method produces a string consisting of all the query's
name/value pairs formatted nicely as a nested list.  This is useful for
debugging purposes:

     print $query->dump

Produces something that looks like:

     <UL>
     <LI>name1
         <UL>
         <LI>value1
         <LI>value2
         </UL>
     <LI>name2
         <UL>
         <LI>value1
         </UL>
     </UL>

You can pass a value of 'true' to dump() in order to get it to print the
results out as plain text, suitable for incorporating into a <PRE> section.

As a shortcut, as of version 1.56 you can interpolate the entire CGI
object into a string and it will be replaced with the the a nice HTML dump
shown above:

     $query=new CGI;
     print "<H2>Current Values</H2> $query\n";

FETCHING ENVIRONMENT VARIABLES
==============================

Some of the more useful environment variables can be fetched through this
interface.  The methods are as follows:

accept()
     Return a list of MIME types that the remote browser accepts. If you
     give this method a single argument corresponding to a MIME type, as in
     $query->accept('text/html'), it will return a floating point value
     corresponding to the browser's preference for this type from 0.0
     (don't want) to 1.0.  Glob types (e.g. text/*) in the browser's
     accept list are handled correctly.

raw_cookie()
     Returns the HTTP_COOKIE variable, an HTTP extension implemented by
     Netscape browsers version 1.1 and higher.  Cookies have a special
     format, and this method call just returns the raw form (?cookie
     dough).  See cookie() for ways of setting and retrieving cooked
     cookies.

user_agent()
     Returns the HTTP_USER_AGENT variable.  If you give this method a
     single argument, it will attempt to pattern match on it, allowing you
     to do something like $query->user_agent(netscape);

path_info()
     Returns additional path information from the script URL.  E.G.
     fetching /cgi-bin/your_script/additional/stuff will result in
     $query->path_info() returning "additional/stuff".

path_translated()
     As per path_info() but returns the additional path information
     translated into a physical path, e.g.
     "/usr/local/etc/httpd/htdocs/additional/stuff".

remote_host()
     Returns either the remote host name or IP address.  if the former is
     unavailable.

script_name() Return the script name as a partial URL, for self-refering scripts.
referer()
     Return the URL of the page the browser was viewing prior to fetching
     your script.  Not available for all browsers.

*auth_type ()*
     Return the authorization/verification method in use for this script,
     if any.

*remote_user ()*
     Return the authorization/verification name used for user
     verification, if this script is protected.

*user_name ()*
     Attempt to obtain the remote user's name, using a variety of
     different techniques.  This only works with older browsers such as
     Mosaic.  Netscape does not reliably report the user name!

request_method()
     Returns the method used to access your script, usually one of 'POST',
     'GET' or 'HEAD'.

CREATING HTML ELEMENTS:
=======================

In addition to its shortcuts for creating form elements, CGI.pm defines
general HTML shortcut methods as well.  HTML shortcuts are named after a
single HTML element and return a fragment of HTML text that you can then
print or manipulate as you like.

This example shows how to use the HTML methods:

     $q = new CGI;
     print $q->blockquote(
     		     "Many years ago on the island of",
     		     $q->a({href=>"http://crete.org/"},"Crete"),
     		     "there lived a minotaur named",
                                  $q->strong("Fred."),
     		    ),
                    $q->hr;

This results in the following HTML code (extra newlines have been added
for readability):

     <blockquote>
             Many years ago on the island of
     <a HREF="http://crete.org/">Crete</a> there lived
             a minotaur named <strong>Fred.</strong>
             </blockquote>
             <hr>

If you find the syntax for calling the HTML shortcuts awkward, you can
import them into your namespace and dispense with the object syntax
completely (see the next section for more details):

     use CGI shortcuts;	# IMPORT HTML SHORTCUTS
     print blockquote(
     	     "Many years ago on the island of",
     	     a({href=>"http://crete.org/"},"Crete"),
     	     "there lived a minotaur named",
                          strong("Fred."),
     	     ),
                    hr;

PROVIDING ARGUMENTS TO HTML SHORTCUTS
-------------------------------------

The HTML methods will accept zero, one or multiple arguments.  If you
provide no arguments, you get a single tag:

     print hr;
     #  gives "<hr>"

If you provide one or more string arguments, they are concatenated
together with spaces and placed between opening and closing tags:

     print h1("Chapter","1");
     # gives "<h1>Chapter 1</h1>"

If the first argument is an associative array reference, then the keys and
values of the associative array become the HTML tag's attributes:

     print a({href=>'fred.html',target=>'_new'},
     	"Open a new frame");
     # gives <a href="fred.html",target="_new">Open a new frame</a>

You are free to use CGI.pm-style dashes in front of the attribute names if
you prefer:

     print img {-src=>'fred.gif',-align=>'LEFT'};
     # gives <img ALIGN="LEFT" SRC="fred.gif">

Generating new HTML tags
------------------------

Since no mere mortal can keep up with Netscape and Microsoft as they
battle it out for control of HTML, the code that generates HTML tags is
general and extensible.  You can create new HTML tags freely just by
referring to them on the import line:

     use CGI shortcuts,winkin,blinkin,nod;

Now, in addition to the standard CGI shortcuts, you've created HTML tags
named "winkin", "blinkin" and "nod".  You can use them like this:

     print blinkin {color=>'blue',rate=>'fast'},"Yahoo!";
     # <blinkin COLOR="blue" RATE="fast">Yahoo!</blinkin>

IMPORTING CGI METHOD CALLS INTO YOUR NAME SPACE
===============================================

As a convenience, you can import most of the CGI method calls directly
into your name space.  The syntax for doing this is:

     use CGI <list of methods>;

The listed methods will be imported into the current package; you can call
them directly without creating a CGI object first.  This example shows how
to import the *param()* and *header()* methods, and then use them directly:

     use CGI param,header;
     print header('text/plain');
     $zipcode = param('zipcode');

You can import groups of methods by referring to a number of special names:

cgi
     Import all CGI-handling methods, such as *param()*, path_info() and
     the like.

form
     Import all fill-out form generating methods, such as *textfield()*.

html2
     Import all methods that generate HTML 2.0 standard elements.

html3
     Import all methods that generate HTML 3.0 proposed elements (such as
     <table>, <super> and <sub>).

netscape
     Import all methods that generate Netscape-specific HTML extensions.

shortcuts
     Import all HTML-generating shortcuts (i.e. 'html2' + 'html3' +
     'netscape')...

standard
     Import "standard" features, 'html2', 'form' and 'cgi'.

all
     Import all the available methods.  For the full list, see the CGI.pm
     code, where the variable %TAGS is defined.

Note that in the interests of execution speed CGI.pm does *not* use the
standard *Note Exporter: Exporter, syntax for specifying load symbols.
This may change in the future.

If you import any of the state-maintaining CGI or form-generating methods,
a default CGI object will be created and initialized automatically the
first time you use any of the methods that require one to be present.
This includes *param()*, *textfield()*, *submit()* and the like.  (If you
need direct access to the CGI object, you can find it in the global
variable *$CGI::Q*).  By importing CGI.pm methods, you can create visually
elegant scripts:

     use CGI standard,html2;
     print
         header,
         start_html('Simple Script'),
         h1('Simple Script'),
         start_form,
         "What's your name? ",textfield('name'),p,
         "What's the combination?",
         checkbox_group(-name=>'words',
     	  	      -values=>['eenie','meenie','minie','moe'],
     		      -defaults=>['eenie','moe']),p,
         "What's your favorite color?",
         popup_menu(-name=>'color',
     	          -values=>['red','green','blue','chartreuse']),p,
         submit,
         end_form,
         hr,"\n";

     if (param) {
        print
     	   "Your name is ",em(param('name')),p,
     	   "The keywords are: ",em(join(", ",param('words'))),p,
     	   "Your favorite color is ",em(param('color')),".\n";
     }
     print end_html;

AUTHOR INFORMATION
==================

Copyright 1995,1996, 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.

Address bug reports and comments to: lstein@genome.wi.mit.edu

CREDITS
=======

Thanks very much to:

Matt Heffron (heffron@falstaff.css.beckman.com)
James Taylor (james.taylor@srs.gov)
Scott Anguish <sanguish@digifix.com>
Mike Jewell (mlj3u@virginia.edu)
Timothy Shimmin (tes@kbs.citri.edu.au)
Joergen Haegg (jh@axis.se)
Laurent Delfosse (delfosse@csgrad1.cs.wvu.edu)
Richard Resnick (applepi1@aol.com)
Craig Bishop (csb@barwonwater.vic.gov.au)
Tony Curtis (tc@vcpc.univie.ac.at)
Tim Bunce (Tim.Bunce@ig.co.uk)
Tom Christiansen (tchrist@convex.com)
Andreas Koenig (k@franz.ww.TU-Berlin.DE)
Tim MacKenzie (Tim.MacKenzie@fulcrum.com.au)
Kevin B. Hendricks (kbhend@dogwood.tyler.wm.edu)
Stephen Dahmen (joyfire@inxpress.net)
...and many many more...
     for suggestions and bug fixes.

A COMPLETE EXAMPLE OF A SIMPLE FORM-BASED SCRIPT
================================================

     #!/usr/local/bin/perl
     
         	use CGI;
     
     $query = new CGI;

     print $query->header;
     print $query->start_html("Example CGI.pm Form");
     print "<H1> Example CGI.pm Form</H1>\n";
     &print_prompt($query);
     &do_work($query);
     	&print_tail;
     print $query->end_html;
     
     sub print_prompt {
          	   my($query) = @_;
     
          	   print $query->startform;
          	   print "<EM>What's your name?</EM><BR>";
          	   print $query->textfield('name');
          	   print $query->checkbox('Not my real name');
     
          	   print "<P><EM>Where can you find English Sparrows?</EM><BR>";
          	   print $query->checkbox_group(
                                      -name=>'Sparrow locations',
     			 -values=>[England,France,Spain,Asia,Hoboken],
     			         -linebreak=>'yes',
     			 -defaults=>[England,Asia]);
     
          	   print "<P><EM>How far can they fly?</EM><BR>",
                 	$query->radio_group(
     			-name=>'how far',
     	        -values=>['10 ft','1 mile','10 miles','real far'],
     	        -default=>'1 mile');
     
          	   print "<P><EM>What's your favorite color?</EM>  ";
          	   print $query->popup_menu(-name=>'Color',
     				    -values=>['black','brown','red','yellow'],
     				    -default=>'red');
     
          	   print $query->hidden('Reference','Monty Python and the Holy Grail');
     
          	   print "<P><EM>What have you got there?</EM><BR>";
          	   print $query->scrolling_list(
     			 -name=>'possessions',
     		 -values=>['A Coconut','A Grail','An Icon',
     		           'A Sword','A Ticket'],
     		 -size=>5,
     		 -multiple=>'true');
     
          	   print "<P><EM>Any parting comments?</EM><BR>";
          	   print $query->textarea(-name=>'Comments',
     		                  -rows=>10,
     				  -columns=>50);
     
          	   print "<P>",$query->reset;
          	   print $query->submit('Action','Shout');
          	   print $query->submit('Action','Scream');
          	   print $query->endform;
          	   print "<HR>\n";
     }
     
     sub do_work {
          	   my($query) = @_;
          	   my(@values,$key);

     print "<H2>Here are the current settings in this form</H2>";

     foreach $key ($query->param) {
      	      print "<STRONG>$key</STRONG> -> ";
      	      @values = $query->param($key);
      	      print join(", ",@values),"<BR>\n";
               }
      	}
     
      	sub print_tail {
     print <<END;
      	<HR>
      	<ADDRESS>Lincoln D. Stein</ADDRESS><BR>
      	<A HREF="/">Home Page</A>
      	END
      	}

BUGS
====

This module has grown large and monolithic.  Furthermore it's doing many
things, such as handling URLs, parsing CGI input, writing HTML, etc., that
should be done in separate modules.  It should be discarded in favor of
the CGI::* modules, but somehow I continue to work on it.

Note that the code is truly contorted in order to avoid spurious warnings
when programs are run with the -w switch.

SEE ALSO
========

*Note CGI/Carp: CGI/Carp,, *Note URI/URL: URI/URL,, *Note CGI/Request:
CGI/Request,, *Note CGI/MiniSvr: CGI/MiniSvr,, *Note CGI/Base: CGI/Base,,
*Note CGI/Form: CGI/Form,


File: pm.info,  Node: CGI/Base,  Next: CGI/BasePlus,  Prev: CGI,  Up: Module List

HTTP Daemon Common Gateway Interface (CGI) Base Class
*****************************************************

NAME
====

CGI::Base - HTTP Daemon Common Gateway Interface (CGI) Base Class

SYNOPSIS
========


     use CGI::Base;
     
     $cgi = new CGI::Base;       # reads vars from environment
     
     $cgi->var($name);           # get CGI variable value
     $cgi->var($name, $value);   # set CGI variable value
     
     @names  = $cgi->vars;       # lists standard CGI variables
     
     $mime_type  = $cgi->accept_best(@mime_types);
     $preference = $cgi->accept_type($mime_type);
     
     $cgi->pass_thru($host, $port); # forward request to server
     $cgi->redirect($url);          # redirect client
     
     $cgi->done($dump);     # end response, does NOT send </BODY>
     
     $cgi->exit(@log_msgs); # exit, optionally logging messages
     
     
     # Other functions:
     
     @escaped_texts = html_escape(@texts);   # '>' -> '&lt;' etc
     @texts         = html_br_lines(@texts); #  \n -> '<BR>'
     
     SendHeaders();  # send and flush HTTP header(s)
     
     CGI::Base::Debug($level);

DESCRIPTION
===========

This module implements a CGI::Base object. This object represents the
interface between the application and an HTTP deamon.

In a typical CGI scenario the interface is just a collection of
environment variables. This module makes those variables available either
via a $cgi->var() method or optionally as plain perl variables (see
IMPORTING CGI VARIABLES below).  Small scripts will tend to use the
imported variables, larger scripts may prefer to use the var method.

By default the CGI::Base class will transparently deal with POST and PUT
submissions by reading STDIN into $QUERY_STRING.

The CGI::Base module simplifies CGI debugging by providing logging methods
(which redirect STDERR to a file) and a very handy test mode.  The test
mode automatically detects that the script is not being run by a HTTP
server and requests test input from the user (or command line).

IMPORTING CGI VARIABLES
-----------------------

Users of this module can optionally import the CGI values as ordinary perl
variables of the same name into their package. For example, saying:

     use CGI::Base qw(:DEFAULT QUERY_STRING REQUEST_METHOD);

will allow you to refer to the CGI query string and request method as
simply $QUERY_STRING and $REQUEST_METHOD.  Any changes made to these
variables will be reflected in the values returned by the var() method.

To import all the fixed CGI variables (excludes optional variables string
with HTTP_) use:

     use CGI::Base qw(:DEFAULT :CGI);

NOTES
-----

The CGI::Base class has been specifically designed to enable it to be
subclassed to implement alternative interfaces. For example the
CGI::MiniSvr class implements a 'mini http daemon' which can be spawned
from a CGI script in order, for example, to maintain state information for
a client 'session'.

The CGI::Base class (and classes derived from it) are not designed to
understand the contents of the data they are handling. Only basic data
acquisition tasks and basic metadata parsing are performed by CGI::Base.
The QUERY_STRING is not parsed.

Higher level query processing (parsing of QUERY_STRING and handling of
form fields etc) is performed by the CGI::Request module.

Note that CGI application developers will generally deal with the
CGI::Request class and not directly with the CGI::Base class.

FEATURES
--------

Object oriented and sub-classable.

Exporting of CGI environment variables as plain perl variables.

Supports pass_thru and redirection of URL's.

Extensible attribute system for CGI environment variables.

Very handy automatic test mode if script is run manually.

PRINCIPLES and ASSUMPTIONS
--------------------------

These basic principles and assumptions apply to CGI::Base and can be built
into any application using CGI::Base. Any subclass of CGI::Base, such as
CGI::MiniSvr, must uphold these principles.

STDIN, STDOUT are connected to the client, possibly via a server.

STDERR can be used for error logging (see open_log method).

%ENV should not be used to access CGI parameters. See ENVIRONMENT section
below.

ENVIRONMENT
-----------

The CGI::Base module copies all the CGI/1.1 standard environment variables
into internal storage. See the definition of %CgiEnv and  @CgiObj. The
stored values are available either via the var method or as exported
variables.

It is recommended that $ENV{...} is not used to access the CGI variables
because alternative CGI interfaces, such as CGI::MiniSvr, may not bother
to maintain %ENV consistent with the internal values. The simple scalar
variables are also much faster to access.

RECENT CHANGES
--------------

  1. Changes to create compatability with CGI::Form.

  2. Miscellaneous small bug fixes.

  3. get_url() now adds SERVER_PORT to the url. pass_thru() split into
     component methods forward_request() and pass_back().  The new
     forward_request method can shutdown() the sending side of the socket.
     SendHeaders does nothing and returns undef if called more than once.
     All these changes are useful for sophisticated applications.

  4. and 2.3 Slightly improved documentation. Added html_br_lines() to
     purify html_escape().  Added SIGPIPE handling (not used by default).
     Documented the automatic test mode. Assorted other minor clean ups.

  5. Added support for any letter case in HTTP headers. Fixed (worked
     around) a perl/stdio bug which affected POST handling in the MiniSvr.
     Added $ENTITY_BODY to hold the Entity-Body for PUT, POST and CHECKIN
     methods. $QUERY_STRING now only set from $ENTITY_BODY if CONTENT_TYPE
     is application/x-www-form-urlencoded. Changed some uses of map to
     foreach.  Slight improved performance of pass_thru.

  6. A major overhaul. Now much more object oriented but retaining the
     ability to export CGI variables. A new var() method provides access
     to CGI variables in a controlled manner. Some rather fancy footwork
     with globs and references to hash elements enables the global
     variables and hash elements to be automatically kept in sync with
     each other.  Take a look at the link_global_vars method. An export
     tag is provided to simplify importing the CGI variables.

     The new code is also much faster, mainly because it does less. Less
     work is done up front, more is defered until actually used. I have
     removed the 'expand variables' concept for now. It might return later.
     The code for read_entity_body(), get_vars_from_env() and accept_best()
     and many others has been revised. All the code now compiles with use
     strict;

     SendHeaders can now be told to automatically add a server Status-Line
     header if one is not included in the headers to be output. This
     greatly simplifies header handling in the MiniSvr and fixes the
     redirect() method.

     The module file can be run as a cgi script to execute a demo/test. You
     may need to chmod +x this file and teach your httpd that it can
     execute *.pm files.

  7. The done method no longer sends </BODY>. It was appealing but
     inappropriate for it to do so.  Added html_escape function and
     exported it by default (this should be moved into an HTML module once
     we have one). Applied html_escape to as_string.  ContentTypeHdr,
     LocationHdr, StatusHdr and ServerHdr no longer exported by default.
     Added Debug function.  Set default Debug level to 0 (off). Code to
     set $URI is no longer invoked by default and has been moved to a new
     get_uri method.  This avoids the overhead for setting $URI which few
     people used.  Methods like as_string which make use of $URI now call
     get_uri if needed.

  8. POST data read more robust. fmt() renamed to as_string(). pass_thru()
     now takes host and port parameters, applies a timeout and has better
     logging.  HTTP_REFERER defined by default. Assorted fixes and tidyups.


FUTURE DEVELOPMENTS
-------------------

Full pod documentation.

None of this is perfect. All suggestions welcome.

How reliable is CONTENT_LENGTH?

Pod documentation for the methods needs to be added.

Header handling is not ideal (but it's getting better).  Header handling
should be moved into an HTTP specific module.

Need mechanism to identify a 'session'. This may come out of the ongoing
HTTP security work. A session-id would be very useful for any advanced
form of inter-query state maintenance.  The CGI::Base module may have a
hand in providing some form of session-id but would not be involved in any
further use of it.

For very large POST's we may need some mechanism to replace
read_entity_body on a per call basis or at least prevent its automatic
use. Subclassing is probably the 'right' way to do this.

These functions should be moved out into a CGI::BasePlus module since few
simple CGI applications need them:  pass_thru, forward_request, pass_back,
new_server_link, pass_thru_headers. The CGI::BasePlus module would still
be a 'package CGI::Base;'.

AUTHOR, COPYRIGHT and ACKNOWLEDGEMENTS
--------------------------------------

This code is Copyright (C) Tim Bunce 1995. All rights reserved.  This code
is free software; you can redistribute it and/or modify it under the same
terms as Perl itself.

This code includes ideas from the work of Steven E. Brenner
<S.E.Brenner@bioc.cam.ac.uk> (cgi-lib), Lincoln Stein
<lstein@genome.wi.mit.edu> (CGI.pm), Pratap Pereira
<pereira@ee.eng.ohio-state.edu> (phttpd) and possibly others.

IN NO EVENT SHALL THE AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
THIS SOFTWARE AND ITS DOCUMENTATION (INCLUDING, BUT NOT LIMITED TO, LOST
PROFITS) EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.

SEE ALSO
--------

URI::URL, CGI::Request, CGI::MiniSvr

SUPPORT
-------

Please use comp.infosystems.www.* and comp.lang.perl.misc for support.
Please do _NOT_ contact the author directly. I'm sorry but I just don't
have the time.


File: pm.info,  Node: CGI/BasePlus,  Next: CGI/Carp,  Prev: CGI/Base,  Up: Module List

HTTP CGI Base Class with Handling of Multipart Forms
****************************************************

NAME
====

CGI::BasePlus - HTTP CGI Base Class with Handling of Multipart Forms

DESCRIPTION
===========

This module implements a CGI::BasePlus object that is identical in
behavior to CGI::Base except that it provides special handling for
postings of MIME type multipart/form-data (which may get very long).  In
the case of these types of postings, parts that are described as being
from a file upload are copied into a temporary file in /usr/tmp, a
filehandle is opened on the temporary files, and the name of the
filehandle is returned to the caller in the $CGI::Base:QUERY_STRING
variable.

Please see *Note CGI/Base: CGI/Base, for more information.

SEE ALSO
--------

URI::URL, CGI::Request, CGI::MiniSvr, CGI::Base


File: pm.info,  Node: CGI/Carp,  Next: CGI/Fast,  Prev: CGI/BasePlus,  Up: Module List

CGI routines for writing to the HTTPD (or other) error log
**********************************************************

NAME
====

*CGI::Carp* - CGI routines for writing to the HTTPD (or other) error log

SYNOPSIS
========

     use CGI::Carp;

     croak "We're outta here!";
     confess "It was my fault: $!";
     carp "It was your fault!";
     warn "I'm confused";
     die  "I'm dying.\n";

DESCRIPTION
===========

CGI scripts have a nasty habit of leaving warning messages in the error
logs that are neither time stamped nor fully identified.  Tracking down
the script that caused the error is a pain.  This fixes that.  Replace the
usual

     use Carp;

with

     use CGI::Carp

And the standard warn(), die (), croak(), confess() and carp() calls will
automagically be replaced with functions that write out nicely
time-stamped messages to the HTTP server error log.

For example:

     [Fri Nov 17 21:40:43 1995] test.pl: I'm confused at test.pl line 3.
     [Fri Nov 17 21:40:43 1995] test.pl: Got an error message: Permission denied.
     [Fri Nov 17 21:40:43 1995] test.pl: I'm dying.

REDIRECTING ERROR MESSAGES
==========================

By default, error messages are sent to STDERR.  Most HTTPD servers direct
STDERR to the server's error log.  Some applications may wish to keep
private error logs, distinct from the server's error log, or they may wish
to direct error messages to STDOUT so that the browser will receive them.

The `carpout()' function is provided for this purpose.  Since carpout() is
not exported by default, you must import it explicitly by saying

     use CGI::Carp qw(carpout);

The carpout() function requires one argument, which should be a reference
to an open filehandle for writing errors.  It should be called in a BEGIN
block at the top of the CGI application so that compiler errors will be
caught.  Example:

     BEGIN {
       use CGI::Carp qw(carpout);
       open(LOG, ">>/usr/local/cgi-logs/mycgi-log") or
         die("Unable to open mycgi-log: $!\n");
       carpout(LOG);
     }

carpout() does not handle file locking on the log for you at this point.

The real STDERR is not closed - it is moved to SAVEERR.  Some servers,
when dealing with CGI scripts, close their connection to the browser when
the script closes STDOUT and STDERR.  SAVEERR is used to prevent this from
happening prematurely.

You can pass filehandles to carpout() in a variety of ways.  The "correct"
way according to Tom Christiansen is to pass a reference to a filehandle
GLOB:

     carpout(\*LOG);

This looks weird to mere mortals however, so the following syntaxes are
accepted as well:

     carpout(LOG);
     carpout(main::LOG);
     carpout(main'LOG);
     carpout(\LOG);
     carpout(\'main::LOG');

     ... and so on

Use of carpout() is not great for performance, so it is recommended for
debugging purposes or for moderate-use applications.  A future version of
this module may delay redirecting STDERR until one of the CGI::Carp
methods is called to prevent the performance hit.

MAKING PERL ERRORS APPEAR IN THE BROWSER WINDOW
===============================================

If you want to send fatal (die, confess) errors to the browser, ask to
import the special "fatalsToBrowser" subroutine:

     use CGI::Carp qw(fatalsToBrowser);
     die "Bad error here";

Fatal errors will now be echoed to the browser as well as to the log.
CGI::Carp arranges to send a minimal HTTP header to the browser so that
even errors that occur in the early compile phase will be seen.  Nonfatal
errors will still be directed to the log file only (unless redirected with
carpout).

AUTHORS
=======

Lincoln D. Stein <lstein@genome.wi.mit.edu>.  Feel free to redistribute
this under the Perl Artistic License.

carpout() added and minor corrections by Marc Hedlund <hedlund@best.com>
on 11/26/95.

SEE ALSO
========

Carp, CGI::Base, CGI::BasePlus, CGI::Request, CGI::MiniSvr, CGI::Form,
CGI::Response


File: pm.info,  Node: CGI/Fast,  Next: CGI/Form,  Prev: CGI/Carp,  Up: Module List

CGI Interface for Fast CGI
**************************

NAME
====

CGI::Fast - CGI Interface for Fast CGI

SYNOPSIS
========

     use CGI::Fast qw(:standard);
     $COUNTER = 0;
     while (new CGI::Fast) {
     	print header;
     	print start_html("Fast CGI Rocks");
     	print
     	    h1("Fast CGI Rocks"),
     	    "Invocation number ",b($COUNTER++),
             " PID ",b($$),".",
     	    hr;
         print end_html;
     }

DESCRIPTION
===========

CGI::Fast is a subclass of the CGI object created by CGI.pm.  It is
specialized to work well with the Open Market FastCGI standard, which
greatly speeds up CGI scripts by turning them into persistently running
server processes.  Scripts that perform time-consuming initialization
processes, such as loading large modules or opening persistent database
connections, will see large performance improvements.

OTHER PIECES OF THE PUZZLE
==========================

In order to use CGI::Fast you'll need a FastCGI-enabled Web server.  Open
Market's server is FastCGI-savvy.  There are also freely redistributable
FastCGI modules for NCSA httpd 1.5 and Apache.  FastCGI-enabling modules
for Microsoft Internet Information Server and Netscape Communications
Server have been announced.

In addition, you'll need a version of the Perl interpreter that has been
linked with the FastCGI I/O library.  Precompiled binaries are available
for several platforms, including DEC Alpha, HP-UX and SPARC/Solaris, or
you can rebuild Perl from source with patches provided in the FastCGI
developer's kit.  The FastCGI Perl interpreter can be used in place of
your normal Perl without ill consequences.

You can find FastCGI modules for Apache and NCSA httpd, precompiled Perl
interpreters, and the FastCGI developer's kit all at URL:

     http://www.fastcgi.com/

WRITING FASTCGI PERL SCRIPTS
============================

FastCGI scripts are persistent: one or more copies of the script are
started up when the server initializes, and stay around until the server
exits or they die a natural death.  After performing whatever one-time
initialization it needs, the script enters a loop waiting for incoming
connections, processing the request, and waiting some more.

A typical FastCGI script will look like this:

     #!/usr/local/bin/perl    # must be a FastCGI version of perl!
     use CGI::Fast;
     &do_some_initialization();
     while ($q = new CGI::Fast) {
     	&process_request($q);
     }

Each time there's a new request, CGI::Fast returns a CGI object to your
loop.  The rest of the time your script waits in the call to new().  When
the server requests that your script be terminated, new() will return
undef.  You can of course exit earlier if you choose.  A new version of the
script will be respawned to take its place (this may be necessary in order
to avoid Perl memory leaks in long-running scripts).

CGI.pm's default CGI object mode also works.  Just modify the loop this
way:

     while (new CGI::Fast) {
     	&process_request;
     }

Calls to header(), start_form(), etc. will all operate on the current
request.

INSTALLING FASTCGI SCRIPTS
==========================

See the FastCGI developer's kit documentation for full details.  On the
Apache server, the following line must be added to srm.conf:

     AddType application/x-httpd-fcgi .fcgi

FastCGI scripts must end in the extension .fcgi.  For each script you
install, you must add something like the following to srm.conf:

     AppClass /usr/etc/httpd/fcgi-bin/file_upload.fcgi -processes 2

This instructs Apache to launch two copies of file_upload.fcgi at startup
time.

USING FASTCGI SCRIPTS AS CGI SCRIPTS
====================================

Any script that works correctly as a FastCGI script will also work
correctly when installed as a vanilla CGI script.  However it will not see
any performance benefit.

CAVEATS
=======

I haven't tested this very much.

AUTHOR INFORMATION
==================

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.

Address bug reports and comments to: lstein@genome.wi.mit.edu

BUGS
====

This section intentionally left blank.

SEE ALSO
========

*Note CGI/Carp: CGI/Carp,, *Note CGI: CGI,

=cut


File: pm.info,  Node: CGI/Form,  Next: CGI/Imagemap,  Prev: CGI/Fast,  Up: Module List

Build Smart HTML Forms on Top of the CGI:: Modules
**************************************************

NAME
====

CGI::Form - Build Smart HTML Forms on Top of the CGI:: Modules

ABSTRACT
========

This perl library uses perl5 objects to make it easy to create Web
fill-out forms and parse their contents.  This package defines CGI
objects, entities that contain the values of the current query string and
other state variables.  Using a CGI object's methods, you can examine
keywords and parameters passed to your script, and create forms whose
initial values are taken from the current query (thereby preserving state
information).

INSTALLATION:
=============

To use this package, install it in your perl library path (usually
/usr/local/lib/perl5/ and add the following to your perl CGI script:

     Use CGI::Form;

DESCRIPTION
===========

CREATING A NEW FORM OBJECT AND PROCESSING PARAMETERS:
-----------------------------------------------------

     $query = new CGI::Form;

This will parse the input (from both POST and GET methods) and store it
into a perl5 object called $query.  This method is inherited from *Note
CGI/Request: CGI/Request,.  See its manpage for details.  Similarly,
CGI::Form uses CGI::Request to get and set named query parameters, e.g.

     @values = $query->param('foo');

     -and-

     $query->param('foo','an','array','of','values');
     or whatever!

CALLING CGI::Form FUNCTIONS THAT TAKE MULTIPLE ARGUMENTS
--------------------------------------------------------

In versions of Form.pm prior to 2.8, it could get difficult to remember
the proper order of arguments in CGI function calls that accepted five or
six different arguments.  As of 2.8, there's a better way to pass
arguments to the various CGI functions.  In this style, you pass a series
of name=>argument pairs, like this:

     $field = $query->radio_group(-name=>'OS',
                                  -values=>[Unix,Windows,Macintosh],
                                  -default=>'Unix');

The advantages of this style are that you don't have to remember the exact
order of the arguments, and if you leave out a parameter, in most cases it
will default to some reasonable value.  If you provide a parameter that
the method doesn't recognize, it will usually do something useful with it,
such as incorporating it into the HTML form tag.  For example if Netscape
decides next week to add a new JUSTIFICATION parameter to the text field
tags, you can start using the feature without waiting for a new version of
CGI.pm:

     $field = $query->textfield(-name=>'State',
                                -default=>'gaseous',
                                -justification=>'RIGHT');

This will result in an HTML tag that looks like this:

     <INPUT TYPE="textfield" NAME="State" VALUE="gaseous"
                    JUSTIFICATION="RIGHT">

Parameter names are case insensitive: you can use -name, or -Name or
-NAME.  You don't have to use the hyphen if you don't want to.  After
creating a CGI object, call the *use_named_parameters()* method with a
nonzero value.  This will tell CGI.pm that you intend to use named
parameters exclusively:

     $query = new CGI;
     $query->use_named_parameters(1);
     $field = $query->radio_group('name'=>'OS',
                                  'values'=>['Unix','Windows','Macintosh'],
                                  'default'=>'Unix');

Actually, CGI.pm only looks for a hyphen in the first parameter.  So you
can leave it off subsequent parameters if you like.  Something to be wary
of is the potential that a string constant like "values" will collide with
a keyword (and in fact it does!) While Perl usually figures out when
you're referring to a function and when you're referring to a string, you
probably should put quotation marks around all string constants just to
play it safe.

CREATING A SELF-REFERENCING URL THAT PRESERVES STATE INFORMATION:
-----------------------------------------------------------------

     $myself = $query->self_url
     print "<A HREF=$myself>I'm talking to myself.</A>

self_url() will return a URL, that, when selected, will reinvoke this
script with all its state information intact.  This is most useful when
you want to jump around within the document using internal anchors but you
don't want to disrupt the current contents of the form(s).  Something like
this will do the trick.

     $myself = $query->self_url
     print "<A HREF=$myself#table1>See table 1</A>
     print "<A HREF=$myself#table2>See table 2</A>
     print "<A HREF=$myself#yourself>See for yourself</A>

This method is actually defined in *Note CGI/Base: CGI/Base,, but is passed
through here for compatability with CGI.pm

CREATING THE HTTP HEADER:
-------------------------

     print $query->header;

     -or-

     print $query->header('image/gif');

header() returns the Content-type: header.  you can provide your own MIME
type if you choose, otherwise it defaults to text/html.

This method is provided for compatability with CGI.pm *only*.  It is much
better to use the SendHeaders() method of *Note CGI/Base: CGI/Base,.

*NOTE:* This is a temporary method that will be replaced by the
CGI::Response module as soon as it is released.

GENERATING A REDIRECTION INSTRUCTION
------------------------------------

     print $query->redirect('http://somewhere.else/in/movie/land');

redirect the browser elsewhere.  If you use redirection like this, you
should *not* print out a header as well.

This method is provided for compatability with CGI.pm *only*.  New scripts
should use CGI::Base's redirect() method instead.

CREATING THE HTML HEADER:
-------------------------

     print $query->start_html(-title=>'Secrets of the Pyramids',
                              -author=>'fred@capricorn.org',
                              -base=>'true',
                              -BGCOLOR=>"#00A0A0"');

     -or-

     print $query->start_html('Secrets of the Pyramids',
                              'fred@capricorn.org','true',
                              'BGCOLOR="#00A0A0"');

This will return a canned HTML header and the opening <BODY> tag.  All
parameters are optional.   In the named parameter form, recognized
parameters are -title, -author and -base (see below for the explanation).
Any additional parameters you provide, such as the Netscape unofficial
BGCOLOR attribute, are added to the <BODY> tag.

Positional parameters are as follows:

Parameters:

     The title


     The author's e-mail address (will create a <LINK REV="MADE"> tag if
     present


     A 'true' flag if you want to include a <BASE> tag in the header.  This
     helps resolve relative addresses to absolute ones when the document
     is moved, but makes the document hierarchy non-portable.  Use with
     care!

5, 6...
     Any other parameters you want to include in the <BODY> tag.  This is
     a good place to put Netscape extensions, such as colors and wallpaper
     patterns.

ENDING THE HTML DOCUMENT:
-------------------------

     print $query->end_html

This ends an HTML document by printing the </BODY></HTML> tags.

CREATING FORMS:
===============

*General note*  The various form-creating methods all return strings to
the caller, containing the tag or tags that will create the requested form
element.  You are responsible for actually printing out these strings.
It's set up this way so that you can place formatting tags around the form
elements.

*Another note* The default values that you specify for the forms are only
used the *first* time the script is invoked.  If there are already values
present in the query string, they are used, even if blank.  If you want to
change the value of a field from its previous value, call the param()
method to set it.

*Yet another note* By default, the text and labels of form elements are
escaped according to HTML rules.  This means that you can safely use
"<CLICK ME>" as the label for a button.  However, it also interferes with
your ability to incorporate special HTML character sequences, such as
&Aacute;, into your fields.  If you wish to turn off automatic escaping,
call the autoEscape() method with a false value immediately after creating
the CGI object:

     $query = new CGI::Form;
     $query->autoEscape(undef);

CREATING AN ISINDEX TAG
-----------------------

     print $query->isindex($action);

Prints out an <ISINDEX> tag.  Not very exciting.  The optional parameter
specifies an ACTION="<URL>" attribute.

STARTING AND ENDING A FORM
--------------------------

     print $query->startform($method,$action,$encoding);
       <... various form stuff ...>
     print $query->endform;

startform() will return a <FORM> tag with the optional method, action and
form encoding that you specify.  The defaults are:

method: POST     action: this script     encoding:
application/x-www-form-urlencoded

The encoding method tells the browser how to package the various fields of
the form before sending the form to the server.  Two values are possible:

*application/x-www-form-urlencoded*
     This is the older type of encoding used by all browsers prior to
     Netscape 2.0.  It is compatible with many CGI scripts and is suitable
     for short fields containing text data.

*multipart/form-data*
     This is the newer type of encoding introduced by Netscape 2.0.  It is
     suitable for forms that contain very large fields or that are
     intended for transferring binary data.  Most importantly, it enables
     the "file upload" feature of Netscape 2.0 forms.

     Forms that use this type of encoding are not easily interpreted by
     CGI scripts unless they use CGI.pm or another library designed to
     handle them.

For your convenience, Form.pm defines two subroutines that contain the
values of the two alternative encodings:

     use CGI::Form(URL_ENCODED,MULTIPART);

For compatability, the startform() method uses the older form of encoding
by default.  If you want to use the newer form of encoding by default, you
can call *start_multipart_form()* instead of *startform()*.

endform() returns a </FORM> tag.

CREATING A TEXT FIELD
---------------------

     print $query->textfield(-name=>'field_name',
     	                    -default=>'starting value',
     	                    -size=>50,
     	                    -maxlength=>80);
     	-or-

     print $query->textfield('field_name','starting value',50,80);

textfield() will return a text input field.

Parameters

     The first parameter is the required name for the field (-name).


     The optional second parameter is the default starting value for the
     field contents (-default).


     The optional third parameter is the size of the field in
     characters (-size).


     The optional fourth parameter is the maximum number of characters the
          field will accept (-maxlength).

As with all these methods, the field will be initialized with its previous
contents from earlier invocations of the script.  When the form is
processed, the value of the text field can be retrieved with:

     $value = $query->param('foo');

If you want to reset it from its initial value after the script has been
called once, you can do so like this:

     $query->param('foo',"I'm taking over this value!");

CREATING A BIG TEXT FIELD
-------------------------

     print $query->textarea(-name=>'foo',
     	 		  -default=>'starting value',
     	                  -rows=>10,
     	                  -columns=>50);

     -or

     print $query->textarea('foo','starting value',10,50);

textarea() is just like textfield, but it allows you to specify rows and
columns for a multiline text entry box.  You can provide a starting value
for the field, which can be long and contain multiple lines.

CREATING A PASSWORD FIELD
-------------------------

     print $query->password_field(-name=>'secret',
     				-value=>'starting value',
     				-size=>50,
     				-maxlength=>80);
     	-or-

     print $query->password_field('secret','starting value',50,80);

password_field() is identical to textfield(), except that its contents
will be starred out on the web page.

CREATING A FILE UPLOAD FIELD
----------------------------

     print $query->filefield(-name=>'uploaded_file',
     	                    -default=>'starting value',
     	                    -size=>50,
     	 		    -maxlength=>80);
     	-or-

     print $query->filefield('uploaded_file','starting value',50,80);

filefield() will return a file upload field for Netscape 2.0 browsers.  In
order to take full advantage of this *you must use the new multipart
encoding scheme* for the form.  You can do this either by calling
*startform()* with an encoding type of *$CGI::MULTIPART*, or by calling
the new method *start_multipart_form()* instead of vanilla *startform()*.

Parameters

     The first parameter is the required name for the field (-name).


     The optional second parameter is the starting value for the field
     contents to be used as the default file name (-default).

     The beta2 version of Netscape 2.0 currently doesn't pay any attention
     to this field, and so the starting value will always be blank.  Worse,
     the field loses its "sticky" behavior and forgets its previous
     contents.  The starting value field is called for in the HTML
     specification, however, and possibly later versions of Netscape will
     honor it.


     The optional third parameter is the size of the field in characters
     (-size).


     The optional fourth parameter is the maximum number of characters the
     field will accept (-maxlength).

When the form is processed, you can retrieve the entered filename by
calling param().

     $filename = $query->param('uploaded_file');

In Netscape Beta 1, the filename that gets returned is the full local
filename on the *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 machine, 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

In Netscape Beta 2, only the last part of the file path (the filename
itself) is returned.  I don't know what the release behavior will be.

The filename returned is also a file handle.  You can read the contents of
the file using standard Perl file reading calls:

     # Read a text file and print it out
     while (<$filename>) {
        print;
             }

     # Copy a binary file to somewhere safe
     open (OUTFILE,">>/usr/local/web/users/feedback");
     	while ($bytesread=read($filename,$buffer,1024)) {
     	   print OUTFILE $buffer;
     }

CREATING A POPUP MENU
---------------------

     print $query->popup_menu('menu_name',
                              ['eenie','meenie','minie'],
                              'meenie');

     -or-

     %labels = ('eenie'=>'your first choice',
                'meenie'=>'your second choice',
                'minie'=>'your third choice');
     print $query->popup_menu('menu_name',
                              ['eenie','meenie','minie'],
                              'meenie',\%labels);

     -or (named parameter style)-

     print $query->popup_menu(-name=>'menu_name',
     			    -values=>['eenie','meenie','minie'],
     	                    -default=>'meenie',
     	                    -labels=>\%labels);

popup_menu() creates a menu.

  1. The required first argument is the menu's name (-name).

  2. The required second argument (-values) is an array *reference*
     containing the list of menu items in the menu.  You can pass the
     method an anonymous array, as shown in the example, or a reference to
     a named array, such as "\@foo".

  3. The optional third parameter (-default) is the name of the default
     menu choice.  If not specified, the first item will be the default.
     The values of the previous choice will be maintained across queries.

  4. The optional fourth parameter (-labels) is provided for people who
     want to use different values for the user-visible label inside the
     popup menu nd the value returned to your script.  It's a pointer to an
     associative array relating menu values to user-visible labels.  If you
     leave this parameter blank, the menu values will be displayed by
     default.  (You can also leave a label undefined if you want to).

     When the form is processed, the selected value of the popup menu can
be retrieved using:

     $popup_menu_value = $query->param('menu_name');

CREATING A SCROLLING LIST
-------------------------

     print $query->scrolling_list('list_name',
                                  ['eenie','meenie','minie','moe'],
                                  ['eenie','moe'],5,'true');
        -or-

     print $query->scrolling_list('list_name',
                                  ['eenie','meenie','minie','moe'],
                                  ['eenie','moe'],5,'true',
                                  \%labels);

     -or-

     print $query->scrolling_list(-name=>'list_name',
                                  -values=>['eenie','meenie','minie','moe'],
                                  -default=>['eenie','moe'],
     	                        -size=>5,
     	                        -multiple=>'true',
                                  -labels=>\%labels);

scrolling_list() creates a scrolling list.

Parameters:

     The first and second arguments are the list name (-name) and values
     (-values).  As in the popup menu, the second argument should be an
     array reference.


     The optional third argument (-default) can be either a reference to a
     list containing the values to be selected by default, or can be a
     single value to select.  If this argument is missing or undefined,
     then nothing is selected when the list first appears.  In the named
     parameter version, you can use the synonym "-defaults" for this
     parameter.


     The optional fourth argument is the size of the list (-size).


     The optional fifth argument can be set to true to allow multiple
     simultaneous selections (-multiple).  Otherwise only one selection
     will be allowed at a time.


     The optional sixth argument is a pointer to an associative array
     containing long user-visible labels for the list items (-labels).  If
     not provided, the values will be displayed.

     When this form is procesed, all selected list items will be returned
     as a list under the parameter name 'list_name'.  The values of the
     selected items can be retrieved with:

          @selected = $query->param('list_name');

CREATING A GROUP OF RELATED CHECKBOXES
--------------------------------------

     print $query->checkbox_group(-name=>'group_name',
                                  -values=>['eenie','meenie','minie','moe'],
                                  -default=>['eenie','moe'],
     	                        -linebreak=>'true',
     	                        -labels=>\%labels);

     print $query->checkbox_group('group_name',
                                  ['eenie','meenie','minie','moe'],
                                  ['eenie','moe'],'true',\%labels);

     HTML3-COMPATIBLE BROWSERS ONLY:

     print $query->checkbox_group(-name=>'group_name',
                                  -values=>['eenie','meenie','minie','moe'],
     	                        -rows=2,-columns=>2);

checkbox_group() creates a list of checkboxes that are related by the same
name.

Parameters:

     The first and second arguments are the checkbox name and values,
     respectively (-name and -values).  As in the popup menu, the second
     argument should be an array reference.  These values are used for the
     user-readable labels printed next to the checkboxes as well as for the
     values passed to your script in the query string.


     The optional third argument (-default) can be either a reference to a
     list containing the values to be checked by default, or can be a
     single value to checked.  If this argument is missing or undefined,
     then nothing is selected when the list first appears.


     The optional fourth argument (-linebreak) can be set to true to place
     line breaks between the checkboxes so that they appear as a vertical
     list.  Otherwise, they will be strung together on a horizontal line.


     The optional fifth argument is a pointer to an associative array
     relating the checkbox values to the user-visible labels that will will
     be printed next to them (-labels).  If not provided, the values will
     be used as the default.


     *HTML3-compatible browsers* (such as Netscape) can take advantage of
     the optional parameters *-rows*, and *-columns*.  These parameters
     cause checkbox_group() to return an HTML3 compatible table containing
     the checkbox group formatted with the specified number of rows and
     columns.  You can provide just the -columns parameter if you wish;
     checkbox_group will calculate the correct number of rows for you.

     To include row and column headings in the returned table, you can use
     the *-rowheader* and *-colheader* parameters.  Both of these accept a
     pointer to an array of headings to use.  The headings are just
     decorative.  They don't reorganize the interpetation of the
     checkboxes - they're still a single named unit.

When the form is processed, all checked boxes will be returned as a list
under the parameter name 'group_name'.  The values of the "on" checkboxes
can be retrieved with:

     @turned_on = $query->param('group_name');

CREATING A STANDALONE CHECKBOX
------------------------------

     print $query->checkbox(-name=>'checkbox_name',
     			   -checked=>'checked',
     		           -value=>'ON',
     		           -label=>'CLICK ME');

     -or-

     print $query->checkbox('checkbox_name','checked','ON','CLICK ME');

checkbox() is used to create an isolated checkbox that isn't logically
related to any others.

Parameters:

     The first parameter is the required name for the checkbox (-name).  It
     will also be used for the user-readable label printed next to the
     checkbox.


     The optional second parameter (-checked) specifies that the checkbox
     is turned on by default.  Synonyms are -selected and -on.


     The optional third parameter (-value) specifies the value of the
     checkbox when it is checked.  If not provided, the word "on" is
     assumed.


     The optional fourth parameter (-label) is the user-readable label to
     be attached to the checkbox.  If not provided, the checkbox name is
     used.

The value of the checkbox can be retrieved using:

     $turned_on = $query->param('checkbox_name');

CREATING A RADIO BUTTON GROUP
-----------------------------

     print $query->radio_group(-name=>'group_name',
     			     -values=>['eenie','meenie','minie'],
                               -default=>'meenie',
     			     -linebreak=>'true',
     			     -labels=>\%labels);

     -or-

     print $query->radio_group('group_name',['eenie','meenie','minie'],
                                            'meenie','true',\%labels);

     HTML3-COMPATIBLE BROWSERS ONLY:

     print $query->checkbox_group(-name=>'group_name',
                                  -values=>['eenie','meenie','minie','moe'],
     	                        -rows=2,-columns=>2);

radio_group() creates a set of logically-related radio buttons (turning
one member of the group on turns the others off)

Parameters:

     The first argument is the name of the group and is required (-name).


     The second argument (-values) is the list of values for the radio
     buttons.  The values and the labels that appear on the page are
     identical.  Pass an array *reference* in the second argument, either
     using an anonymous array, as shown, or by referencing a named array as
     in "\@foo".


     The optional third parameter (-default) is the name of the default
     button to turn on. If not specified, the first item will be the
     default.  You can provide a nonexistent button name, such as "-" to
     start up with no buttons selected.


     The optional fourth parameter (-linebreak) can be set to 'true' to put
     line breaks between the buttons, creating a vertical list.


     The optional fifth parameter (-labels) is a pointer to an associative
     array relating the radio button values to user-visible labels to be
     used in the display.  If not provided, the values themselves are
     displayed.


     *HTML3-compatible browsers* (such as Netscape) can take advantage of
     the optional parameters *-rows*, and *-columns*.  These parameters
     cause radio_group() to return an HTML3 compatible table containing
     the radio group formatted with the specified number of rows and
     columns.  You can provide just the -columns parameter if you wish;
     radio_group will calculate the correct number of rows for you.

     To include row and column headings in the returned table, you can use
     the *-rowheader* and *-colheader* parameters.  Both of these accept a
     pointer to an array of headings to use.  The headings are just
     decorative.  They don't reorganize the interpetation of the radio
     buttons - they're still a single named unit.

When the form is processed, the selected radio button can be retrieved
using:

     $which_radio_button = $query->param('group_name');

CREATING A SUBMIT BUTTON
------------------------

     print $query->submit(-name=>'button_name',
     		        -value=>'value');

     -or-

     print $query->submit('button_name','value');

submit() will create the query submission button.  Every form should have
one of these.

Parameters:

     The first argument (-name) is optional.  You can give the button a
     name if you have several submission buttons in your form and you want
     to distinguish between them.  The name will also be used as the
     user-visible label.  Be aware that a few older browsers don't deal
     with this correctly and *never* send back a value from a button.


     The second argument (-value) is also optional.  This gives the button
     a value that will be passed to your script in the query string.

You can figure out which button was pressed by using different values for
each one:

     $which_one = $query->param('button_name');

CREATING A RESET BUTTON
-----------------------

     print $query->reset

reset() creates the "reset" button.  Note that it restores the form to its
value from the last time the script was called, NOT necessarily to the
defaults.

CREATING A DEFAULT BUTTON
-------------------------

     print $query->defaults('button_label')

defaults() creates a button that, when invoked, will cause the form to be
completely reset to its defaults, wiping out all the changes the user ever
made.

CREATING A HIDDEN FIELD
-----------------------

     print $query->hidden(-name=>'hidden_name',
                          -default=>['value1','value2'...]);

     -or-

     print $query->hidden('hidden_name','value1','value2'...);

hidden() produces a text field that can't be seen by the user.  It is
useful for passing state variable information from one invocation of the
script to the next.

Parameters:

     The first argument is required and specifies the name of this field
     (-name).


     The second argument is also required and specifies its value
     (-default).  In the named parameter style of calling, you can provide
     a single value here or a reference to a whole list

Fetch the value of a hidden field this way:

     $hidden_value = $query->param('hidden_name');

Note, that just like all the other form elements, the value of a hidden
field is "sticky".  If you want to replace a hidden field with some other
values after the script has been called once you'll have to do it manually:

     $query->param('hidden_name','new','values','here');

CREATING A CLICKABLE IMAGE BUTTON
---------------------------------

     print $query->image_button(-name=>'button_name',
     			        -src=>'/source/URL',
     			        -align=>'MIDDLE');

     -or-

     print $query->image_button('button_name','/source/URL','MIDDLE');

image_button() produces a clickable image.  When it's clicked on the
position of the click is returned to your script as "button_name.x" and
"button_name.y", where "button_name" is the name you've assigned to it.

Parameters:

     The first argument (-name) is required and specifies the name of this
     field.


     The second argument (-src) is also required and specifies the URL

The third option (-align, optional) is an alignment type, and may be TOP, BOTTOM or MIDDLE
Fetch the value of the button this way:      $x =
$query->param('button_name.x');      $y = $query->param('button_name.y');

DEBUGGING:
==========

If you are running the script from the command line or in the perl
debugger, you can pass the script a list of keywords or parameter=value
pairs on the command line or from standard input (you don't have to worry
about tricking your script into reading from environment variables).  You
can pass keywords like this:

     your_script.pl keyword1 keyword2 keyword3

or this:

     your_script.pl keyword1+keyword2+keyword3

or this:

     your_script.pl name1=value1 name2=value2

or this:

     your_script.pl name1=value1&name2=value2

or even as newline-delimited parameters on standard input.

When debugging, you can use quotes and backslashes to escape characters in
the familiar shell manner, letting you place spaces and other funny
characters in your parameter=value pairs:

     your_script.pl name1='I am a long value' name2=two\ words

DUMPING OUT ALL THE NAME/VALUE PAIRS
------------------------------------

The dump() method produces a string consisting of all the query's
name/value pairs formatted nicely as a nested list.  This is useful for
debugging purposes:

     print $query->dump

Produces something that looks like:

     <UL>
     <LI>name1
         <UL>
         <LI>value1
         <LI>value2
         </UL>
     <LI>name2
         <UL>
         <LI>value1
         </UL>
     </UL>

You can pass a value of 'true' to dump() in order to get it to print the
results out as plain text, suitable for incorporating into a <PRE> section.

FETCHING ENVIRONMENT VARIABLES
==============================

All the environment variables, such as REMOTE_HOST and HTTP_REFERER, are
available through the CGI::Base object.  You can get at these variables
using with the cgi() method (inherited from CGI::Request):

     $query->cgi->var('REMOTE_HOST');

AUTHOR INFORMATION
==================

This code is copyright 1995 by Lincoln Stein and the Whitehead Institute
for Biomedical Research.  It may be used and modified freely.  I request,
but do not require, that this credit appear in the code.

Address bug reports and comments to: lstein@genome.wi.mit.edu

A COMPLETE EXAMPLE OF A SIMPLE FORM-BASED SCRIPT
================================================

     #!/usr/local/bin/perl
     
             use CGI::Form;
     
             $query = new CGI::Form;

     print $query->header;
     print $query->start_html("Example CGI.pm Form");
     print "<H1> Example CGI.pm Form</H1>\n";
     &print_prompt($query);
     &do_work($query);
     	&print_tail;
     print $query->end_html;
     
     sub print_prompt {
          	   my($query) = @_;
     
          	   print $query->startform;
          	   print "<EM>What's your name?</EM><BR>";
          	   print $query->textfield('name');
          	   print $query->checkbox('Not my real name');
     
          	   print "<P><EM>Where can you find English Sparrows?</EM><BR>";
          	   print $query->checkbox_group('Sparrow locations',
     			 [England,France,Spain,Asia,Hoboken],
     			 [England,Asia]);
     
          	   print "<P><EM>How far can they fly?</EM><BR>",
                 	$query->radio_group('how far',
     	       ['10 ft','1 mile','10 miles','real far'],
     	       '1 mile');
     
          	   print "<P><EM>What's your favorite color?</EM>  ";
          	   print $query->popup_menu('Color',['black','brown','red','yellow'],'red');
     
          	   print $query->hidden('Reference','Monty Python and the Holy Grail');
     
          	   print "<P><EM>What have you got there?</EM>  ";
          	   print $query->scrolling_list('possessions',
     		 ['A Coconut','A Grail','An Icon',
     		  'A Sword','A Ticket'],
     		 undef,
     		 10,
     		 'true');
     
          	   print "<P><EM>Any parting comments?</EM><BR>";
          	   print $query->textarea('Comments',undef,10,50);
     
          	   print "<P>",$query->reset;
          	   print $query->submit('Action','Shout');
          	   print $query->submit('Action','Scream');
          	   print $query->endform;
          	   print "<HR>\n";
     }
     
     sub do_work {
          	   my($query) = @_;
          	   my(@values,$key);

     print "<H2>Here are the current settings in this form</H2>";

     foreach $key ($query->param) {
      	      print "<STRONG>$key</STRONG> -> ";
      	      @values = $query->param($key);
      	      print join(", ",@values),"<BR>\n";
               }
      	}
     
      	sub print_tail {
     print <<END;
      	<HR>
      	<ADDRESS>Lincoln D. Stein</ADDRESS><BR>
      	<A HREF="/">Home Page</A>
      	END
      	}

BUGS
====

This module doesn't do as much as CGI.pm, and it takes longer to load.
Such is the price of flexibility.

SEE ALSO
========

*Note URI/URL: URI/URL,, *Note CGI/Request: CGI/Request,, *Note
CGI/MiniSvr: CGI/MiniSvr,, *Note CGI/Base: CGI/Base,, *Note CGI: CGI,


File: pm.info,  Node: CGI/Imagemap,  Next: CGI/MiniSvr,  Prev: CGI/Form,  Up: Module List

imagemap behavior for CGI programs
**********************************

NAME
====

CGI::Imagemap.pm - imagemap behavior for CGI programs

SYNOPSIS
========

     use CGI::Imagemap;
     
     $map = new CGI::Imagemap;
     $map->setmap(@map);
     $action = $map->action($x,$y);
     
     -- or --

     use CGI::Imagemap 'action_map';
     
     $action = action_map($x,$y,@map);

DESCRIPTION
===========

CGI::Imagemap allows CGI programmers to place TYPE=IMAGE form fields on
their HTML fill-out forms, with either client-side or server-side maps
emulated.

The imagemap file follows that of the NCSA imagemap program.  Each point
is an x,y tuple.  Each line in the map consists of one of the following
formats.  Comment lines start with "#".

     circle action center edgepoint
     rect action upperleft lowerright
     point action point
     poly action point1 point2 ... pointN
     default action

Using "point" and "default" in the same map makes no sense. If "point" is
used, the action for the closest one is selected.

To use CGI::Imagemap, define an image submit map on your form with
something like:

     <input type=image name=mv_todo
          SRC="image_url">

You can pass a "client-side" imagemap like this:

     <input type="hidden" name="todo.map"
     		value="rect action1 0,0 25,20">
     <input type="hidden" name="todo.map"
     		value="rect action2 26,0 50,20">
     <input type="hidden" name="todo.map"
     		value="rect action3 51,0 75,20">
     <input type="hidden" name="todo.map"
     		value="default action0">

If the @map passed parameter contains a NUL (\0) in the first array
position, the map is assumed to be null-separated and @map is built by
splitting it.  This allows a null-separated todo.map with multiple values
(parsed by a cgi-lib.pl or the like) to be referenced.

All of the following examples assume the above definitions in your form.

Static Methods
--------------

CGI::Imagemap allows the export of two routines, *action_map* and
*map_untaint*.   If you choose to use CGI::Imagemap statically, call the
module with:

     use CGI::Imagemap qw(action_map map_untaint);

action_map(x,y,map)
     We are assuming the map definition above, with the *type=image*
     variable named `todo', and the map in *todo.map*. You can pass the map
     in one of two ways.  The first is compatible with the CGI.pm (or
     CGI::*) modules, and passes the map as an array:

          $query = new CGI;
          my $x = $query->param('todo.x');
          my $y = $query->param('todo.y');
          my $map = $query->param('todo.map');
          $action = action_map($x, $y, $map);

     If you are using the old *cgi-lib.pl* library, which places multiple
     instances of the same form variable in a scalar, separated by null
     (\0) characters, you can do this:

          ReadParse(*FORM);
          my $x = $FORM{'todo.x'};
          my $y = $FORM{'todo.y'};
          my $map = $FORM{'todo.map'};
          $action = action_map($x, $y, $map);

map_untaint($untaint)
     If you are running with taint checking, as is suggested for CGI
     programs, you can use map_untaint(1) to set map untainting on a
     global basis.  (If using class methods, each has its own instance of
     untainting).

     It ensures all characters in the action fit pattern of [-\w.+@]+,
     meaning alphnumerics, underscores, dashes (-), periods, and the @
     sign.  It also checks the methods (rect,poly,point,default,circle)
     and ensures that points/tuples are only integers.  Once that is done,
     it untaints the passed form variables.

          map_untaint(1);    # Turns on untainting
          map_untaint('yes');# Same as above

          map_untaint(0);    # Disable untainting
          map_untaint('no'); # Same as above
          
          $status = map_untaint(); # Get status

     Default is no untainting.

Class Methods
-------------

The class methods for CGI::Imagemap are much the same as above, with the
exception that multiple imagemaps are then maintained by the module, with
full independence. The following method definitions assume the CGI::Form
module is being used, like this:

     use CGI::Form;
     use CGI::Imagemap;

     $query  = new CGI::Form;
     $map    = new CGI::Imagemap;

setmap(@map)
     This sets the map for the instance.

          $map = new CGI::Imagemap;
          $map->setmap($query->param('todo.map'));

addmap(@map)
     This adds a new map action specification *to the current map*.

          $map->addmap('point action5 3,9'));

action(x,y)
     This finds the action, based on the active map and the values of x
     and y,

          $x = $query->param('todo.x');
          $y = $query->param('todo.y');
          $action = $map->action($x, $y);

untaint()
     Sets, unsets, or returns the taint status for the instance.

          $map->untaint(1);       # Turns on untainting
          $map->untaint('yes');   # Same as above
          $map->untaint(1);       # Disables untainting
          $map->untaint('yes');   # Same as above
          $status = $map->untaint(); # Get status

version()
     Returns the version number of the module.

EXAMPLE
=======

A couple of self-contained examples are included in the CGI::Imagemap
package.  They are:

     testmap     -  Uses the CGI::Form module
     testmap.old -  Uses the old cgi-lib.pl

BUGS
====

The untainting stuff is not totally independent - threading might not work
very well.  This can be fixed if it is important - in the CGI world, I
doubt it.

AUTHOR
======

Mike Heins, Internet Robotics, <mikeh@iac.net>

CREDITS
=======

This work is heavily kited from the Perl imagemap program originally
written by V. Khera <khera@kciLink.com>.


File: pm.info,  Node: CGI/MiniSvr,  Next: CGI/Out,  Prev: CGI/Imagemap,  Up: Module List

Adds to CGI::Base the ability for a CGI script to become a mini http server.
****************************************************************************

NAME
====

CGI::MiniSvr - Adds to CGI::Base the ability for a CGI script to become a
mini http server.

SYNOPSIS
========


     use CGI::MiniSvr;
     
     $cgi = new CGI::MiniSvr;
     $cgi = new CGI::MiniSvr $port_or_path;
     $cgi = new CGI::MiniSvr $port_or_path, $timeout_mins;
     
     $cgi->port;               # return MiniSvr port number with leading colon

     $cgi->spawn;              # fork/detach from httpd
     
     $cgi->get;                # get input
     
     $cgi->pass_thru($host, $port);
     $cgi->redirect($url);
     
     $cgi->done;               # end 'page' and close connection (high-level)
     $cgi->close;              # just close connection (low-level)

See also the CGI::Base methods.

DESCRIPTION
===========

This file implements the CGI::MiniSvr object. This object represents an
alternative interface between the application and an HTTP deamon.

In a typical CGI scenario the interface is just a collection of
environment variables passed to a process which then generated some outout
and exits. The CGI::Base class implements this standard interface.

The CGI::MiniSvr class inherits from CGI::Base and extends it to implement
a 'mini http daemon' which can be spawned (forked) from a CGI script in
order to maintain state information for a client 'session'.

This is very useful. It neatly side-steps many of the painful issues
involved in writing real-world multi-screen applications using the
standard CGI interface (namely saving and restoring state between screens).

Another use for the MiniSvr is to allow cgi scripts to produce output
pages with dynamically generated in-line graphics (for example). To do
this the script would spawn a MiniSvr and refer to its port number in the
URL's for the embedded images. The MiniSvr would then sit on the port,
with a relatively short timeout, ready to serve the requests for those
images.  Once all the images have been served the MiniSvr would simply
exit.

Like the CGI::Base module the CGI::MiniSvr module does not do any
significant data parsing. Higher level query processing (forms etc) is
performed by the CGI::Request module.

Note that the implementation of these modules means that you should invoke
`new CGI::Base;' before `new CGI::MiniSvr;'. This is the natural order
anyway and so should not be a problem.

WARNING!
--------

This module is *not* a good solution to many problems! It is only a good
solution to some. It should only be used by those who understand why it is
*not* a good solution to many problems!

For those who don't see the pitfalls of the mini server approach, consider
just this one example:  what happens to your machine if new 'sessions'
start, on average, faster than abandoned ones timeout?

Security and short-lifespan URL's are some of the other problems.

If in doubt don't use it! If you do then don't blame me for any of the
problems you may (will) experience. *You have been warned!*

DIRECT ACCESS USAGE
-------------------

In this mode the MiniSvr creates an internet domain socket and returns to
the client a page with URL's which contain the MiniSvr's own port number.

     $q = GetRequest();      # get initial request
     $cgi = new CGI::MiniSvr;# were going to switch to CGI::MiniSvr later
     $port = $cgi->port;     # get our port number (as ':NNNN') for use in URL's
     $me = "http://$SERVER_NAME$port$SCRIPT_NAME"; # build my url
     print "Hello... <A HREF="$me?INSIDE"> Step Inside ...</A>\r\n";
     $cgi->done(1);          # flush out page, include debugging
     $cgi->spawn and exit 0; # fork, original cgi process exits
     CGI::Query::Interface($cgi); # default to new interface

     while($q = GetQuery() or $cgi->exit){ # await request/timeout
        ...
     }

INDIRECT ACCESS USAGE
---------------------

In this mode the MiniSvr creates a unix domain socket and returns to the
client a page with a hidden field containing the path to the socket.

     $q = GetRequest(); # get initial request
     $path = $q->param('_minisvr_socket_path');
     if ($path) {
         # just pass request on to our mini server
         $q->cgi->pass_thru('', $path) or (...handle timeout...)
         $q->cgi->done;
     } else {
         # launch new mini server
         $path = "/tmp/cgi.$$";
         $cgi = new CGI::MiniSvr $path; # unix domain socket
         # code here mostly same as 'DIRECT ACCESS' above except that
         # the returned page has an embedded field _minisvr_socket_path
         # set to $path
         ...
     }

SUBCLASSING THE MINISVR
-----------------------

In some cases you may wish to have more control over the behaviour of the
mini-server, such as handling some requests at a low level without
disturbing the application.  Subclassing the server is generally a good
approach. Use something like this:

     #   Define a specialised subclass of the MiniSvr for this application
     {
       package CGI::MiniSvr::FOO;
       use CGI::MiniSvr;
       @ISA = qw(CGI::MiniSvr);

     # Default behaviour for everything except GET requests for .(gif|html|jpg)
     # Note that we must take great care not to: a) try to pass_thru to ourselves
     # (it would hang), or b) pass_thru to the server a request which it will
     # try to satisfy by starting another instance of this same script!

     sub method_GET {
         my $self = shift;
         if ($self->{SCRIPT_NAME} =~ m/\.(gif|jpg|html)$/){
             $self->pass_thru('', $self->{ORIG_SERVER_PORT});
             $self->done;
             return 'NEXT';
         }
         1;
     }
     # ... other overriding methods can be defined here ...
       }

Once defined you can use your new customised mini server by changing:

     $cgi = new CGI::MiniSvr;

into:

     $cgi = new CGI::MiniSvr::FOO;

With the example code above any requests for gif, jpg or html will be
forwarded to the server which originally invoked this script. The
application no longer has to deal with them. *Note:* this is just an
example usage for the mechanism, you would typically generate pages in
which any embedded images had URL's which refer explicitly to the main
httpd.

With a slight change in the code above you can arrange for the handling of
the pass-thru to occur in a subprocess. This frees the main process to
handle other requests. Since the MiniSvr typically only exists for one
process, forking off a subprocess to handle a request is only useful for
browsers such as Netscape which make multiple parallel requests for inline
images.

     if ($self->{SCRIPT_NAME} =~ m/\.(gif|html|jpg)$/){
         if ($self->fork == 0) {
             $self->pass_thru('', $self->{ORIG_SERVER_PORT});
             $self->exit;
         }
         $self->done;
         return 'NEXT';
     }

Note that forking can be expensive. It might not be worth doing for small
images.

FEATURES
--------

Object oriented and sub-classable.

Transparent low-level peer validation (no application involvement but
extensible through subclassing).

Transparent low-level pass_thru/redirecting of URL's the application is
not interested in  (no application involvement but extensible through
subclassing).

Effective timeout mechanism with default and per-call settings.

Good emulation of standard CGI interface (for code portability).

RECENT CHANGES
--------------

  1. and 2.3 Slightly improved documentation. Added a basic fork() method.
     Fixed timeout to throw an exception so it's reliable on systems which
     restart system calls. Socket/stdio/filehandle code improved. Cleaned
     up done/close relationship. Added experimental support for optionally
     handling requests by forking on a case-by-case basis. This is handy
     for serving multiple simultaneous image requests from Netscape for
     example.  Added notes about the MiniSvr, mainly from discussions with
     Jack Shirazi Removed old explicit port searching code from
     _new_inet_socket().  Improved SIGPIPE handling (see CGI::Base).

  2. Fixed (worked around) a perl/stdio bug which affected POST handling.
     Changed some uses of map to foreach. Slightly improved debugging.
     Added support for any letter case in HTTP headers. Enhanced test code.

  3. Added more documentation and examples. The max pending connections
     parameter for listen() can now be specified as a parameter to new().
     SIGPIPE now ignored by default. Simplified inet socket code with ideas
     from Jack Shirazi. Improved server Status-Line header handling. Fixed
     validate_peer() error handling and redirect().  Simplified get_vars()
     by splitting into get_valid_connection() and read_headers(). Moved
     example method_GET() out of MiniSvr and into the test script.

     The module file can be run as a cgi script to execute a demo/test. You
     may need to chmod +x this file and teach your httpd that it can
     execute *.pm files.

  4. Added note about possible use of MiniSvr to serve dynamically
     generated in-line images. Added optional DoubleFork mechanism to
     spawn which might be helpful for buggy httpd's, off by default.

  5. Added support for an 'indirect, off-net, access' via a local UNIX
     domain socket in the file system. Now uses strict. ORIG_* values now
     stored within object and not exported as globals (Base CGI vars
     remain unchanged).  See CGI::Base for some more details.


FUTURE DEVELOPMENTS
-------------------

Full pod documentation.

None of this is perfect. All suggestions welcome.

Test unix domain socket mechanism.

Issue/problem - the handling of headers. Who outputs them and when? We
have a sequence of: headers, body, end, read, headers, body, end, read
etc. The problem is that a random piece of code can't tell if the headers
have been output yet. A good solution will probably have to wait till we
have better tools for writing HTML and we get away from pages of print
statements.

A method for setting PATH_INFO and PATH_TRANSLATED to meaningful values
would be handy.

AUTHOR, COPYRIGHT and ACKNOWLEDGEMENTS
--------------------------------------

This code is Copyright (C) Tim Bunce 1995. All rights reserved.  This
program is free software; you can redistribute it and/or modify it under
the same terms as Perl itself.

This module includes ideas from Pratap Pereira
<pereira@ee.eng.ohio-state.edu>, Jack Shirazi <js@biu.icnet.uk> and others.

IN NO EVENT SHALL THE AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
THIS SOFTWARE AND ITS DOCUMENTATION (INCLUDING, BUT NOT LIMITED TO, LOST
PROFITS) EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.

SEE ALSO
--------

CGI::Base, CGI::Request, URI::URL

SUPPORT
-------

Please use comp.infosystems.www.* and comp.lang.perl.misc for support.
Please do _NOT_ contact the author directly. I'm sorry but I just don't
have the time.


File: pm.info,  Node: CGI/Out,  Next: CGI/Request,  Prev: CGI/MiniSvr,  Up: Module List

buffer output when building CGI programs
****************************************

NAME
====

CGI::Out - buffer output when building CGI programs

SYNOPSIS
========

     use CGI;
     use CGI::Out;

     $query = new CGI;
     savequery $query;		# to reconstruct input

     $CGI::Out::mailto = 'fred';	# override default of $<

     out $query->header();
     out $query->start_html(
     	-title=>'A test',
     	-author=>'muir@idiom.com');

     croak "We're outta here!";
     confess "It was my fault: $!";
     carp "It was your fault!";
     warn "I'm confused";
     die  "I'm dying.\n";

     use CGI::Out qw(carpout);
     carpout(\*LOG);

DESCRIPTION
===========

This is a helper routine for building CGI programs.  It buffers stdout
until you're completed building your output.  If you should get an error
before you are finished, then it will display a nice error message (in
HTML), log the error, and send email about the problem.

It wraps all of the functions provided by CGI::Carp and Carp.  Do not
"use" them directly, instead just "use CGI::Out".

Instead of print, use `out'.

AUTHOR
======

David Muir Sharnoff <muir@idiom.com>

SEE ALSO
========

Carp, CGI::Carp, CGI, CGI::Wrap

BUGS
====

No support for formats is provided by CGI::Out.


File: pm.info,  Node: CGI/Request,  Next: CGI/Response,  Prev: CGI/Out,  Up: Module List

Parse client request via a CGI interface
****************************************

NAME
====

CGI::Request - Parse client request via a CGI interface

SYNOPSIS
========


     use CGI::Request;
     
     # Simple interface: (combines SendHeaders, new and import_names)
     
     $req = GetRequest($pkg);
     
     print FmtRequest();            # same as: print $req->as_string
     
     
     # Full Interface:
     
     $req = new CGI::Request;       # fetch and parse request
     
     $field_value = $req->param('FieldName');
     @selected    = $req->param('SelectMultiField');
     @keywords    = $req->keywords; # from ISINDEX
     
     print $req->as_string;         # format Form and CGI variables
     
     # import form fields into a package as perl variables!
     $req->import_names('R');
     print "$R::FieldName";
     print "@R::SelectMultiField";
     
     @value = $req->param_or($fieldname, $default_return_value);

     # Access to CGI interface (see CGI::Base)

     $cgi_obj = $req->cgi;
     $cgi_var = $req->cgi->var("REMOTE_ADDR");
     
     
     # Other Functions:
     
     CGI::Request::Interface($cgi);  # specify alternative CGI
     
     CGI::Request::Debug($level);    # log to STDERR (see CGI::Base)
     
     
     # Cgi-lib compatibility functions
     # use CGI::Request qw(:DEFAULT :cgi-lib); to import them
     
     &ReadParse(*input);
     &MethGet;
     &PrintHeader;
     &PrintVariables(%input);

DESCRIPTION
===========

This module implements the CGI::Request object. This object represents a
single query / request / submission from a WWW user. The CGI::Request
class understands the concept of HTML forms and fields, specifically how
to parse a CGI QUERY_STRING.

SMALLEST EXAMPLE
----------------

This is the smallest useful CGI::Request script:

     use CGI::Request;
     GetRequest();
     print FmtRequest();

SIMPLE EXAMPLE
--------------

This example demonstrates a simple ISINDEX based query, importing results
into a package namespace and escaping of text:

     #!/usr/local/bin/perl  # add -T to test tainted behaviour

     use CGI::Base;
     use CGI::Request;

     GetRequest('R');       # get and import request into R::...

     # Just to make life more interesting add an ISINDEX.
     # Try entering: "aa bb+cc dd=ee ff&gg hh<P>ii"
     print "<ISINDEX>\r\n";

     print "<B>You entered:</B> ", # print results safely
           join(', ', CGI::Base::html_escape(@R::KEYWORDS))."\r\n";

     print FmtRequest();    # show formatted version of request

CGI
---

A CGI::Request object contains a reference to a CGI::Base object (or an
object derived from CGI::Base). It uses the services of that object to get
the raw request information.

Note that CGI::Request does not inherit from CGI::Base it just uses an
instance of a CGI::Base object.

See the cgi method description for more information.

FEATURES
--------

Is object oriented and sub-classable.

Can export form field names as normal perl variables.

Integrates with CGI::MiniSvr.

RECENT CHANGES
--------------

  1. Fixed bug in import_names().  Now works properly with both scalar and
     array elements.

  2. through 2.74 Minor changes to accomodate Forms interface.

  3. thru 2.3 Minor enhancements to documentation and debugging. Added
     notes about relationship with CGI and how to access CGI variables.

  4. Updates for changed CGI:Base export tags. No longer setting
     @CGI::Request::QUERY_STRING. Added param_or() method.

     The module file can be run as a cgi script to execute a demo/test. You
     may need to chmod +x this file and teach your httpd that it can
     execute *.pm files (or create a copy/symlink with another name).

  5. GetRequest now call SendHeaders (in CGI::Base) for you. This works
     *much* better than the old 'print PrintHeaders;'. PrintHeaders is no
     longer exported by default. as_string now uses the new html_escape
     method (in CGI::Base) to safely format strings with embedded html.
     Debugging now defaults to off. New Debug function added. Image map
     coords are automatically recognised and stored as parameters X and Y.
     Added a sequence number mechanism to assist debugging MiniSvr
     applications (does not impact/cost anything for non minisvr apps).

  6. Default package for import_names() removed, you must supply a package
     name. GetRequest() won't call import_names unless a package name has
     been given, thus GetRequest no longer defaults to importing names.
     Added as_string() method (which automatically calls cgi->as_string).
     param() will croak if called in a scalar context for a multi-values
     field.


FUTURE DEVELOPMENTS
-------------------

None of this is perfect. All suggestions welcome.

Note that this module is *not* the place to put code which generates HTML.
We'll need separate modules for that (which are being developed).

AUTHOR, COPYRIGHT and ACKNOWLEDGEMENTS
--------------------------------------

This code is Copyright (C) Tim Bunce 1995. All rights reserved.  This code
is free software; you can redistribute it and/or modify it under the same
terms as Perl itself.

The cgi-lib functions are based on cgi-lib.pl version 1.7 which is
Copyright 1994 Steven E. Brenner.

IN NO EVENT SHALL THE AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
THIS SOFTWARE AND ITS DOCUMENTATION (INCLUDING, BUT NOT LIMITED TO, LOST
PROFITS) EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.

SEE ALSO
--------

CGI::Base, URI::Escape

SUPPORT
-------

Please use comp.infosystems.www.* and comp.lang.perl.misc for support.
Please do _NOT_ contact the author directly. I'm sorry but I just don't
have the time.

FUNCTIONS
=========

GetRequest
----------


     GetRequest();
     GetRequest($package_name);
     $req = GetRequest(...);

GetRequest is the main entry point for simple (non-object oriented) use of
the CGI::Request module. It combines output (and flushing) of the standard
Content-Type header, request processing and optional importing of the
resulting values into a package (see import_names).

This function also enables autoflush on stdout. This has a slight
efficiency cost but huge benefits in reduced frustration by novice users
wondering why, for example, the output of system("foo") appears before
their own output.

See `new CGI::Request' for more details.

FmtRequest
----------


     print FmtRequest();

Return a HTML string which describes the last (current) client request
parameters and the current raw CGI parameters.  Designed to be used for
debugging purposes.

Interface
---------


     $cgi = Interface();

Return the default CGI interface object. Rarely used by applications.

If no interface has been defined yet it will automatically create a new
CGI::Base object, set that as the default interface and return it. This is
the mechanism by which simple applications get to use the CGI::Base
interface without knowing anything about it.

This function can also be use to define a new default interface (such as
CGI::MiniSvr) by passing a reference to a CGI::Base object or a object
derived from CGI::Base.

Debug
-----


     $old_level = CGI::Request::Debug();
     $old_level = CGI::Request::Debug($new_level);

Set debug level for the CGI::Request module. Debugging info is logged to
STDERR (see CGI::Base for examples of how to redirect STDERR).

METHODS
=======

new
---


     $req = new CGI::Request;
     $req = new CGI::Request $cgi_interface;
     $req = new CGI::Request $cgi_interface, $timeout_in_seconds;

CGI::Request object constructor. Only the first form listed above should
be used by most applications.

Note that, unlike GetRequest, new CGI::Request does not call SendHeaders
for you. You have the freedom to control how you send your headers and
what headers to send.

The returned $req CGI::Request object stores the request parameter values.
Parameters can be retrieved using the param method.

Index keywords (ISINDEX) are automatically recognised, parsed and stored
as values of the 'KEYWORDS' parameter. The keywords method provides an
easy way to retrieve the list of keywords.

Image Map (ISMAP) coordinates are automatically recognised, parsed and
stored as parameters 'X' and 'Y'.

as_string
---------


     print $req->as_string;

Return an HTML string containing all the query parameters and CGI
parameters neatly and safely formatted. Very useful for debugging.

extract_values
--------------


     $req->extract_values($QUERY_STRING)

This method extracts parameter name/value pairs from a string (typically
QUERY_STRING) and stores them in the objects hash.  Not normally called by
applications, new() calls it automatically.

The parameter names and values are individually unescaped using the
uri_unescape() function in the URI::URL module.

For ISINDEX keyword search requests (QUERY_STRING contains no '=' or '&')
the string is split on /+/ and the keywords are then individually
unescaped and stored.  Either the keywords() method (or param('KEYWORDS'))
can be used to recover the values.

keywords
--------


     @words = $req->keywords

Return the keywords associated with an ISINDEX query.

params
------


     @names = $req->params

Return a list of all known parameter names in the order in which they're
defined

param
-----


     $value  = $req->param('field_name1');
     @values = $req->param('field_name2');	# e.g. select multiple
     $req->param('field_name3', $new_value);
     $req->param('field_name4', @new_values);

Returns the value(s) of a named parameter. Returns an empty list/undef if
the parameter name is not known. Returns '' for a parameter which had no
value.

If invoked in a list context param returns the list of values in the same
order they were returned by the client (typically from a select multiple
form field).

Warning: If invoked in a scalar context and the parameter has more than
one value the param method will die. This catches badly constructed forms
where a field may have been copied but its name left unchanged.

If more than one argument is provided, the second and subsequent arguments
are used to set the value of the parameter. The previous values, if any,
are returned. Note that setting a new value has no external effect and is
only included for completeness.

Note that param does not return CGI variables (REMOTE_ADDR etc) since
those are CGI variables and not form parameters. To access CGI variables
see the cgi method in this module and the CGI::Base module documentation.

delete
------

     $req->delete('field_name1');

Remove the specified field name from the parameter list

param_or
--------

     $value  = $req->param_or('field_name1', $default);
     @values = $req->param_or('field_name2', @defaults);

If the current request was a query (QUERY_STRING defined) then this method
is identical to the param method with only one argument.

If the current request was not a query (QUERY_STRING undefined) then this
method simply returns its second and subsequent parameters.

The method is designed to be used as a form building utility.

import_names
------------


     $req->import_names('R')

Convert all request parameters into perl variables in a specified package.
This avoids the need to use $req->param('name'), you can simply sat
$R::name ('R' is the recommended package names).

Note: This is a convenience function for simple CGI scripts. It should
*not* be used with the MiniSvr since there is no way to reset or unimport
the values from one request before importing the values of the next.

cgi
---


     $cgi = $req->cgi;

This method returns the current CGI::Request default CGI interface object.
It is primarily intended as a handy shortcut for accessing CGI::Base
methods: $req->cgi->done(), $req->cgi->var("REMOTE_ADDR");


File: pm.info,  Node: CGI/Response,  Next: CGI/Switch,  Prev: CGI/Request,  Up: Module List

Respond to CGI requests
***********************

NAME
====

*CGI::Response* - Respond to CGI requests

SYNOPSIS
========

Simple Interface
----------------

     use CGI::Response qw(:Simple);
     print ContentType;
     print "<html><head>\n"; # .....

Full Interface
--------------

     use CGI::Response;
     $response = new CGI::Response;
     $response->content_type;
     print $response->as_string;
     print "<html><head>\n"; # .....

DESCRIPTION
===========

*CGI::Response* is a Perl5 module for constructing responses to Common
Gateway Interface (CGI) requests.  It is designed to be light-weight and
efficient for the most common tasks, and also to provide access to all
HTTP response features for more advanced CGI applications.

There are two ways to use CGI::Response.  For basic applications, the
Simple Interface provides a number of plain functions that cover the most
commonly-used CGI response headers.  More advanced applications may employ
the Full Interface object methods to access any HTTP header, or to add
experimental or non-standard headers.  Both interfaces try to generate
reasonable defaults whenever possible.

For efficiency, just the Simple Interface functions are compiled on
start-up.  Full Interface methods are compiled only when they are called.
This helps to make CGI::Response usable in a variety of applications.
[See *Note SelfLoader: SelfLoader, for more information.]

Simple Interface
----------------

The Simple Interface methods are *not* exported by default.  In order to
use them, you must import them explicitly.  You can import all of the
methods at once by saying:

     use CGI::Response qw(:Simple);

Or, you can import just one function by listing it by name, as in:

     use CGI::Response qw(ContentType);

Only one Simple Interface function should be called in a response, since
all of these functions terminate the response header (that is, send the
blank line denoting the end of the header) immediately upon execution.  If
you need to use a combination of headers not provided by the Simple
Interface, use the Full Interface instead.

All of the Simple Interface functions force a flush on the
currently-selected output channel (that is, they set `$| = 1').  This is
done to prevent a common probelm in CGI scripts, where a `system()' or
`exec()' call causes output before the response header, and generates a
server error.  If you do not want `$| = 1', you should either set it back
to 0 after using the Simple Interface, or you should employ the Full
Interface, which does not have this side effect.

For reference, below is a list of the headers sent by each function, and
the default header values, if any.  Arguments are listed in the order they
should appear.  Square brackets ([]) indicate optional arguments; angled
brackets (<>) indicate required arguments.

     Function      Argument(s)      Header(s)      Default(s)
     --------      -----------      ---------      ----------
     &ContentType  [content-type]   Content-Type   text/html

     &Redirect     <Location/URI>   Location       [none]
                   [permanent?]     URI            [none]
                                    Content-Type   text/html
                                    Status         302 Moved Temporarily

     &NoCache      [content-type]   Content-Type   text/html
                                    Pragma         no-cache
                                    Expires        [now]

     &NoContent                     Status         204 No Content

Each of these functions is documented more completely below, and examples
for each are provided.

&ContentType
     This is the most commonly-used function.  It identifies the Internet
     Media Type of the entity that follows.  If you call it without an
     argument, it will send `text/html' as the content-type.

          use CGI::Response qw(:Simple);
          print &ContentType;   # defaults to text/html

     Otherwise, you can specify some other content-type:

          use CGI::Response qw(:Simple);
          print &ContentType('image/gif');

     This function should be called as early as possible to prevent server
     errors (see the note on $| above).

&Redirect
     A redirect causes the user-agent to make a follow-up request for some
     other resource.  Some user-agents will be better than others at
     complying with a redirect, so this function tries to be as explicit as
     possible.

     You are required to give one argument, specifying the URL which the
     user-agent should request.  A second argument is accepted as a Boolean
     value - if any second argument is present, the browser will be told
     that the requested resource has moved permanently to a new URL (that
     is, future requests for the document should be to the new URL, not to
     the one which was first requested).

          use CGI::Response qw(:Simple);
          print &Redirect('http://www.company.com/', 'permanent');
          # this resource has moved permanently, status 301

     If no second argument is given, the redirect will be specified as
     temporary.

          use CGI::Response qw(:Simple);
          print &Redirect('http://www.company.com/');
          # this resource has moved temporarily, status 302

     A brief HTML page is output after the header so that users whose
     user-agents fail to recognize the redirect will get an informative
     message with a link to the redirect.  Use the Full Interface to supply
     some other page or none at all.

&NoCache
     This function tries to inform user-agents and proxy servers that the
     included resource should not be cached.  It does so by sending both an
     `Expires' header, set for immediate expiration, and a `Pragma:
     no-cache' header, which older user-agents and servers might not
     recognize.

     Preventing caching is important to CGI applications which produce
     output based on some factor of the request (such as which user-agent
     made the request).  For instance, a shopping-basket application would
     not want to allow caching of an order information page, which may
     contain user-specific information.

     It must be noted, however, that caches prevent excess network load and
     cache-friendly applications are always preferable to use of the
     &NoCache function.  This function should only be used when there is no
     other alternative.

     &NoCache takes one optional argument, the content-type of the entity
     to follow.  Therefore, its call is nearly identical to the
     &ContentType function, and the two functions may be interchanged
     easily.  As with &ContentType, if you call &NoCache without an
     argument, it will send `text/html' as the content-type.

          use CGI::Response qw(:Simple);
          print &NoCache;   # defaults to text/html

     Otherwise, you can specify some other content-type:

          use CGI::Response qw(:Simple);
          print &NoCache('image/gif');

     As noted earlier, this function should be called as early as possible
     to prevent server errors (see the note on $| above).

&NoContent
     &NoContent allows a script to accept input without changing the
     current page in the user-agent's view.  This may be useful for a
     successful form input that requires no response, or for an imagemap
     click that does not have a defined link.

     A No Content response does not reset form fields after submission.
     HTTP/1.1 will include a `205 Reset Document' status for this purpose,
     and a future version of this module will provide a &Reset function to
     support this status.

     This function sends only one header, `Status: 204 No Content', and it
     takes no arguments.

          use CGI::Response qw(:Simple);
          print &NoContent;

Full Interface
--------------

The Full Interface is still under development and is not currently
documented.

DEPENDENCIES
============

SEE ALSO
========

CGI::Base(3pm), CGI::BasePlus(3pm), CGI::Request(3pm), CGI::Lite(3pm),
CGI(3pm), CGI::Form(3pm), LWP(3pm), SelfLoader(3pm)

NOTES
=====

Please note that future versions are not guaranteed to be
backwards-compatible with this version.  The interface will be frozen at
version 0.1 (first beta release).

VERSION
=======

     Version:      0.03 (alpha release)
     Release date: 02 December 1995

AUTHOR
======

     Marc Hedlund <hedlund@best.com>
     Copyright 1995, All rights reserved


File: pm.info,  Node: CGI/Switch,  Next: CGI/Wrap,  Prev: CGI/Response,  Up: Module List

Try more than one constructors and return the first object available
********************************************************************

NAME
====

CGI::Switch - Try more than one constructors and return the first object
available

SYNOPSIS
========

     use CGISwitch;

     -or-

     use CGI::Switch This, That, CGI::XA, Foo, Bar, CGI;

     my $q = new CGI::Switch;

DESCRIPTION
===========

Per default the new() method tries to call new() in the three packages
Apache::CGI, CGI::XA, and CGI. It returns the first CGI object it succeeds
with.

The import method allows you to set up the default order of the modules to
be tested.

SEE ALSO
========

perl(1), Apache(3), CGI(3), CGI::XA(3)

AUTHOR
======

Andreas König <a.koenig@mind.de>


File: pm.info,  Node: CGI/Wrap,  Next: CGI/XA,  Prev: CGI/Switch,  Up: Module List

buffer output when building CGI programs
****************************************

NAME
====

CGI::Wrap - buffer output when building CGI programs

SYNOPSIS
========

     use CGI;
     use CGI::Croak;
     use CGI::Wrap;

     $query = new CGI;
     savequery $query;		# to reconstruct input
     $CGI::Out::mailto = 'fred';	# override default of $<

     run \&myfunc, @myargs		# a function
     run sub { code }		# an inline function
     run 'code'			# something to eval

     sub myfunc {
     	out $query->header();
     	out $query->start_html(
     		-title=>'A test',
     		-author=>'muir@idiom.com');
     }

DESCRIPTION
===========

This is a helper routine for building CGI programs.  It buffers stdout
until you're completed building your output.  If you should get an error
before you are finished, then it will display a nice error message (in
HTML), log the error, and send email about the problem.

To use it, you must condense your program down to a single function call
and then use CGI::Wrap::run to call it.

Instead of print, use `out'.

AUTHOR
======

David Muir Sharnoff <muir@idiom.com>

SEE ALSO
========

Carp, CGI::Carp, CGI::Out,  CGI

BUGS
====

No support for formats is provided by CGI::Wrap.


File: pm.info,  Node: CGI/XA,  Next: CPAN,  Prev: CGI/Wrap,  Up: Module List

Clone of CGI.pm with less backwards compatibility and less namespace pollution
******************************************************************************

NAME
====

CGI::XA - Clone of CGI.pm with less backwards compatibility and less
namespace pollution

SYNOPSIS
========

     use CGI::XA;
     # then follow the CGI.pm docs and see if it does the same.

BE AWARE, THIS IS ALPHA SOFTWARE
================================

It's main purpose is to start a discussion about CGI.pm. Maybe parts of
this will be folded back to CGI.pm, and then probably this module won't be
developed any further.

DESCRIPTION
===========

I have started with major hacks on top of Lincoln's version 2.23 of CGI.pm
in order to get rid of both AUTOLOADING and uncontrolled global variables.

I release this package as CGI::XA (which stands for "for Apache") for a
limited audience as a test case.

This software is alpha software and it is not clear if it will be
supported for a longer time. My preferred solution would be, Lincoln
accepts (most of) the changes and continues with his excellent work.

where are the main differences?
-------------------------------

     No AUTOLOAD
     use strict clean
     no exports
     no cgi-lib.pl compatibility
     no "Q" namespace
     abandoned the rearrange method in several places

DOCUMENTATION
-------------

is in CGI.pm with which we are quite compatible with. See comments in the
code. If you could supply test cases for methods that are not depending on
a browser, we'd be glad to hear from you.

AUTHOR
======

Lincoln D. Stein is th author of the original code which was the basis for
this development. Responsibility is with Andreas König
<andreas.koenig@mind.de>

SEE ALSO
========

perl(1), Apache(3), Apache::Switch(3).


File: pm.info,  Node: CPAN,  Next: Carp,  Prev: CGI/XA,  Up: Module List

query, download and build perl modules from CPAN sites
******************************************************

NAME
====

CPAN - query, download and build perl modules from CPAN sites

SYNOPSIS
========

Interactive mode:

     perl -MCPAN -e shell;

Batch mode:

     use CPAN;

     autobundle, bundle, bundles, expand, install, make, test

ALPHA ALERT
===========

The interface of this *package is not yet stable*. Parts of it may still
change. This is especially true for the programming interface. The
interactive "shell" interface is already rather well established.

DESCRIPTION
===========

The CPAN module is designed to automate the building and installing of
perl modules and extensions including the searching and fetching from the
net.

Modules are fetched from one or more of the mirrored CPAN (Comprehensive
Perl Archive Network) sites and unpacked in a dedicated directory.

The CPAN module also supports the concept of named and versioned 'bundles'
of modules. Bundles simplify the handling of sets of related modules. See
BUNDLES below.

The package contains a session manager and a cache manager. There is no
status retained between sessions. The session manager keeps track of what
has been fetched, built and installed in the current session. The cache
manager keeps track of the disk space occupied by the make processes and
deletes excess space in a simple FIFO style.

Interactive Mode
----------------

The interactive mode is entered by running

     perl -MCPAN -e shell

which puts you into a readline interface. You will have most fun if you
install Term::ReadKey and Term::ReadLine to enjoy both history and
completion.

Once you are on the command line, type 'h' and the rest should be
self-explanatory.

CPAN::Shell
-----------

The commands that are available in the shell interface are methods in the
package CPAN::Shell. If you enter the shell command, all your input is
split on whitespace, the first word is being interpreted as the method to
be called and the rest of the words are treated as arguments to this
method.

If you do not enter the shell, most of the available shell commands are
both available as methods (`CPAN::Shell->install(...)') and as functions
in the calling package (`install(...)').

Cache Manager
-------------

Currently the cache manager only keeps track of the build directory
($CPAN::Config->{build_dir}). It is a simple FIFO mechanism that deletes
complete directories below build_dir as soon as the size of all
directories there gets bigger than $CPAN::Config->{build_cache} (in MB).

There is another directory ($CPAN::Config->{keep_source_where}) where the
original distribution files are kept. This directory is not covered by the
cache manager and must be controlled by the user. If you choose to have
the same directory as build_dir and as keep_source_where directory, then
your sources will be deleted with the same fifo mechanism.

Bundles
-------

A bundle is just a perl module in the namespace Bundle:: that does not
define any functions or methods. It usually only contains documentation.

It starts like a perl module with a package declaration and a $VERSION
variable. After that the pod section looks like any other pod with the
only difference, that one pod section exists starting with (verbatim):

     =head1 CONTENTS

In this pod section each line obeys the format

     Module_Name [Version_String] [- optional text]

The only required part is the first field, the name of a module (eg.
Foo::Bar, ie. *not* the name of the distribution file). The rest of the
line is optional. The comment part is delimited by a dash just as in the
man page header.

The distribution of a bundle should follow the same convention as other
distributions. The bundle() function in the CPAN module simply parses the
module that defines the bundle and returns the module names that are
listed in the described CONTENTS section.

Bundles are treated specially in the CPAN package. If you say 'install
Bundle::Tkkit' (assuming such a bundle exists), CPAN will install all the
modules in the CONTENTS section of the pod.  You can install your own
Bundles locally by placing a conformant Bundle file somewhere into your
@INC path. The autobundle() command does that for you by including all
currently installed in a snapshot bundle file.

autobundle
----------

autobundle() writes a bundle file into the directory
$CPAN::Config->{cpan_home}/Bundle directory. The file contains a list of
all modules that are both available from CPAN and currently installed
within @INC. The name of the bundle file is based on the current date and
a counter.

Pragma: force
-------------

Normally CPAN keeps track of what it has done within the current session
and doesn't try to build a package a second time regardless if it
succeeded or not. The force command takes as first argument the method to
invoke (currently: make, test, or install) and executes the command from
scratch.

Example:

     cpan> install OpenGL
     OpenGL up-to-date.
     cpan> force install OpenGL
     Running make
     OpenGL-0.4/
     OpenGL-0.4/COPYRIGHT
     [...]

CONFIGURATION
=============

When the CPAN module is installed a site wide configuration file is
created as CPAN/Config.pm. The default values defined there can be
overridden in another configuration file: CPAN/MyConfig.pm. You can store
this file in $HOME/.cpan/CPAN/MyConfig.pm if you want, because $HOME/.cpan
is added to the search path of the CPAN module before the use() or
require() statements.

Currently the following keys in the hash reference $CPAN::Config are
defined:

     build_cache       size of cache for directories to build modules
     build_dir         locally accessible directory to build modules
     cache_expire      after how many days refetch index files
     cpan_home         local directory reserved for this package
     gzip		    location of external program gzip
     inhibit-startup-message
                       if true, does not print the startup message
     keep_source       keep the source in a local directory?
     keep_source_where where keep the source (if we do)
     make              location of external program make
     make_arg	    arguments that should always be passed to 'make'
     make_install_arg  same as make_arg for 'make install'
     makepl_arg	    arguments passed to 'perl Makefile.PL'
     more              location of external program more (or any pager)
     tar               location of external program tar
     unzip             location of external program unzip
     urllist	    arrayref to nearby CPAN sites (or equivalent locations)

SECURITY
========

There's no security layer in the alpha version of CPAN.pm. CPAN.pm helps
you to install foreign, unmasked, unsigned code on your machine. It's not
different than when you do that on your own, but you should be warned now.

EXPORT
======

Most functions in package CPAN are exported per default. The reason for
this is that the primary use is intended for the cpan-shell or for
one-liners.

Debugging
=========

The debugging of this module is a pretty difficult task, because we have
interferences of the software producing the indices on CPAN, of the
mirroring process, of improper packaging, of improper configuration and of
bugs within CPAN.pm.

In interactive mode you can try "o debug" which will list options for
debugging the various parts of the package. The output may not be very
useful for you as it's just a byproduct of my own testing, but if you have
an idea which part of the package may have a bug, it's certainly worth to
give it a try and send me more specific output. You should know that "o
debug" has built-in completion support.

Prerequisites
-------------

If you have a local mirror of CPAN and can access all files with "file:"
URLs, then you only need perl5.003 to run this module. Otherwise you need
Net::FTP intalled. LWP may be required for non-UNIX systems.

This module presumes that all packages on CPAN

   * Declare their $VERSION variable in an easy to parse manner. This
     prerequisite can hardly be relaxed because it consumes by far too much
     memory to load all packages into a single program just to determine
     the $VERSION variable . Currently all programs that are dealing with
     VERSION use something like this (requires MakeMaker-5.38, but don't
     bother if you don't have it):

          perl -MExtUtils::MakeMaker -le \
              'print MM->parse_version($ARGV[0])' filename

     If you are author of a package and wonder if your VERSION can be
     parsed, please try the above method.

   * Come as compressed or gzipped tarfiles or as zip files (well we try to
     handle a bit more, but without much enthusiasm).

AUTHOR
======

Andreas König <a.koenig@mind.de>

SEE ALSO
========

perl(1)


File: pm.info,  Node: Carp,  Next: Color,  Prev: CPAN,  Up: Module List

warn of errors (from perspective of caller)
*******************************************

NAME
====

carp - warn of errors (from perspective of caller)

croak - die of errors (from perspective of caller)

confess - die of errors with stack backtrace

SYNOPSIS
========

     use Carp;
     croak "We're outta here!";

DESCRIPTION
===========

The Carp routines are useful in your own modules because they act like
die() or warn(), but report where the error was in the code they were
called from.  Thus if you have a routine Foo() that has a carp() in it,
then the carp() will report the error as occurring where Foo() was called,
not where carp() was called.


File: pm.info,  Node: Color,  Next: Compress/Zlib,  Prev: Carp,  Up: Module List

implements color functions and names
************************************

NAME
====

Color.pm - implements color functions and names

SYNOPSIS
========

     use VRML::Color;

DESCRIPTION
===========

*Netscape colornames are:*

     aliceblue
     antiquewhite
     aqua
     aquamarine
     azure
     beige
     bisque
     black
     blanchedalmond
     blue
     blueviolet
     brown
     burlywood
     cadetblue
     chartreuse
     chocolate
     coral
     cornflowerblue
     cornsilk
     crimson
     cyan
     darkblue
     darkcyan
     darkgoldenrod
     darkgray
     darkgreen
     darkkhaki
     darkmagenta
     darkolivegreen
     darkorange
     darkorchid
     darkred
     darksalmon
     darkseagreen
     darkslateblue
     darkslategray
     darkturquoise
     darkviolet
     deeppink
     deepskyblue
     dimgray
     dodgerblue
     firebrick
     floralwhite
     forestgreen
     fuchsia
     gainsboro
     ghostwhite
     gold
     goldenrod
     gray
     green
     greenyellow
     honeydew
     hotpink
     indianred
     indigo
     ivory
     khaki
     lavender
     lavenderblush
     lawngreen
     lemonchiffon
     lightblue
     lightcoral
     lightcyan
     lightgoldenrodyellow
     lightgreen
     lightgrey
     lightpink
     lightsalmon
     lightseagreen
     lightskyblue
     lightslategray
     lightsteelblue
     lightyellow
     lime
     limegreen
     linen
     magenta
     maroon
     mediumaquamarine
     mediumblue
     mediumorchid
     mediumpurple
     mediumseagreen
     mediumslateblue
     mediumspringgreen
     mediumturquoise
     mediumvioletred
     midnightblue
     mintcream
     mistyrose
     moccasin
     navajowhite
     navy
     oldlace
     olive
     olivedrab
     orange
     orangered
     orchid
     palegoldenrod
     palegreen
     paleturquoise
     palevioletred
     papayawhip
     peachpuff
     peru
     pink
     plum
     powderblue
     purple
     red
     rosybrown
     royalblue
     saddlebrown
     salmon
     sandybrown
     seagreen
     seashell
     sienna
     silver
     skyblue
     slateblue
     slategray
     snow
     springgreen
     steelblue
     tan
     teal
     thistle
     tomato
     turquoise
     violet
     wheat
     white
     whitesmoke
     yellow
     yellowgreen

You can also use

     yellow%30 = '0.3 0.3 0'	yellow%30
     gray%30 = '0.7 0.7 0.7' gray%30 !!!


File: pm.info,  Node: Compress/Zlib,  Next: Config,  Prev: Color,  Up: Module List

Interface to zlib compression library
*************************************

NAME
====

Compress::Zlib - Interface to zlib compression library

SYNOPSIS
========

     use Compress::Zlib ;

     ($d, $status) = deflateInit() ;
     ($out, $status) = $d->deflate($buffer) ;
     ($out, $status) = $d->flush() ;
     $d->dict_adler() ;

     ($i, $status) = inflateInit() ;
     ($out, $status) = $i->inflate($buffer) ;
     $i->dict_adler() ;

     $dest = compress($source) ;
     $dest = uncompress($source) ;

     $gz = gzopen($filename, $mode) ;
     $status = $gz->gzread($buffer [,$size]) ;
     $status = $gz->gzreadline($line) ;
     $status = $gz->gzwrite($buffer) ;
     $status = $gz->gzflush($flush) ;
     $status = $gz->gzclose() ;
     $errstring = $gz->gzerror() ;
     $gzerrno

     $crc = adler32($buffer [,$crc]) ;
     $crc = crc32($buffer [,$crc]) ;

     ZLIB_VERSION

DESCRIPTION
===========

The *Compress::Zlib* module provides a Perl interface to the *zlib*
compression library (see `' in this node for details about where to get
*zlib*). Most of the functionality provided by *zlib* is available in
*Compress::Zlib*.

The module can be split into two general areas of functionality, namely
in-memory compression/decompression and read/write access to *gzip* files.
Each of these areas will be discussed separately below.

*WARNING: The interface defined in this document is alpha and is liable to
change.*

DEFLATE
=======

The interface *Compress::Zlib* provides to the in-memory *deflate* (and
*inflate*) functions has been modified to fit into a Perl model.

The main difference is that for both inflation and deflation, the Perl
interface will *always* consume the complete input buffer before
returning. Also the output buffer returned will be automatically grown to
fit the amount of output available.

Here is a definition of the interface available:

($d, $status) = deflateInit()
-----------------------------

Initialises a deflation stream.

It combines the features of the *zlib* functions *deflateInit*,
*deflateInit2* and *deflateSetDictionary*.

If successful, it will return the initialised deflation stream, $d and
$status of `Z_OK' in a list context. In scalar context it returns the
deflation stream, $d, only.

If not successful, the returned deflation stream ($d) will be undef and
$status will hold the exact *zlib* error code.

The function takes one optional parameter, a reference to a hash.  The
contents of the hash allow the deflation interface to be tailored.

Below is a list of the valid keys that the hash can take:

Level
     Defines the compression level. Valid values are 1 through 9,
     `Z_BEST_SPEED', `Z_BEST_COMPRESSION', and `Z_DEFAULT_COMPRESSION'.

     The default is `Z_DEFAULT_COMPRESSION'.

Method
     Defines the compression method. The only valid value at present (and
     the default) is `Z_DEFLATED'.

WindowBits
     For a definition of the meaning and valid values for WindowBits refer
     to the *zlib* documentation for *deflateInit2*.

     Defaults to `MAX_WBITS'.

MemLevel
     For a definition of the meaning and valid values for MemLevel refer
     to the *zlib* documentation for *deflateInit2*.

     Defaults to `MAX_MEM_LEVEL'.

Strategy
     Defines the strategy used to tune the compression. The valid values
     are `Z_DEFAULT_STRATEGY', `Z_FILTERED' and `Z_HUFFMAN_ONLY'.

     The default is `Z_DEFAULT_STRATEGY'.

Dictionary
     When a dictionary is specified *Compress::Zlib* will automatically
     call *deflateSetDictionary* directly after calling *deflateInit*. The
     Adler32 value for the dictionary can be obtained by calling tht method
     `$d-'dict_adler()>.

     The default is no dictionary.

Bufsize
     Sets the initial size for the deflation buffer. If the buffer has to
     be reallocated to increase the size, it will grow in increments of
     Bufsize.

     The default is 4096.

Here is an example of using the *deflateInit* optional parameter to
override the default buffer size and compression level.

     deflateInit( {Bufsize => 300, Level => Z_BEST_SPEED } ) ;

($out, $status) = $d->deflate($buffer)
--------------------------------------

Deflates the contents of *$buffer*. When finished, *$buffer* will be
completely processed (assuming there were no errors). If the deflation was
successful it returns the deflated output, *$out*, and a status value,
$status, of `Z_OK'.

On error, *$out* will be undef and $status will contain the *zlib* error
code.

In a scalar context *deflate* will return *$out* only.

As with the *deflate* function in *zlib*, it is not necessarily the case
that any output will be produced by this method. So don't rely on the fact
that *$out* is empty for an error test.

($out, $status) = $d->flush()
-----------------------------

Finishes the deflation. Any pending output will be returned via *$out*.
$status will have a value `Z_OK' if successful.

In a scalar context flush will return *$out* only.

Note that flushing can degrade the compression ratio, so it should only be
used to terminate a decompression.

$d->dict_adler()
----------------

Returns the adler32 value for the dictionary.

Example
-------

Here is a trivial example of using *deflate*. It simply reads standard
input, deflates it and writes it to standard output.

     use Compress::Zlib ;

     $x = deflateInit()
        or die "Cannot create a deflation stream\n" ;

     while (<>)
     {
         ($output, $status) = $x->deflate($_) ;
     
         $status == Z_OK
             or die "deflation failed\n" ;

     print $output ;
         }

     ($output, $status) = $x->flush() ;

     $status == Z_OK
         or die "deflation failed\n" ;

     print $output ;

INFLATE
=======

Here is a definition of the interface:

($i, $status) = inflateInit()
-----------------------------

Initialises an inflation stream.

In a list context it returns the inflation stream, *$i*, and the *zlib*
status code ($status). In a scalar context it returns the inflation stream
only.

If successful, *$i* will hold the inflation stream and $status will be
`Z_OK'.

If not successful, *$i* will be undef and $status will hold the *zlib*
error code.

The function takes one optional parameter, a reference to a hash.  The
contents of the hash allow the inflation interface to be tailored.

Below is a list of the valid keys that the hash can take.

WindowBits
     For a definition of the meaning and valid values for WindowBits refer
     to the *zlib* documentation for *inflateInit2*.

     Defaults to `MAX_WBITS'.

Bufsize
     Sets the initial size for the inflation buffer. If the buffer has to
     be reallocated to increase the size, it will grow in increments of
     Bufsize.

     Default is 4096.

Dictionary
     The default is no dictionary.

Here is an example of using the *inflateInit* optional parameter to
override the default buffer size.

     deflateInit( {Bufsize => 300 } ) ;

($out, $status) = $i->inflate($buffer)
--------------------------------------

Inflates the complete contents of *$buffer*

Returns `Z_OK' if successful and `Z_STREAM_END' if the end of the
compressed data has been reached.

$i->dict_adler()
----------------

Example
-------

Here is an example of using *inflate*.

     use Compress::Zlib ;

     $x = inflateInit()
        or die "Cannot create a inflation stream\n" ;

     $input = '' ;

     while (read(STDIN, $input, 4096))
     {
         ($output, $status) = $x->inflate($input) ;

     print $output
         if $status == Z_OK or $status == Z_STREAM_END ;

     last if $status != Z_OK ;
         }

     die "inflation failed\n"
         unless $status == Z_STREAM_END ;

COMPRESS/UNCOMPRESS
===================

Two high-level functions are provided by *zlib* to perform in-memory
compression. They are *compress* and *uncompress*. Two Perl subs are
provided which provide similar functionality.

*$dest = compress($source) ;*
     Compresses *$source*. If successful it returns the compressed data.
     Otherwise it returns undef.

*$dest = uncompress($source) ;*
     Uncompresses *$source*. If successful it returns the uncompressed
     data. Otherwise it returns undef.

GZIP INTERFACE
==============

A number of functions are supplied in *zlib* for reading and writing
*gzip* files. This module provides an interface to most of them. In
general the interface provided by this module operates identically to the
functions provided by *zlib*. Any differences are explained below.

*$gz = gzopen(filename, mode)*
     This function operates identically to the *zlib* equivalent except
     that it returns an object which is used to access the other *gzip*
     methods.

     As with the *zlib* equivalent, the *mode* parameter is used to
     specify both whether the file is opened for reading or writing and to
     optionally specify a a compression level. Refer to the *zlib*
     documentation for the exact format of the *mode* parameter.

*$status = $gz->gzread($buffer [, $size]) ;*
     Reads *$size* bytes from the compressed file into *$buffer*. If
     *$size* is not specified, it will default to 4096. If the scalar
     *$buffer* is not large enough, it will be extended automatically.

*$status = $gz->gzreadline($line) ;*
     Reads the next line from the compressed file into *$line*.

     It is legal to intermix calls to *gzread* and *gzreadline*.

     At this time *gzreadline* ignores the variable $/
     ($INPUT_RECORD_SEPARATOR or $RS when English is in use). The end of a
     line is denoted by the C character `'\n''.

*$status = $gz->gzwrite($buffer) ;*
     Writes the contents of *$buffer* to the compressed file.

*$status = $gz->gzflush($flush) ;*
     Flushes all pending output into the compressed file.  Works
     identically to the *zlib* function it interfaces to. Note that the
     use of *gzflush* can degrade compression.

     Refer to the *zlib* documentation for the valid values of *$flush*.

*$gz->gzclose*
     Closes the compressed file. Any pending data is flushed to the file
     before it is closed.

*$gz->gzerror*
     Returns the *zlib* error message or number for the last operation
     associated with $gz. The return value will be the *zlib* error number
     when used in a numeric context and the *zlib* error message when used
     in a string context. The *zlib* error number constants, shown below,
     are available for use.

          Z_OK
          Z_STREAM_END
          Z_ERRNO
          Z_STREAM_ERROR
          Z_DATA_ERROR
          Z_MEM_ERROR
          Z_BUF_ERROR

$gzerrno
     The $gzerrno scalar holds the error code associated with the most
     recent *gzip* routine. Note that unlike *gzerror()*, the error is
     *not* associated with a particular file.

     As with *gzerror()* it returns an error number in numeric context and
     an error message in string context. Unlike *gzerror()* though, the
     error message will correspond to the *zlib* message when the error is
     associated with *zlib* itself, or the UNIX error message when it is
     not (i.e. *zlib* returned `Z_ERRORNO').

     As there is an overlap between the error numbers used by *zlib* and
     UNIX, $gzerrno should only be used to check for the presence of an
     error in numeric context. Use *gzerror()* to check for specific
     *zlib* errors. The *gzcat* example below shows how the variable can
     be used safely.

Examples
--------

Here is an example script which uses the interface. It implements a
*gzcat* function.

     use Compress::Zlib ;

     die "Usage: gzcat file...\n"
     	unless @ARGV ;

     foreach $file (@ARGV) {
         $gz = gzopen($file, "rb")
     	    or die "Cannot open $file: $gzerrno\n" ;

     print $buffer
         while $gz->gzread($buffer) > 0 ;
     die "Error reading from $file: $gzerrno\n"
         if $gzerrno != Z_STREAM_END ;
     
     $gz->gzclose() ;
         }

Below is a script which makes use of *gzreadline*. It implements a very
simple grep like script.

     use Compress::Zlib ;

     die "Usage: gzgrep pattern file...\n"
         unless @ARGV >= 2;

     $pattern = shift ;

     foreach $file (@ARGV) {
         $gz = gzopen($file, "rb")
              or die "Cannot open $file: $gzerrno\n" ;
     
         while ($gz->gzreadline($_) > 0) {
             print if /$pattern/ ;
         }
     
         die "Error reading from $file: $gzerrno\n"
             if $gzerrno != Z_STREAM_END ;
     
         $gz->gzclose() ;
     }

CHECKSUM FUNCTIONS
==================

Two functions are provided by *zlib* to calculate a checksum. For the Perl
interface, the order of the two parameters in both functions has been
reversed. This allows both running checksums and one off calculations to
be done.

     $crc = adler32($buffer [,$crc]) ;
     $crc = crc32($buffer [,$crc]) ;

CONSTANTS
=========

All the *zlib* constants are automatically imported when you make use of
*Compress::Zlib*.

AUTHOR
======

The *Compress::Zlib* module was written by Paul Marquess,
`pmarquess@bfsec.bt.co.uk'. The latest copy of the module can be found on
CPAN in `modules/by-module/Compress/Compress-Zlib-x.x.tar.gz'.

The *zlib* compression library was written by Jean-loup Gailly
`gzip@prep.ai.mit.edu' and Mark Adler `madler@alumni.caltech.edu'.  It is
available at `ftp://ftp.uu.net/pub/archiving/zip/zlib*' and
`ftp://swrinde.nde.swri.edu/pub/png/src/zlib*'.

Questions about *zlib* itself should be sent to `zlib@quest.jpl.nasa.gov'
or, if this fails, to the addresses given for the authors above.

MODIFICATION HISTORY
====================

0.1 2nd October 1995.
---------------------

First public release of *Compress::Zlib*.

0.2 5th October 1995.
---------------------

Fixed a minor allocation problem in Zlib.xs

0.3 12th October 1995.
----------------------

Added prototype specification.

0.4 25th June 1996.
-------------------

  1. Documentation update.

  2. Upgraded to support zlib 1.0.2

  3. Added dictionary interface.

  4. Fixed bug in gzreadline - previously it would keep returning the same
     buffer. This bug was reported by Helmut Jarausch

  5. Removed dependancy to zutil.h and so dropped support for

     DEF_MEM_LEVEL (use MAX_MEM_LEVEL instead)     DEF_WBITS     (use
     MAX_WBITS instead)



File: pm.info,  Node: Config,  Next: ConfigFile,  Prev: Compress/Zlib,  Up: Module List

access Perl configuration information
*************************************

NAME
====

Config - access Perl configuration information

SYNOPSIS
========

     use Config;
     if ($Config{'cc'} =~ /gcc/) {
     	print "built by gcc\n";
     }

     use Config qw(myconfig config_sh config_vars);

     print myconfig();

     print config_sh();

     config_vars(qw(osname archname));

DESCRIPTION
===========

The Config module contains all the information that was available to the
`Configure' program at Perl build time (over 900 values).

Shell variables from the `config.sh' file (written by Configure) are
stored in the readonly-variable `%Config', indexed by their names.

Values stored in config.sh as 'undef' are returned as undefined values.
The perl exists function can be used to check if a named variable exists.

myconfig()
     Returns a textual summary of the major perl configuration values.
     See also -V in `Switches', *Note Perlrun: (perl.info)perlrun,.

config_sh()
     Returns the entire perl configuration information in the form of the
     original config.sh shell variable assignment script.

config_vars(@names)
     Prints to STDOUT the values of the named configuration variable. Each
     is printed on a separate line in the form:

          name='value';

     Names which are unknown are output as `name='UNKNOWN';'.  See also
     `-V:name' in `Switches', *Note Perlrun: (perl.info)perlrun,.

EXAMPLE
=======

Here's a more sophisticated example of using %Config:

     use Config;

     defined $Config{sig_name} || die "No sigs?";
     foreach $name (split(' ', $Config{sig_name})) {
     	$signo{$name} = $i;
     	$signame[$i] = $name;
     	$i++;
     }

     print "signal #17 = $signame[17]\n";
     if ($signo{ALRM}) {
     	print "SIGALRM is $signo{ALRM}\n";
     }

WARNING
=======

Because this information is not stored within the perl executable itself
it is possible (but unlikely) that the information does not relate to the
actual perl binary which is being used to access it.

The Config module is installed into the architecture and version specific
library directory ($Config{installarchlib}) and it checks the perl version
number when loaded.

NOTE
====

This module contains a good example of how to use tie to implement a cache
and an example of how to make a tied variable readonly to those outside of
it.


File: pm.info,  Node: ConfigFile,  Next: Convert/UU,  Prev: Config,  Up: Module List

Perl module to read and write Windows-like config files
*******************************************************

NAME
====

ConfigFile.pm - Perl module to read and write Windows-like config files

SYSNOPSIS
=========

     use ConfigFile;
     $config = new ConfigFile "config_file_path";
     $val = $config->Parameter ($section, $parameter);
     $config->Parameter ($section, $parameter, $val);

DESCRIPTION
===========

This module provides an easy and standard way for accessing configuration
files from Perl. Its structure is meant to be very simple and extendable.
The module reads and writes configuration files that are simular to
Microsoft Windows INI files.

The Windows INI file format was chosen because of its simplicity, the
ability to have multiple sections, and the wide spread use in many
hundreds of applications. The file format consists of three types of
lines: section declarations, definitions, and comments.

   * Section declarations Section declarations simply mark the start of
     another section in the configuration file. It is easily recognizable
     because of the square brackets ([]) that surround the section name.
     Any white space that is placed on this line-before, inside, or after
     the square  brackets-is ignored. Any white space within the section
     name is squeezed down to a single space.

   * Section definitions Section definitions are the actual settings. The
     section definitions consists of key and value pairs that are
     seperated by an equal sign (=). Any white space that is before or
     after the key or value  is ignored. White space in the key portion is
     left intact and is squeezed down to one space. The value portion is
     treated the same as a key unless it is surrounded by double quotes
     ("), in which case the white space remains as is and the double
     quotes are  removed from the value portion.

   * Comments Comments are totally ignored. Comment lines begin with
     either a semicolon (;) or a pound sign (#). White space is allowed
     before the semicolon and pound sign. A comment can not be on  the
     same line as a section definition.

Configuration File Example
--------------------------

     ; Mail configuration

     [ Mail ]
     
     User = hickey
     Connection Type = imap

AUTHOR
======

Gerard Hickey hickey@ctron.com


File: pm.info,  Node: Convert/UU,  Next: Crypt/DES,  Prev: ConfigFile,  Up: Module List

Perl module for uuencode and uudecode
*************************************

NAME
====

Convert::UU, uuencode, uudecode - Perl module for uuencode and uudecode

SYNOPSIS
========

     use Convert::UU qw(uudecode uuencode);
     $encoded_string = uuencode($string,[$filename],[$mode]);
     ($string,$filename,$mode) = uudecode($string);
     $string = uudecode($string); # in scalar context

DESCRIPTION
===========

uuencode() takes as the first argument a scalar that is to be uuencoded.
Alternatively a filehandle may be passed that must be opened for reading.
It returns the uuencoded string including begin and end. Second and third
argument are optional and specify filename and mode. If unspecified these
default to "uuencode.uu" and 644.

uudecode() takes a string as argument which will be uudecoded. If the
argument is a filehandle this will be read instead. Leading and trailing
garbage will be ignored. The function returns the uudecoded string for the
first begin/end pair. In array context it returns an array whose first
element is the uudecoded string, the second is the filename and the third
is the mode.

EXPORT
======

Both uudecode and uuencode are in @EXPORT_OK.

PORTABILITY
===========

No effort has been made yet to port this module to non UNIX operating
systems. Volunteers are welcome.

AUTHOR
======

Andreas Koenig <andreas.koenig@mind.de>. With code stolen from Hans Mulder
<hansm@wsinti05.win.tue.nl> and Randal L. Schwartz <merlyn@teleport.com>.

SEE ALSO
========

puuencode(1), puudecode(1) for examples of how to use this module.


File: pm.info,  Node: Crypt/DES,  Next: Crypt/IDEA,  Prev: Convert/UU,  Up: Module List

Perl interface to DES block cipher
**********************************

NAME
====

DES - Perl interface to DES block cipher

SYNOPSIS
========

     use Crypt::DES;

DESCRIPTION
===========

This perl extension is an implementation of the DES block cipher algorithm.
The module implements the Crypt::BlockCipher interface, which has the
following methods

blocksize =item keysize =item encrypt =item decrypt
FUNCTIONS
=========

blocksize
     Returns the size (in bytes) of the block cipher.

keysize
     Returns the size (in bytes) of the key.

new
          my $cipher = new DES $key;

     This creates a new DES BlockCipher object, using $key, where $key is
     a key of `keysize()' bytes.

encrypt
          my $cipher = new DES $key;
          my $ciphertext = $cipher->encrypt($plaintext);

     This function encrypts $plaintext and returns the $ciphertext where
     $plaintext and $ciphertext should be of `blocksize()' bytes.

decrypt
          my $cipher = new DES $key;
          my $plaintext = $cipher->decrypt($ciphertext);

     This function decrypts $ciphertext and returns the $plaintext where
     $plaintext and $ciphertext should be of `blocksize()' bytes.

EXAMPLE
=======

     my $key = pack("H16", "0123456789ABCDEF");
     my $cipher = new DES $key;
     my $ciphertext = $cipher->encrypt("plaintex");	# NB - 8 bytes
     print unpack("H16", $ciphertext), "\n";

SEE ALSO
========

Crypt::IDEA

Bruce Schneier, *Applied Cryptography*, 1995, Second Edition, published by
John Wiley & Sons, Inc.

COPYRIGHT
=========

The implementation of the DES algorithm was developed by, and is copyright
of, Eric Young (eay@mincom.oz.au).  Other parts of this perl extension are
copyright of Systemics Ltd ( http://www.systemics.com/ ).


File: pm.info,  Node: Crypt/IDEA,  Next: Cwd,  Prev: Crypt/DES,  Up: Module List

Perl interface to IDEA block cipher
***********************************

NAME
====

IDEA - Perl interface to IDEA block cipher

SYNOPSIS
========

     use Crypt::IDEA;

DESCRIPTION
===========

This perl extension is an implementation of the IDEA block cipher
algorithm.  The module implements the Crypt::BlockCipher interface, which
has the following methods

blocksize =item keysize =item encrypt =item decrypt
FUNCTIONS
=========

blocksize
     Returns the size (in bytes) of the block cipher.

keysize
     Returns the size (in bytes) of the key.

new
          my $cipher = new IDEA $key;

     This creates a new IDEA BlockCipher object, using $key, where $key is
     a key of `keysize()' bytes.

encrypt
          my $cipher = new IDEA $key;
          my $ciphertext = $cipher->encrypt($plaintext);

     This function encrypts $plaintext and returns the $ciphertext where
     $plaintext and $ciphertext should be of `blocksize()' bytes.

decrypt
          my $cipher = new IDEA $key;
          my $plaintext = $cipher->decrypt($ciphertext);

     This function decrypts $ciphertext and returns the $plaintext where
     $plaintext and $ciphertext should be of `blocksize()' bytes.

EXAMPLE
=======

     my $key = pack("H32", "0123456789ABCDEF0123456789ABCDEF");
     my $cipher = new IDEA $key;
     my $ciphertext = $cipher->encrypt("plaintex");	# NB - 8 bytes
     print unpack("H16", $ciphertext), "\n";

SEE ALSO
========

Crypt::DES

Bruce Schneier, *Applied Cryptography*, 1995, Second Edition, published by
John Wiley & Sons, Inc.

COPYRIGHT
=========

This implementation is copyright Systemics Ltd ( http://www.systemics.com/
).

The IDEA algorithm is patented in Europe and the United States by
Ascom-Tech AG.


File: pm.info,  Node: Cwd,  Next: DB_File,  Prev: Crypt/IDEA,  Up: Module List

get pathname of current working directory
*****************************************

NAME
====

getcwd - get pathname of current working directory

SYNOPSIS
========

     use Cwd;
     $dir = cwd;

     use Cwd;
     $dir = getcwd;

     use Cwd;
     $dir = fastgetcwd;

     use Cwd 'chdir';
     chdir "/tmp";
     print $ENV{'PWD'};

DESCRIPTION
===========

The getcwd() function re-implements the getcwd(3) (or getwd(3)) functions
in Perl.

The fastcwd() function looks the same as getcwd(), but runs faster.  It's
also more dangerous because you might conceivably chdir() out of a
directory that you can't chdir() back into.

The cwd() function looks the same as getcwd and fastgetcwd but is
implemented using the most natural and safe form for the current
architecture. For most systems it is identical to `pwd` (but without the
trailing line terminator). It is recommended that cwd (or another *cwd()
function) is used in all code to ensure portability.

If you ask to override your chdir() built-in function, then your PWD
environment variable will be kept up to date.  (See `Overriding builtin
functions', *Note Perlsub: (perl.info)perlsub,.) Note that it will only be
kept up to date if all packages which use chdir import it from Cwd.


File: pm.info,  Node: DB_File,  Next: DCE/Login,  Prev: Cwd,  Up: Module List

Perl5 access to Berkeley DB
***************************

NAME
====

DB_File - Perl5 access to Berkeley DB

SYNOPSIS
========

     use DB_File ;
     use strict 'untie' ;
     
     [$X =] tie %hash,  'DB_File', [$filename, $flags, $mode, $DB_HASH] ;
     [$X =] tie %hash,  'DB_File', $filename, $flags, $mode, $DB_BTREE ;
     [$X =] tie @array, 'DB_File', $filename, $flags, $mode, $DB_RECNO ;

     $status = $X->del($key [, $flags]) ;
     $status = $X->put($key, $value [, $flags]) ;
     $status = $X->get($key, $value [, $flags]) ;
     $status = $X->seq($key, $value, $flags) ;
     $status = $X->sync([$flags]) ;
     $status = $X->fd ;

     # BTREE only
     $count = $X->get_dup($key) ;
     @list  = $X->get_dup($key) ;
     %list  = $X->get_dup($key, 1) ;

     # RECNO only
     $a = $X->length;
     $a = $X->pop ;
     $X->push(list);
     $a = $X->shift;
     $X->unshift(list);

     untie %hash ;
     untie @array ;

DESCRIPTION
===========

DB_File is a module which allows Perl programs to make use of the
facilities provided by Berkeley DB.  If you intend to use this module you
should really have a copy of the Berkeley DB manual pages at hand. The
interface defined here mirrors the Berkeley DB interface closely.

Berkeley DB is a C library which provides a consistent interface to a
number of database formats.  DB_File provides an interface to all three of
the database types currently supported by Berkeley DB.

The file types are:

DB_HASH
     This database type allows arbitrary key/value pairs to be stored in
     data files. This is equivalent to the functionality provided by other
     hashing packages like DBM, NDBM, ODBM, GDBM, and SDBM. Remember
     though, the files created using DB_HASH are not compatible with any
     of the other packages mentioned.

     A default hashing algorithm, which will be adequate for most
     applications, is built into Berkeley DB. If you do need to use your
     own hashing algorithm it is possible to write your own in Perl and
     have DB_File use it instead.

DB_BTREE
     The btree format allows arbitrary key/value pairs to be stored in a
     sorted, balanced binary tree.

     As with the DB_HASH format, it is possible to provide a user defined
     Perl routine to perform the comparison of keys. By default, though,
     the keys are stored in lexical order.

DB_RECNO
     DB_RECNO allows both fixed-length and variable-length flat text files
     to be manipulated using the same key/value pair interface as in
     DB_HASH and DB_BTREE.  In this case the key will consist of a record
     (line) number.

How does DB_File interface to Berkeley DB?
------------------------------------------

DB_File allows access to Berkeley DB files using the tie() mechanism in
Perl 5 (for full details, see `tie()', *Note Perlfunc:
(perl.info)perlfunc,). This facility allows DB_File to access Berkeley DB
files using either an associative array (for DB_HASH & DB_BTREE file
types) or an ordinary array (for the DB_RECNO file type).

In addition to the tie() interface, it is also possible to access most of
the functions provided in the Berkeley DB API directly.  See `THE API
INTERFACE' in this node.

Opening a Berkeley DB Database File
-----------------------------------

Berkeley DB uses the function dbopen() to open or create a database.  Here
is the C prototype for dbopen():

     DB*
     dbopen (const char * file, int flags, int mode,
             DBTYPE type, const void * openinfo)

The parameter type is an enumeration which specifies which of the 3
interface methods (DB_HASH, DB_BTREE or DB_RECNO) is to be used.
Depending on which of these is actually chosen, the final parameter,
*openinfo* points to a data structure which allows tailoring of the
specific interface method.

This interface is handled slightly differently in DB_File. Here is an
equivalent call using DB_File:

     tie %array, 'DB_File', $filename, $flags, $mode, $DB_HASH ;

The `filename', `flags' and `mode' parameters are the direct equivalent of
their dbopen() counterparts. The final parameter $DB_HASH performs the
function of both the type and `openinfo' parameters in dbopen().

In the example above $DB_HASH is actually a pre-defined reference to a
hash object. DB_File has three of these pre-defined references.  Apart
from $DB_HASH, there is also $DB_BTREE and $DB_RECNO.

The keys allowed in each of these pre-defined references is limited to the
names used in the equivalent C structure. So, for example, the $DB_HASH
reference will only allow keys called `bsize', `cachesize', `ffactor',
`hash', `lorder' and `nelem'.

To change one of these elements, just assign to it like this:

     $DB_HASH->{'cachesize'} = 10000 ;

The three predefined variables $DB_HASH, $DB_BTREE and $DB_RECNO are
usually adequate for most applications.  If you do need to create extra
instances of these objects, constructors are available for each file type.

Here are examples of the constructors and the valid options available for
DB_HASH, DB_BTREE and DB_RECNO respectively.

     $a = new DB_File::HASHINFO ;
     $a->{'bsize'} ;
     $a->{'cachesize'} ;
     $a->{'ffactor'};
     $a->{'hash'} ;
     $a->{'lorder'} ;
     $a->{'nelem'} ;

     $b = new DB_File::BTREEINFO ;
     $b->{'flags'} ;
     $b->{'cachesize'} ;
     $b->{'maxkeypage'} ;
     $b->{'minkeypage'} ;
     $b->{'psize'} ;
     $b->{'compare'} ;
     $b->{'prefix'} ;
     $b->{'lorder'} ;

     $c = new DB_File::RECNOINFO ;
     $c->{'bval'} ;
     $c->{'cachesize'} ;
     $c->{'psize'} ;
     $c->{'flags'} ;
     $c->{'lorder'} ;
     $c->{'reclen'} ;
     $c->{'bfname'} ;

The values stored in the hashes above are mostly the direct equivalent of
their C counterpart. Like their C counterparts, all are set to a default
values - that means you don't have to set all of the values when you only
want to change one. Here is an example:

     $a = new DB_File::HASHINFO ;
     $a->{'cachesize'} =  12345 ;
     tie %y, 'DB_File', "filename", $flags, 0777, $a ;

A few of the values need extra discussion here. When used, the C
equivalent of the keys `hash', `compare' and `prefix' store pointers to C
functions. In DB_File these keys are used to store references to Perl
subs. Below are templates for each of the subs:

     sub hash
     {
         my ($data) = @_ ;
         ...
         # return the hash value for $data
     	return $hash ;
     }

     sub compare
     {
     	my ($key, $key2) = @_ ;
         ...
         # return  0 if $key1 eq $key2
         #        -1 if $key1 lt $key2
         #         1 if $key1 gt $key2
         return (-1 , 0 or 1) ;
     }

     sub prefix
     {
     	my ($key, $key2) = @_ ;
         ...
         # return number of bytes of $key2 which are
         # necessary to determine that it is greater than $key1
         return $bytes ;
     }

See `Changing the BTREE sort order' in this node for an example of using
the `compare' template.

Default Parameters
------------------

It is possible to omit some or all of the final 4 parameters in the call
to tie and let them take default values. As DB_HASH is the most common
file format used, the call:

     tie %A, "DB_File", "filename" ;

is equivalent to:

     tie %A, "DB_File", "filename", O_CREAT|O_RDWR, 0640, $DB_HASH ;

It is also possible to omit the filename parameter as well, so the call:

     tie %A, "DB_File" ;

is equivalent to:

     tie %A, "DB_File", undef, O_CREAT|O_RDWR, 0640, $DB_HASH ;

See `In Memory Databases' in this node for a discussion on the use of undef
in place of a filename.

In Memory Databases
-------------------

Berkeley DB allows the creation of in-memory databases by using NULL (that
is, a `(char *)0' in C) in place of the filename.  DB_File uses undef
instead of NULL to provide this functionality.

DB_HASH
=======

The DB_HASH file format is probably the most commonly used of the three
file formats that DB_File supports. It is also very straightforward to use.

A Simple Example.
-----------------

This example shows how to create a database, add key/value pairs to the
database, delete keys/value pairs and finally how to enumerate the
contents of the database.

     use DB_File ;
     use strict 'untie' ;

     tie %h, "DB_File", "fruit", O_RDWR|O_CREAT, 0640, $DB_HASH
         or die "Cannot open file 'fruit': $!\n";

     # Add a few key/value pairs to the file
     $h{"apple"} = "red" ;
     $h{"orange"} = "orange" ;
     $h{"banana"} = "yellow" ;
     $h{"tomato"} = "red" ;

     # Check for existence of a key
     print "Banana Exists\n\n" if $h{"banana"} ;

     # Delete a key/value pair.
     delete $h{"apple"} ;

     # print the contents of the file
     while (($k, $v) = each %h)
       { print "$k -> $v\n" }

     untie %h ;

here is the output:

     Banana Exists
     
     orange -> orange
     tomato -> red
     banana -> yellow

Note that the like ordinary associative arrays, the order of the keys
retrieved is in an apparently random order.

DB_BTREE
========

The DB_BTREE format is useful when you want to store data in a given
order. By default the keys will be stored in lexical order, but as you
will see from the example shown in the next section, it is very easy to
define your own sorting function.

Changing the BTREE sort order
-----------------------------

This script shows how to override the default sorting algorithm that BTREE
uses. Instead of using the normal lexical ordering, a case insensitive
compare function will be used.

     use DB_File ;
     use strict 'untie' ;

     sub Compare
     {
         my ($key1, $key2) = @_ ;
         "\L$key1" cmp "\L$key2" ;
     }

     # specify the Perl sub that will do the comparison
     $DB_BTREE->{'compare'} = \&Compare ;

     tie %h, "DB_File", "tree", O_RDWR|O_CREAT, 0640, $DB_BTREE
         or die "Cannot open file 'tree': $!\n" ;

     # Add a key/value pair to the file
     $h{'Wall'} = 'Larry' ;
     $h{'Smith'} = 'John' ;
     $h{'mouse'} = 'mickey' ;
     $h{'duck'}  = 'donald' ;

     # Delete
     delete $h{"duck"} ;

     # Cycle through the keys printing them in order.
     # Note it is not necessary to sort the keys as
     # the btree will have kept them in order automatically.
     foreach (keys %h)
       { print "$_\n" }

     untie %h ;

Here is the output from the code above.

     mouse
     Smith
     Wall

There are a few point to bear in mind if you want to change the ordering
in a BTREE database:

  1. The new compare function must be specified when you create the
     database.

  2. You cannot change the ordering once the database has been created.
     Thus you must use the same compare function every time you access the
     database.


Handling duplicate keys
-----------------------

The BTREE file type optionally allows a single key to be associated with
an arbitrary number of values. This option is enabled by setting the flags
element of `$DB_BTREE' to R_DUP when creating the database.

There are some difficulties in using the tied hash interface if you want
to manipulate a BTREE database with duplicate keys. Consider this code:

     use DB_File ;
     use strict 'untie' ;
     
     $filename = "tree" ;
     unlink $filename ;
     
     # Enable duplicate records
     $DB_BTREE->{'flags'} = R_DUP ;
     
     tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0640, $DB_BTREE
     	or die "Cannot open $filename: $!\n";
     
     # Add some key/value pairs to the file
     $h{'Wall'} = 'Larry' ;
     $h{'Wall'} = 'Brick' ; # Note the duplicate key
     $h{'Wall'} = 'Brick' ; # Note the duplicate key and value
     $h{'Smith'} = 'John' ;
     $h{'mouse'} = 'mickey' ;

     # iterate through the associative array
     # and print each key/value pair.
     foreach (keys %h)
       { print "$_  -> $h{$_}\n" }

     untie %h ;

Here is the output:

     Smith   -> John
     Wall    -> Larry
     Wall    -> Larry
     Wall    -> Larry
     mouse   -> mickey

As you can see 3 records have been successfully created with key `Wall' -
the only thing is, when they are retrieved from the database they *seem*
to have the same value, namely `Larry'. The problem is caused by the way
that the associative array interface works. Basically, when the
associative array interface is used to fetch the value associated with a
given key, it will only ever retrieve the first value.

Although it may not be immediately obvious from the code above, the
associative array interface can be used to write values with duplicate
keys, but it cannot be used to read them back from the database.

The way to get around this problem is to use the Berkeley DB API method
called `seq'.  This method allows sequential access to key/value pairs.
See `THE API INTERFACE' in this node for details of both the `seq' method
and the API in general.

Here is the script above rewritten using the `seq' API method.

     use DB_File ;
     use strict 'untie' ;
     
     $filename = "tree" ;
     unlink $filename ;
     
     # Enable duplicate records
     $DB_BTREE->{'flags'} = R_DUP ;
     
     $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0640, $DB_BTREE
     	or die "Cannot open $filename: $!\n";
     
     # Add some key/value pairs to the file
     $h{'Wall'} = 'Larry' ;
     $h{'Wall'} = 'Brick' ; # Note the duplicate key
     $h{'Wall'} = 'Brick' ; # Note the duplicate key and value
     $h{'Smith'} = 'John' ;
     $h{'mouse'} = 'mickey' ;
     
     # iterate through the btree using seq
     # and print each key/value pair.
     for ($status = $x->seq($key, $value, R_FIRST) ;
          $status == 0 ;
          $status = $x->seq($key, $value, R_NEXT) )
       {  print "$key -> $value\n" }
     
     undef $x ;
     untie %h ;

that prints:

     Smith   -> John
     Wall    -> Brick
     Wall    -> Brick
     Wall    -> Larry
     mouse   -> mickey

This time we have got all the key/value pairs, including the multiple
values associated with the key `Wall'.

The get_dup method.
-------------------

DB_File comes with a utility method, called `get_dup', to assist in
reading duplicate values from BTREE databases. The method can take the
following forms:

     $count = $x->get_dup($key) ;
     @list  = $x->get_dup($key) ;
     %list  = $x->get_dup($key, 1) ;

In a scalar context the method returns the number of values associated
with the key, `$key'.

In list context, it returns all the values which match `$key'. Note that
the values will be returned in an apparently random order.

In list context, if the second parameter is present and evaluates TRUE,
the method returns an associative array. The keys of the associative array
correspond to the the values that matched in the BTREE and the values of
the array are a count of the number of times that particular value
occurred in the BTREE.

So assuming the database created above, we can use `get_dup' like this:

     $cnt  = $x->get_dup("Wall") ;
     print "Wall occurred $cnt times\n" ;

     %hash = $x->get_dup("Wall", 1) ;
     print "Larry is there\n" if $hash{'Larry'} ;
     print "There are $hash{'Brick'} Brick Walls\n" ;

     @list = $x->get_dup("Wall") ;
     print "Wall =>	[@list]\n" ;

     @list = $x->get_dup("Smith") ;
     print "Smith =>	[@list]\n" ;
     
     @list = $x->get_dup("Dog") ;
     print "Dog =>	[@list]\n" ;

and it will print:

     Wall occurred 3 times
     Larry is there
     There are 2 Brick Walls
     Wall =>	[Brick Brick Larry]
     Smith =>	[John]
     Dog =>	[]

Matching Partial Keys
---------------------

The BTREE interface has a feature which allows partial keys to be matched.
This functionality is *only* available when the `seq' method is used along
with the R_CURSOR flag.

     $x->seq($key, $value, R_CURSOR) ;

Here is the relevant quote from the dbopen man page where it defines the
use of the R_CURSOR flag with seq:

     Note, for the DB_BTREE access method, the returned key is not
     necessarily an exact match for the specified key. The returned key
     is the smallest key greater than or equal to the specified key,
     permitting partial key matches and range searches.

In the example script below, the `match' sub uses this feature to find and
print the first matching key/value pair given a partial key.

     use DB_File ;
     use Fcntl ;
     use strict 'untie' ;

     sub match
     {
         my $key = shift ;
         my $value ;
         my $orig_key = $key ;
         $x->seq($key, $value, R_CURSOR) ;
         print "$orig_key\t-> $key\t-> $value\n" ;
     }

     $filename = "tree" ;
     unlink $filename ;

     $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0640, $DB_BTREE
         or die "Cannot open $filename: $!\n";
     
     # Add some key/value pairs to the file
     $h{'mouse'} = 'mickey' ;
     $h{'Wall'} = 'Larry' ;
     $h{'Walls'} = 'Brick' ;
     $h{'Smith'} = 'John' ;

     print "IN ORDER\n" ;
     for ($st = $x->seq($key, $value, R_FIRST) ;
     	 $st == 0 ;
          $st = $x->seq($key, $value, R_NEXT) )
     
       {  print "$key -> $value\n" }
     
     print "\nPARTIAL MATCH\n" ;

     match "Wa" ;
     match "A" ;
     match "a" ;

     undef $x ;
     untie %h ;

Here is the output:

     IN ORDER
     Smith -> John
     Wall  -> Larry
     Walls -> Brick
     mouse -> mickey

     PARTIAL MATCH
     Wa -> Wall  -> Larry
     A  -> Smith -> John
     a  -> mouse -> mickey

DB_RECNO
========

DB_RECNO provides an interface to flat text files. Both variable and fixed
length records are supported.

In order to make RECNO more compatible with Perl the array offset for all
RECNO arrays begins at 0 rather than 1 as in Berkeley DB.

As with normal Perl arrays, a RECNO array can be accessed using negative
indexes. The index -1 refers to the last element of the array, -2 the
second last, and so on. Attempting to access an element before the start
of the array will raise a fatal run-time error.

A Simple Example
----------------

Here is a simple example that uses RECNO.

     use DB_File ;
     use strict 'untie' ;

     tie @h, "DB_File", "text", O_RDWR|O_CREAT, 0640, $DB_RECNO
         or die "Cannot open file 'text': $!\n" ;

     # Add a few key/value pairs to the file
     $h[0] = "orange" ;
     $h[1] = "blue" ;
     $h[2] = "yellow" ;

     # Check for existence of a key
     print "Element 1 Exists with value $h[1]\n" if $h[1] ;

     # use a negative index
     print "The last element is $h[-1]\n" ;
     print "The 2nd last element is $h[-2]\n" ;

     untie @h ;

Here is the output from the script:

     Element 1 Exists with value blue
     The last element is yellow
     The 2nd last element is blue

Extra Methods
-------------

As you can see from the example above, the tied array interface is quite
limited. To make the interface more useful, a number of methods are
supplied with DB_File to simulate the standard array operations that are
not currently implemented in Perl's tied array interface. All these
methods are accessed via the object returned from the tie call.

Here are the methods:

*$X->push(list) ;*
     Pushes the elements of list to the end of the array.

*$value = $X->pop ;*
     Removes and returns the last element of the array.

*$X->shift*
     Removes and returns the first element of the array.

*$X->unshift(list) ;*
     Pushes the elements of list to the start of the array.

*$X->length*
     Returns the number of elements in the array.

Another Example
---------------

Here is a more complete example that makes use of some of the methods
described above. It also makes use of the API interface directly (see `THE
API INTERFACE' in this node).

     use strict ;
     use vars qw(@h $H $file $i) ;
     use DB_File ;
     use Fcntl ;
     
     $file = "text" ;

     unlink $file ;

     $H = tie @h, "DB_File", $file, O_RDWR|O_CREAT, 0640, $DB_RECNO
         or die "Cannot open file $file: $!\n" ;
     
     # first create a text file to play with
     $h[0] = "zero" ;
     $h[1] = "one" ;
     $h[2] = "two" ;
     $h[3] = "three" ;
     $h[4] = "four" ;

     # Print the records in order.
         #
         # The length method is needed here because evaluating a tied
         # array in a scalar context does not return the number of
         # elements in the array.

     print "\nORIGINAL\n" ;
     foreach $i (0 .. $H->length - 1) {
         print "$i: $h[$i]\n" ;
     }

     # use the push & pop methods
     $a = $H->pop ;
     $H->push("last") ;
     print "\nThe last record was [$a]\n" ;

     # and the shift & unshift methods
     $a = $H->shift ;
     $H->unshift("first") ;
     print "The first record was [$a]\n" ;

     # Use the API to add a new record after record 2.
     $i = 2 ;
     $H->put($i, "Newbie", R_IAFTER) ;

     # and a new record before record 1.
     $i = 1 ;
     $H->put($i, "New One", R_IBEFORE) ;

     # delete record 3
     $H->del(3) ;

     # now print the records in reverse order
     print "\nREVERSE\n" ;
     for ($i = $H->length - 1 ; $i >= 0 ; -- $i)
       { print "$i: $h[$i]\n" }

     # same again, but use the API functions instead
     print "\nREVERSE again\n" ;
     my ($s, $k, $v)  ;
     for ($s = $H->seq($k, $v, R_LAST) ;
              $s == 0 ;
              $s = $H->seq($k, $v, R_PREV))
       { print "$k: $v\n" }

     undef $H ;
     untie @h ;

and this is what it outputs:

     ORIGINAL
     0: zero
     1: one
     2: two
     3: three
     4: four

     The last record was [four]
     The first record was [zero]

     REVERSE
     5: last
     4: three
     3: Newbie
     2: one
     1: New One
     0: first

     REVERSE again
     5: last
     4: three
     3: Newbie
     2: one
     1: New One
     0: first

Notes:

  1. Rather than iterating through the array, `@h' like this:

          foreach $i (@h)

     it is necessary to use either this:

          foreach $i (0 .. $H->length - 1)

     or this:

          for ($a = $H->get($k, $v, R_FIRST) ;
               $a == 0 ;
               $a = $H->get($k, $v, R_NEXT) )

  2. Notice that both times the put method was used the record index was
     specified using a variable, `$i', rather than the literal value
     itself. This is because put will return the record number of the
     inserted line via that parameter.


THE API INTERFACE
=================

As well as accessing Berkeley DB using a tied hash or array, it is also
possible to make direct use of most of the API functions defined in the
Berkeley DB documentation.

To do this you need to store a copy of the object returned from the tie.

     $db = tie %hash, "DB_File", "filename" ;

Once you have done that, you can access the Berkeley DB API functions as
DB_File methods directly like this:

     $db->put($key, $value, R_NOOVERWRITE) ;

*Important:* If you have saved a copy of the object returned from tie, the
underlying database file will *not* be closed until both the tied variable
is untied and all copies of the saved object are destroyed. See `The
strict untie pragma' in this node for more details.

     use DB_File ;
     $db = tie %hash, "DB_File", "filename"
         or die "Cannot tie filename: $!" ;
     ...
     undef $db ;
     untie %hash ;

All the functions defined in `dbopen' in this node are available except for
close() and dbopen() itself. The DB_File method interface to the supported
functions have been implemented to mirror the way Berkeley DB works
whenever possible. In particular note that:

   * The methods return a status value. All return 0 on success.  All
     return -1 to signify an error and set $! to the exact error code. The
     return code 1 generally (but not always) means that the key specified
     did not exist in the database.

     Other return codes are defined. See below and in the Berkeley DB
     documentation for details. The Berkeley DB documentation should be
     used as the definitive source.

   * Whenever a Berkeley DB function returns data via one of its
     parameters, the equivalent DB_File method does exactly the same.

   * If you are careful, it is possible to mix API calls with the tied
     hash/array interface in the same piece of code. Although only a few of
     the methods used to implement the tied interface currently make use of
     the cursor, you should always assume that the cursor has been changed
     any time the tied hash/array interface is used. As an example, this
     code will probably not do what you expect:

          $X = tie %x, 'DB_File', $filename, O_RDWR|O_CREAT, 0777, $DB_BTREE
              or die "Cannot tie $filename: $!" ;

          # Get the first key/value pair and set  the cursor
          $X->seq($key, $value, R_FIRST) ;

          # this line will modify the cursor
          $count = scalar keys %x ;

          # Get the second key/value pair.
          # oops, it didn't, it got the last key/value pair!
          $X->seq($key, $value, R_NEXT) ;

     The code above can be rearranged to get around the problem, like this:

          $X = tie %x, 'DB_File', $filename, O_RDWR|O_CREAT, 0777, $DB_BTREE
              or die "Cannot tie $filename: $!" ;

          # this line will modify the cursor
          $count = scalar keys %x ;

          # Get the first key/value pair and set  the cursor
          $X->seq($key, $value, R_FIRST) ;

          # Get the second key/value pair.
          # worked this time.
          $X->seq($key, $value, R_NEXT) ;

All the constants defined in `dbopen' in this node for use in the flags
parameters in the methods defined below are also available. Refer to the
Berkeley DB documentation for the precise meaning of the flags values.

Below is a list of the methods available.

*$status = $X->get($key, $value [, $flags]) ;*
     Given a key (`$key') this method reads the value associated with it
     from the database. The value read from the database is returned in the
     $value parameter.

     If the key does not exist the method returns 1.

     No flags are currently defined for this method.

*$status = $X->put($key, $value [, $flags]) ;*
     Stores the key/value pair in the database.

     If you use either the R_IAFTER or R_IBEFORE flags, the `$key'
     parameter will have the record number of the inserted key/value pair
     set.

     Valid flags are R_CURSOR, R_IAFTER, R_IBEFORE, R_NOOVERWRITE and
     R_SETCURSOR.

*$status = $X->del($key [, $flags]) ;*
     Removes all key/value pairs with key `$key' from the database.

     A return code of 1 means that the requested key was not in the
     database.

     R_CURSOR is the only valid flag at present.

*$status = $X->fd ;*
     Returns the file descriptor for the underlying database.

     See `Locking Databases' in this node for an example of how to make
     use of the `fd' method to lock your database.

*$status = $X->seq($key, $value, $flags) ;*
     This interface allows sequential retrieval from the database. See
     `dbopen' in this node for full details.

     Both the `$key' and $value parameters will be set to the key/value
     pair read from the database.

     The flags parameter is mandatory. The valid flag values are R_CURSOR,
     R_FIRST, R_LAST, R_NEXT and R_PREV.

*$status = $X->sync([$flags]) ;*
     Flushes any cached buffers to disk.

     R_RECNOSYNC is the only valid flag at present.

HINTS AND TIPS
==============

The strict untie pragma
-----------------------

If you run Perl version 5.004 or later (actually any version from the
5.003_01 development release on will suffice) and you make use of the
Berkeley DB API, it is is *very* strongly recommended that you always
include the `use strict 'untie'' pragma in any of your scripts that make
use of DB_File.

Even if you don't currently make use of the API interface, it is still a
good idea to include the pragma. It won't affect the performance of your
script, but it will prevent problems in the future.

If possible you should try to run with the full strict pragma, but that is
another story. For further details see *Note Strict: strict, and `WHY YOU
SHOULD ALWAYS `use strict'', *Note Perldsc: (perl.info)perldsc,.

To illustrate the importance of including the untie pragma, here is an
example script that fails in an unexpected place because it doesn't use it:

     use DB_File ;
     use Fcntl ;
     
     $X = tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_CREAT
         or die "Cannot tie first time: $!" ;
     
     $x{123} = 456 ;
     
     untie %x ;
     
     $X = tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_CREAT
         or die "Cannot tie second time: $!" ;

     untie %x ;

When run the script will produce this error message:

     Cannot tie second time: Invalid argument at bad.file line 12.

Although the error message above refers to the second tie statement in the
script, the source of the problem is really with the untie statement that
precedes it.

To understand why there is a problem at all with the untie statement,
consider what the tie does for a moment.

Whenever the tie is executed, it creates a logical link between a Perl
variable, the associative array `%x' in this case, and a Berkeley DB
database, `tst.fil'. The logical link ensures that all operation on the
associative array are automatically mirrored to the database file.

In normal circumstances the untie is enough to break the logical link and
also close the database. In this particular case there is another logical
link, namely the API object returned from the tie and stored in `$X'.
Whenever the untie is executed in this case, only the link between the
associative array and the database will be broken. The API object in `$X'
is still valid, so the database will not be closed.

The end result of this is that when the second tie is executed, the
database will be in an inconsistent state (i.e. it is still opened by the
first tie) - thus the second tie will fail.

If the `use strict 'untie'' pragma is included in the script, like this:

     use DB_File ;
     use Fcntl ;
     use strict 'untie' ;
     
     $X = tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_CREAT
         or die "Cannot tie first time: $!" ;
     
     $x{123} = 456 ;
     
     untie %x ;
     
     $X = tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_CREAT
         or die "Cannot tie second time: $!" ;

then the error message becomes:

     Can't untie: 1 inner references still exist at bad.file line 11.

which pinpoints the real problem. Finally the script can now be modified
to fix the original problem by destroying the API object before the untie:

     ...
     $x{123} = 456 ;

     undef $X ;
     untie %x ;
     
     $X = tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_CREAT
     ...

Locking Databases
-----------------

Concurrent access of a read-write database by several parties requires
them all to use some kind of locking.  Here's an example of Tom's that
uses the *fd* method to get the file descriptor, and then a careful open()
to give something Perl will flock() for you.  Run this repeatedly in the
background to watch the locks granted in proper order.

     use strict 'untie';
     use DB_File;

     use strict;

     sub LOCK_SH { 1 }
     sub LOCK_EX { 2 }
     sub LOCK_NB { 4 }
     sub LOCK_UN { 8 }

     my($oldval, $fd, $db, %db, $value, $key);

     $key = shift || 'default';
     $value = shift || 'magic';

     $value .= " $$";

     $db = tie(%db, 'DB_File', '/tmp/foo.db', O_CREAT|O_RDWR, 0644)
     	    || die "dbcreat /tmp/foo.db $!";
     $fd = $db->fd;
     print "$$: db fd is $fd\n";
     open(DB_FH, "+<&=$fd") || die "dup $!";

     unless (flock (DB_FH, LOCK_SH | LOCK_NB)) {
     	print "$$: CONTENTION; can't read during write update!
     		    Waiting for read lock ($!) ....";
     	unless (flock (DB_FH, LOCK_SH)) { die "flock: $!" }
     }
     print "$$: Read lock granted\n";

     $oldval = $db{$key};
     print "$$: Old value was $oldval\n";
     flock(DB_FH, LOCK_UN);

     unless (flock (DB_FH, LOCK_EX | LOCK_NB)) {
     	print "$$: CONTENTION; must have exclusive lock!
     		    Waiting for write lock ($!) ....";
     	unless (flock (DB_FH, LOCK_EX)) { die "flock: $!" }
     }

     print "$$: Write lock granted\n";
     $db{$key} = $value;
     $db->sync;
     sleep 10;

     flock(DB_FH, LOCK_UN);
     undef $db;
     untie %db;
     close(DB_FH);
     print "$$: Updated db to $key=$value\n";

Sharing databases with C applications
-------------------------------------

There is no technical reason why a Berkeley DB database cannot be shared
by both a Perl and a C application.

The vast majority of problems that are reported in this area boil down to
the fact that C strings are NULL terminated, whilst Perl strings are not.

Here is a real example. Netscape 2.0 keeps a record of the locations you
visit along with the time you last visited them in a DB_HASH database.
This is usually stored in the file `~/.netscape/history.db'. The key field
in the database is the location string and the value field is the time the
location was last visited stored as a 4 byte binary value.

If you haven't already guessed, the location string is stored with a
terminating NULL. This means you need to be careful when accessing the
database.

Here is a snippet of code that is loosely based on Tom Christiansen's
*ggh* script (available from your nearest CPAN archive in
`authors/id/TOMC/scripts/nshist.gz').

     use DB_File ;
     use Fcntl ;
     use strict 'untie' ;

     $dotdir = $ENV{HOME} || $ENV{LOGNAME};

     $HISTORY = "$dotdir/.netscape/history.db";

     tie %hist_db, 'DB_File', $HISTORY
         or die "Cannot open $HISTORY: $!\n" ;;

     # Dump the complete database
     while ( ($href, $binary_time) = each %hist_db ) {

     # remove the terminating NULL
     $href =~ s/\x00$// ;

     # convert the binary time into a user friendly string
     $date = localtime unpack("V", $binary_time);
     print "$date $href\n" ;
         }

     # check for the existence of a specific key
     # remember to add the NULL
     if ( $binary_time = $hist_db{"http://mox.perl.com/\x00"} ) {
         $date = localtime unpack("V", $binary_time) ;
         print "Last visited mox.perl.com on $date\n" ;
     }
     else {
         print "Never visited mox.perl.com\n"
     }

     untie %hist_db ;

COMMON QUESTIONS
================

Why is there Perl source in my database?
----------------------------------------

If you look at the contents of a database file created by DB_File, there
can sometimes be part of a Perl script included in it.

This happens because Berkeley DB uses dynamic memory to allocate buffers
which will subsequently be written to the database file. Being dynamic,
the memory could have been used for anything before DB malloced it. As
Berkeley DB doesn't clear the memory once it has been allocated, the
unused portions will contain random junk. In the case where a Perl script
gets written to the database, the random junk will correspond to an area
of dynamic memory that happened to be used during the compilation of the
script.

Unless you don't like the possibility of there being part of your Perl
scripts embedded in a database file, this is nothing to worry about.

How do I store complex data structures with DB_File?
----------------------------------------------------

Although DB_File cannot do this directly, there is a module which can
layer transparently over DB_File to accomplish this feat.

Check out the MLDBM module, available on CPAN in the directory
`modules/by-module/MLDBM'.

What does "Invalid Argument" mean?
----------------------------------

You will get this error message when one of the parameters in the tie call
is wrong. Unfortunately there are quite a few parameters to get wrong, so
it can be difficult to figure out which one it is.

Here are a couple of possibilities:

  1. Attempting to reopen a database without closing it. See `The strict
     untie pragma' in this node for an example.

  2. Using the O_WRONLY flag.


What does "Bareword 'DB_File' not allowed" mean?
------------------------------------------------

You will encounter this particular error message when you have the `strict
'subs'' pragma (or the full strict pragma) in your script.  Consider this
script:

     use strict ;
     use DB_File ;
     use vars qw(%x) ;
     tie %x, DB_File, "filename" ;

Running it produces the error in question:

     Bareword "DB_File" not allowed while "strict subs" in use

To get around the error, place the word DB_File in either single or double
quotes, like this:

     tie %x, "DB_File", "filename" ;

Although it might seem like a real pain, it is really worth the effort of
having a `use strict' in all your scripts.

HISTORY
=======

  1. First Release.

  2. When DB_File is opening a database file it no longer terminates the
     process if *dbopen* returned an error. This allows file protection
     errors to be caught at run time. Thanks to Judith Grass
     <grass@cybercash.com> for spotting the bug.

  3. Added prototype support for multiple btree compare callbacks.

  4. DB_File has been in use for over a year. To reflect that, the version
     number has been incremented to 1.0.

     Added complete support for multiple concurrent callbacks.

     Using the push method on an empty list didn't work properly. This has
     been fixed.

  5. Fixed a core dump problem with SunOS.

     The return value from TIEHASH wasn't set to NULL when dbopen returned
     an error.

  6. Merged OS/2 specific code into DB_File.xs

     Removed some redundant code in DB_File.xs.

     Documentation update.

     Allow negative subscripts with RECNO interface.

     Changed the default flags from O_RDWR to O_CREAT|O_RDWR.

     The example code which showed how to lock a database needed a call to
     sync added. Without it the resultant database file was empty.

     Added get_dup method.

  7. Documentation update.

     DB_File now imports the constants (O_RDWR, O_CREAT etc.) from Fcntl
     automatically.

     The standard hash function exists is now supported.

     Modified the behavior of get_dup. When it returns an associative
     array, the value is the count of the number of matching BTREE values.


BUGS
====

Some older versions of Berkeley DB had problems with fixed length records
using the RECNO file format. The newest version at the time of writing was
1.85 - this seems to have fixed the problems with RECNO.

I am sure there are bugs in the code. If you do find any, or can suggest
any enhancements, I would welcome your comments.

AVAILABILITY
============

DB_File comes with the standard Perl source distribution. Look in the
directory `ext/DB_File'.

Berkeley DB is available at your nearest CPAN archive (see `"CPAN"', *Note
Perlmod: (perl.info)perlmod, for a list) in `src/misc/db.1.85.tar.gz', or
via the host `ftp.cs.berkeley.edu' in `/ucb/4bsd/db.tar.gz'.  It is *not*
under the GPL.

If you are running IRIX, then get Berkeley DB from
`http://reality.sgi.com/ariel'. It has the patches necessary to compile
properly on IRIX 5.3.

SEE ALSO
========

`perl(1)' in this node, `dbopen(3)' in this node, `hash(3)' in this node,
`recno(3)' in this node, `btree(3)' in this node

AUTHOR
======

The DB_File interface was written by Paul Marquess
<pmarquess@bfsec.bt.co.uk>.  Questions about the DB system itself may be
addressed to Keith Bostic <bostic@cs.berkeley.edu>.


File: pm.info,  Node: DCE/Login,  Next: DCE/Registry,  Prev: DB_File,  Up: Module List

Perl extension for interfacing to the DCE login API
***************************************************

NAME
====

DCE::Login - Perl extension for interfacing to the DCE login API

SYNOPSIS
========

     use DCE::Login;
     my($l, $status) = DCE::Login->get_current_context;
     my $pwent = $l->get_pwent;

DESCRIPTION
===========

Perl extension for interfacing to the DCE login API.

AUTHOR
======

Doug MacEachern <dougm@osf.org>

SEE ALSO
========

perl(1), DCE::login_base(3), DCE::Registry(3).


File: pm.info,  Node: DCE/Registry,  Next: DCE/Status,  Prev: DCE/Login,  Up: Module List

Perl interface to DCE Registry API
**********************************

NAME
====

DCE::Registry - Perl interface to DCE Registry API

SYNOPSIS
========

     use DCE::Registry;

     my $rgy = DCE::Registry->site_open($site_name);

DESCRIPTION
===========

This module provides an OO Perl interface to the DCE Registry API.  The
sec_rgy_ prefix has been dropped and methods are invoked via a blessed
registry_context object.

AUTHOR
======

Doug MacEachern <dougm@osf.org>

SEE ALSO
========

perl(1), DCE::rgybase(3), DCE::Status(3), DCE::Login(3), DCE::UUID(3).


File: pm.info,  Node: DCE/Status,  Next: DCE/UUID,  Prev: DCE/Registry,  Up: Module List

Make sense of DCE status codes
******************************

NAME
====

DCE::Status - Make sense of DCE status codes

SYNOPSIS
========

     use DCE::Status;
     
     $errstr = error_inq_text($status);

     tie $status => DCE::Status;

DESCRIPTION
===========


File: pm.info,  Node: DCE/UUID,  Next: DCE/login_base,  Prev: DCE/Status,  Up: Module List

Misc UUID functions
*******************

NAME
====

DCE::UUID - Misc UUID functions

SYNOPSIS
========

     use DCE::UUID;

DESCRIPTION
===========

DCE::UUID exports the following functions:

uuid_create()
          my($uuid, $status) = uuid_create();

uuid_hash()
          my($hash, $status) = uuid_hash($uuid);

AUTHOR
======

Doug MacEachern <dougm@osf.org>

SEE ALSO
========

perl(1), DCE::Status(3), DCE::Registry(3), DCE::Login(3).


File: pm.info,  Node: DCE/login_base,  Next: DCE/rgybase,  Prev: DCE/UUID,  Up: Module List

Constants from sec_login_*.h
****************************

NAME
====

DCE::login_base - Constants from sec_login_*.h

SYNOPSIS
========

     use DCE::login_base;

DESCRIPTION
===========

These constant methods are inherited by DCE::Login, a developer should not
need to use this module and it's methods directly.

AUTHOR
======

h2xs

SEE ALSO
========

perl(1), DCE::Login(3), DCE::Registry(3).


File: pm.info,  Node: DCE/rgybase,  Next: Data/Dumper,  Prev: DCE/login_base,  Up: Module List

Constants from dce/rgybase.h
****************************

NAME
====

DCE::rgybase - Constants from dce/rgybase.h

SYNOPSIS
========

     use DCE::rgybase;

DESCRIPTION
===========

These constant methods are inherited by DCE::Registry, a developer should
not need to use this module and it's methods directly.

Here is a list of the available constants:

     acct_admin_audit
     acct_admin_client
     acct_admin_flags_none
     acct_admin_server
     acct_admin_valid
     acct_auth_dup_skey
     acct_auth_flags_none
     acct_auth_forwardable
     acct_auth_post_dated
     acct_auth_proxiable
     acct_auth_renewable
     acct_auth_tgt
     acct_key_group
     acct_key_last
     acct_key_none
     acct_key_org
     acct_key_person
     acct_user_flags_none
     acct_user_passwd_valid
     domain_group
     domain_last
     domain_org
     domain_person
     max_unix_passwd_len
     name_max_len
     name_t_size
     no_override
     no_resolve_pname
     override
     pgo_flags_none
     pgo_is_an_alias
     pgo_is_required
     pgo_projlist_ok
     plcy_pwd_flags_none
     plcy_pwd_no_spaces
     plcy_pwd_non_alpha
     pname_max_len
     pname_t_size
     prop_auth_cert_unbound
     prop_embedded_unix_id
     prop_readonly
     prop_shadow_passwd
     properties_none
     quota_unlimited
     resolve_pname
     rgynbase_v0_0_included
     status_ok
     uxid_unknown
     wildcard_name
     wildcard_sid

AUTHOR
======

h2xs

SEE ALSO
========

perl(1), DCE::Registry(3), DCE::Login(3).


File: pm.info,  Node: Data/Dumper,  Next: Data/Flow,  Prev: DCE/rgybase,  Up: Module List

stringified perl data structures, suitable for both printing and eval
*********************************************************************

NAME
====

Dumper - stringified perl data structures, suitable for both printing and
eval

SYNOPSIS
========

     use Data::Dumper;

     # simple procedural interface
     print Dumper($foo, $bar);

     # extended usage with names
     print Data::Dumper->Dump([$foo, $bar], [qw(foo *ary)]);

     # configuration variables
     {
       local $Data::Dump::Purity = 1;
       eval Data::Dumper->Dump([$foo, $bar], [qw(foo *ary)]);
     }

     # OO usage
     $d = Data::Dumper->new([$foo, $bar], [qw(foo *ary)]);
        ...
     print $d->Dump;
        ...
     $d->Purity(1);
     eval $d->Dump;

DESCRIPTION
===========

Given a list of scalars or reference variables, writes out their contents
in perl syntax. The references can also be objects.  The contents of each
variable is output in a single Perl statement.

The return value can be evaled to get back the original reference
structure. Bear in mind that a reference so created will not preserve
pointer equalities with the original reference.

Handles self-referential structures correctly.  Any references that are the
same as one of those passed in will be marked `$VARn', and other duplicate
references to substructures within `$VARn' will be appropriately labeled
using arrow notation.

The default output of self-referential structures can be evaled, but the
nested references to `$VARn' will be undefined, since a recursive structure
cannot be constructed using one Perl statement.  You can set
$Data::Dumper::Purity to 1 to get additional statements that will
correctly fill in these references.

In the extended usage form, the references to be dumped can be given
user-specified names.  If a name begins with a *, the output will describe
the dereferenced type of the supplied reference for hashes and arrays.

Several styles of output are possible, all controlled by setting
$Data::Dumper::Indent or using the corresponding method name.  Style 0
spews output without any newlines, indentation, or spaces between list
items.  It is the most compact format possible that can still be called
valid perl.  Style 1 outputs a readable form with newlines but no fancy
indentation (each level in the structure is simply indented by a fixed
amount of whitespace).  Style 2 (the default) outputs a very readable form
which takes into account the length of hash keys (so the hash value lines
up).  Style 3 is like style 2, but also annotates the elements of arrays
with their index (but the comment is on its own line, so array output
consumes twice the number of lines).

Methods
-------

*PACKAGE*->new(*ARRAYREF [*, *ARRAYREF]*)
     Returns a newly created Dumper object.  The first argument is an
     anonymous array of values to be dumped.  The optional second argument
     is an anonymous array of names for the values.  The names need not
     have a leading `$' sign, and must be comprised of alphanumeric
     characters.  You can begin a name with a * to specify that the
     dereferenced type must be dumped instead of the reference itself.

     The prefix specified by $Data::Dumper::Varname will be used with a
     numeric suffix if the name for a value is undefined.

$*OBJ*->Dump  *or*  *PACKAGE*->Dump(*ARRAYREF [*, *ARRAYREF]*)
     Returns the stringified form of the values stored in the object
     (preserving the order in which they were supplied to new), subject to
     the configuration options below.

     The second form, for convenience, simply calls the new method on its
     arguments before dumping the object immediately.

$*OBJ*->Dumpxs  *or*  *PACKAGE*->Dumpxs(*ARRAYREF [*, *ARRAYREF]*)
     This method is available if you were able to compile and install the
     XSUB extension to `Data::Dumper'. It is exactly identical to the
     `Dump' method above, only about 4 to 5 times faster, since it is
     written entirely in C.

$*OBJ*->Seen(*[HASHREF]*)
     Queries or adds to the internal table of already encountered
     references.  You must use Reset to explicitly clear the table if
     needed.  Such references are not dumped; instead, their names are
     inserted wherever they are to be dumped subsequently.

     Expects a anonymous hash of name => value pairs.  Same rules apply
     for names as in new.  If no argument is supplied, will return the
     "seen" list of name => value pairs, in an array context.

$*OBJ*->Values(*[ARRAYREF]*)
     Queries or replaces the internal array of values that will be dumped.

$*OBJ*->Names(*[ARRAYREF]*)
     Queries or replaces the internal array of user supplied names for the
     values that will be dumped.

$*OBJ*->Reset
     Clears the internal table of "seen" references.

Functions
---------

Dumper(LIST)
     Returns the stringified form of the values in the list, subject to the
     configuration options below.  The values will be named `$VARn' in the
     output, where n is a numeric suffix.

DumperX(LIST)
     Identical to the Dumper function above, but this calls the XSUB
     implementation, and is therefore about 3 to 4 times faster.  Only
     available if you were able to compile and install the XSUB extensions
     in `Data::Dumper'.

Configuration Variables/Methods
-------------------------------

Several configuration variables can be used to control the kind of output
generated when using the procedural interface.  These variables are usually
localized in a block so that other parts of the code are not affected by
the change.

These variables determine the default state of the object created by
calling the new method, but cannot be used to alter the state of the object
thereafter.  The equivalent method names should be used instead to query
or set the internal state of the object.

$Data::Dumper::Indent  *or*  $*OBJ*->Indent(*[NEWVAL]*)
     Controls the style of indentation.  It can be set to 0, 1, 2 or 3.  2
     is the default.

$Data::Dumper::Purity  *or*  $*OBJ*->Purity(*[NEWVAL]*)
     Controls the degree to which the output can be evaled to recreate the
     supplied reference structures.  Setting it to 1 will output
     additional perl statements that will correctly recreate nested
     references.  The default is 0.

$Data::Dumper::Pad  *or*  $*OBJ*->Pad(*[NEWVAL]*)
     Specifies the string that will be prefixed to every line of the
     output.  Empty string by default.

$Data::Dumper::Varname  *or*  $*OBJ*->Varname(*[NEWVAL]*)
     Contains the prefix to use for tagging variable names in the output.
     The default is "VAR".

Exports
-------

Dumper
EXAMPLE
=======

     use Data::Dumper;

     package Foo;
     sub new {bless {'a' => 1, 'b' => sub { return "foo" }}, $_[0]};

     package Fuz;                       # a wierd REF-REF-SCALAR object
     sub new {bless \($_ = \ 'fu\'z'), $_[0]};

     package main;
     $foo = Foo->new;
     $fuz = Fuz->new;
     $boo = [ 1, [], "abcd", \*foo,
              {1 => 'a', 023 => 'b', 0x45 => 'c'},
              \\"p\q\'r", $foo, $fuz];
     $bar = eval(Dumper($boo));
     print($@) if $@;
     print Dumper($boo), Dumper($bar);  # pretty print (no array indices)
     
     $Data::Dumper::Indent = 0;         # turn off all pretty print
     print Dumper($boo), "\n";

     $Data::Dumper::Indent = 1;         # mild pretty print
     print Dumper($boo);

     $Data::Dumper::Indent = 3;         # pretty print with array indices
     print Dumper($boo);

     # recursive structure
     @c = ('c');
     $c = \@c;
     $b = {};
     $a = [1, $b, $c];
     $b->{a} = $a;
     $b->{b} = $a->[1];
     $b->{c} = $a->[2];
     print Data::Dumper->Dump([$a,$b,$c], [qw(a b c)]);

     $Data::Dumper::Purity = 1;         # fill in the holes for eval
     print Data::Dumper->Dump([$a, $b], [qw(*a b)]); # print as @a
     print Data::Dumper->Dump([$b, $a], [qw(*b a)]); # print as %b

     $d = Data::Dumper->new([$a,$b], [qw(a b)]);     # go OO
     $d->Seen({'*c' => $c});            # stash a ref without printing it
     $d->Indent(3);
     print $d->Dump;
     $d->Reset;                         # empty the seen cache
     $d->Purity(0);
     print $d->Dump;

BUGS
====

Due to limitations of Perl subroutine call semantics, you cannot pass an
array or hash.  Prepend it with a `\' to pass its reference instead.  This
will be remedied in time, with the arrival of prototypes in later versions
of Perl.  For now, you need to use the extended usage form, and prepend the
name with a * to output it as a hash or array.

Dumper cheats with CODE references.  If a code reference is encountered in
the structure being processed, an anonymous subroutine returning the perl
string-interpolated representation of the original CODE reference will be
inserted in its place, and a warning will be printed if `Purity' is set.
You can eval the result, but bear in mind that the anonymous sub that gets
created is a dummy placeholder. Someday, perl will have a switch to
cache-on-demand the string representation of a compiled piece of code, I
hope.

SCALAR objects have the wierdest looking bless workaround.

AUTHOR
======

Gurusamy Sarathy        gsar@umich.edu

Copyright (c) 1995 Gurusamy Sarathy. All rights reserved.  This program is
free software; you can redistribute it and/or modify it under the same
terms as Perl itself.

VERSION
=======

Version 2.02beta    13 April 1996

SEE ALSO
========

perl(1)


File: pm.info,  Node: Data/Flow,  Next: Date/DateCalc,  Prev: Data/Dumper,  Up: Module List

Perl extension for simple-minded recipe-controlled build of data.
*****************************************************************

NAME
====

Data::Flow - Perl extension for simple-minded recipe-controlled build of
data.

SYNOPSIS
========

     use Data::Flow;
     $recipes = { path  => { default => './MANIFEST'},
     	       contents => { prerequisites => ['path', 'x'] ,
     			     process =>
     			     sub {
     			       my $data = shift;
     			       $data->{ shift() } = `cat $data->get('path')`
     				 x $data->get('x');
     			     }
     			   },
     	     };

     $request = new Data::Flow $recipes;
     $request->set( x => 1);
     print $request->get('contents');

     tie %request, Data::Flow, $recipes;
     $request{x} = 1;
     print $request{contents};

DESCRIPTION
===========

The module Data::Flow provides its services via objects. The objects may
be obtained by the usual

     $request = new Data::Flow $recipes;

paradigm. The argument $recipes is a hash reference, which provides the
rules for request processing. The objects support two methods, set() and
get(). The first one is used to provide input data for processing, the
second one to obtain the output.

The unit of requested information is a *field*. The method set() takes a
pair `field => value', the method get() takes one argument: the `field'.

Every object is created without any fields filled, but it knows how to
*construct* fields basing on other fields or some global into. This
knowledge is provided in the argument $recipe of the new() function. This
is a reference to a hash, keyed by fields. The values of this hash are
hash references themselves, which describe how to acquire the *field*
which is the corresponding key of the initial hash.

The internal hashes may have the following keys:

default
     describes the default value for the key, if none is provided by
     set(). The value becomes the value of the field of the object. No
     additional processing is performed. Example:

          default => $Config{installdir}

`prerequisites'
     gives the fields which are needed for the construction of the given
     field. The corresponding value is an array references. The array
     contains the *required* fields.

     If `defaults' did not satisfy the request for a field, but
     `$recipe->{field}{prerequisites}' exists, the *required* fields are
     build before any further processing is done. Example:

          prerequisites => [ qw(prefix arch) ]

`process'
     contains the rule to build the field. The value is a reference to a
     subroutine taking 2 arguments: the object $request, and the name of
     the required field. It is up to the subroutine to actually fill the
     corresponding field of $data, an error condition is raised if it did
     not. Example:

          process => sub { my $data = shift;
          		   $data->set( time => localtime(time) ) }

`output'
     the corresponing value has the same meaning as for `process', but the
     return value of the subroutine is used as the value of the *field*.
     Example:

          output => sub { localtime(time) }

`filter'
     contains the rule to build the field basing on other fields. The value
     is a reference to an array. The first element of the array is a
     reference to a subroutine, the rest contains names of the fields. When
     the subroutine is called, the arguments are the values of fields of
     the object $request which appear in the array (in the same order). The
     return value of the subroutine is used as the value of the *field*.
     Example:

          filter => [ sub { shift + shift },
          	      'first_half', 'second_half' ]

     Note that the mentioned field will be automatically marked as
     prerequisites.

`class_filter'
     is similar to `filter', but the first argument is the name of the
     method to call, second one is the name of the package to use for the
     method invocation. The rest contains names of field to provide as
     method arguments. Example:

          class_filter => [ 'new', 'FileHandle', 'filename' ]

`method_filter'
     is similar to `class_filter', but the second argument is the name of
     the field which is used to call the method upon. Example:

          method_filter => [ 'show', 'widget_name', 'current_display' ]

Tied interface
--------------

The access to the same functionality is available via tied hash interface.

AUTHOR
======

Ilya Zakharevich, ilya@math.ohio-state.edu

SEE ALSO
========

perl(1), make(1).


File: pm.info,  Node: Date/DateCalc,  Next: Date/Format,  Prev: Data/Flow,  Up: Module List

Date Calculations
*****************

NAME
====

Date::DateCalc - Date Calculations

in compliance with ISO/R 2015-1971 and DIN 1355 standards

SYNOPSIS
========

`use Date::DateCalc;'

(in which case you must fully qualify every function with the name of this
module, i.e. `$flag = Date::DateCalc::leap($year)')

or

`use Date::DateCalc' `qw( leap compress uncompress check_compressed
compressed_to_short' `check_date calc_days day_of_week dates_difference
calc_new_date' `date_time_difference calc_new_date_time date_to_short
date_to_string' `week_number first_in_week weeks_in_year day_name_tab
month_name_tab' `decode_day decode_month decode_date days_in_month );'

(or only portions thereof, whatever you need)

or

`use DateCalc qw(:all);'

(which imports everything)

DESCRIPTION
===========

===========
-----------

Convention:
-----------

===========
-----------

In the following, "$year" stands for a "complete" year number (like
"1995", for instance), whereas "$yy" may be an abbreviated year number
(like "95") OR a complete year number.

Year numbers must be positive integers (greater than zero).

"$mm" stands for the number of a month (from 1 to 12), and "$dd" is the
number of a day in a month (from 1 to 28,29,30 or 31, depending on the
month and the year).

Hint: The functions that support abbreviated year numbers are the
functions whose names contain the word "compress" and the function
"decode_date".

====================
--------------------

`$flag = leap($year);'
----------------------

====================
--------------------

This function returns a boolean value which is "true" (1) if the year
"$year" is a leap year, and "false" (0) otherwise.

No check is made if the year "$year" is in the valid range.

For years less than 1, the result is probably meaningless (it IS almost
meaningless, anyway, for years before 1582).

==============================
------------------------------

`$date = compress($yy,$mm,$dd);'
--------------------------------

==============================
------------------------------

This function encodes a date in 16 bits. The encoding scheme is as follows:

     Bit-No.:       FEDCBA9 8765 43210
     Contents:      yyyyyyy mmmm ddddd

All bits equal to zero is equivalent to "<no date>".

Through this encoding scheme, it is possible to COMPARE ENCODED DATES for
equality and ORDER (less than/greater than) WITHOUT any previous DECODING!!

However, this function can only handle dates within one century.

This century can be biased at will by choosing a base century and year. In
this module, the base century is set to 1900 and the base year to 70.
(Standard on UNIX systems)

This allows the function to handle dates from 1970 up to 2069.

If the year "$yy" is equal to, say, 95, it is automatically assumed that
1995 is meant. However, if you specify a year number which is SMALLER than
70, like 64, for instance, it is assumed that you meant 2064.

You are not confined to abbreviated year numbers (smaller than 100),
however. The function also accepts complete year numbers, provided that
they are in the supported range (that is, from 1970 to 2069).

If no valid date is specified, zero is returned.

======================================
--------------------------------------

`($cc,$yy,$mm,$dd) = uncompress($date);'
----------------------------------------

======================================
--------------------------------------

This function decodes dates that were encoded by "compress".  It returns
the century, year, month and day of the date encoded in "$date" in the
variables "$cc", "$yy", "$mm" and "$dd", respectively.

The expression "$cc + $yy" yields the complete year number (for example,
1900 + 95 = 1995).

If "$date" is zero, all return values are zero as well.

Apart from this, no other checks are performed by this function.

================================
--------------------------------

`$flag = check_compressed($date);'
----------------------------------

================================
--------------------------------

This function returns a boolean value which is "true" (1) if "$date"
contains a valid encoded date, and "false" (0) otherwise.

When determining validity, leap years are taken into account, i.e., the
29th of february is rejected in non-leap years.

======================================
--------------------------------------

`$datestr = compressed_to_short($date);'
----------------------------------------

======================================
--------------------------------------

This function converts the encoded date in "$date" to a string of the
format "dd-mmm-yy", which is returned.

("mmm" is the 3-letter abbreviation (in english) of the month)

If the date in "$date" is invalid, the string "<no date>" is returned.

Note that the string which is returned by this function is always exactly
9 characters long.

==================================
----------------------------------

`$flag = check_date($year,$mm,$dd);'
------------------------------------

==================================
----------------------------------

This function returns a boolean value which is "true" (1) if the three
numbers "$year", "$mm" and "$dd" represent a valid date, and "false" (0)
otherwise.

When determining validity, leap years are taken into account, i.e., the
29th of february is rejected in non-leap years.

Year numbers must be greater than zero (negative values will be
interpreted as large positive numbers due to their internal 2's complement
representation). A year number of zero is invalid.

=================================
---------------------------------

`$days = calc_days($year,$mm,$dd);'
-----------------------------------

=================================
---------------------------------

This function returns the (theoretical) number of days between the first
of january of the year one and the given date.

The function doesn't take into account the change from the Julian to the
Gregorian calendar used today in 1582.

It is needed to calculate the difference in days between two dates and the
day of week.

Zero is returned if no valid date is specified.

======================================
--------------------------------------

`$weekday = day_of_week($year,$mm,$dd);'
----------------------------------------

======================================
--------------------------------------

This function calculates the day of week for the given date (which must be
a valid date).

The return values have the following meaning:

     0       =       Error
     1       =       Monday
     2       =       Tuesday
     3       =       Wednesday
     4       =       Thursday
     5       =       Friday
     6       =       Saturday
     7       =       Sunday

The value zero is returned if the date is not valid.

============================================================
------------------------------------------------------------

`$days = dates_difference($year1,$mm1,$dd1,$year2,$mm2,$dd2);'
--------------------------------------------------------------

============================================================
------------------------------------------------------------

This function calculates the difference in days between the two given
dates.

The function calculates the difference "date 2" - "date 1", i.e., you
normally specify the two dates in chronological order.

If date 1 is later than date 2, the result will be negative, which allows
you to use this function to compare dates.

If one of the two dates is invalid, the result will degrade to the value
of the function "calc_days" for the other date. If both dates are invalid,
the result is zero.

=======================================================
-------------------------------------------------------

`($year,$mm,$dd) = calc_new_date($year,$mm,$dd,$offset);'
---------------------------------------------------------

=======================================================
-------------------------------------------------------

Starting from the given date, a new date can be calculated with this
function which is "$offset" days away from the original date. "$offset"
may be positive (for a date later than the original date) or negative (for
a date earlier than the given date).

If the date cannot be calculated (for instance, if the given date is
invalid or the new date would be before the year one), only zeros are
returned.

===========================================
-------------------------------------------

`($days,$hh,$mm,$ss) = date_time_difference( $year1,$month1,$day1,$hh1,$mm1,$ss1, $year2,$month2,$day2,$hh2,$mm2,$ss2 );'
-------------------------------------------------------------------------------------------------------------------------

===========================================
-------------------------------------------

This function calculates the difference in days, hours, minutes and
seconds between the two given dates.

The function calculates the difference "date 2" - "date 1", i.e., you
normally specify the two dates in chronological order.

If date 1 is later than date 2, the result will be negative in every of
the four return values, which allows you to use this function to compare
dates and to feed its output into the function explained next in this
text, "calc_new_date_time".

If one of the two date/time pairs is invalid, the result will degrade to
the value of the other date/time argument, converted to days, hours,
minutes and seconds. If both date/time pairs are invalid, the result is
zero in every return value.

A date/time pair is invalid either when the date is invalid or when the
values for hour, minute and second are outside the range of 0..23, 0..59
and 0..59, respectively.

=====================================================
-----------------------------------------------------

`($year,$month,$day,$hh,$mm,$ss) = calc_new_date_time( $year,$month,$day,$hh,$mm,$ss, $days_offset,$hh_offset,$mm_offset,$ss_offset );'
---------------------------------------------------------------------------------------------------------------------------------------

=====================================================
-----------------------------------------------------

Starting from the given date and time, a new date and time can be
calculated with this function.

The new date will be "$days_offset" days and "$hh_offset" hours,
"$mm_offset" minutes and "$ss_offset" seconds away from the original date.
The values of these four offsets may be positive or negative,
independently from each other. This means that you can add, for instance,
9 hours and subtract 5 minutes at the same time.

If the new date and time cannot be calculated (for instance, if the given
date is invalid or the new date would be before the year one, or the
values for hour, minute and second are outside the range of 0..23, 0..59
and 0..59, respectively), only zeros are returned in all return values.

========================================
----------------------------------------

`$datestr = date_to_short($year,$mm,$dd);'
------------------------------------------

========================================
----------------------------------------

This function converts the given date to a string of the format "www
dd-mmm-yyyy", which is returned.

"www" is a (3-letter) abbreviation of the day of week, and "mmm" is a
(3-letter) abbreviation of the month (both in english).

If the given date is invalid, the string "<no date>" is returned.

=========================================
-----------------------------------------

`$datestr = date_to_string($year,$mm,$dd);'
-------------------------------------------

=========================================
-----------------------------------------

This function converts the given date to a string of the format
"wwwwwwwww, dd mmmmmmmmm yyyy", which is returned.

"wwwwwwwww" is the day of week and "mmmmmmmmm" the name of the month (both
in english).

If the given date is invalid, the string "<no date>" is returned.

===========================================
-------------------------------------------

`($week,$year) = week_number($year,$mm,$dd);'
---------------------------------------------

===========================================
-------------------------------------------

This function calculates the number of the week in which the given date
lies.

This can occasionally be the last week of the previous year or the first
week of the next year.

=============================================
---------------------------------------------

`($year,$mm,$dd) = first_in_week($week,$year);'
-----------------------------------------------

=============================================
---------------------------------------------

This function calculates the date of the first day (the Monday) of the
given week in the given year.

The return value "$year" is adjusted accordingly if the first day of the
given week lies in the previous or next year (also if the given week
number is greater than the number of weeks in the given year!).

If the date cannot be calculated (for instance, if the calculated date
would be before the year one), only zeros are returned.

With help of the expression

     ($year,$mm,$dd) = first_in_week(week_number($year,$mm,$dd));

it is possible to easily calculate the date of the Monday belonging to the
week in which the given date lies.

Alternatively, the expression

     ($year,$mm,$dd) =
     calc_new_date($year,$mm,$dd,-day_of_week($year,$mm,$dd)+1);

can be used to achieve the same effect.

==============================
------------------------------

`$weeks = weeks_in_year($year);'
--------------------------------

==============================
------------------------------

This function returns the number of weeks of the given year (52 or 53
weeks).

No check is made if the year "$year" is in the valid range.

For years less than 1, the result is probably meaningless.

===================================
-----------------------------------

`$day_name = day_name_tab($weekday);'
-------------------------------------

===================================
-----------------------------------

This function accesses the internal table of the days of week.

It returns the corresponding string for each numeric value of a day of
week (as returned by the function "day_of_week").

The value of "$weekday" is taken modulo 8 (!) internally to prevent
out-of-range access to the internal array.

The strings which are returned are the following:

     0       =>      Error
     1       =>      Monday
     2       =>      Tuesday
     3       =>      Wednesday
     4       =>      Thursday
     5       =>      Friday
     6       =>      Saturday
     7       =>      Sunday

=====================================
-------------------------------------

`$month_name = month_name_tab($month);'
---------------------------------------

=====================================
-------------------------------------

This function accesses the internal table of the months' names.

It returns the corresponding string for each numeric value of a month.

The value of "$month" is taken modulo 13 (!) internally to prevent
out-of-range access to the internal array.

The strings which are returned are the following:

     0       =>      Error
     1       =>      January
     2       =>      February
     3       =>      March
     4       =>      April
     5       =>      May
     6       =>      June
     7       =>      July
     8       =>      August
     9       =>      September
     		10       =>      October
     		11       =>      November
     		12       =>      December

===============================
-------------------------------

`$weekday = decode_day($buffer);'
---------------------------------

===============================
-------------------------------

This function provides the inverse of the function "day_name_tab".

Whereas "day_name_tab" takes a number as its argument and returns a
string, "decode_day" takes a string (of any length) and tries to match it
with the table of the names of days (Monday, Tuesday, and so on) and
returns the corresponding number (1..7).

Only the first 3 characters are checked (in case-insensitive manner) for a
unique match. If it uniquely identifies the day, one or two characters are
sufficient:

     Name of the day:     Uniquely identified by:     Value returned:

     Monday        M, Mo, Mon, ... Monday            1
     Tuesday          Tu, Tue, ... Tuesday           2
     Wednesday     W, We, Wed, ... Wednesday         3
     Thursday         Th, Thu, ... Thursday          4
     Friday        F, Fr, Fri, ... Friday            5
     Saturday         Sa, Sat, ... Saturday          6
     Sunday           Su, Sun, ... Sunday            7

If there is no match, zero is returned.

This function is roughly equivalent to an associative array:

     %day_tab = ( 'Mon' => 1, 'Tue' => 2, 'Wed' => 3, 'Thu' => 4,
                  'Fri' => 5, 'Sat' => 6, 'Sun' => 7);

     $weekday = $day_tab{$buffer};

except for the capability of recognizing abbreviations and to be
case-independent.

===============================
-------------------------------

`$month = decode_month($buffer);'
---------------------------------

===============================
-------------------------------

This function provides the inverse of the function "month_name_tab".

Whereas "month_name_tab" takes a number as its argument and returns a
string, "decode_month" takes a string (of any length) and tries to match
it with the table of the names of months (January, February, and so on)
and returns the corresponding number (1..12).

Only the first 3 characters are checked (in case-insensitive manner) for a
unique match. If it uniquely identifies the month, one or two characters
are sufficient:

     Name of the month:     Uniquely identified by:     Value returned:

     January          Ja, Jan, ... January           1
     February      F, Fe, Feb, ... February          2
     March                Mar, ... March             3
     April            Ap, Apr, ... April             4
     May                  May, ... May               5
     June                 Jun, ... June              6
     July                 Jul, ... July              7
     August           Au, Aug, ... August            8
     September     S, Se, Sep, ... September         9
     October       O, Oc, Oct, ... October          10
     November      N, No, Nov, ... November         11
     December      D, De, Dec, ... December         12

If there is no match, zero is returned.

This function is roughly equivalent to an associative array:

     %month_tab = ( 'Jan' => 1, 'Feb' => 2, 'Mar' => 3, 'Apr' => 4,
                    'May' => 5, 'Jun' => 6, 'Jul' => 7, 'Aug' => 8,
                    'Sep' => 9, 'Oct' => 10, 'Nov' => 11, 'Dec' => 12);

     $month = $month_tab{$buffer};

except for the capability of recognizing abbreviations and to be
case-independent.

=======================================
---------------------------------------

`($year,$mm,$dd) = decode_date($buffer);'
-----------------------------------------

=======================================
---------------------------------------

With help of this function, it is possible to recognize dates in almost
any format, provided the date is given as "day - month - year".

The day and the year must be given as numbers, the month may be specified
either by number or an abbreviation (up to 3 characters long) of the
month's name (case is ignored).

If they uniquely identify the month, one or two letters are sufficient
(e.g. "s" for september or "ja" for january).

The year may be abbreviated as well, for instance "95" instead of "1995".
(Year numbers below 100 are incremented by 1900.)

Any number of non-digits may precede the number of the day and follow the
number of the year.

Between the number of the day and the month, as well as between the month
and the number of the year, any number of non-alphanumeric characters
(i.e., all characters not in [A-Za-z0-9]) may be interspersed.

If after removing the preceding and trailing non-digit characters the
string consists only of digits, it is automatically mapped to the day,
month and year depending on its length, as intuitively as possible, as
follows:

     Length:        Mapping:
       3              dmy
       4              dmyy
       5              dmmyy
       6              ddmmyy
       7              dmmyyyy
       8              ddmmyyyy

Example:

All the following strings will be recognized as "january 3rd 1964":

     3.1.64
     3 1 64
     			 03.01.64
     			 03/01/64
     			3. Jan 1964
     			3. Jan '64
     			 03-Jan-64
     			 3.Jan1964
     3Jan64
      3ja64
      3164

If no valid date can be deduced from its input, the function returns zeros
in all its return values.

=================================
---------------------------------

`$days = days_in_month($year,$mm);'
-----------------------------------

=================================
---------------------------------

This function accesses the internal table of the months' lengths and
returns the length in days of the given month "$mm" in the given year
"$year".

It is necessary to specify the year "$year" since the length of the month
february is 29 instead of 28 in leap years.

This function is useful, for example, to calculate the last day of a month
or the last working-day (payday!) of a month.

Last working-day of the month (legal holidays not taken into account):

     $dd = days_in_month($year,$mm);
     $dw = day_of_week($year,$mm,$dd) - 1;
     if ($dw > 4)
     {
         ($year,$mm,$dd) = calc_new_date($year,$mm,$dd,4-$dw);
     }

Last working-day of the month (legal holidays taken into account):

(assuming that the array $holiday[$year][$mm][$dd] = 1; contains all legal
holidays)

     $dd = days_in_month($year,$mm);
     while (1)
     {
         while ($holiday[$year][$mm][$dd])
         {
             ($year,$mm,$dd) = calc_new_date($year,$mm,$dd,-1);
         }
         $dw = day_of_week($year,$mm,$dd) - 1;
         if ($dw > 4)
         {
             ($year,$mm,$dd) = calc_new_date($year,$mm,$dd,4-$dw);
         }
         else { last; }
     }

The value of "$mm" is taken modulo 13 (!) internally to prevent
out-of-range access to the internal array.

The values the internal array contains are the following:

     normal             leap
      month             year              year

     0                 0                 0
     1                31                31
     2                28                29
     3                31                31
     4                30                30
     5                31                31
     6                30                30
     7                31                31
     8                31                31
     9                30                30
     	  10                31                31
     	  11                30                30
     	  12                31                31

=====================================
-------------------------------------

`$version = Date::DateCalc::Version();'
---------------------------------------

=====================================
-------------------------------------

This function returns a string with the (numeric) version number of the
"DateCalc" extension package.

Since this function is not exported, you always have to qualify it
explicitly (i.e., "`Date::DateCalc::Version()'").

This is to avoid possible conflicts with version functions from other
packages.

EXAMPLE
=======

     #!perl -w
     
     use strict;
     no strict "vars";
     
     use Date::DateCalc qw(:all);
     
     print "\n";
     
     $ok = 0;
     while (! $ok)
     {
         print "Please enter the date of your birthday (day-month-year): ";
         $date = <STDIN>;
         print "\n";
         ($yy1,$mm1,$dd1) = decode_date($date);
         if ($yy1)
         {
             $datestr = date_to_short($yy1,$mm1,$dd1);
             print "Your date is: $datestr\n";
             print "\n";
             print "Is that correct? (Yes/No) ";
             $response = <STDIN>;
             print "\n";
             $ok = ($response =~ /^Y/i);
         }
     }
     print "Your birthday is: $datestr\n";
     print "\n";
     
     $ok = 0;
     while (! $ok)
     {
         print "Please enter today's date (day-month-year): ";
         $date = <STDIN>;
         print "\n";
         ($yy2,$mm2,$dd2) = decode_date($date);
         if ($yy2)
         {
             $datestr = date_to_short($yy2,$mm2,$dd2);
             print "Your date is: $datestr\n";
             print "\n";
             print "Is that correct? (Yes/No) ";
             $response = <STDIN>;
             print "\n";
             $ok = ($response =~ /^Y/i);
         }
     }
     print "Today's date is: $datestr\n";
     print "\n";
     
     $days = dates_difference($yy1,$mm1,$dd1,$yy2,$mm2,$dd2);
     print "You are $days days old.\n";
     print "\n";
     
     __END__

SEE ALSO
========

perl(1), perlsub(1), perlmod(1), perlxs(1), perlxstut(1), perlguts(1).

VERSION
=======

This man page documents Date::DateCalc, version 2.2.

AUTHOR
======

Steffen Beyer <sb@sdm.de> (sd&m GmbH&Co.KG, Munich, Germany)

COPYRIGHT
=========

Copyright (c) 1996 by Steffen Beyer. All rights reserved.

LICENSE AGREEMENT
=================

This package is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.


File: pm.info,  Node: Date/Format,  Next: Date/Manip,  Prev: Date/DateCalc,  Up: Module List

Date formating subroutines
**************************

NAME
====

Date::Format - Date formating subroutines

SYNOPSIS
========

     use Date::Format;
     
     @lt = timelocal(time);
     
     print time2str($template, time);
     print strftime($template, @lt);
     
     print time2str($template, time, $zone);
     print strftime($template, @lt, $zone);
     
     print ctime(time);
     print ascctime(@lt);
     
     print ctime(time, $zone);
     print asctime(@lt, $zone);

DESCRIPTION
===========

This module provides routines to format dates into ASCII strings. They
correspond to the C library routines strftime and ctime.

time2str(TEMPLATE, TIME [, ZONE])
     `time2str' converts TIME into an ASCII string using the conversion
     specification given in `TEMPLATE'. `ZONE' if given specifies the zone
     which the output is required to be in, `ZONE' defaults to your
     current zone.

strftime(TEMPLATE, TIME [, ZONE])
     strftime is similar to `time2str' with the exception that the time is
     passed as an array, such as the array returned by localtime.

ctime(TIME [, ZONE])
     ctime calls `time2str' with the given arguments using the conversion
     specification `"%a %b %e %T %Y\n"'

asctime(TIME [, ZONE])
     asctime calls `time2str' with the given arguments using the
     conversion specification `"%a %b %e %T %Y\n"'

MULTI-LANGUAGE SUPPORT
======================

Date::Format is capable of formating into several languages, these are
English, French, German and Italian. Changing the language is done via a
static method call, for example

     Date::Format->language('German');

will change the language in which all subsequent dates are formatted.

This is only a first pass, I am considering changing this to be

     $lang = Date::Language->new('German');
     $lang->time2str("%a %b %e %T %Y\n", time);

I am open to suggestions on this.

CONVERSION SPECIFICATION
========================

Each conversion specification  is  replaced  by  appropriate characters
as   described  in  the  following  list.   The appropriate  characters
are  determined  by   the   LC_TIME category of the program's locale.

     %%	PERCENT
     %a	day of the week abbr
     %A	day of the week
     %b	month abbr
     %B 	month
     %c 	ctime format: Sat Nov 19 21:05:57 1994
     %d 	numeric day of the month
     %e 	DD
     %D 	MM/DD/YY
     %h 	month abbr
     %H 	hour, 24 hour clock, leading 0's)
     %I 	hour, 12 hour clock, leading 0's)
     %j 	day of the year
     %k 	hour
     %l 	hour, 12 hour clock
     %m 	month number, starting with 1
     %M 	minute, leading 0's
     %n 	NEWLINE
     %o	ornate day of month -- "1st", "2nd", "25th", etc.
     %p 	AM or PM
     %r 	time format: 09:05:57 PM
     %R 	time format: 21:05
     %s	seconds since the Epoch, UCT
     %S 	seconds, leading 0's
     %t 	TAB
     %T 	time format: 21:05:57
     %U 	week number, Sunday as first day of week
     %w 	day of the week, numerically, Sunday == 0
     %W 	week number, Monday as first day of week
     %x 	date format: 11/19/94
     %X 	time format: 21:05:57
     %y	year (2 digits)
     %Y	year (4 digits)
     %Z 	timezone in ascii. eg: PST
     %z	timezone in format -/+0000

AUTHOR
======

Graham Barr <Graham.Barr@tiuk.ti.com>

REVISION
========

$Revision: 2.6 $

COPYRIGHT
=========

Copyright (c) 1995 Graham Barr. All rights reserved. This program is free
software; you can redistribute it and/or modify it under the same terms as
Perl itself.


File: pm.info,  Node: Date/Manip,  Next: Date/Parse,  Prev: Date/Format,  Up: Module List

date manipulation routines
**************************

NAME
====

Date::Manip - date manipulation routines

SYNOPSIS
========

     use Date::Manip;

     $date=&ParseDate(\@args)
     $date=&ParseDate($string)
     $date=&ParseDate(\$string)

     @date=&UnixDate($date,@format)
     $date=&UnixDate($date,@format)

     $delta=&ParseDateDelta(\@args)
     $delta=&ParseDateDelta($string)
     $delta=&ParseDateDelta(\$string)

     $d=&DateCalc($d1,$d2,$errref,$del)

     $date=&Date_SetTime($date,$hr,$min,$sec)
     $date=&Date_SetTime($date,$time)

     $date=&Date_GetPrev($date,$dow,$today,$hr,$min,$sec)
     $date=&Date_GetPrev($date,$dow,$today,$time)

     $date=&Date_GetNext($date,$dow,$today,$hr,$min,$sec)
     $date=&Date_GetNext($date,$dow,$today,$time)

     &Date_Init($lang,$format,$tz,$convtz)

     $version=&DateManipVersion

     The following routines are used by the above routines (though they can
     also be called directly).  Make sure that $y is entered as the full 4
     digit year... 2 digit years may give wrong results.  Most (if not all)
     of the information below can be gotten from UnixDate which is really
     the way I intended it to be gotten.

     $day=&Date_DayOfWeek($m,$d,$y)
     $secs=&Date_SecsSince1970($m,$d,$y,$h,$mn,$s)
     $days=&Date_DaysSince999($m,$d,$y)
     $day=&Date_DayOfYear($m,$d,$y)
     $days=&Date_DaysInYear($y)
     $wkno=&Date_WeekOfYear($m,$d,$y,$first)
     $flag=&Date_LeapYear($y)
     $day=&Date_DaySuffix($d)
     $tz=&Date_TimeZone()

DESCRIPTION
===========

This is a set of routines to work with the Gregorian calendar (the one
currently in use).  The Julian calendar defined leap years as every 4th
year.  The Gregorian calendar improved this by making every 100th year NOT
a leap year, unless it was also the 400th year.  The Gregorian calendar
has been extrapolated back to the year 1000 AD and forward to the year
9999 AD.  Note that in historical context, the Julian calendar was in use
until 1582 when the Gregorian calendar was adopted by the Catholic church.
Protestant countries did not accept it until later; Germany and
Netherlands in 1698, British Empire in 1752, Russia in 1918.

Note that the Gregorian calendar is itself imperfect.  Each year is on
average 26 seconds too long, which means that every 3,323 years, a day
should be removed from the calendar.  No attempt is made to correct for
that.

Among other things, these routines allow you to:

1.  Enter a date and be able to choose any format conveniant

2.  Compare two dates, entered in widely different formats to determine
which is earlier

3.  Extract any information you want from ANY date using a format string
 similar to the Unix date command

4.  Determine the amount of time between two dates

5.  Add a time offset to a date to get a second date (i.e. determine the
 date 132 days ago or 2 years and 3 months after Jan 2, 1992)

6.  Work with dates with dates using international formats (foreign month
  names, 12-10-95 referring to October rather than December, etc.).

Each of these tasks is trivial (one or two lines at most) with this
package.

Although the word date is used extensively here, it is actually somewhat
misleading.  This package works with the full date AND time (year, month,
day, hour, minute, second, timezone).

In the documentation below, US formats are used, but in most cases, a
non-English equivalent will work equally well.

EXAMPLES
========

1.  Parsing a date from any conveniant format

     $date=&ParseDate("today");
     $date=&ParseDate("1st thursday in June 1992");
     $date=&ParseDate("05-10-93");
     $date=&ParseDate("12:30 Dec 12th 1880");
     $date=&ParseDate("8:00pm december tenth");
     if (! $date) {
       # Error in the date
     }

2.  Compare two dates

     $date1=&ParseDate($string1);
     $date2=&ParseDate($string2);
     if ($date1 lt $date2) {
       # date1 is earlier
     } else {
       # date2 is earlier (or the two dates are identical)
     }

3.  Extract information from a date.

     print &UnixDate("today","The time is now %T on %b %e, %Y.");
     =>  "The time is now 13:24:08 on Feb  3, 1996."

4.  The amount of time between two dates.

     $date1=&ParseDate($string1);
     $date2=&ParseDate($string2);
     $delta=&DateCalc($date1,$date2,\$err);
     => 0:0:DD:HH:MM:SS   the days, hours, minutes, and seconds between the two
     $delta=&DateCalc($date1,$date2,\$err,1);
     => YY:MM:DD:HH:MM:SS  the years, months, etc. between the two

     Read the documentation below for an explanation of the difference.

5.  To determine a date a given offset from another.

     $date=&DateCalc("today","+ 3hours 12minutes 6 seconds",\$err);
     $date=&DateCalc("12 hours ago","12:30 6Jan90",\$err);

6.  To work with dates in another language.

     &Date_Init("French","non-US");
     $date=&ParseDate("1er decembre 1990");

ParseDate
          $date=&ParseDate(\@args)
          $date=&ParseDate($string)
          $date=&ParseDate(\$string)

     This takes an array or a string containing a date and parses it.
     When the date is included as an array (for example, the arguments to
     a program) the array should contain a valid date in the first one or
     more elements (elements after a valid date are ignored).  Elements
     containing a valid date are shifted from the array.  The largest
     possible number of elements which can be correctly interpreted as a
     valid date are always used.  If a string is entered rather than an
     array, that string is tested for a valid date.  The string is
     unmodified, even if passed in by reference.

     Times may be written as:   1) HH:MN  [Zone]      HH:MN:SS  [Zone]
     HH:MN am  [Zone]      HH:MN:SS am  [Zone]   2) hh:MN  [Zone]
     hh:MN:SS  [Zone]      hh:MN am  [Zone]      hh:MN:SS am [Zone]

     Fractional seconds are also supported in parsing both as:
     HH:MN:SS:SSSS  [Zone]   HH:MN:SS.SSSS  [Zone] but the fractional part
     is discarded.

     The time may also include the timezone.  Timezones always appear
     after the time and must be separated from all other parts of the
     time/date by spaces.  For now, only rudimentary timezone handling is
     done.  At the time the date is parsed, it is converted to a specific
     time zone (which defaults to whatever time zone you are in, but this
     can be overridden using the Date_Init routine described below).
     After that, the time zone is never used.  Once converted, information
     about the time zone is no longer stored or used.

     Valid formats for a full date and time (and examples of how Dec 10,
     1965 at 9:00 pm might appear) are:   DateTime      Date=YYMMDD
         1965121021:00:00  65121021:00      Time=format 1

          Date Time
          Date%Time
            Date=mm%dd, mm%dd%YY     12/10/65 21:00    12 10 1965 9:00pm
            Date=mmm%dd, mmm%dd%YY   December-10-65-9:00:00pm
            Date=dd%mmm, dd%mmm%YY   10/December/65 9:00:00pm

          Date Time
            Date=mmmdd, mmmdd YY, mmmDDYY, mmm DDYY
                                     Dec10 65 9:00:00 pm    December 10 1965 9:00pm
            Date=ddmmm, ddmmm YY, ddmmmYY, dd mmmYY
                                     10Dec65 9:00:00 pm     10 December 1965 9:00pm

          TimeDate
          Time Date
          Time%Date
            Date=mm%dd, mm%dd%YY     9:00pm 12.10.65      21:00 12/10/1965
            Date=mmm%dd, mmm%dd%YY   9:00pm December/10/65
            Date=dd%mmm, dd%mmm%YY   9:00pm 10-December-65  21:00/10/Dec/65

          TimeDate
          Time Date
            Date=mmmdd, mmmdd YY, mmmDDYY
                                     21:00:00DeCeMbEr10
            Date=ddmmm, ddmmm YY, ddmmmYY, dd mmmYY
                                     21:00 10Dec95

          which dofw in mmm at time
          which dofw in mmm YY at time  "first sunday in june 1996 at 14:00"

     In addition, the following strings are recognized:   today   now
     (synonym for today)   yesterday (exactly 24 hours before now)
     tomorrow  (exactly 24 hours from now)

          %       One of the valid date separators: - . / or whitespace (the same
                  character must be used for all occurences of a single date)
                  example: mm%dd%YY works for 1-1-95, 1 1 95, or 1/1/95
          YY      year in 2 or 4 digit format
          MM      two digit month (01 to 12)
          mm      one or two digit month (1 to 12 or 01 to 12)
          mmm     month name or 3 character abbreviation
          DD      two digit day (01 to 31)
          dd      one or two digit day (1 to 31 or 01 to 31)
          HH      two digit hour in 12 or 24 hour mode (00 to 23)
          hh      one or two digit hour in 12 or 24 hour mode (0 to 23 or 00 to 23)
          MN      two digit minutes (00 to 59)
          SS      two digit seconds (00 to 59)
          which   one of the strings (first-fifth, 1st-5th, or last)
          dofw    either the 3 character abbreviation or full name of a day of
                  the week

     Some things to note:

     All strings are case insensitive.  "December" and "DEceMBer" both
     work.

     When a part of the date is not given, defaults are used: year defaults
     to current year; hours, minutes, seconds to 00.

     In the above, the mm%dd formats can be switched to dd%mm by calling
     Date_Init and telling it to use a non-US date format.

     All "Date Time" and "DateTime" type formats allow the word "at" in
     them (i.e.  Jan 12 at 12:00) (and at can replace the space).  So the
     following are both acceptable: "Jan 12at12:00" and "Jan 12 at 12:00".

     A time is usually entered in 24 hour mode.  It can be followed by
     "am" or "pm" to force it to be read in in 12 hour mode.

     The year may be entered as 2 or 4 digits.  If entered as 2 digits, it
     is taken to be the year in the range CurrYear-89 to CurrYear+10.  So,
     if the current year is 1996, the range is [1907 to 2006] so entering
     the year 00 refers to 2000, 05 to 2005, but 07 refers to 1907.

     Any number of spaces or tabs can be used anyhere whitespace is
     appropriate.

     Dates are always checked to make sure they are valid.

     In all of the formats, the day of week ("Friday") can be entered
     anywhere in the date and it will be checked for accuracy.  In other
     words,   "Tue Jul 16 1996 13:17:00" will work but   "Jul 16 1996
     Wednesday 13:17:00" will not (because Jul 16, 1996 is Tuesday, not
     Wednesday).  Note that depending on where the weekday comes, it may
     give unexpected results when used in array context.  For example, the
     date ("Jun","25","Sun","1990") would return June 25 of the current
     year since only Jun 25, 1990 is not Sunday.

     The date returned is YYYYMMDDHH:MM:SS.  The advantage of this time
     format is that two times can be compared using simple string
     comparisons to find out which is later.  Also, it is readily
     understood by a human.

UnixDate
          @date=&UnixDate($date,@format)
          $date=&UnixDate($date,@format)

     This takes a date and a list of strings containing formats roughly
     identical to the format strings used by the UNIX date(1) command.
     Each format is parsed and an array of strings corresponding to each
     format is returned.

     $date must be of the form produced by &ParseDate.

     The format options are:

          Year
              %y     year                     - 00 to 99
              %Y     year                     - 0001 to 9999
          Month, Week
              %m     month of year            - 01 to 12
              %f     month of year            - " 1" to "12"
              %b,%h  month abbreviation       - Jan to Dec
              %B     month name               - January to December
              %U     week of year, Sunday
                     as first day of week     - 00 to 53
              %W     week of year, Monday
                     as first day of week     - 00 to 53
          Day
              %j     day of the year          - 001 to 366
              %d     day of month             - 01 to 31

          %e     day of month             - " 1" to "31"
          %v     weekday abbreviation     - " S"," M"," T"," W","Th"," F","Sa"
          %a     weekday abbreviation     - Sun to Sat
          %A     weekday name             - Sunday to Saturday
          %w     day of week              - 0 (Sunday) to 6
          %E     day of month with suffix - 1st, 2nd, 3rd...
           Hour
          %H     hour                     - 00 to 23
          %k     hour                     - " 0" to "23"
          %i     hour                     - " 1" to "12"
          %I     hour                     - 01 to 12
          %p     AM or PM
           Minute, Second, Timezone
          %M     minute                   - 00 to 59
          %S     second                   - 00 to 59
          %s     seconds from Jan 1, 1970 - negative if before 1/1/1970
          %z,%Z  timezone (3 characters)  - "EDT"
           Date, Time
          %c     %a %b %e %H:%M:%S %Y     - Fri Apr 28 17:23:15 1995
          %C,%u  %a %b %e %H:%M:%S %z %Y  - Fri Apr 28 17:25:57 EDT 1995
          %D,%x  %m/%d/%y                 - 04/28/95
          %l     date in ls(1) format
                   %b %e $H:$M            - Apr 28 17:23  (if within 6 months)
                   %b %e  %Y              - Apr 28  1993  (otherwise)
          %r     %I:%M:%S %p              - 05:39:55 PM
          %R     %H:%M                    - 17:40
          %T,%X  %H:%M:%S                 - 17:40:58
          %V     %m%d%H%M%y               - 0428174095
          %Q     %Y%m%d                   - 19961025
          %F     %A, %B %e, %Y            - Sunday, January  1, 1996
           Other formats
          %n     insert a newline character
          %t     insert a tab character
          %%     insert a `%' character
          %+     insert a `+' character
           All other formats insert the character following the %.  If a lone
           percent is the final character in a format, it is ignored.

     Note that the ls format applies to date within the past OR future 6
     months!

     The following formats are currently unused but may be used in the
     future:   goq GJKLNOP 1234567890 !@#$^&*()_|-=\`[];',./~{}:<>?

     This routine is loosely based on date.pl (version 3.2) by Terry
     McGonigal.  No code was used, but most of his formats were.

ParseDateDelta
          $delta=&ParseDateDelta(\@args)
          $delta=&ParseDateDelta($string)
          $delta=&ParseDateDelta(\$string)

     This takes an array and shifts a valid delta date (an amount of time)
     from the array.  Recognized deltas are of the form:   +Yy +Mm +Dd +Hh
     +MNmn +Ss       examples:          +4 hours +3mn -2second          +
     4 hr 3 minutes -2          4 hour + 3 min -2 s   +Y:+M:+D:+H:+MN:+S
        examples:          0:0:0:4:3:-2          +4:3:-2   mixed format
        examples:          4 hour 3:-2

     A field in the format +Yy is a sign, a number, and a string specifying
     the type of field.  The sign is "+", "-", or absent (defaults to the
     last sign given).  The valid strings specifying the field type are:
     y:  y, yr, year, years    m:  m, mon, month, months    d:  d, day,
     days    h:  h, hr, hour, hours    mn: mn, min, minute, minutes    s:
     s, sec, second, seconds

     Also, the "s" string may be omitted.  The sign, number, and string may
     all be separated from each other by any number of whitespaces.

     In the date, all fields must be given in the order: y m d h mn s.  Any
     number of them may be omitted provided the rest remain in the correct
     order.  In the 2nd (colon) format, from 2 to 6 of the fields may be
     given.  For example +D:+H:+MN:+S may be given to specify only four of
     the fields.  In any case, both the MN and S field may be present.  No
     spaces may be present in the colon format.

     Deltas may also be given as a combination of the two formats.  For
     example, the following is valid: +Yy +D:+H:+MN:+S.  Again, all fields
     must be given in the correct order.

     The word "in" may be prepended to the delta ("in 5 years") and the
     word "ago" may be appended ("6 months ago").  The "in" is completely
     ignored.  The "ago" has the affect of reversing all signs that appear
     in front of the components of the delta.  I.e. "-12 yr 6 mon ago" is
     identical to "+12yr +6mon" (don't forget that there is an impled
     minus sign in front of the 6 because when no sign is explicitely
     given, it carries the previously entered sign).

     One thing is worth noting.  When a delta consists only of
     day/hour/min/sec, it is returned in a "normalized" form.  That is,
     the signs are adjusted so as to be all positive or all negative.  For
     example, "+ 2 day - 2hour" does not return "0:0:2:-2:0:0".  It
     returns "0:0:1:22:0:0" (1 day 22 hours which is equivalent).  I find
     (and I think most others agree) that this is a more useful form.

DateCalc
          $d=&DateCalc($d1,$d2,\$err [,$del])

     This takes two dates, deltas, or one of each and performs the
     appropriate calculation with them.  Dates must be in the format given
     by &ParseDate and or must be a string which can be parsed as a date.
     Deltas must be in the format returned by &ParseDateDelta or must be a
     string that can be parsed as a delta.  Two deltas add together to
     form a third delta.  A date and a delta returns a 2nd date.  Two
     dates return a delta (the difference between the two dates).

     Note that in many cases, it is somewhat ambiguous what the delta
     actually refers to.  Although it is ALWAYS known how many months in a
     year, hours in a day, etc., it is NOT known how many days form a
     month.  As a result, the part of the delta containing month/year and
     the part with sec/min/hr/day must be treated separately.  For
     example, "Mar 31, 12:00:00" plus a delta of 1month 2days would yield
     "May 2 12:00:00".  The year/month is first handled while keeping the
     same date.  Mar 31 plus one month is Apr 31 (but since Apr only has
     30 days, it becomes Apr 30).  Apr 30 + 2 days is May 2.

     In the case where two dates are entered, the resulting delta can take
     on two different forms.  By default, an absolutely correct delta
     (ignoring daylight savings time) is returned in days, hours, minutes,
     and seconds.  If $del is non-nil, a delta is returned using years and
     months as well.  The year and month part is calculated first followed
     by the rest.  For example, the two dates "Mar 12 1995" and "Apr 10
     1995" would have an absolutely correct delta of "29 days" but if $del
     is non-nil, it would be returned as "1 month - 2 days".  Also, "Mar
     31" and "Apr 30" would have deltas of "30 days" or "1 month" (since
     Apr 31 doesn't exist, it drops down to Apr 30).  The latter is
     (sometimes) a more human way of looking at things (you'd say 1 month
     and 2 days more often then 33 days), but it is not a meaningful in
     terms of absolute time.

     $err is set to:    1 is returned if $d1 is not a delta or date    2
     is returned if $d2 is not a delta or date    3 is returned if the
     date is outside the years 1000 to 9999

     Nothing is returned if an error occurs.

     If $del is non-nil, both $d1 and $d2 must be dates.

     When an absolutely correct delta is returned, signs are adjusted so
     that they are all positive or all negative.  See the note above in the
     ParseDateDelta section for more explanation.

Date_SetTime
          $date=&Date_SetTime($date,$hr,$min,$sec)
          $date=&Date_SetTime($date,$time)

     This takes a date sets the time in that date.  For example, to get
     the time for 7:30 tomorrow, use the lines:

          $date=&ParseDate("tomorrow")
          $date=&Date_SetTime($date,"7:30")

Date_GetPrev
          $date=&Date_GetPrev($date,$dow,$today,$hr,$min,$sec)
          $date=&Date_GetPrev($date,$dow,$today,$time)

     This takes a date and returns the date of the previous $day.  For
     example, if $dow is "Fri", it returns the date of the previous
     Friday.  If $date is Friday, it will return either $date (if $today
     is non-zero) or the Friday a week before (if $today is 0).  The time
     is also set according to the optional $hr,$min,$sec (or $time in the
     format HH:MM:SS or HH:MM).

Date_GetNext
          $date=&Date_GetNext($date,$dow,$today,$hr,$min,$sec)
          $date=&Date_GetNext($date,$dow,$today,$time)

     Similar to Date_GetPrev.

Date_DayOfWeek
          $day=&Date_DayOfWeek($m,$d,$y);

     Returns the day of the week (0 for Sunday, 6 for Saturday).  Dec 31,
     0999 was Tuesday.

Date_SecsSince1970
          $secs=&Date_SecsSince1970($m,$d,$y,$h,$mn,$s)

     Returns the number of seconds since Jan 1, 1970 00:00 (negative if
     date is earlier).

Date_DaysSince999
          $days=&Date_DaysSince999($m,$d,$y)

     Returns the number of days since Dec 31, 0999.

Date_DayOfYear
          $day=&Date_DayOfYear($m,$d,$y);

     Returns the day of the year (001 to 366)

Date_DaysInYear
          $days=&Date_DaysInYear($y);

     Returns the number of days in the year (365 or 366)

Date_WeekOfYear
          $wkno=&Date_WeekOfYear($m,$d,$y,$first);

     Figure out week number.  $first is the first day of the week which is
     usually 0 (Sunday) or 1 (Monday), but could be any number between 0
     and 6 in practice.

Date_LeapYear
          $flag=&Date_LeapYear($y);

     Returns 1 if the argument is a leap year Written by David Muir
     Sharnoff <muir@idiom.com>

Date_DaySuffix
          $day=&Date_DaySuffix($d);

     Add `st', `nd', `rd', `th' to a date (ie 1st, 22nd, 29th).  Works for
     international dates.

Date_TimeZone
          $tz=&Date_TimeZone

     This returns a timezone.  It looks in the following places for a
     timezone in the following order:    $ENV{TZ}    $main::TZ
     /etc/TIMEZONE    date '+%Z' If it's not found in any of those places,
     GMT is returned.  Obviously, this does not guarantee the correct
     timezone.

Date_Init
          $flag=&Date_Init();
          $flag=&Date_Init($lang,$format,$tz,$convtz);

     Normally, it is not necessary to explicitely call Date_Init.  The
     first time any of the other routines are called, Date_Init will be
     called to set everything up.  If for some reason you want to parse
     dates in multiple languages, you can pass in the language and format
     information and reinitialize everything for a different language.

     Recognized values of $lang are:    English    French    Swedish
     Others will be added in the future (contributions are welcome).

     $format should be "US" or any other string.  Most US people look at
     the date 12/10/96 as MM/DD/YY or Dec 10, 1996.  Many countries would
     regard this as Oct 12, 1996 instead.  Setting the $form variable to
     "US" forces the first one.  Anything else forces the 2nd.

     $tz and $convtz are both time zones.  $tz should be the current time
     zone and $convtz should be the time zone you want to work in (GMT for
     example).

     All four arguments are optional.  For example, to stop working in the
     current time zone and start working in GMT, use:

          $flag=&Date_Init("","","","GMT");

     If you change timezones in the middle of using Date::Manip, comparing
     dates from before the switch to dates from after the switch will
     produce incorrect results.

DateManipVersion
          $version=&DateManipVersion

     Returns the version of Date::Manip.

KNOWN BUGS
==========

If you use Date::Manip to sort a number of dates, you must call Date_Init
either explicitely, or by way of some other Date::Manip routine before it
is used in the sort.  For example, the following code fails:

     use Date::Manip;
     # &Date_Init;
     sub sortDate {
         my($date1, $date2);
         $date1 = &ParseDate($a);
         $date2 = &ParseDate($b);
         return ($date1 cmp $date2);
     }
     @date = ("Fri 16 Aug 96",
              "Mon 19 Aug 96",
              "Thu 15 Aug 96");
     @i=sort sortDate @dates;

but if you uncomment the Date_Init line, it works.  The reason for this is
that the first time you call Date_Init, it initializes a number of items
used by Date::Manip.  Some of these are sorted.  It turns out that perl
does not like a sort within a sort.  The solution is to do the
initialization sorting ahead of time by calling Date_Init explicitely.

If you are running a script which uses Date::Manip over a period of time
which starts in one time zone and ends in another (i.e. it switches form
Daylight Savings Time to Standard Time or vice versa), many things may be
wrong (especially elapsed time).  Since the most likely place for
Date::Manip probably gets the current time zone is from an environment
variable, you will have to reset this variable (by logging out or other
means) and restart the script under the new environment before it is back
to normal.

If you try to put Date::Manip under RCS control, you are going to have
problems.  RCS replaces strings of the form "$Date...$" with the current
date.  This form occurs all over in Date::Manip.  Since very few people
will ever have a desire to do this, I have not worried about it.  Perhaps
some time in the future.

One other feature (not a bug :-) is that the "%s" format in UnixDate
returns the number of seconds since Jan 1, 1970 in the CURRENT time zone,
not since GMT.

AUTHOR
======

Sullivan Beck (beck@qtp.ufl.edu)


File: pm.info,  Node: Date/Parse,  Next: Des,  Prev: Date/Manip,  Up: Module List

Parse date strings into time values
***********************************

NAME
====

Date::Parse - Parse date strings into time values

SYNOPSIS
========

     use Date::Parse;
     
     $time = str2time($date);
     
     ($ss,$mm,$hh,$day,$month,$year,$zone) = strptime($date);

DESCRIPTION
===========

`Date::Parse' provides two routines for parsing date strings into time
values.

str2time(DATE [, ZONE])
     `str2time' parses DATE and returns a unix time value, or undef upon
     failure.  `ZONE', if given, specifies the timezone to assume when
     parsing if the date string does not specify a timezome.

strptime(DATE [, ZONE])
     `strptime' takes the same arguments as str2time but returns an array
     of values `($ss,$mm,$hh,$day,$month,$year,$zone)'. Elements are only
     defined if they could be extracted from the date string. The `$zone'
     element is the timezone offset in seconds from GMT. An empty array is
     returned upon failure.

MULTI-LANGUAGE SUPPORT
======================

Date::Parse is capable of parsing dates in several languages, these are
English, French, German and Italian. Changing the language is done via a
static method call, for example

     Date::Parse->language('German');

will cause Date::Parse to attempt to parse any subsequent dates in German.

This is only a first pass, I am considering changing this to be

     $lang = Date::Language->new('German');
     $lang->str2time("25 Jun 1996 21:09:55 +0100");

I am open to suggestions on this.

AUTHOR
======

Graham Barr <Graham.Barr@tiuk.ti.com>

REVISION
========

$Revision: 2.5 $

COPYRIGHT
=========

Copyright (c) 1995 Graham Barr. All rights reserved. This program is free
software; you can redistribute it and/or modify it under the same terms as
Perl itself.


File: pm.info,  Node: Des,  Next: Devel/CoreStack,  Prev: Date/Parse,  Up: Module List

Des extension module for Perl
*****************************

NAME
====

Des - Des extension module for Perl

DESCRIPTION
===========

The Des extension module gives access to the DES library.

The following is a brief and over-simplified description of the relevant
stuff about DES.

DES keys are 8-byte blocks. A key is passed to a perl function as an
8-byte string. Before keys can be used to encrypt or decrypt data, the key
needs to be transformed into a key schedule using the function set_key.
There is a certain amount of overhead in creating these key schedules
(which are 128 bytes or 256 bytes depending on implementation and
architecture) so they can be created and cached for later if desired.
Encryption and decryption can be done in 3 modes:

ECB (electronic code book) mode
     Takes a des_cblock (perl 8-byte string) and produces another
     des_cblock.  (Very rarely useful for large amounts of plain text,
     subject to known plaintext attacks under certain circumstances, only
     slightly faster than CBC or PCBC mode, and you lose even this
     advantage in perl).

CBC (cipher block chaining) mode
     Takes an arbitrary length string, pads it out (internally) on the
     right with NULs to a multiple of 8-bytes. Encrypts/decrypts the data
     and produces output (same size as padded input) which is an exact
     multiple of 8 bytes long. Changing a single bit of the cleartext
     affects all the following ciphertext. However, changing a single bit
     of the ciphertext affects only the corresponding cleartext block and
     the following block. This is occasionally an advantage but is usually
     a disadvantage.

PCBC mode
     A modified CBC mode with indefinite proagation of single bit errors
     both from cleartext to ciphertext *and* from ciphertext to cleartext.
     "Usually" the best mode (for certain values of "usually").

Functions imported by *use Des*.
--------------------------------

string_to_key (STRING)
     Takes an arbitrary STRING and munges it (with a one-way function) into
     a DES key, which is returned.

set_key (KEY)
     The DES key KEY (which must be a string of exactly 8 bytes) is turned
     into a key schedule which is returned.

ecb_encrypt (INPUT, SCHEDULE)
     The INPUT argument (which must be a string of exactly 8 bytes) is
     encrypted using ECB mode using key schedule SCHEDULE (created using
     set_key) and the resulting 8-byte string is returned.

ecb_decrypt (INPUT, SCHEDULE)
     The INPUT argument (which must be a string of exactly 8 bytes) is
     decrypted using ECB mode using key schedule SCHEDULE (created using
     set_key) and the resulting 8-byte string is returned.

cbc_encrypt (INPUT, OUTPUT, SCHEDULE, IV)
     The INPUT argument can be of arbitrary length, although it will be
     internally padded on the right with NULs to the nearest multiple of 8
     bytes.  INPUT is taken and encrypted using CBC mode with key schedule
     SCHEDULE and initialisation vector IV. If OUTPUT is not undef then it
     assumed to be an lvalue which is grown (if necessary) and receives
     the encrypted output. Whether or not OUTPUT is undef, the output is
     also available as the return value of the function.

cbc_decrypt (INPUT, OUTPUT, SCHEDULE, IV)
     The INPUT argument can be of arbitrary length, although it will be
     internally padded on the right with NULs to the nearest multiple of 8
     bytes.  INPUT is taken and decrypted using CBC mode with key schedule
     SCHEDULE and initialisation vector IV. If OUTPUT is not undef then it
     assumed to be an lvalue which is grown (if necessary) and receives
     the decrypted output. Whether or not OUTPUT is undef, the output is
     also available as the return value of the function.

pcbc_encrypt (INPUT, OUTPUT, SCHEDULE, IV)
     The INPUT argument can be of arbitrary length, although it will be
     internally padded on the right with NULs to the nearest multiple of 8
     bytes.  INPUT is taken and encrypted using PCBC mode with key
     schedule SCHEDULE and initialisation vector IV. If OUTPUT is not
     undef then it assumed to be an lvalue which is grown (if necessary)
     and receives the encrypted output. Whether or not OUTPUT is undef,
     the output is also available as the return value of the function.

pcbc_decrypt (INPUT, OUTPUT, SCHEDULE, IV)
     The INPUT argument can be of arbitrary length, although it will be
     internally padded on the right with NULs to the nearest multiple of 8
     bytes.  INPUT is taken and decrypted using PCBC mode with key
     schedule SCHEDULE and initialisation vector IV. If OUTPUT is not
     undef then it assumed to be an lvalue which is grown (if necessary)
     and receives the decrypted output. Whether or not OUTPUT is undef,
     the output is also available as the return value of the function.

pcbc_cksum (INPUT, SCHEDULE, IV)
     The INPUT argument can be of arbitrary length, although it will be
     internally padded on the right with NULs to the nearest multiple of 8
     bytes.  CBC mode is used to generate an 8-byte cryptographic checksum
     using key schedule SCHEDULE and initialisation vector IV. This
     checksum is returned.

Functions in package Des which can be imported
----------------------------------------------

random_key ()
     Produces a random DES key based on current time, PID and a counter.

read_password (PROMPT [, VERIFY])
     Prints PROMPT on the terminal, turns off echo if possible and reads a
     password from the keyboard. If the optional VERIFY argument is present
     and true than the password is prompted for a second time and the two
     are compared. If different, the prompting is repeated. The resulting
     string is turned into a DES key (using string_to_key (q.v.)
     internally) and that key is returned.

AUTHOR
------

Malcolm Beattie, `mbeattie@sable.ox.ac.uk', 6 Dec 1994.


File: pm.info,  Node: Devel/CoreStack,  Next: Devel/DProf,  Prev: Des,  Up: Module List

try to generate a stack dump from a core file
*********************************************

NAME
====

Devel::CoreStack - try to generate a stack dump from a core file

SYNOPSIS
========

     perl -MDevel::CoreStack -e 'stack'

     perl -MDevel::CoreStack -e 'stack("../myperl", "./mycore", "debugger")'

DESCRIPTION
===========

This module attempts to generate a stack dump from a core file by locating
the best available debugger (if any) and running it with the appropriate
arguments and command script.


File: pm.info,  Node: Devel/DProf,  Next: Devel/Peek,  Prev: Devel/CoreStack,  Up: Module List

a Perl code profiler
********************

NAME
====

Devel::DProf - a Perl code profiler

SYNOPSIS
========

     perl5 -d:DProf test.pl

DESCRIPTION
===========

The Devel::DProf package is a Perl code profiler.  This will collect
information on the execution time of a Perl script and of the subs in that
script.  This information can be used to determine which subroutines are
using the most time and which subroutines are being called most often.
This information can also be used to create an execution graph of the
script, showing subroutine relationships.

To profile a Perl script run the perl interpreter with the -d debugging
switch.  The profiler uses the debugging hooks.  So to profile script
`test.pl' the following command should be used:

     perl5 -d:DProf test.pl

When the script terminates the profiler will dump the profile information
to a file called `tmon.out'.  A tool like *dprofpp* can be used to
interpret the information which is in that profile.  The following command
will print the top 15 subroutines which used the most time:

     dprofpp

To print an execution graph of the subroutines in the script use the
following command:

     dprofpp -T

Consult `dprofpp' in this node for other options.

PROFILE FORMAT
==============

The profile is a text file which looks like this:

     #fOrTyTwO
     $hz=100;
     $XS_VERSION='DProf 19960205';
     # All values are given in HZ
     $rrun_utime=2; $rrun_stime=0; $rrun_rtime=7
     PART2
     + 26 28 566822884 DynaLoader::import
     - 26 28 566822884 DynaLoader::import
     + 27 28 566822885 main::bar
     - 27 28 566822886 main::bar
     + 27 28 566822886 main::baz
     + 27 28 566822887 main::bar
     - 27 28 566822888 main::bar
     [....]

The first line is the magic number.  The second line is the hertz value, or
clock ticks, of the machine where the profile was collected.  The third
line is the name and version identifier of the tool which created the
profile.  The fourth line is a comment.  The fifth line contains three
variables holding the user time, system time, and realtime of the process
while it was being profiled.  The sixth line indicates the beginning of
the sub entry/exit profile section.

The columns in *PART2* are:

     sub entry(+)/exit(-) mark
     app's user time at sub entry/exit mark, in ticks
     app's system time at sub entry/exit mark, in ticks
     app's realtime at sub entry/exit mark, in ticks
     fully-qualified sub name, when possible

AUTOLOAD
========

When Devel::DProf finds a call to an `&AUTOLOAD' subroutine it looks at the
`$AUTOLOAD' variable to find the real name of the sub being called.  See
`"Autoloading"', *Note Perlsub: (perl.info)perlsub,.

BUGS
====

XSUBs, builtin functions, and destructors cannot be measured by
Devel::DProf.

Mail bug reports and feature requests to the perl5-porters mailing list at
`<perl5-porters@africa.nicoh.com>'.

SEE ALSO
========

*Note Perl: (perl.info)perl,, `dprofpp' in this node, times(2)


File: pm.info,  Node: Devel/Peek,  Next: Devel/SelfStubber,  Prev: Devel/DProf,  Up: Module List

A data debugging tool for the XS programmer
*******************************************

NAME
====

Devel::Peek - A data debugging tool for the XS programmer

SYNOPSIS
========

     use Devel::Peek 'Dump';
     Dump( $a );
     Dump( $a, 5 );
     	Devel::Peek::mstat "Point 5";

DESCRIPTION
===========

Devel::Peek contains functions which allows raw Perl datatypes to be
manipulated from a Perl script.  This is used by those who do XS
programming to check that the data they are sending from C to Perl looks
as they think it should look.  The trick, then, is to know what the raw
datatype is supposed to look like when it gets to Perl.  This document
offers some tips and hints to describe good and bad raw data.

It is very possible that this document will fall far short of being useful
to the casual reader.  The reader is expected to understand the material in
the first few sections of *Note Perlguts: (perl.info)perlguts,.

Devel::Peek supplies a `Dump()' function which can dump a raw Perl
datatype, and `mstat("marker")' function to report on memory usage (if
perl is compiled with corresponding option).  It also supplies
`SvREFCNT()', `SvREFCNT_inc()', and `SvREFCNT_dec()' which can query,
increment, and decrement reference counts on SVs.  This document will take
a passive, and safe, approach to data debugging and for that it will
describe only the `Dump()' function.

EXAMPLES
========

The following examples don't attempt to show everything as that would be a
monumental task, and, frankly, we don't want this manpage to be an
internals document for Perl.  The examples do demonstrate some basics of
the raw Perl datatypes, and should suffice to get most determined people
on their way.  There are no guidewires or safety nets, nor blazed trails,
so be prepared to travel alone from this point and on and, if at all
possible, don't fall into the quicksand (it's bad for business).

Oh, one final bit of advice: take *Note Perlguts: (perl.info)perlguts,
with you.  When you return we expect to see it well-thumbed.

A simple scalar string
----------------------

Let's begin by looking a simple scalar which is holding a string.

     use Devel::Peek 'Dump';
     $a = "hello";
     Dump $a;

The output:

     SV = PVIV(0xbc288)
       REFCNT = 1
       FLAGS = (POK,pPOK)
       IV = 0
       PV = 0xb2048 "hello"
       CUR = 5
       LEN = 6

This says `$a' is an SV, a scalar.  The scalar is a PVIV, a string.  Its
reference count is 1.  It has the `POK' flag set, meaning its current PV
field is valid.  Because POK is set we look at the PV item to see what is
in the scalar.  If the FLAGS had been IOK we would look at the IV item.
CUR indicates the number of characters in the PV.  LEN indicates the
number of bytes requested for the PV (one more than CUR, in this case,
because LEN includes an extra byte for the end-of-string marker).

A simple scalar number
----------------------

If the scalar contains a number the raw SV will be leaner.

     use Devel::Peek 'Dump';
     $a = 42;
     Dump $a;

The output:

     SV = IV(0xbc818)
       REFCNT = 1
       FLAGS = (IOK,pIOK)
       IV = 42

This says `$a' is an SV, a scalar.  The scalar is an IV, a number.  Its
reference count is 1.  It has the `IOK' flag set, meaning it is currently
being evaluated as a number.  Because IOK is set we look at the IV item to
see what is in the scalar.

A simple scalar with an extra reference
---------------------------------------

If the scalar from the previous example had an extra reference:

     use Devel::Peek 'Dump';
     $a = 42;
     $b = \$a;
     Dump $a;

The output:

     SV = IV(0xbe860)
       REFCNT = 2
       FLAGS = (IOK,pIOK)
       IV = 42

Notice that this example differs from the previous example only in its
reference count.  Compare this to the next example, where we dump `$b'
instead of `$a'.

A reference to a simple scalar
------------------------------

This shows what a reference looks like when it references a simple scalar.

     use Devel::Peek 'Dump';
     $a = 42;
     $b = \$a;
     Dump $b;

The output:

     SV = RV(0xf041c)
       REFCNT = 1
       FLAGS = (ROK)
       RV = 0xbab08
     SV = IV(0xbe860)
       REFCNT = 2
       FLAGS = (IOK,pIOK)
       IV = 42

Starting from the top, this says `$b' is an SV.  The scalar is an RV, a
reference.  It has the `ROK' flag set, meaning it is a reference.  Because
ROK is set we have an RV item rather than an IV or PV.  Notice that Dump
follows the reference and shows us what `$b' was referencing.  We see the
same `$a' that we found in the previous example.

A reference to an array
-----------------------

This shows what a reference to an array looks like.

     use Devel::Peek 'Dump';
     $a = [42];
     Dump $a;

The output:

     SV = RV(0xf041c)
       REFCNT = 1
       FLAGS = (ROK)
       RV = 0xb2850
     SV = PVAV(0xbd448)
       REFCNT = 1
       FLAGS = ()
       IV = 0
       NV = 0
       ARRAY = 0xb2048
       ALLOC = 0xb2048
       FILL = 0
       MAX = 0
       ARYLEN = 0x0
       FLAGS = (REAL)
     Elt No. 0
     SV = IV(0xbe860)
       REFCNT = 1
       FLAGS = (IOK,pIOK)
       IV = 42

This says `$a' is an SV and that it is an RV.  That RV points to another
SV which is a PVAV, an array.  The array has one element, element zero,
which is another SV. The field `FILL' above indicates the last element in
the array, similar to `$#$a'.

If `$a' pointed to an array of two elements then we would see the
following.

     use Devel::Peek 'Dump';
     $a = [42,24];
     Dump $a;

The output:

     SV = RV(0xf041c)
       REFCNT = 1
       FLAGS = (ROK)
       RV = 0xb2850
     SV = PVAV(0xbd448)
       REFCNT = 1
       FLAGS = ()
       IV = 0
       NV = 0
       ARRAY = 0xb2048
       ALLOC = 0xb2048
       FILL = 0
       MAX = 0
       ARYLEN = 0x0
       FLAGS = (REAL)
     Elt No. 0
     SV = IV(0xbe860)
       REFCNT = 1
       FLAGS = (IOK,pIOK)
       IV = 42
     Elt No. 1
     SV = IV(0xbe818)
       REFCNT = 1
       FLAGS = (IOK,pIOK)
       IV = 24

Note that `Dump' will not report all the elements in the array, only
several first (depending on how deep it already went into the report tree).

A reference to a hash
---------------------

The following shows the raw form of a reference to a hash.

     use Devel::Peek 'Dump';
     $a = {hello=>42};
     Dump $a;

The output:

     SV = RV(0xf041c)
       REFCNT = 1
       FLAGS = (ROK)
       RV = 0xb2850
     SV = PVHV(0xbd448)
       REFCNT = 1
       FLAGS = ()
       IV = 1
       NV = 0
       ARRAY = 0xbd748
       KEYS = 1
       FILL = 1
       MAX = 7
       RITER = -1
       EITER = 0x0
     Elt "hello" => 0xbaaf0
     SV = IV(0xbe860)
       REFCNT = 1
       FLAGS = (IOK,pIOK)
       IV = 42

This shows `$a' is a reference pointing to an SV.  That SV is a PVHV, a
hash.

Dumping a large array or hash
-----------------------------

The `Dump()' function, by default, dumps up to 4 elements from a toplevel
array or hash.  This number can be increased by supplying a second
argument to the function.

     use Devel::Peek 'Dump';
     $a = [10,11,12,13,14];
     Dump $a;

Notice that `Dump()' prints only elements 10 through 13 in the above code.
The following code will print all of the elements.

     use Devel::Peek 'Dump';
     $a = [10,11,12,13,14];
     Dump $a, 5;

A reference to an SV which holds a C pointer
--------------------------------------------

This is what you really need to know as an XS programmer, of course.  When
an XSUB returns a pointer to a C structure that pointer is stored in an SV
and a reference to that SV is placed on the XSUB stack.  So the output from
an XSUB which uses something like the T_PTROBJ map might look something
like this:

     SV = RV(0xf381c)
       REFCNT = 1
       FLAGS = (ROK)
       RV = 0xb8ad8
     SV = PVMG(0xbb3c8)
       REFCNT = 1
       FLAGS = (OBJECT,IOK,pIOK)
       IV = 729160
       NV = 0
       PV = 0
       STASH = 0xc1d10       "CookBookB::Opaque"

This shows that we have an SV which is an RV.  That RV points at another
SV.  In this case that second SV is a PVMG, a blessed scalar.  Because it
is blessed it has the OBJECT flag set.  Note that an SV which holds a C
pointer also has the `IOK' flag set.  The `STASH' is set to the package
name which this SV was blessed into.

The output from an XSUB which uses something like the T_PTRREF map, which
doesn't bless the object, might look something like this:

     SV = RV(0xf381c)
       REFCNT = 1
       FLAGS = (ROK)
       RV = 0xb8ad8
     SV = PVMG(0xbb3c8)
       REFCNT = 1
       FLAGS = (IOK,pIOK)
       IV = 729160
       NV = 0
       PV = 0

BUGS
====

Readers have been known to skip important parts of *Note Perlguts:
(perl.info)perlguts,, causing much frustration for all.

SEE ALSO
========

*Note Perlguts: (perl.info)perlguts,, and *Note Perlguts:
(perl.info)perlguts,, again.


File: pm.info,  Node: Devel/SelfStubber,  Next: Devel/Symdump,  Prev: Devel/Peek,  Up: Module List

generate stubs for a SelfLoading module
***************************************

NAME
====

Devel::SelfStubber - generate stubs for a SelfLoading module

SYNOPSIS
========

To generate just the stubs:

     use Devel::SelfStubber;
     Devel::SelfStubber->stub('MODULENAME','MY_LIB_DIR');

or to generate the whole module with stubs inserted correctly

     use Devel::SelfStubber;
     $Devel::SelfStubber::JUST_STUBS=0;
     Devel::SelfStubber->stub('MODULENAME','MY_LIB_DIR');

MODULENAME is the Perl module name, e.g. Devel::SelfStubber, NOT
'Devel/SelfStubber' or 'Devel/SelfStubber.pm'.

MY_LIB_DIR defaults to '.' if not present.

DESCRIPTION
===========

Devel::SelfStubber prints the stubs you need to put in the module before
the __DATA__ token (or you can get it to print the entire module with
stubs correctly placed). The stubs ensure that if a method is called, it
will get loaded. They are needed specifically for inherited autoloaded
methods.

This is best explained using the following example:

Assume four classes, A,B,C & D.

A is the root class, B is a subclass of A, C is a subclass of B, and D is
another subclass of A.

     A
                            / \
                           B   D
                          /
                         C

If D calls an autoloaded method 'foo' which is defined in class A, then
the method is loaded into class A, then executed. If C then calls method
'foo', and that method was reimplemented in class B, but set to be
autoloaded, then the lookup mechanism never gets to the AUTOLOAD mechanism
in B because it first finds the method already loaded in A, and so
erroneously uses that. If the method foo had been stubbed in B, then the
lookup mechanism would have found the stub, and correctly loaded and used
the sub from B.

So, for classes and subclasses to have inheritance correctly work with
autoloading, you need to ensure stubs are loaded.

The SelfLoader can load stubs automatically at module initialization with
the statement 'SelfLoader->load_stubs()';, but you may wish to avoid
having the stub loading overhead associated with your initialization
(though note that the SelfLoader::load_stubs method will be called sooner
or later - at latest when the first sub is being autoloaded). In this
case, you can put the sub stubs before the __DATA__ token. This can be
done manually, but this module allows automatic generation of the stubs.

By default it just prints the stubs, but you can set the global
$Devel::SelfStubber::JUST_STUBS to 0 and it will print out the entire
module with the stubs positioned correctly.

At the very least, this is useful to see what the SelfLoader thinks are
stubs - in order to ensure future versions of the SelfStubber remain in
step with the SelfLoader, the SelfStubber actually uses the SelfLoader to
determine which stubs are needed.


File: pm.info,  Node: Devel/Symdump,  Next: Devel/TraceFuncs,  Prev: Devel/SelfStubber,  Up: Module List

dump symbol names or the symbol table
*************************************

NAME
====

Devel::Symdump - dump symbol names or the symbol table

SYNOPSIS
========

     # Constructor
     require Devel::Symdump;
     @packs = qw(some_package another_package);
     $obj = Devel::Symdump->new(@packs);        # no recursion
     $obj = Devel::Symdump->rnew(@packs);       # with recursion
     
     # Methods
     @array = $obj->packages;
     @array = $obj->scalars;
     @array = $obj->arrays;
     @array = $obj->hashs;
     @array = $obj->functions;
     @array = $obj->filehandles;
     @array = $obj->dirhandles;
     @array = $obj->unknowns;
     
     $string = $obj->as_string;
     $string = $obj1->diff($obj2);

     # Methods with autogenerated objects
     # all of those call new(@packs) internally
     @array = Devel::Symdump->packages(@packs);
     @array = Devel::Symdump->scalars(@packs);
     @array = Devel::Symdump->arrays(@packs);
     @array = Devel::Symdump->hashes(@packs);
     @array = Devel::Symdump->functions(@packs);
     @array = Devel::Symdump->filehandles(@packs);
     @array = Devel::Symdump->dirhandles(@packs);
     @array = Devel::Symdump->unknowns(@packs);

DESCRIPTION
===========

This little package serves to access the symbol table of perl.

`Devel::Symdump->rnew(@packages)' returns a symbol table object for all subtrees below @packages. Nested Modules are analyzed recursively. If no package is given as argument, it defaults to `main'. That means to get the whole symbol table, just do a `rnew' without arguments.
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

`Devel::Symdump->new(@packages)' does not go into recursion and only analyzes the packages that are given as arguments.
-----------------------------------------------------------------------------------------------------------------------

The methods packages(), scalars(), arrays(), hashes(), functions(),
filehandles(), dirhandles(), and unknowns() each return an array of fully
qualified symbols of the specified type in all packages that are held
within a Devel::Symdump object, but without the leading `$', `@' or %.  In
a scalar context, they will return the number of such symbols.  Unknown
symbols are usually either formats or variables that haven't yet got a
defined value.

As_string() prints a simple string representation of the object.

Diff() prints the difference between two Devel::Symdump objects in human
readable form. The format is similar to the one used by the as_string
method.

SUBCLASSING
===========

The design of this package is intentionally primitiv and allows it to be
subclassed easily. An example of a useful subclass is
Devel::Symdump::Export, a package which exports all methods of the
Devel::Symdump package and turns them into functions.

AUTHORS
=======

Andreas Koenig `<koenig@franz.ww.TU-Berlin.DE>' and Tom Christiansen
`<tchrist@perl.com>'.  Based on the old `dumpvar.pl' by Larry Wall.

VERSION
=======

This release is $Revision: 1.23 $.


File: pm.info,  Node: Devel/TraceFuncs,  Next: DirHandle,  Prev: Devel/Symdump,  Up: Module List

trace function calls as they happen.
************************************

NAME
====

Devel::TraceFuncs - trace function calls as they happen.

SYNOPSIS
========

Usage:

require Devel::TraceFuncs;

     max_trace_depth 5;
     trace_file "foo.out";
     trace_file $file_handle;

     sub foo {
       IN(my $f, "a message");

     DEBUG "hellooo!";
       }

DESCRIPTION
===========

Devel::TraceFuncs provides utilities to trace the execution of a program.
It can print traces that look something like:

     +-> global: '0'
     |  +-> main::fo(4, 5) (in ./t.pm:32): 'now then'
     |  |  +-> main::fp(4, 5) (in ./t.pm:19)
     |  |  |  +-> main::fq() (in ./t.pm:13)
     |  |  |  |  que pee doll (in ./t.pm:8)
     |  |  |  +-< main::fq() (in ./t.pm:13)
     |  |  |  cee dee (in ./t.pm:14)
     |  |  +-< main::fp(4, 5) (in ./t.pm:19)
     |  |  ha
     |  |  hs (in ./t.pm:20)
     |  +-< main::fo(4, 5) (in ./t.pm:32): 'now then'
     |  done (in ./t.pm:34)
     +-< global: '0'

IN
--

A trace begins when a function calls IN.  A my'd variable is passed in,
such that when that function exits, the destructor for the variable is
called.  If this trace is to be printed, the opening line of the trace in
printed at this time.  Any other parameters are concatenated together, and
printed on both the opening and closing lines of the trace.

I wish the syntax could be a little nicer here, but I couldn't find
anything in perl that resembles Tcl's *uplevel* or *upvar* commands.  If I
was one of the perl gods, I could have figured out a way to do something
like perl5db.pl:

     sub sub {
       # create a new subroutine, with a my'd TraceFunc object
     }

DEBUG
-----

Print some text to the trace file, at the correct depth in the trace.  If
the last parameter ends in "!", the arguments are printed, regardless of
current depth.

trace_file
----------

trace_file takes one argument, which is either a file name or an open file
handle.  All trace output will go to this file.

max_trace_depth
---------------

To avoid lots of nesting, particularly from recursive function calls, you
can set the maximum depth to be traced.  If this is -1 (the default), all
levels of functions are traced.  If it is 0, no trace output occurs,
except for DEBUG statements that end in "!".

EXAMPLE
=======

     #!/usr/local/bin/perl -w
     
     use Devel::TraceFuncs;
     use strict;
     
     sub fq {
       IN(my $f);
       DEBUG "que", "pee", "doll!";
     }
     
     sub fp {
       IN(my $f);
       fq();
       DEBUG "cee", "dee";
     }
     
     sub fo {
       IN(my $f, "now", "then");
       &fp;
       DEBUG "ha\nhs";
     }
     
     if (@ARGV) {
       max_trace_depth shift;
     }
     
     if (@ARGV) {
       trace_file shift;
     }
     
     IN(my $f, 0);
     fo(4,5);
     
     DEBUG "done";
     
     =head1 BUGS

For some reason, the closing lines are reversed in this example:

     use Devel::TraceFuncs;

     max_trace_depth -1;

     sub g {
       IN(my $f);
     }
     
     sub f {
       IN(my $f);
       g();
     }

     f();

What it boils down to is not letting IN be the last line of a function.
In the debugger, the objects are destructed in the correct order, so this
must be caused by some sort of performance optimization in the perl
runtime.

AUTHOR
======

Joe Hildebrand

     Copyright (c) 1996 Joe Hildebrand. All rights reserved.
     This program is free software; you can redistribute it and/or
     modify it under the same terms as Perl itself.

MODIFICATION HISTORY
====================

Version 0.1, 1 Jun 1996


File: pm.info,  Node: DirHandle,  Next: DynaLoader,  Prev: Devel/TraceFuncs,  Up: Module List

supply object methods for directory handles
*******************************************

NAME
====

DirHandle - supply object methods for directory handles

SYNOPSIS
========

     use DirHandle;
     $d = new DirHandle ".";
     if (defined $d) {
         while (defined($_ = $d->read)) { something($_); }
         $d->rewind;
         while (defined($_ = $d->read)) { something_else($_); }
         undef $d;
     }

DESCRIPTION
===========

The `DirHandle' method provide an alternative interface to the opendir(),
closedir(), readdir(), and rewinddir() functions.

The only objective benefit to using `DirHandle' is that it avoids
namespace pollution by creating globs to hold directory handles.


File: pm.info,  Node: DynaLoader,  Next: English,  Prev: DirHandle,  Up: Module List

Dynamically load C libraries into Perl code
*******************************************

NAME
====

DynaLoader - Dynamically load C libraries into Perl code

dl_error(), dl_findfile(), dl_expandspec(), dl_load_file(),
dl_find_symbol(), dl_undef_symbols(), dl_install_xsub(), bootstrap() -
routines used by DynaLoader modules

SYNOPSIS
========

     package YourPackage;
     require DynaLoader;
     @ISA = qw(... DynaLoader ...);
     bootstrap YourPackage;

DESCRIPTION
===========

This document defines a standard generic interface to the dynamic linking
mechanisms available on many platforms.  Its primary purpose is to
implement automatic dynamic loading of Perl modules.

This document serves as both a specification for anyone wishing to
implement the DynaLoader for a new platform and as a guide for anyone
wishing to use the DynaLoader directly in an application.

The DynaLoader is designed to be a very simple high-level interface that
is sufficiently general to cover the requirements of SunOS, HP-UX, NeXT,
Linux, VMS and other platforms.

It is also hoped that the interface will cover the needs of OS/2, NT etc
and also allow pseudo-dynamic linking (using `ld -A' at runtime).

It must be stressed that the DynaLoader, by itself, is practically useless
for accessing non-Perl libraries because it provides almost no Perl-to-C
'glue'.  There is, for example, no mechanism for calling a C library
function or supplying arguments.  It is anticipated that any glue that may
be developed in the future will be implemented in a separate dynamically
loaded module.

DynaLoader Interface Summary

     @dl_library_path
     @dl_resolve_using
     @dl_require_symbols
     $dl_debug
                                                     Implemented in:
     bootstrap($modulename)                               Perl
     @filepaths = dl_findfile(@names)                     Perl

     $libref  = dl_load_file($filename)                   C
     $symref  = dl_find_symbol($libref, $symbol)          C
     @symbols = dl_undef_symbols()                        C
     dl_install_xsub($name, $symref [, $filename])        C
     $message = dl_error                                  C

@dl_library_path
     The standard/default list of directories in which dl_findfile() will
     search for libraries etc.  Directories are searched in order:
     $dl_library_path[0], [1], ... etc

     @dl_library_path is initialised to hold the list of 'normal'
     directories (`/usr/lib', etc) determined by *Configure*
     (`$Config{'libpth'}').  This should ensure portability across a wide
     range of platforms.

     @dl_library_path should also be initialised with any other directories
     that can be determined from the environment at runtime (such as
     LD_LIBRARY_PATH for SunOS).

     After initialisation @dl_library_path can be manipulated by an
     application using push and unshift before calling dl_findfile().
     Unshift can be used to add directories to the front of the search
     order either to save search time or to override libraries with the
     same name in the 'normal' directories.

     The load function that dl_load_file() calls may require an absolute
     pathname.  The dl_findfile() function and @dl_library_path can be
     used to search for and return the absolute pathname for the
     library/object that you wish to load.

@dl_resolve_using
     A list of additional libraries or other shared objects which can be
     used to resolve any undefined symbols that might be generated by a
     later call to load_file().

     This is only required on some platforms which do not handle dependent
     libraries automatically.  For example the Socket Perl extension
     library (`auto/Socket/Socket.so') contains references to many socket
     functions which need to be resolved when it's loaded.  Most platforms
     will automatically know where to find the 'dependent' library (e.g.,
     `/usr/lib/libsocket.so').  A few platforms need to to be told the
     location of the dependent library explicitly.  Use @dl_resolve_using
     for this.

     Example usage:

          @dl_resolve_using = dl_findfile('-lsocket');

@dl_require_symbols
     A list of one or more symbol names that are in the library/object file
     to be dynamically loaded.  This is only required on some platforms.

dl_error()
     Syntax:

          $message = dl_error();

     Error message text from the last failed DynaLoader function.  Note
     that, similar to errno in unix, a successful function call does not
     reset this message.

     Implementations should detect the error as soon as it occurs in any of
     the other functions and save the corresponding message for later
     retrieval.  This will avoid problems on some platforms (such as SunOS)
     where the error message is very temporary (e.g., dlerror()).

$dl_debug
     Internal debugging messages are enabled when $dl_debug is set true.
     Currently setting $dl_debug only affects the Perl side of the
     DynaLoader.  These messages should help an application developer to
     resolve any DynaLoader usage problems.

     $dl_debug is set to `$ENV{'PERL_DL_DEBUG'}' if defined.

     For the DynaLoader developer/porter there is a similar debugging
     variable added to the C code (see dlutils.c) and enabled if Perl was
     built with the *-DDEBUGGING* flag.  This can also be set via the
     PERL_DL_DEBUG environment variable.  Set to 1 for minimal information
     or higher for more.

dl_findfile()
     Syntax:

          @filepaths = dl_findfile(@names)

     Determine the full paths (including file suffix) of one or more
     loadable files given their generic names and optionally one or more
     directories.  Searches directories in @dl_library_path by default and
     returns an empty list if no files were found.

     Names can be specified in a variety of platform independent forms.
     Any names in the form *-lname* are converted into `libname.*', where
     `.*' is an appropriate suffix for the platform.

     If a name does not already have a suitable prefix and/or suffix then
     the corresponding file will be searched for by trying combinations of
     prefix and suffix appropriate to the platform: "$name.o", "lib$name.*"
     and "$name".

     If any directories are included in @names they are searched before
     @dl_library_path.  Directories may be specified as *-Ldir*.  Any other
     names are treated as filenames to be searched for.

     Using arguments of the form `-Ldir' and `-lname' is recommended.

     Example:

          @dl_resolve_using = dl_findfile(qw(-L/usr/5lib -lposix));

dl_expandspec()
     Syntax:

          $filepath = dl_expandspec($spec)

     Some unusual systems, such as VMS, require special filename handling
     in order to deal with symbolic names for files (i.e., VMS's Logical
     Names).

     To support these systems a dl_expandspec() function can be implemented
     either in the `dl_*.xs' file or code can be added to the autoloadable
     dl_expandspec() function in `DynaLoader.pm'.  See `DynaLoader.pm' for
     more information.

dl_load_file()
     Syntax:

          $libref = dl_load_file($filename)

     Dynamically load $filename, which must be the path to a shared object
     or library.  An opaque 'library reference' is returned as a handle for
     the loaded object.  Returns undef on error.

     (On systems that provide a handle for the loaded object such as SunOS
     and HPUX, $libref will be that handle.  On other systems $libref will
     typically be $filename or a pointer to a buffer containing $filename.
     The application should not examine or alter $libref in any way.)

     This is function that does the real work.  It should use the current
     values of @dl_require_symbols and @dl_resolve_using if required.

          SunOS: dlopen($filename)
          HP-UX: shl_load($filename)
          Linux: dld_create_reference(@dl_require_symbols); dld_link($filename)
          NeXT:  rld_load($filename, @dl_resolve_using)
          VMS:   lib$find_image_symbol($filename,$dl_require_symbols[0])

dl_find_symbol()
     Syntax:

          $symref = dl_find_symbol($libref, $symbol)

     Return the address of the symbol $symbol or undef if not found.  If
     the target system has separate functions to search for symbols of
     different types then dl_find_symbol() should search for function
     symbols first and then other types.

     The exact manner in which the address is returned in $symref is not
     currently defined.  The only initial requirement is that $symref can
     be passed to, and understood by, dl_install_xsub().

          SunOS: dlsym($libref, $symbol)
          HP-UX: shl_findsym($libref, $symbol)
          Linux: dld_get_func($symbol) and/or dld_get_symbol($symbol)
          NeXT:  rld_lookup("_$symbol")
          VMS:   lib$find_image_symbol($libref,$symbol)

dl_undef_symbols()
     Example

          @symbols = dl_undef_symbols()

     Return a list of symbol names which remain undefined after
     load_file().  Returns `()' if not known.  Don't worry if your
     platform does not provide a mechanism for this.  Most do not need it
     and hence do not provide it, they just return an empty list.

dl_install_xsub()
     Syntax:

          dl_install_xsub($perl_name, $symref [, $filename])

     Create a new Perl external subroutine named $perl_name using $symref
     as a pointer to the function which implements the routine.  This is
     simply a direct call to newXSUB().  Returns a reference to the
     installed function.

     The $filename parameter is used by Perl to identify the source file
     for the function if required by die(), caller() or the debugger.  If
     $filename is not defined then "DynaLoader" will be used.

bootstrap()
     Syntax:

     bootstrap($module)

     This is the normal entry point for automatic dynamic loading in Perl.

     It performs the following actions:

        * locates an auto/$module directory by searching @INC

        * uses dl_findfile() to determine the filename to load

        * sets @dl_require_symbols to `("boot_$module")'

        * executes an `auto/$module/$module.bs' file if it exists
          (typically used to add to @dl_resolve_using any files which are
          required to load the module on the current platform)

        * calls dl_load_file() to load the file

        * calls dl_undef_symbols() and warns if any symbols are undefined

        * calls dl_find_symbol() for "boot_$module"

        * calls dl_install_xsub() to install it as "${module}::bootstrap"

        * calls &{"${module}::bootstrap"} to bootstrap the module (actually
          it uses the function reference returned by dl_install_xsub for
          speed)

AUTHOR
======

Tim Bunce, 11 August 1994.

This interface is based on the work and comments of (in no particular
order): Larry Wall, Robert Sanders, Dean Roehrich, Jeff Okamoto, Anno
Siegel, Thomas Neumann, Paul Marquess, Charles Bailey, myself and others.

Larry Wall designed the elegant inherited bootstrap mechanism and
implemented the first Perl 5 dynamic loader using it.


File: pm.info,  Node: English,  Next: Env,  Prev: DynaLoader,  Up: Module List

use nice English (or awk) names for ugly punctuation variables
**************************************************************

NAME
====

English - use nice English (or awk) names for ugly punctuation variables

SYNOPSIS
========

     use English;
     ...
     if ($ERRNO =~ /denied/) { ... }

DESCRIPTION
===========

This module provides aliases for the built-in variables whose names no one
seems to like to read.  Variables with side-effects which get triggered
just by accessing them (like $0) will still be affected.

For those variables that have an *awk* version, both long and short
English alternatives are provided.  For example, the $/ variable can be
referred to either $RS or $INPUT_RECORD_SEPARATOR if you are using the
English module.

See *Note Perlvar: (perl.info)perlvar, for a complete list of these.


File: pm.info,  Node: Env,  Next: EventServer,  Prev: English,  Up: Module List

perl module that imports environment variables
**********************************************

NAME
====

Env - perl module that imports environment variables

SYNOPSIS
========

     use Env;
     use Env qw(PATH HOME TERM);

DESCRIPTION
===========

Perl maintains environment variables in a pseudo-associative-array named
%ENV.  For when this access method is inconvenient, the Perl module Env
allows environment variables to be treated as simple variables.

The Env::import() function ties environment variables with suitable names
to global Perl variables with the same names.  By default it does so with
all existing environment variables (`keys %ENV').  If the import function
receives arguments, it takes them to be a list of environment variables to
tie; it's okay if they don't yet exist.

After an environment variable is tied, merely use it like a normal
variable.  You may access its value

     @path = split(/:/, $PATH);

or modify it

     $PATH .= ":.";

however you'd like.  To remove a tied environment variable from the
environment, assign it the undefined value

     undef $PATH;

AUTHOR
======

Chip Salzenberg <`chip@fin.uucp'>


File: pm.info,  Node: EventServer,  Next: Exporter,  Prev: Env,  Up: Module List

the all singing, all dancing server. Handles i/o driven clients, timer driven clients, and interrupt driven clients, all at the same time. Allows user defined events also. If there are any more types of clients, please tell me.
***********************************************************************************************************************************************************************************************************************************

NAME
====

EventServer - the all singing, all dancing server.  Handles i/o driven
clients, timer driven clients, and interrupt driven clients, all at the
same time. Allows user defined events also. If there are any more types of
clients, please tell me.

SYNOPSIS
========

Functions can be imported and used:

     use EventServer;
     
     $r1 = register_timed_client($obj1,$time1,$coderef1);
     $r2 = register_interval_client($obj2,$time2,$coderef2);
     $r3 = register_signal_client($obj3,$signal3,$coderef3);
     $r4 = register_io_client($obj4,$mode4,$coderef4_r,
     		$coderef4_w,$coderef4_rw);
     $r5 = register_child_termination_client($obj5,$pid5,$coderef5);
     $r6 = register_event_client($obj6,$eventName6,$coderef6);
     
     trigger_on_deregistering($r1,$coderef7);
     cancel_registration($r3);
     $ordered_keys_ref = ordered_keys_ref();
     
     $time = maximum_inactive_server_time();
     set_maximum_inactive_server_time($time);
     execute_in_array_context_with_timeout($timeout,$timeout_retcode,
     		$error_retcode,$coderef,@args);
     
     fork_with_child_retaining_clients($r1,$r2,...);
     
     sub something {add_event($eventName)}
     
     start_server();

Or the class can be used with methods:

     require EventServer;
     $S = EventServer;
     
     $r1 = $S->registerTimedClient($obj1,$time1,$coderef1);
     $r2 = $S->registerIntervalClient($obj2,$time2,$coderef2);
     $r3 = $S->registerSignalClient($obj3,$signal3,$coderef3);
     $r4 = $S->registerIOClient($obj4,$mode4,$coderef4_r,
     		$coderef4_w,$coderef4_rw);
     $r5 = $S->registerChildTerminationClient($obj5,$pid5,$coderef5);
     $r6 = $S->registerEventClient($obj6,$eventName6,$coderef6);
     
     $S->triggerOnDeregistering($r1,$coderef7);
     $S->cancelRegistration($r3);
     $ordered_keys_ref = $S->orderedKeysRef();
     
     $time = $S->maximumInactiveServerTime();
     $S->setMaximumInactiveServerTime($time);
     $S->executeInArrayContextWithTimeout($timeout,$timeout_retcode,
     		$error_retcode,$coderef,@args);
     
     $S->forkWithChildRetainingClients($r1,$r2,...);
     
     sub something {$S->addEvent($eventName)}
     
     $S->startServer();

IMPORTANT
=========

The 'ALRM' signal is used extensively, as is alarm().  You should NOT call
the function alarm() as this will corrupt the internal logic of the
server. Similarly sleep() should not be used either, as this is often
implemented in terms of alarm().

Instead use execute_in_array_context_with_timeout() which is better anyway
since it allows multiple clients to set alarms simultaneously and allows
nested alarms. However, for this reason, registering a client to receive
'ALRM' signals is probably of no use.

Also, if you assign to the %SIG hash, or install signal handlers through
POSIX yourself, then you may corrupt the logic of the server. If you need
to do this for something other than a signal (e.g. __WARN__), that should
be okay, otherwise you should probably create a subclass to install the
handlers you want (see `"The SIG hash and signals"' in this node and
`"Creating Subclasses"' in this node).

CONTENTS
========

`"NAME"' in this node

`"SYNOPSIS"' in this node

`"IMPORTANT"' in this node

`"CONTENTS"' in this node

`"Function and Method Summary"' in this node

`"Including the server in your program"' in this node

`"Starting the server"' in this node

`"Registering clients (general)"' in this node

`"Registering clients (methods)"' in this node

`"Client order for simultaneous events"' in this node

`"Deregistering clients"' in this node

`"Timeouts within client code"' in this node

`"Forking child processes"' in this node

`"Times and Timing"' in this node

`"The SIG hash and signals"' in this node

`"Example"' in this node

`"Creating Subclasses"' in this node

`"Example subclasses"' in this node

`"Possible problems"' in this node

`"Questions and Answers"' in this node

`"AUTHOR"' in this node

`"COPYRIGHT"' in this node

`"MODIFICATION HISTORY"' in this node

Function and Method Summary
===========================

There are 15 public functions/methods:

8 dealing with registering clients;

1 to add user defined events

3 dealing with executing code and timeouts;

1 to fork the process;

and 1 to start the server.

Functions are:

     register_interval_client(O/R,INTERVAL,FUNCREF,ARG)
     register_timed_client(O/R,TIMEOUT,FUNCREF,ARG)
     register_io_client(O/R,MODE,HANDLE,RFUNCREF,WFUNCREF,RWFUNCREF,ARG)
     register_signal_client(O/R,SIGNAL,FUNCREF,ARG)
     register_child_termination_client(O/R,PID,FUNCREF,ARG)
     register_event_client(O/R,EVENT,FUNCREF,ARG)
     
     trigger_on_deregistering(REGISTRY_KEY,FUNCREF)
     cancel_registration(REGISTRY_KEY)
     
     add_event(EVENT)
     
     maximum_inactive_server_time()
     set_maximum_inactive_server_time(TIME)
     execute_in_array_context_with_timeout(TIMEOUT,TRET,ERET,FUNCREF,ARGS)
     
     fork_with_child_retaining_clients(LIST_OF_REGISTRY_KEYS)
     
     start_server();

And defined as methods:

     $SERVER->registerIntervalClient(O/R,INTERVAL,FUNCREF,ARG)
     $SERVER->registerTimedClient(O/R,TIMEOUT,FUNCREF,ARG)
     $SERVER->registerIOClient(O/R,MODE,HANDLE,RFUNCREF,WFUNCREF,RWFUNCREF,ARG)
     $SERVER->registerSignalClient(O/R,SIGNAL,FUNCREF,ARG)
     $SERVER->registerChildTerminationClient(O/R,PID,FUNCREF,ARG)
     $SERVER->registerEventClient(O/R,EVENT,FUNCREF,ARG)
     
     $SERVER->triggerOnDeregistering(REGISTRY_KEY,FUNCREF);
     $SERVER->cancelRegistration(REGISTRY_KEY);
     
     $SERVER->addEvent(EVENT)
     
     $SERVER->maximumInactiveServerTime()
     $SERVER->setMaximumInactiveServerTime(TIME)
     $SERVER->executeInArrayContextWithTimeout(TIMEOUT,TRET,ERET,FUNCREF,ARGS)
     
     $SERVER->forkWithChildRetainingClients(LIST_OF_REGISTRY_KEYS)
     
     $SERVER->startServer();

Including the server in your program
====================================

The server is included in your program with the line

     use EventServer;

to import the functions, or

     require EventServer;

if used as a class.

Starting the server
===================

The server is started by executing the function or method

start_server();
EventServer->startServer();
     In either case, if a subclass has been defined correctly, then the
     server will be started using that subclass.

Registering clients (general)
=============================

Clients are registered with the server using any of the 6 registering
methods listed in the next section. They all have various points in common:

1. $SERVER is assumed to be EventServer or a subclass;

2. All registration methods return a RegistryKey object on success which
holds the registration key, and false on failure. (Note previous versions
returned a string - the current version should be fully compatible with
previous versions). The registration key is unique to the registration,
depending on all the parameters passed to the registration method - i.e a
single object can be registered multiple times using different parameters
or registration methods (multiple *identical* registrations will return
the same key, and will result in only one registration). To alter the
parameters of an existing registration, pass the registration key to the
registration method instead of the object (see 'O/R' below).  But note
that this generates a new RegistryKey object since the registration
parameters are now different (the old RegistryKey object is deregistered,
and is essentially useless). Reregistering an existing registration so
that it is identical to another registration will just derigister the
first registration, returning the existing identical RegistryKey object
(i.e.  as stated above, there will only be one registry entry for
identical parameters regardless of how you register them).

3. 'O/R' is the object being registered or the registration key of an
already registered object. The object can be anything (previous versions
restricted it to be class names or objects that returned true ref()
values). This object is passed to FUNCREF (see below) as the first
argument.

4. 'ARG' is anything. It is passed to FUNCREF (see below) as the last
argument.  If nothing is passed, then ARG is defaulted to undef();

5. At least one 'FUNCREF' argument is required. All FUNCREF arguments are
CODE references to the function which is executed when the client is
triggered. Where there is more than one FUNCREF to be specified, the one
called will depend on the trigger type. When triggered, the FUNCREF is
called as:

     &FUNCREF(OBJECT,REGISTRY_KEY,some method specific args,ARG);

where:

     OBJECT is the object registered (the 'O' in 'O/R' above);
     REGISTRY_KEY is the registration key for that registration
        (the 'R' in 'O/R' above, returned by registration methods);
     ARG is the last argument passed to the registration method
        ('ARG' above);

This call to FUNCREF takes place within a timeout. The current maximum
timeout value can be retrieved using maximum_inactive_server_time(), and
can be set using set_maximum_inactive_server_time(). (These access and set
the global $EventServer::MAX_INACTIVE_SERVER_TIME.) The default value is
60 seconds. Any fatal errors caused by executing FUNCREF are trapped, and
cause the client to be deregistered.  A timeout will also cause the client
to be deregistered.

NOTE however that a call to exit() cannot be trapped and will cause the
server process to exit. Similarly, a call to dump() also cannot be trapped
and will cause the server process to core dump.

Registering clients (methods)
=============================

register_interval_client (O/R,INTERVAL,FUNCREF,ARG)
$SERVER->registerIntervalClient(O/R,INTERVAL,FUNCREF,ARG)
     INTERVAL is a time (see `"Times and Timing"' in this node). The
     client is triggered after every INTERVAL seconds. Triggering effects
     the function call

          &FUNCREF(OBJECT,REGISTRY_KEY,INTERVAL,ARG);

register_timed_client (O/R,TIMEOUT,FUNCREF,ARG)
$SERVER->registerTimedClient(O/R,TIMEOUT,FUNCREF,ARG)
     TIMEOUT is a time (see `"Times and Timing"' in this node). The client
     is triggered after TIMEOUT seconds and then deregistered. Triggering
     effects the function call

          &FUNCREF(OBJECT,REGISTRY_KEY,TIMEOUT,ARG);

register_io_client(O/R,MODE,HANDLE,RFUNCREF,WFUNCREF,RWFUNCREF,ARG)
$SERVER->registerIOClient(O/R,MODE,HANDLE,RFUNCREF,WFUNCREF,RWFUNCREF,ARG)
     MODE is 'r', 'w' or 'rw' depending on whether the trigger should be
     for input pending (read won't block), output possible (write won't
     block) or both.  HANDLE is the fully qualified package name of the
     filehandle which has already been opened, on which i/o is tested.
     RFUNCREF, WFUNCREF and RWFUNCREF are three 'FUNCREF's (see above).
     If input is pending on HANDLE, this triggers the call

          &RFUNCREF(OBJECT,REGISTRY_KEY,HANDLE,ARG);

     if output is possible on HANDLE, this triggers the call

          &WFUNCREF(OBJECT,REGISTRY_KEY,HANDLE,ARG);

     and if both input and output won't block, then this triggers the call

          &RWFUNCREF(OBJECT,REGISTRY_KEY,HANDLE,ARG);

     If MODE 'r' has been specified, then obviously only RFUNCREF can ever
     get called, and similarly if MODE 'w' has been specified, then only
     WFUNCREF can ever get called. However, if MODE 'rw' has been
     specified, then any of the three functions could be called depending
     on what becomes non-blocking first.

     In all cases of MODE, all three FUNCREF's must be CODE references.

     Note, unlike previous versions, now if you make multiple registrations
     for a specific filehandle, then client functions are still only
     triggered when they are guaranteed to be non-blocking. To paraphrase,
     if any FUNCREF is called, you are guaranteed to be able to do a
     sysread(), syswrite() or accept() (whichever is appropriate).

register_signal_client (O/R,SIGNAL,FUNCREF,ARG)
$SERVER->registerSignalClient(O/R,SIGNAL,FUNCREF,ARG)
     SIGNAL is a valid trappable signal. The signals are obtained from the
     Config module. (Previous versions specified them explicitly in
     subroutines). The 'allSignals' method retuns the list of signals.

     The client is triggered after the signal is trapped (and after the
     signal handler has exited). Triggering effects the function call

          &FUNCREF(OBJECT,REGISTRY_KEY,SIGNAL,NSIGS,ARG);

     where

          NSIGS is the number of times the signal was
              received since this function was last called.
          and SIGNAL is the canonical name for the signal
          (which may be different from what was passed in the
          case of 'CHLD'/'CLD'. You can always use either - the
          correct signal name for the system will be used.)

     Note that 'ALRM' and 'CLD' (or 'CHLD' or 'CHILD') are specially
     handled, and registering for these signals is of little use.  For
     alarms, use execute_in_array_context_with_timeout(), and to find out
     when a child process has died, register with
     register_child_termination_client().

     Signals which have no clients registered for them will cause the
     default action to occur (i.e. they will not be trapped).

     Signals are not passed to the clients immediately, they are put into
     the queue and clients are triggered when the signal queue is checked.
     If you need some action to occur IMMEDIATELY on receipt of the
     signal, you will need to create a subclass to handle this. (This is
     because setting up an 'immediately signalled' type of client is
     fraught with difficulties, and is likely to lead to an unstable
     process - I tried it. And that was even without having signal
     handlers stacked through recursive calls to it. Mind you, it should
     be doable with POSIX signals, and is almost, but some bug that I
     haven't tracked down yet seems to propagate a die past an eval if
     called from within the handler, so its not yet implemented for POSIX
     signals in the server.)

     Signal handlers are NOT installed until the server has been started
     (see `"Starting the server"' in this node).

     All signal handlers are reset to default if the server loop exits
     (see `"Questions and Answers"' in this node).

     See also `"The SIG hash and signals"' in this node.

register_child_termination_client (O/R,PID,FUNCREF,ARG)
$SERVER->registerChildTerminationClient(O/R,PID,FUNCREF,ARG)
     PID is the process id of the child process. When that child dies this
     triggers the function call

          &FUNCREF(OBJECT,REGISTRY_KEY,DATA,ARG);

     Where data is either: the process id of the terminated child; or an
     array reference with two items in the array - the process id and the
     child termination status as given by '$?' . The choice of which is
     returned is set by calling always_return_child_termination_status()
     with a boolean argument - true means return the array reference,
     false means return the pid only. The default is false for backward
     compatibility.

     Note that if forking the server, you should use
     fork_with_child_retaining_clients() rather than just a fork().

register_event_client (O/R,EVENT,FUNCREF,ARG)
$SERVER->registerEventClient(O/R,EVENT,FUNCREF,ARG)
     EVENT is any string. If any client adds the event EVENT into the
     server's event loop (using add_event(EVENT)) then this will trigger
     the call

          &FUNCREF(OBJECT,REGISTRY_KEY,EVENT,ARG);

     for this client. This allows clients for user defined events

add_event (EVENT)
$SERVER->addEvent(EVENT)
     Simply adds the string EVENT to the end of the event queue.  Any
     clients waiting for this event (registered using the
     register_event_client() function) are triggered.

always_return_child_termination_status(BOOLEAN)
$SERVER->alwaysReturnChildTerminationStatus(BOOLEAN)
     Sets whether the register_child_termination_client() call will
     trigger a callback with just the child's pid as the third argument
     (BOOLEAN true), or a reference to an array holding the pid and the
     termination status (BOOLEAN false). Note that this affects the call
     dynamically - the trigger checks as its triggering to see what type
     of argument it should pass.

     The default is false for backward compatibility.

Client order for simultaneous events
====================================

If two events occur simultaneously, or an event occurs for which more than
one client is registered, then more than one client will be triggered in
the same server loop.  You may want to ensure that for any pair of
clients, a specific client is always called before another in this
situation.

This can be achieved using the following function:

ordered_keys_ref()
$SERVER->orderedKeysRef()
     This method/function returns a reference to an ARRAY type object.
     This object holds RegistryKey objects in whatever order you want to
     specify. In cases where more than one client is to be triggered
     within a single server loop, the order of the keys within this array
     determines the ordering of client activation. For example, this

          $r1 = register_...;
          $r2 = register_...;
          push(@{ordered_keys_ref()},$r2,$r1);

     will ensure that in such a case, the client registered on key '$r2'
     will always be called before the client registered on key '$r1'.

     The object returned by ordered_keys_ref() is actually an object of
     class EventServer::OrderedKeys, and there are several methods in this
     class which may make it easier for you to manipulate the array
     (though just treating it as an array reference is absolutely fine):

          $order = ordered_keys_ref();
          $order->push_keys(LIST_OF_KEYS);
          $order->pop_key();
          $order->shift_key();
          $order->unshift_keys(LIST_OF_KEYS);
          $order->insert_keys_before(INDEX,LIST_OF_KEYS);
          $order->delete_key_at(INDEX);

Deregistering clients
=====================

There are two methods for deregistering clients. One is to use the fact
that FUNCREF calls have fatal die() errors trapped - which means that a
client can die() when it is triggered, and this will cause that client to
be deregistered. (Timing out will have the same effect, but is a silly way
to do it since all other clients may be blocked until the timeout is
finished).

NOTE that generating an 'ALRM' signal (e.g. with "kill 'ALRM,$$") will
produce a die() since the alarm handler dies. This means that if you
produce an ALRM signal, you are effectively timing out the client, and
hence deregistering it.

The second method is to use the function/method provided:

cancel_registration (REGISTRY_KEY);
$SERVER->cancelRegistration(REGISTRY_KEY);
     This deregisters the client that was registered on the key
     REGISTRY_KEY.

The server will deregister a client if there are any problems with it. You
can find out when a client is deregistered by setting a function to be
triggered when the client is deregistered using the function/method:

trigger_on_deregistering (REGISTRY_KEY,FUNCREF);
$SERVER->triggerOnDeregistering(REGISTRY_KEY,FUNCREF);
     This returns true (REGISTRY_KEY) on success, false (undef) on
     failure. On success, the code reference FUNCREF has been added to the
     clients registration such that when the client is deregistered, this
     triggers the call:

          &FUNCREF(OBJECT,REGISTRY_KEY,method specific args,ARG);

     where the 'method specific args' are determined by the type of
     registration used (as specified in the section `"Registering clients
     (methods)"' in this node), and the other terms are as previously
     defined.

Timeouts within client code
===========================

Note alarm() should not be used (see `"IMPORTANT"' in this node). Instead,
a function/method has been provided which allows for nested timeouts.

execute_in_array_context_with_timeout (TIMEOUT,TRET,ERET,FUNCREF,ARGS)
$SERVER->executeInArrayContextWithTimeout(TIMEOUT,TRET,ERET,FUNCREF,ARGS)
     TIMEOUT is a time (see `"Times and Timing"' in this node). This sets
     the timeout for the call (note that times are rounded up to the next
     integer number of seconds);

     TRET is the value/object returned as the first element of the return
     array if the call is timed out;

     ERET is the value/object returned as the first element of the return
     array if the call produces a fatal error;

     FUNCREF is the CODE reference which is called;

     ARGS are the arguments which are passed to FUNCREF when it is called.

     This method calls FUNCREF in an array context (if you want to make a
     call in a scalar context, wrap the function and pass the wrapped
     function reference, e.g.

          sub wrapper { (scalar_call(@_)) }

     and FUNCREF = \&wrapper), with arguments ARGS. i.e the call is

          @ret = &FUNCREF(ARGS);

     If the call is not timed out, and does not produce an error, then the
     array returned by the FUNCREF call (@ret) is returned.  If a timeout
     occured, then the array (TRET) is returned, and if an error occurred
     during the FUNCREF call, then the array (ERET, $@) is returned.

     This method allows timeouts to be nested - i.e. you can call this
     method within another function which is being timed out by this
     method.

maximum_inactive_server_time()
$SERVER->maximumInactiveServerTime()
     Returns the current value that this is set to. This determines the
     maximum time before triggered clients are timed out. Default is 60
     (seconds).

set_maximum_inactive_server_time (TIME)
$SERVER->setMaximumInactiveServerTime(TIME)
     Sets this value. It should be a positive value.

Forking child processes
=======================

The call fork() works fine, but the resulting child is a copy of the
server with all the clients retained. If the fork is to be followed by an
exec, this is fine. But otherwise, you need to know which clients are
still registered, and which ones you don't want.

Instead of worrying about this, I provide a function/method to fork the
server retaining ONLY those clients you know you want. All other clients
are deregistered in the child.

fork_with_child_retaining_clients (LIST_OF_REGISTRY_KEYS)
$SERVER->forkWithChildRetainingClients(LIST_OF_REGISTRY_KEYS)
     This function/method works and returns as fork(): On failure, undef
     is returned, on success the process is forked and the child gets 0
     returned while the parent gets the process id of the child returned.

     In addition, only those clients with registry keys specified as
     arguments when this method is called, have their registration
     retained in the child. (Note that if you are handling signals in
     addition to whatever else, you may want to retain those signal
     handling clients in the child).

     This saves you from needing to think about which clients need to be
     deregistered in the child - you only need to consider which ones need
     to be kept.

Times and Timing
================

Note that all times should be specified in seconds, and can be fractional
(e.g. 2.35). However the fractional part may be of no use depending on
where it is used.

Currently, timing-out code using execute_in_array_context_with_timeout()
has values rounded up to the next highest integer , e.g. '2.35' will be
used as '3', and '2' will be used as '3' (this latter use is because
alarm() can be up to one second less).  This is because alarm() is being
used to time out code in this function, and alarm() only has a 1 second
resolution.

Timing in the Interval and Timer client registration is dependent on the
resolution available from a clock timer used from Perl. If the default
time() is used, then fractional seconds are effectively rounded up to the
next integer, since the times can only be ticked down in seconds.
Resolutions will specify how many digits after the decimal point are used.
The maximum resolution is one microsecond (six digits after the decimal
point).  Non-significant digits may be rounded up or down.

The server specifies the timing method during initialization.  Currently,
if syscall() and the gettimeofday() system call are available, these are
used, otherwise time() is used.

However, the availability of the gettimeofday() call is established with a
call to the method timeClass() in the OS specific class given by the OS
name as obtained from Config, appended to 'EventServer::'.

For example, if this module is run on SunOS, Config says that the OS name
('osname' parameter) is 'sunos', in which case the call

     EventServer::sunos->timeClass()

is made. If this call produces a die(), that is trapped, and the default
time class (using time()) is used.  If this does not die, it is assumed to
return a reference to an array, with first element being the time class to
use, and the second any initialization.

For example, in the case of SunOS, this returns

     ['EventServer::Gettimeofday',116];

which specifies to use the Gettimeofday class, and initializes this class
with the syscall number required to make the call to gettimeofday().

Please tell me what is best on any specific platform, I'll try to include
support for it. Currently automatically supported are SunOS 4.*, IRIX 5.*,
and Linux. You can add specific OS support just be adding the package and
timeClass() method as shown.

Remember, you can always let it default to the plain Time class - this is
usually sufficient.

The SIG hash and signals
========================

If you assign to the %SIG hash, or install signal handlers through POSIX
yourself, then you may corrupt the logic of the server. If you need to do
this for anything other than a signal (e.g. __WARN__), that should be okay,
otherwise you should probably create a subclass to install the handlers
you want (see `"Creating Subclasses"' in this node).

If you want to trap a signal, do it by registering a signal client.  If
you want to trap a signal and need to have control during the signal
handler, then subclass the EventServer class and set the handler in the
subclass. And note that any handler which dies will deregister any client
which sends a signal for that handler. Its usually a bad idea to do too
much in a signal handler (see `"Possible problems"' in this node.

However, if you are definitely not going to register any clients for a
particular signal, you can assign your own signal handler for that signal
(though not for ALRM and CHLD).

Terminating children have their pid's removed from the process list before
clients receive the 'CLD' signal. For this reason you should not wait()
for terminating children. If you want to be notified of this, use the
register_child_termination_client() registration method. For this reason,
registering a client to receive 'CLD' signals is probably of no use.

Signals which have no clients registered for them will not be trapped.

See also `"Timeouts within client code"' in this node, `"IMPORTANT"' in
this node and the entries for methods register_signal_client() and
register_child_termination_client().

Example
=======

Note that you can execute this example with `perl5 -x EventServer.pm'
assuming you are in the perl lib directory where you installed this module.

The example program below registers all the various types of clients.

o A timer client (expiring after 3 seconds), which is also told that it is
being deregistered when it dies;

o an interval client (sending a SIGCONT every 4.3 seconds for 4 times,
then deregistering) - on the fourth triggering this client calls a
function to test nested timeouts. That should timeout after 3 seconds,
though an interrupt could terminate it quicker;

o a signal client which also tests re-registering (triggered on receiving
the first 'CONT' from the interval client, at which point it reregisters,
changing the function that is called to 'cont_test2' which makes it catch
the second SIGCONT from the interval client, and then deregister);

o an event client, which waits for the event 'CHECK' - that event is sent
on the third triggering of the interval client.  The Event client calls a
nested timeout which tests the functionality of nested timeouts. That
should timeout after 3 seconds, though an interrupt could terminate it
quicker;

o an i/o client, which waits for some input on STDIN (requires a <RETURN>
to be triggered) and then deregisters;

o a child termination client (the process forks right at the beginning,
and the child sleeps for 10 seconds then terminates);

o and finally another signal client which will take two SIGINT's (usually
generated by typing cntrl-C) then deregisters, which means that the next
SIGINT will cause the default signal action to occur (program termination).

Note that the server will terminate when all clients are deregistered so
if you want to see everything you need to run this at least twice - once
you can terminate by giving three cntrl-C's BEFORE all the other clients
have deregistered (you can keep the io client registered by not typing
<RETURN>), and the second time you can let the program terminate by
letting all the clients deregister (two cntrl-C's and a <RETURN> get rid
of the SIGINT client and the io client - all other clients get
deregistered within the first 20 seconds).

#!perl5

     BEGIN {print "Initializing, process id is $$\n";}
     use EventServer;
     
     # Timer test client (after 3 seconds)
     $r = register_timed_client([],3,sub {print STDERR "Timed test\n"})
     	|| die "Timed test not registered";
     
     # Deregistering Trigger test
     trigger_on_deregistering($r,
       sub {print STDERR "Deregistering Trigger test\n"}) ||
     	 die "Deregistering Trigger test not registered";
     
     # Interval test client (every 4.3 seconds, 4 times)
     register_interval_client([],4.3,\&interval_test)
     	|| die "Interval test not registered";
     
     sub interval_test {
         $C++;print STDERR "Interval test $C\n";
         kill 'CONT',$$;
         if ($C == 3) {
     	 add_event('CHECK');
         } elsif ($C > 3) {
     	 $t=time;
     	 execute_in_array_context_with_timeout(2.5,0,0,\&t4_test);
     	 print STDERR 'Nested timeout returned after ',time-$t," secs\n";
     	 die;
         }
     }
     
     sub t3_test {
         execute_in_array_context_with_timeout(2.5,0,0,
     					   sub {select(undef,undef,undef,9)});
     }
     
     sub t4_test {
         execute_in_array_context_with_timeout(6.5,0,0,
     					   sub {select(undef,undef,undef,9)});
     }
     
     sub t1_test {
         print STDERR "Event client test\n";
         $t=time;
         execute_in_array_context_with_timeout(6.5,0,0,\&t3_test);
         print STDERR 'Nested timeout returned after ',time-$t," secs\n";
         die;
     }
     
     register_event_client([],'CHECK',\&t1_test) ||
        die "Event test not registered";
     
     # Signal test client (once after first Interval test)
     $r = register_signal_client([],'CONT',\&cont_test)
     	|| die "Signal test not registered";
     
     # Reregistration test client (once after second Interval test)
     sub cont_test {
       print STDERR "Signal test\n";
       register_signal_client($r,'CONT',\&cont_test2)
     }
     sub cont_test2 {print STDERR "Reregistering test\n";die}
     
     # IO test client (once after user types <RETURN>)
     register_io_client([],'r',STDIN,\&io,\&io,\&io) ||
     	die "STDIN test not registered";
     sub io {$l=<STDIN>;print STDERR "IO test: $l";die}
     
     # Child Termination test client (after 10 seconds)
     defined($pid = fork) || die "Couldn't fork";
     if($pid==0){
       #Keep the child around for 10 seconds
       $SIG{'INT'} = 'IGNORE';sleep(10);warn "Child Died\n";exit(23);
     }
     print STDERR "Start child process pid = $pid\n";
     always_return_child_termination_status(1);
     register_child_termination_client([],$pid,
       sub {print STDERR "Child (pid=$_[2]->[0]) terminated with status ",$_[2]->[1]>>8,"\n"}) ||
     	die "Not registered";
     
     # Signal test client (catches 2 ^C, then uses default SIGINT)
     register_signal_client([],'INT',
       sub {$A++;print STDERR "INT caught $A\n";$A>1 && die})
     	|| die "Signal test not registered";
     
     print "Starting server now\n";
     start_server();
     
     __END__

Creating Subclasses
===================

The EventServer server is designed with subclassing in mind.  There is
only so much generality that can be catered for in any class, and specific
applications will do much better by subclassing and specializing.

In making a subclass of the server, the following points are of note:

1.  The server class is specified in the variable

     $EventServer::SERVER_CLASS.

To allow your subclass to handle ALL methods (including signal handling,
initialization and exporting of functions) you need to specify this
variable before require'ing the EventServer.  This is best done as

     package MyServer;
     BEGIN {$EventServer::SERVER_CLASS ||= MyServer;}
     @ISA = qw(EventServer);
     require EventServer;

Note that the @ISA call _MUST_ be before the 'require' since the require
contains initialization calls that need to do method lookups on
$EventServer::SERVER_CLASS.

Making the assignment conditional on the variable being false allows your
class to be subclassed as well.

2.  The initialization is a method called init().  Specifying the
SERVER_CLASS variable above will ensure that the init method is called in
the subclass rather than the EventServer class.

Initialization occurs when EventServer is require'd.

3.  The initialization sets several system constants:

     EINTR EBADF EINVAL EFAULT WNOHANG

and will produce a fatal error if they cannot be set.

These are set when the method _setConstantsAndTimeClass() is called from
init(), which in turn calls _setConstants().  The constants are set using
the methods _setEINTR(), _setEBADF(), _setEINVAL(), _setEFAULT(), and
_setWNOHANG().

So, for example, to specify the values for SunOS 4, you could declare the
following method in a subclass:

     sub _setConstants {
        my($self) = @_;
        $self->_setEINTR(0x4);
        $self->_setEBADF(0x9);
        $self->_setEINVAL(0x16);
        $self->_setEFAULT(0xe);
        $self->_setWNOHANG(0x1);
     }

4.  The initialization sets and initializes the variable time class to
use. It does this by finding the OS name from Config ($Config{'osname'})
and making the call:

     EventServer::<osname>->timeClass()

where <osname> is the OS name as found from CONFIG.  If this call does not
die() (any call to die() is trapped), then it is assumed to return an
array reference to an array consisting of the time class to use as the
first element, and values to initialize the time class for subsequent
elements.

Typically, this would be 'EventServer::Gettimeofday' as the first element,
and the syscall number for the gettimeofday call as the second element
(e.g. SYS_gettimeofday from syscall.h on many systems). However, you could
explicitly specify the default 'EventServer::Time' using this method, or a
completely different class.

If you roll your own time class, it must have the following methods
implemented appropriately:

     initialize(?)		# Whatever
     now()			# Return an object representing the time now
     newFromSeconds(SECONDS)# Return an object representing SECONDS
     copy()			# Return new object representing the time in 'self'
     newFromDiff(OTHER)	# Return an object representing the time difference
     			# between 'self' and OTHER
     original()		# Return the time in its original format
     isPositive		# Is the time positive? Return boolean
     smallerTime(OTHER)	# Return object with smaller time, 'self' or OTHER
     time()			# Return the time as a number (a float if needed)
     wholeSecondsRoundedDown()# Return time as an integer, ignoring fractions

The method timeClass() gives the class being used to handle times.
Available are EventServer::Time using the time() function in Perl
(resolution 1 second) and EventServer::Gettimeofday which uses the
gettimeofday() C system call using syscall.

5.  The init() sets the list of signals that can be registered for. The
list is obtained from the Config module, minus the untrappable KILL and
STOP signals.

6.  The setSignalHandlers() method

The setSignalHandlers() method creates the signal handlers if necessary,
and installs those that are to be permanently installed. All signals have
a signal handler assigned.

Unlike previous versions, in order to elminate possible reentrancy bugs,
the signal handlers do not execute in subclasses. They are functions in
their own namespace which do the absolute minimum possible (mostly just
incrementing a variable).

To reimplement a signal handler, you need to respecify the
signalHandlerFor() method. This method takes as argument the signal name,
and returns the name of the handler. The handlers should increment the
global $EventServer::Signal::<SIGNAME>, e.g. the 'TERM' signal handler
should increment the global $EventServer::Signal::TERM.  (This is all they
do by default).

The ALRM handler is implemented slightly differently, and should not be
reimplemented unless you know what you're doing.

Handlers are normally only installed when a client registers for that
signal. However, ALRM and CHLD are permanently registered. You can specify
which handlers are permanently registered by reimplementing the
isSpecialSignalHandler() method. This returns true for those signals which
should have permanently installed handlers. But note that if you
reimplement this, you should include ALRM and CHLD (or CLD) among the set
of signals which return true.

Note that any handler which is set to die on receipt of a signal will
deregister any client which sends a that signal.

7.  The server can be started using

     start_server();

or

     EventServer->startServer();

or

     MyServer->startServer();

since startServer() actually starts the server using the class specified
in  $EventServer::SERVER_CLASS

Example subclasses
==================

The SunOS example is not necessary, and is just here for illustrative
purposes (though can be used).

     ############################################################
     # Subclass for SunOS4. Speeds up initialization and
     # ensures the use of gettimeofday(2) system call.
     # Also SunOS doesn't need to have handlers reinstalled
     # when they are called.
     # NOTE that you can use EventServer
     # on SunOS or any other OS without this subclass.
     #
     package EventServer_SunOS4;
     
     BEGIN {
       if (`/bin/uname -sr` =~ /^SunOS\s+4/i) {
          $EventServer::SERVER_CLASS ||=
     	EventServer_SunOS4;
       } else {
          warn "Warning: system is not SunOS4 - using plain EventServer class\n";
       }
     }
     
     @ISA = qw(EventServer);
     require EventServer;
     
     sub _setConstantsAndTimeClass {
         my($self) = @_;
         $self->_setConstants();
         $self->_setTimeClass(EventServer::Gettimeofday,116);
     }

     sub _setConstants {
         my($self) = @_;
         $self->_setEINTR(0x4);
         $self->_setEBADF(0x9);
         $self->_setEINVAL(0x16);
         $self->_setEFAULT(0xe);
         $self->_setWNOHANG(0x1);
     }
     
     # No need to reset signal handlers within signal handlers for SunOS
     # Though this is redundant, since POSIX handlers will be used anyway.
     sub signalHandlerForSpecialSignal {
         my($self,$signal) = @_;
         $signal =~ tr/A-Z/a-z/;
         'EventServer::Signal::posix_' . $signal;
     }
     sub defaultSignalHandlerFor {
         my($self,$signal) = @_;
     
         my $handler = $self->_handlerPrefix() . $signal;
         unless ( defined(&{$handler}) ) {
     	 eval sprintf('sub %s {$%s++;die "\n"} $%s=0;',
     	 	     $handler,$handler,$handler);
         }
         $handler;
     }
     
     1;
     __END__

Possible problems
=================

Posting from Todd Hoff

     >From: tmh@ictv.com (Todd Hoff)
     Newsgroups: comp.lang.perl
     Subject: Re: Perl 5: alarm BSD vs. SysV
     Date: 3 Apr 1995 10:38:35 -0700
     Organization: ICTV, Inc.
     Lines: 24
     Message-ID: <3lpbqr$gbm@anxious.ictv.com>
     
     In article <3lomapINN334@calvin.lif.icnet.uk>,
     >Have you guys tried re-setting the signal handler within the
     >handler. Some systems reset the signal handler to default
     >after it is called.
     >
     >sig handler {
     >   $SIG{'ALRM'} = 'handler';
     >   ...
     >}
     
     Each UNIX vendor has chosen which version of the "old" signal semantics
     to emulate, thus signal work is not very portable and bug prone.
     Setting the handler in the handler breaks miserably because an interrupt
     can occur before the handler is set. What sucks is that you are
     unlikley to see problems unless you have a loaded machine or
     high interrupt rate, both of which i usually have :-(
     
     The only solution is for perl to use POSIX signals which are safe
     (but harder to understand). As an aside do not do anything in a signal
     handler but set a flag which tells you if you should call a handler
     in the main line logic. Reentrancy bugs are intermitent and nasty.
     --
     Todd Hoff     | My words are my own.
     tmh@ictv.com  | And i have all this extra white space...

In addition, perl has the problem that signals can interrupt a malloc -
and this seems prone to causing a SIGSEGV.

The problems are decreased in this server because most of the time it will
probably be in the select call, in which case signals are likely to hit it
mostly during a select call, not a malloc. But you should be prepared for
your server to die, and have some automated procedure to restart it - like
a cron job. This is a general problem of signals and perl (and C), not a
specific problem of the server.

If you want the general problem illustrated in a simple way, the following
is nice and clear, and will give a core dump after a few seconds:

     @a = qw(1, 2, 3, 4);
     $sig_happened = 0;
     
     $SIG{'ALRM'} = 'sig_handler';
     alarm(1);
     
     while (1)
     {
         foreach $z (@a)
         {
     	reset_handler() if ($sig_happened);
         }
     }
     
     sub reset_handler
     {
         print "Reset the handler\n";
         $sig_happened = 0;
         $SIG{'ALRM'} = 'sig_handler';
         alarm(1);
     }
     
     sub sig_handler
     {
         $sig_happened = 1;
     }
     __END__

Questions and Answers
=====================

Q1. How do I exit the start_server loop.

A1. When there are no more clients registered with the server, the method
noClients() is called. If this method returns a false value then the
start_server loop terminates.  If this returns a true value, then the loop
continues.

The default action is for the server to print the message

     Error: No clients are registered with the server ...

to STDERR and then exit.

To change the default behaviour, create a subclass which redefines
noClients, and use that subclass.  For example

     package MyServer;
     BEGIN {$EventServer::SERVER_CLASS ||= MyServer;}
     @ISA = qw(EventServer);
     require EventServer;
     sub noClients {0} # Just terminate the loop if no clients left.

Note that you don't need this to go into a separate module - it can be in
your main program as an initialization if this is all you need, e.g.

     $EventServer::SERVER_CLASS ||= MyServer;
     @MyServer::ISA = qw(EventServer);
     require EventServer;
     sub MyServer::noClients {0}

AUTHOR
======

This software was developed by Jack Shirazi in the Biomedical Informatics
Unit at the Imperial Cancer Research Fund, and was partly funded by the
European Union Computer Executive Committee under EP6708 `APPLAUSE:
Application and Assessment of Parallel Programming Using Logic'.

COPYRIGHT
=========

Copyright 1995 Imperial Cancer Research Fund, UK. All rights reserved.

This software is distributed under the same terms as Perl.

This program is free software; you can redistribute it and/or modify it
under the terms of either:

a) the GNU General Public License as published by the Free Software
Foundation; either version 1, or (at your option) any later version, or

b) the "Artistic License" which comes with Perl.

This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.  See either the GNU General Public
License or the Artistic License for more details.

MODIFICATION HISTORY
====================

Future Versions (to do)
     Use setitimer if available. Make into SelfLoader class(es) when
     SelfLoader comes on stream? Allow clients option of executing in own
     process (psuedo-threaded). Global store across processes. Mobile
     server. Shadow server.  Automatic termination on dregistration of
     specific clients.

Version 2.3, 5th February 1996
     Added option to return child termination status. Fixed missing
     assignment of arguments in EventServer::_resetVectors which prevented
     closed handles from being deregistered. Made into EventServer package
     only, with Server::Server::EventDriven subclass for backward
     compatibility. Fixed docs. Fixed posix_alarm and resetting_alarm to
     posix_alrm and resetting_alrm.  Altered registering semantics in-line
     with docs (was not returning existing registry key for identical
     registration).

Version 2.2, 8th August 1995
     Bug fix - isReady had wrong number of args.

Version 2.1, 10th July 1995
     Altered signal installers to make SEGV, ILL, PIPE and BUS special
     handlers which are permanently installed.  Added 'Free software'
     copyright.

Version 2.0, 14th June 1995
     Added Andrew Wilcox patch to fix recursive includes in _tryH.
     Invalid arguments to register methods now produce a croak.  Added
     Linux subclass (courtesy of Andrew Wilcox). Added Exportable function
     wrappers to methods. Enabled server loop to terminate. Podified,
     cleaned and added to documentation.  Removed any redundant %SIG 'tie'
     code. Added dummy buffer for gettimeofday syscall to workaround perl
     5.000 (and 5.001?) bug - now works with any perl5 version.

     Changed constants retrieval to not try so hard - now just looks at
     POSIX, Errno and Wait (in perl4 & 5 versions) and uses those - also
     uses classes to get gettimeofday syscall value. Now uses signals
     listed in Config. Now asks the os specific class (obtained from
     Config) for time class and any time class initialization.

     Rewrote sig handlers to mostly do nothing except set a global.
     Rewrote and modularized server loop so that it is easier to alter the
     behaviour in a subclass. Wrapper objects now trigger on same
     'trigger' method. Loop goes through one iteration, then triggers all
     clients in a user defined order (or random order for any not in the
     user defined order). IO clients are guaranteed to be triggered only
     if ready - even if multiple clients are registered on the same handle.

     Added support for POSIX signals - uses them if available.  Fixed
     leaked alarm time logic. Added nested alarm time tests to example.
     Changed all classes to be nested under EventServer.  Changed registry
     keys to be RegistryKey objects. Added client defined events. Altered
     documentation. Put server loop in eval loop. Added signal unblocking
     to handle IRIX bug.

Version 1.2, 10th April 1995
     Altered various internal methods (mainly associated with init) to
     allow subclassing to be more straightforward. Provided example
     subclasses for SunOS4 and IRIX5.  Altered signal handlers to reset
     signal handler after being called to provide support for systems
     which need it.  Removed tie on %SIG due to flakiness (%SIG no longer
     read-only).  Moved the methods required by tie into a separate package
     space. Altered _tryH and _tryCompiling. Fixed bug in
     executeInArrayContextWithTimeout (wasn't handling recursive timeouts
     !). Made 'use strict' and -w clean (though the filehandles need 'no
     strict' in 3 places). Documentation altered.

Version 1.1, 5th April 1995
     EventServer::Time::copy & EventServer::Time::newFromDiff bugfixed,
     EventServer::_noClients error message changed, added
     triggerOnDeregistering method and support methods and altered
     documentation appropriately.

Version 1.0, 10th March 1995
     Base version.


File: pm.info,  Node: Exporter,  Next: ExtUtils/Embed,  Prev: EventServer,  Up: Module List

Implements default import method for modules
********************************************

NAME
====

Exporter - Implements default import method for modules

SYNOPSIS
========

In module ModuleName.pm:

     package ModuleName;
     require Exporter;
     @ISA = qw(Exporter);

     @EXPORT = qw(...);            # symbols to export by default
     @EXPORT_OK = qw(...);         # symbols to export on request
     %EXPORT_TAGS = tag => [...];  # define names for sets of symbols

In other files which wish to use ModuleName:

     use ModuleName;               # import default symbols into my package

     use ModuleName qw(...);       # import listed symbols into my package

     use ModuleName ();            # do not import any symbols

DESCRIPTION
===========

The Exporter module implements a default import method which many modules
choose inherit rather than implement their own.

Perl automatically calls the import method when processing a use statement
for a module. Modules and use are documented in *Note Perlfunc:
(perl.info)perlfunc, and *Note Perlmod: (perl.info)perlmod,. Understanding
the concept of modules and how the use statement operates is important to
understanding the Exporter.

Selecting What To Export
------------------------

Do *not* export method names!

Do *not* export anything else by default without a good reason!

Exports pollute the namespace of the module user.  If you must export try
to use @EXPORT_OK in preference to @EXPORT and avoid short or common
symbol names to reduce the risk of name clashes.

Generally anything not exported is still accessible from outside the
module using the ModuleName::item_name (or $blessed_ref->method) syntax.
By convention you can use a leading underscore on names to informally
indicate that they are 'internal' and not for public use.

(It is actually possible to get private functions by saying:

     my $subref = sub { ... };
     &$subref;

But there's no way to call that directly as a method, since a method must
have a name in the symbol table.)

As a general rule, if the module is trying to be object oriented then
export nothing. If it's just a collection of functions then  @EXPORT_OK
anything but use @EXPORT with caution.

Other module design guidelines can be found in *Note Perlmod:
(perl.info)perlmod,.

Specialised Import Lists
------------------------

If the first entry in an import list begins with !, : or / then the list
is treated as a series of specifications which either add to or delete
from the list of names to import. They are processed left to right.
Specifications are in the form:

     [!]name         This name only
     [!]:DEFAULT     All names in @EXPORT
     [!]:tag         All names in $EXPORT_TAGS{tag} anonymous list
     [!]/pattern/    All names in @EXPORT and @EXPORT_OK which match

A leading ! indicates that matching names should be deleted from the list
of names to import.  If the first specification is a deletion it is
treated as though preceded by :DEFAULT. If you just want to import extra
names in addition to the default set you will still need to include
:DEFAULT explicitly.

e.g., Module.pm defines:

     @EXPORT      = qw(A1 A2 A3 A4 A5);
     @EXPORT_OK   = qw(B1 B2 B3 B4 B5);
     %EXPORT_TAGS = (T1 => [qw(A1 A2 B1 B2)], T2 => [qw(A1 A2 B3 B4)]);

     Note that you cannot use tags in @EXPORT or @EXPORT_OK.
     Names in EXPORT_TAGS must also appear in @EXPORT or @EXPORT_OK.

An application using Module can say something like:

     use Module qw(:DEFAULT :T2 !B3 A3);

Other examples include:

     use Socket qw(!/^[AP]F_/ !SOMAXCONN !SOL_SOCKET);
     use POSIX  qw(:errno_h :termios_h !TCSADRAIN !/^EXIT/);

Remember that most patterns (using //) will need to be anchored with a
leading ^, e.g., `/^EXIT/' rather than `/EXIT/'.

You can say `BEGIN { $Exporter::Verbose=1 }' to see how the specifications
are being processed and what is actually being imported into modules.

Module Version Checking
-----------------------

The Exporter module will convert an attempt to import a number from a
module into a call to $module_name->require_version($value). This can be
used to validate that the version of the module being used is greater than
or equal to the required version.

The Exporter module supplies a default require_version method which checks
the value of $VERSION in the exporting module.

Since the default require_version method treats the $VERSION number as a
simple numeric value it will regard version 1.10 as lower than 1.9. For
this reason it is strongly recommended that you use numbers with at least
two decimal places, e.g., 1.09.

Managing Unknown Symbols
------------------------

In some situations you may want to prevent certain symbols from being
exported. Typically this applies to extensions which have functions or
constants that may not exist on some systems.

The names of any symbols that cannot be exported should be listed in the
`@EXPORT_FAIL' array.

If a module attempts to import any of these symbols the Exporter will will
give the module an opportunity to handle the situation before generating
an error. The Exporter will call an export_fail method with a list of the
failed symbols:

     @failed_symbols = $module_name->export_fail(@failed_symbols);

If the export_fail method returns an empty list then no error is recorded
and all the requested symbols are exported. If the returned list is not
empty then an error is generated for each symbol and the export fails. The
Exporter provides a default export_fail method which simply returns the
list unchanged.

Uses for the export_fail method include giving better error messages for
some symbols and performing lazy architectural checks (put more symbols
into @EXPORT_FAIL by default and then take them out if someone actually
tries to use them and an expensive check shows that they are usable on
that platform).

Tag Handling Utility Functions
------------------------------

Since the symbols listed within %EXPORT_TAGS must also appear in either
@EXPORT or @EXPORT_OK, two utility functions are provided which allow you
to easily add tagged sets of symbols to @EXPORT or @EXPORT_OK:

     %EXPORT_TAGS = (foo => [qw(aa bb cc)], bar => [qw(aa cc dd)]);

     Exporter::export_tags('foo');     # add aa, bb and cc to @EXPORT
     Exporter::export_ok_tags('bar');  # add aa, cc and dd to @EXPORT_OK

Any names which are not tags are added to @EXPORT or @EXPORT_OK unchanged
but will trigger a warning (with -w) to avoid misspelt tags names being
silently added to @EXPORT or @EXPORT_OK. Future versions may make this a
fatal error.


File: pm.info,  Node: ExtUtils/Embed,  Next: ExtUtils/Install,  Prev: Exporter,  Up: Module List

Utilities for embedding Perl in C/C++ applications
**************************************************

NAME
====

ExtUtils::Embed - Utilities for embedding Perl in C/C++ applications

SYNOPSIS
========

     perl -MExtUtils::Embed -e xsinit
     perl -MExtUtils::Embed -e ldopts

DESCRIPTION
===========

ExtUtils::Embed provides utility functions for embedding a Perl interpreter
and extensions in your C/C++ applications.  Typically, an application
*Makefile* will invoke ExtUtils::Embed functions while building your
application.

@EXPORT
=======

ExtUtils::Embed exports the following functions:

xsinit(), ldopts(), ccopts(), perl_inc(), ccflags(), ccdlflags(),
xsi_header(), xsi_protos(), xsi_body()

FUNCTIONS
=========

xsinit()
     Generate C/C++ code for the XS initializer function.

     When invoked as ``perl -MExtUtils::Embed -e xsinit --`' the following
     options are recognized:

     *-o* <output filename> (Defaults to *perlxsi.c*)

     *-o STDOUT* will print to STDOUT.

     *-std* (Write code for extensions that are linked with the current
     Perl.)

     Any additional arguments are expected to be names of modules to
     generate code for.

     When invoked with parameters the following are accepted and optional:

     `xsinit($filename,$std,[@modules])'

     Where,

     *$filename* is equivalent to the *-o* option.

     *$std* is boolean, equivalent to the *-std* option.

     *[@modules]* is an array ref, same as additional arguments mentioned
     above.

Examples
          perl -MExtUtils::Embed -e xsinit -- -o xsinit.c Socket

     This will generate code with an *xs_init* function that glues the
     perl *Socket::bootstrap* function to the C *boot_Socket* function and
     writes it to a file named "xsinit.c".

     Note that DynaLoader is a special case where it must call
     *boot_DynaLoader* directly.

          perl -MExtUtils::Embed -e xsinit

     This will generate code for linking with DynaLoader and each static
     extension found in *$Config{static_ext}*.  The code is written to the
     default file name *perlxsi.c*.

          perl -MExtUtils::Embed -e xsinit -- -o xsinit.c -std DBI DBD::Oracle

     Here, code is written for all the currently linked extensions along
     with code for *DBI* and *DBD::Oracle*.

     If you have a working DynaLoader then there is rarely any need to
     statically link in any other extensions.

ldopts()
     Output arguments for linking the Perl library and extensions to your
     application.

     When invoked as ``perl -MExtUtils::Embed -e ldopts --`' the following
     options are recognized:

     *-std*

     Output arguments for linking the Perl library and any extensions
     linked with the current Perl.

     -I <path1:path2>

     Search path for ModuleName.a archives.  Default path is *@INC*.
     Library archives are expected to be found as
     */some/path/auto/ModuleName/ModuleName.a* For example, when looking
     for *Socket.a* relative to a search path, we should find
     *auto/Socket/Socket.a*

     When looking for *DBD::Oracle* relative to a search path, we should
     find *auto/DBD/Oracle/Oracle.a*

     Keep in mind, you can always supply */my/own/path/ModuleName.a* as an
     additional linker argument.

     *-*  <list of linker args>

     Additional linker arguments to be considered.

     Any additional arguments found before the *-* token are expected to
     be names of modules to generate code for.

     When invoked with parameters the following are accepted and optional:

     `ldopts($std,[@modules],[@link_args],$path)'

     Where,

     *$std* is boolean, equivalent to the *-std* option.

     *[@modules]* is equivalent to additional arguments found before the
     *-* token.

     *[@link_args]* is equivalent to arguments found after the *-* token.

     *$path* is equivalent to the -I option.

     In addition, when ldopts is called with parameters, it will return
     the argument string rather than print it to STDOUT.

Examples
          perl -MExtUtils::Embed -e ldopts

     This will print arguments for linking with *libperl.a*, DynaLoader and
     extensions found in *$Config{static_ext}*.  This includes libraries
     found in *$Config{libs}* and the first ModuleName.a library for each
     extension that is found by searching *@INC* or the path specifed by
     the -I option.  In addition, when ModuleName.a is found, additional
     linker arguments are picked up from the *extralibs.ld* file in the
     same directory.

          perl -MExtUtils::Embed -e ldopts -- -std Socket

     This will do the same as the above example, along with printing
     additional arguments for linking with the Socket extension.

          perl -MExtUtils::Embed -e ldopts -- DynaLoader

     This will print arguments for linking with just the DynaLoader
     extension and *libperl.a*.

          perl -MExtUtils::Embed -e ldopts -- -std Msql -- -L/usr/msql/lib -lmsql

     Any arguments after the second '-' token are additional linker
     arguments that will be examined for potential conflict.  If there is
     no conflict, the additional arguments will be part of the output.

perl_inc()
     For including perl header files this function simply prints:

          -I$Config{archlib}/CORE

     So, rather than having to say:

          perl -MConfig -e 'print "-I$Config{archlib}/CORE"'

     Just say:

          perl -MExtUtils::Embed -e perl_inc

ccflags(), ccdlflags()
     These functions simply print $Config{ccflags} and $Config{ccdlflags}

ccopts()
     This function combines perl_inc(), ccflags() and ccdlflags() into one.

xsi_header()
     This function simply returns a string defining the same *EXTERN_C*
     macro as *perlmain.c* along with #including *perl.h* and *EXTERN.h*.

xsi_protos(@modules)
     This function returns a string of *boot_$ModuleName* prototypes for
     each @modules.

xsi_body(@modules)
     This function returns a string of calls to *newXS()* that glue the
     module *bootstrap* function to *boot_ModuleName* for each @modules.

     xsinit() uses the xsi_* functions to generate most of it's code.

EXAMPLES
========

For examples on how to use *ExtUtils::Embed* for building C/C++
applications with embedded perl, see the eg/ directory and *Note
Perlembed: (perl.info)perlembed,.

=head1 SEE ALSO

*Note Perlembed: (perl.info)perlembed,

AUTHOR
======

Doug MacEachern <`dougm@osf.org'>

Based on ideas from Tim Bunce <`Tim.Bunce@ig.co.uk'> and *minimod.pl* by
Andreas Koenig <`k@anna.in-berlin.de'> and Tim Bunce.


File: pm.info,  Node: ExtUtils/Install,  Next: ExtUtils/Liblist,  Prev: ExtUtils/Embed,  Up: Module List

install files from here to there
********************************

NAME
====

ExtUtils::Install - install files from here to there

SYNOPSIS
========

*use ExtUtils::Install;*

*install($hashref,$verbose,$nonono);*

*uninstall($packlistfile,$verbose,$nonono);*

*pm_to_blib($hashref);*

DESCRIPTION
===========

Both install() and uninstall() are specific to the way ExtUtils::MakeMaker
handles the installation and deinstallation of perl modules. They are not
designed as general purpose tools.

install() takes three arguments. A reference to a hash, a verbose switch
and a don't-really-do-it switch. The hash ref contains a mapping of
directories: each key/value pair is a combination of directories to be
copied. Key is a directory to copy from, value is a directory to copy to.
The whole tree below the "from" directory will be copied preserving
timestamps and permissions.

There are two keys with a special meaning in the hash: "read" and "write".
After the copying is done, install will write the list of target files to
the file named by `$hashref->{write}'. If there is another file named by
`$hashref->{read}', the contents of this file will be merged into the
written file. The read and the written file may be identical, but on AFS
it is quite likely, people are installing to a different directory than
the one where the files later appear.

uninstall() takes as first argument a file containing filenames to be
unlinked. The second argument is a verbose switch, the third is a
no-don't-really-do-it-now switch.

pm_to_blib() takes a hashref as the first argument and copies all keys of
the hash to the corresponding values efficiently. Filenames with the
extension pm are autosplit. Second argument is the autosplit directory.


File: pm.info,  Node: ExtUtils/Liblist,  Next: ExtUtils/MM_OS2,  Prev: ExtUtils/Install,  Up: Module List

determine libraries to use and how to use them
**********************************************

NAME
====

ExtUtils::Liblist - determine libraries to use and how to use them

SYNOPSIS
========

`require ExtUtils::Liblist;'

`ExtUtils::Liblist::ext($potential_libs, $Verbose);'

DESCRIPTION
===========

This utility takes a list of libraries in the form `-llib1 -llib2 -llib3'
and prints out lines suitable for inclusion in an extension Makefile.
Extra library paths may be included with the form `-L/another/path' this
will affect the searches for all subsequent libraries.

It returns an array of four scalar values: EXTRALIBS, BSLOADLIBS,
LDLOADLIBS, and LD_RUN_PATH.

Dependent libraries can be linked in one of three ways:

   * For static extensions

     by the ld command when the perl binary is linked with the extension
     library. See EXTRALIBS below.

   * For dynamic extensions

     by the ld command when the shared object is built/linked. See
     LDLOADLIBS below.

   * For dynamic extensions

     by the DynaLoader when the shared object is loaded. See BSLOADLIBS
     below.

EXTRALIBS
---------

List of libraries that need to be linked with when linking a perl binary
which includes this extension Only those libraries that actually exist are
included.  These are written to a file and used when linking perl.

LDLOADLIBS and LD_RUN_PATH
--------------------------

List of those libraries which can or must be linked into the shared
library when created using ld. These may be static or dynamic libraries.
LD_RUN_PATH is a colon separated list of the directories in LDLOADLIBS. It
is passed as an environment variable to the process that links the shared
library.

BSLOADLIBS
----------

List of those libraries that are needed but can be linked in dynamically
at run time on this platform.  SunOS/Solaris does not need this because ld
records the information (from LDLOADLIBS) into the object file.  This list
is used to create a .bs (bootstrap) file.

PORTABILITY
===========

This module deals with a lot of system dependencies and has quite a few
architecture specific *if*s in the code.

SEE ALSO
========

*Note ExtUtils/MakeMaker: ExtUtils/MakeMaker,


File: pm.info,  Node: ExtUtils/MM_OS2,  Next: ExtUtils/MM_Unix,  Prev: ExtUtils/Liblist,  Up: Module List

methods to override UN*X behaviour in ExtUtils::MakeMaker
*********************************************************

NAME
====

ExtUtils::MM_OS2 - methods to override UN*X behaviour in
ExtUtils::MakeMaker

SYNOPSIS
========

     use ExtUtils::MM_OS2; # Done internally by ExtUtils::MakeMaker if needed

DESCRIPTION
===========

See ExtUtils::MM_Unix for a documentation of the methods provided there.
This package overrides the implementation of these methods, not the
semantics.


File: pm.info,  Node: ExtUtils/MM_Unix,  Next: ExtUtils/MM_VMS,  Prev: ExtUtils/MM_OS2,  Up: Module List

methods used by ExtUtils::MakeMaker
***********************************

NAME
====

ExtUtils::MM_Unix - methods used by ExtUtils::MakeMaker

SYNOPSIS
========

`require ExtUtils::MM_Unix;'

DESCRIPTION
===========

The methods provided by this package are designed to be used in
conjunction with ExtUtils::MakeMaker. When MakeMaker writes a Makefile, it
creates one or more objects that inherit their methods from a package
`MM'. MM itself doesn't provide any methods, but it ISA ExtUtils::MM_Unix
class. The inheritance tree of MM lets operating specific packages take
the responsibility for all the methods provided by MM_Unix. We are trying
to reduce the number of the necessary overrides by defining rather
primitive operations within ExtUtils::MM_Unix.

If you are going to write a platform specific MM package, please try to
limit the necessary overrides to primitive methods, and if it is not
possible to do so, let's work out how to achieve that gain.

If you are overriding any of these methods in your Makefile.PL (in the MY
class), please report that to the makemaker mailing list. We are trying to
minimize the necessary method overrides and switch to data driven
Makefile.PLs wherever possible. In the long run less methods will be
overridable via the MY class.

METHODS
=======

The following description of methods is still under development. Please
refer to the code for not suitably documented sections and complain loudly
to the makemaker mailing list.

Not all of the methods below are overridable in a Makefile.PL. Overridable
methods are marked as (o). All methods are overridable by a platform
specific MM_*.pm file (See *Note ExtUtils/MM_VMS: ExtUtils/MM_VMS, and
*Note ExtUtils/MM_OS2: ExtUtils/MM_OS2,).

Preloaded methods
-----------------

canonpath
     No physical check on the filesystem, but a logical cleanup of a path.
     On UNIX eliminated successive slashes and successive "/.".

catdir
     Concatenate two or more directory names to form a complete path ending
     with a directory. But remove the trailing slash from the resulting
     string, because it doesn't look good, isn't necessary and confuses
     OS2. Of course, if this is the root directory, don't cut off the
     trailing slash :-)

catfile
     Concatenate one or more directory names and a filename to form a
     complete path ending with a filename

curdir
     Returns a string representing of the current directory.  "." on UNIX.

rootdir
     Returns a string representing of the root directory.  "/" on UNIX.

updir
     Returns a string representing of the parent directory.  ".." on UNIX.

SelfLoaded methods
------------------

c_o (o)
     Defines the suffix rules to compile different flavors of C files to
     object files.

cflags (o)
     Does very much the same as the cflags script in the perl
     distribution. It doesn't return the whole compiler command line, but
     initializes all of its parts. The const_cccmd method then actually
     returns the definition of the CCCMD macro which uses these parts.

clean (o)
     Defines the clean target.

const_cccmd (o)
     Returns the full compiler call for C programs and stores the
     definition in CONST_CCCMD.

const_config (o)
     Defines a couple of constants in the Makefile that are imported from
     %Config.

const_loadlibs (o)
     Defines EXTRALIBS, LDLOADLIBS, BSLOADLIBS, LD_RUN_PATH. See *Note
     ExtUtils/Liblist: ExtUtils/Liblist, for details.

constants (o)
     Initializes lots of constants and .SUFFIXES and .PHONY

depend (o)
     Same as macro for the depend attribute.

dir_target (o)
     Takes an array of directories that need to exist and returns a
     Makefile entry for a .exists file in these directories. Returns
     nothing, if the entry has already been processed. We're helpless
     though, if the same directory comes as $(FOO) _and_ as "bar". Both of
     them get an entry, that's why we use "::".

dist (o)
     Defines a lot of macros for distribution support.

dist_basics (o)
     Defines the targets distclean, distcheck, skipcheck, manifest.

dist_ci (o)
     Defines a check in target for RCS.

dist_core (o)
     Defeines the targets dist, tardist, zipdist, uutardist, shdist

dist_dir (o)
     Defines the scratch directory target that will hold the distribution
     before tar-ing (or shar-ing).

dist_test (o)
     Defines a target that produces the distribution in the
     scratchdirectory, and runs 'perl Makefile.PL; make ;make test' in that
     subdirectory.

dlsyms (o)
     Used by AIX and VMS to define DL_FUNCS and DL_VARS and write the *.exp
     files.

dynamic (o)
     Defines the dynamic target.

dynamic_bs (o)
     Defines targets for bootstrap files.

dynamic_lib (o)
     Defines how to produce the *.so (or equivalent) files.

exescan
     Deprecated method. Use libscan instead.

extliblist
     Called by init_others, and calls ext ExtUtils::Liblist. See *Note
     ExtUtils/Liblist: ExtUtils/Liblist, for details.

file_name_is_absolute
     Takes as argument a path and returns true, if it is an absolute path.

find_perl
     Finds the executables PERL and FULLPERL

Methods to actually produce chunks of text for the Makefile
-----------------------------------------------------------

The methods here are called in the order specified by
@ExtUtils::MakeMaker::MM_Sections. This manpage reflects the order as well
as possible. Some methods call each other, so in doubt refer to the code.

force (o)
     Just writes FORCE:

guess_name
     Guess the name of this package by examining the working directory's
     name. MakeMaker calls this only if the developer has not supplied a
     NAME attribute.

has_link_code
     Returns true if C, XS, MYEXTLIB or similar objects exist within this
     object that need a compiler. Does not descend into subdirectories as
     needs_linking() does.

init_dirscan
     Initializes DIR, XS, PM, C, O_FILES, H, PL_FILES, MAN*PODS, EXE_FILES.

init_main
     Initializes NAME, FULLEXT, BASEEXT, PARENT_NAME, DLBASE, PERL_SRC,
     PERL_LIB, PERL_ARCHLIB, PERL_INC, INSTALLDIRS, INST_*, INSTALL*,
     PREFIX, CONFIG, AR, AR_STATIC_ARGS, LD, OBJ_EXT, LIB_EXT, MAP_TARGET,
     LIBPERL_A, VERSION_FROM, VERSION, DISTNAME, VERSION_SYM.

init_others
     Initializes EXTRALIBS, BSLOADLIBS, LDLOADLIBS, LIBS, LD_RUN_PATH,
     OBJECT, BOOTDEP, PERLMAINCC, LDFROM, LINKTYPE, NOOP, FIRST_MAKEFILE,
     MAKEFILE, NOECHO, RM_F, RM_RF, TOUCH, CP, MV, CHMOD, UMASK_NULL

install (o)
     Defines the install target.

installbin (o)
     Defines targets to install EXE_FILES.

libscan (o)
     Takes a path to a file that is found by init_dirscan and returns false
     if we don't want to include this file in the library. Mainly used to
     exclude RCS, CVS, and SCCS directories from installation.

linkext (o)
     Defines the linkext target which in turn defines the LINKTYPE.

lsdir
     Takes as arguments a directory name and a regular expression. Returns
     all entries in the directory that match the regular expression.

macro (o)
     Simple subroutine to insert the macros defined by the macro attribute
     into the Makefile.

makeaperl (o)
     Called by staticmake. Defines how to write the Makefile to produce a
     static new perl.

makefile (o)
     Defines how to rewrite the Makefile.

manifypods (o)
     Defines targets and routines to translate the pods into manpages and
     put them into the INST_* directories.

maybe_command
     Returns true, if the argument is likely to be a command.

maybe_command_in_dirs
     method under development. Not yet used. Ask Ilya :-)

needs_linking (o)
     Does this module need linking? Looks into subdirectory objects (see
     also has_link_code())

nicetext
     misnamed method (will have to be changed). The MM_Unix method just
     returns the argument without further processing.

     On VMS used to insure that colons marking targets are preceded by
     space - most Unix Makes don't need this, but it's necessary under VMS
     to distinguish the target delimiter from a colon appearing as part of
     a filespec.

parse_version
     parse a file and return what you think is $VERSION in this file set to

pasthru (o)
     Defines the string that is passed to recursive make calls in
     subdirectories.

path
     Takes no argument, returns the environment variable PATH as an array.

perl_script
     Takes one argument, a file name, and returns the file name, if the
     argument is likely to be a perl script. On MM_Unix this is true for
     any ordinary, readable file.

perldepend (o)
     Defines the dependency from all *.h files that come with the perl
     distribution.

pm_to_blib
     Defines target that copies all files in the hash PM to their
     destination and autosplits them. See `pm_to_blib', *Note
     ExtUtils/Install: ExtUtils/Install,

post_constants (o)
     Returns an empty string per default. Dedicated to overrides from
     within Makefile.PL after all constants have been defined.

post_initialize (o)
     Returns an empty string per default. Used in Makefile.PLs to add some
     chunk of text to the Makefile after the object is initialized.

postamble (o)
     Returns an empty string. Can be used in Makefile.PLs to write some
     text to the Makefile at the end.

prefixify
     Check a path variable in $self from %Config, if it contains a prefix,
     and replace it with another one.

     Takes as arguments an attribute name, a search prefix and a
     replacement prefix. Changes the attribute in the object.

processPL (o)
     Defines targets to run *.PL files.

realclean (o)
     Defines the realclean target.

replace_manpage_separator
     Takes the name of a package, which may be a nested package, in the
     form Foo/Bar and replaces the slash with `::'. Returns the
     replacement.

static (o)
     Defines the static target.

static_lib (o)
     Defines how to produce the *.a (or equivalent) files.

staticmake (o)
     Calls makeaperl.

subdir_x (o)
     Helper subroutine for subdirs

subdirs (o)
     Defines targets to process subdirectories.

test (o)
     Defines the test targets.

test_via_harness (o)
     Helper method to write the test targets

test_via_script (o)
     Other helper method for test.

tool_autosplit (o)
     Defines a simple perl call that runs autosplit. May be deprecated by
     pm_to_blib soon.

tools_other (o)
     Defines SHELL, LD, TOUCH, CP, MV, RM_F, RM_RF, CHMOD, UMASK_NULL in
     the Makefile. Also defines the perl programs MKPATH,
     WARN_IF_OLD_PACKLIST, MOD_INSTALL. DOC_INSTALL, and UNINSTALL.

tool_xsubpp (o)
     Determines typemaps, xsubpp version, prototype behaviour.

top_targets (o)
     Defines the targets all, subdirs, config, and O_FILES

writedoc
     Obsolete, depecated method. Not used since Version 5.21.

xs_c (o)
     Defines the suffix rules to compile XS files to C.

xs_o (o)
     Defines suffix rules to go from XS to object files directly. This is
     only intended for broken make implementations.

SEE ALSO
========

*Note ExtUtils/MakeMaker: ExtUtils/MakeMaker,


File: pm.info,  Node: ExtUtils/MM_VMS,  Next: ExtUtils/MakeMaker,  Prev: ExtUtils/MM_Unix,  Up: Module List

methods to override UN*X behaviour in ExtUtils::MakeMaker
*********************************************************

NAME
====

ExtUtils::MM_VMS - methods to override UN*X behaviour in
ExtUtils::MakeMaker

SYNOPSIS
========

     use ExtUtils::MM_VMS; # Done internally by ExtUtils::MakeMaker if needed

DESCRIPTION
===========

See ExtUtils::MM_Unix for a documentation of the methods provided there.
This package overrides the implementation of these methods, not the
semantics.

Methods always loaded
---------------------

eliminate_macros
     Expands MM[KS]/Make macros in a text string, using the contents of
     identically named elements of `%$self', and returns the result as a
     file specification in Unix syntax.

fixpath
     Catchall routine to clean up problem MM[SK]/Make macros.  Expands
     macros in any directory specification, in order to avoid juxtaposing
     two VMS-syntax directories when MM[SK] is run.  Also expands
     expressions which are all macro, so that we can tell how long the
     expansion is, and avoid overrunning DCL's command buffer when MM[KS]
     is running.

     If optional second argument has a TRUE value, then the return string
     is a VMS-syntax directory specification, otherwise it is a VMS-syntax
     file specification.

catdir
     Concatenates a list of file specifications, and returns the result as
     a VMS-syntax directory specification.

catfile
     Concatenates a list of file specifications, and returns the result as
     a VMS-syntax directory specification.

curdir (override)
     Returns a string representing of the current directory.

rootdir (override)
     Returns a string representing of the root directory.

updir (override)
     Returns a string representing of the parent directory.

SelfLoaded methods
------------------

Those methods which override default MM_Unix methods are marked
"(override)", while methods unique to MM_VMS are marked "(specific)".  For
overridden methods, documentation is limited to an explanation of why this
method overrides the MM_Unix method; see the ExtUtils::MM_Unix
documentation for more details.

guess_name (override)
     Try to determine name of extension being built.  We begin with the
     name of the current directory.  Since VMS filenames are
     case-insensitive, however, we look for a `.pm' file whose name
     matches that of the current directory (presumably the 'main' `.pm'
     file for this extension), and try to find a package statement from
     which to obtain the Mixed::Case package name.

find_perl (override)
     Use VMS file specification syntax and CLI commands to find and invoke
     Perl images.

path (override)
     Translate logical name DCL$PATH as a searchlist, rather than trying
     to split string value of `$ENV{'PATH'}'.

maybe_command (override)
     Follows VMS naming conventions for executable files.  If the name
     passed in doesn't exactly match an executable file, appends `.Exe' to
     check for executable image, and `.Com' to check for DCL procedure.
     If this fails, checks `Sys$Share:' for an executable file having the
     name specified.  Finally, appends `.Exe' and checks again.

maybe_command_in_dirs (override)
     Uses DCL argument quoting on test command line.

perl_script (override)
     If name passed in doesn't specify a readable file, appends `.pl' and
     tries again, since it's customary to have file types on all files
     under VMS.

file_name_is_absolute (override)
     Checks for VMS directory spec as well as Unix separators.

replace_manpage_separator
     Use as separator a character which is legal in a VMS-syntax file name.

init_others (override)
     Provide VMS-specific forms of various utility commands, then hand off
     to the default MM_Unix method.

constants (override)
     Fixes up numerous file and directory macros to insure VMS syntax
     regardless of input syntax.  Also adds a few VMS-specific macros and
     makes lists of files comma-separated.

const_loadlibs (override)
     Basically a stub which passes through library specfications provided
     by the caller.  Will be updated or removed when VMS support is added
     to ExtUtils::Liblist.

cflags (override)
     Bypass shell script and produce qualifiers for CC directly (but warn
     user if a shell script for this extension exists).  Fold multiple
     /Defines into one, since some C compilers pay attention to only one
     instance of this qualifier on the command line.

const_cccmd (override)
     Adds directives to point C preprocessor to the right place when
     handling #include <sys/foo.h> directives.  Also constructs CC command
     line a bit differently than MM_Unix method.

pm_to_blib (override)
     DCL *still* accepts a maximum of 255 characters on a command line, so
     we write the (potentially) long list of file names to a temp file,
     then persuade Perl to read it instead of the command line to find
     args.

tool_autosplit (override)
     Use VMS-style quoting on command line.

tool_sxubpp (override)
     Use VMS-style quoting on xsubpp command line.

xsubpp_version (override)
     Test xsubpp exit status according to VMS rules ($sts & 1 ==> good)
     rather than Unix rules ($sts == 0 ==> good).

tools_other (override)
     Adds a few MM[SK] macros, and shortens some the installatin commands,
     in order to stay under DCL's 255-character limit.  Also changes
     EQUALIZE_TIMESTAMP to set revision date of target file to one second
     later than source file, since MMK interprets precisely equal revision
     dates for a source and target file as a sign that the target needs to
     be updated.

dist (override)
     Provide VMSish defaults for some values, then hand off to default
     MM_Unix method.

c_o (override)
     Use VMS syntax on command line.  In particular, $(DEFINE) and
     $(PERL_INC) have been pulled into $(CCCMD).  Also use MM[SK] macros.

xs_c (override)
     Use MM[SK] macros.

xs_o (override)
     Use MM[SK] macros, and VMS command line for C compiler.

top_targets (override)
     Use VMS quoting on command line for Version_check.

dlsyms (override)
     Create VMS linker options files specifying universal symbols for this
     extension's shareable image, and listing other shareable images or
     libraries to which it should be linked.

dynamic_lib (override)
     Use VMS Link command.

dynamic_bs (override)
     Use VMS-style quoting on Mkbootstrap command line.

static_lib (override)
     Use VMS commands to manipulate object library.

manifypods (override)
     Use VMS-style quoting on command line, and VMS logical name to
     specify fallback location at build time if we can't find pod2man.

processPL (override)
     Use VMS-style quoting on command line.

installbin (override)
     Stay under DCL's 255 character command line limit once again by
     splitting potentially long list of files across multiple lines in
     realclean target.

subdir_x (override)
     Use VMS commands to change default directory.

clean (override)
     Split potentially long list of files across multiple commands (in
     order to stay under the magic command line limit).  Also use MM[SK]
     commands for handling subdirectories.

realclean (override)
     Guess what we're working around?  Also, use MM[SK] for subdirectories.

dist_basics (override)
     Use VMS-style quoting on command line.

dist_core (override)
     Syntax for invoking `VMS_Share' differs from that for Unix `shar', so
     `shdist' target actions are VMS-specific.

dist_dir (override)
     Use VMS-style quoting on command line.

dist_test (override)
     Use VMS commands to change default directory, and use VMS-style
     quoting on command line.

install (override)
     Work around DCL's 255 character limit several times,and use VMS-style
     command line quoting in a few cases.

perldepend (override)
     Use VMS-style syntax for files; it's cheaper to just do it directly
     here than to have the MM_Unix method call catfile repeatedly.  Also
     use config.vms as source of original config data if the Perl
     distribution is available; config.sh is an ancillary file under VMS.
     Finally, if we have to rebuild Config.pm, use MM[SK] to do it.

makefile (override)
     Use VMS commands and quoting.

test (override)
     Use VMS commands for handling subdirectories.

test_via_harness (override)
     Use VMS-style quoting on command line.

test_via_script (override)
     Use VMS-style quoting on command line.

makeaperl (override)
     Undertake to build a new set of Perl images using VMS commands.  Since
     VMS does dynamic loading, it's not necessary to statically link each
     extension into the Perl image, so this isn't the normal build path.
     Consequently, it hasn't really been tested, and may well be
     incomplete.

nicetext (override)
     Insure that colons marking targets are preceded by space, in order to
     distinguish the target delimiter from a colon appearing as part of a
     filespec.


File: pm.info,  Node: ExtUtils/MakeMaker,  Next: ExtUtils/Manifest,  Prev: ExtUtils/MM_VMS,  Up: Module List

create an extension Makefile
****************************

NAME
====

ExtUtils::MakeMaker - create an extension Makefile

SYNOPSIS
========

`use ExtUtils::MakeMaker;'

`WriteMakefile( ATTRIBUTE => VALUE [, ...] );'

which is really

`MM->new(\%att)->flush;'

DESCRIPTION
===========

This utility is designed to write a Makefile for an extension module from
a Makefile.PL. It is based on the Makefile.SH model provided by Andy
Dougherty and the perl5-porters.

It splits the task of generating the Makefile into several subroutines
that can be individually overridden.  Each subroutine returns the text it
wishes to have written to the Makefile.

MakeMaker is object oriented. Each directory below the current directory
that contains a Makefile.PL. Is treated as a separate object. This makes
it possible to write an unlimited number of Makefiles with a single
invocation of WriteMakefile().

How To Write A Makefile.PL
--------------------------

The short answer is: Don't. Run h2xs(1) before you start thinking about
writing a module. For so called pm-only modules that consist of `*.pm'
files only, h2xs has the very useful -X switch. This will generate dummy
files of all kinds that are useful for the module developer.

The medium answer is:

     use ExtUtils::MakeMaker;
     WriteMakefile( NAME => "Foo::Bar" );

The long answer is below.

Default Makefile Behaviour
--------------------------

The generated Makefile enables the user of the extension to invoke

     perl Makefile.PL # optionally "perl Makefile.PL verbose"
     make
     make test        # optionally set TEST_VERBOSE=1
     make install     # See below

The Makefile to be produced may be altered by adding arguments of the form
`KEY=VALUE'. E.g.

     perl Makefile.PL PREFIX=/tmp/myperl5

Other interesting targets in the generated Makefile are

     make config     # to check if the Makefile is up-to-date
     make clean      # delete local temp files (Makefile gets renamed)
     make realclean  # delete derived files (including ./blib)
     make ci         # check in all the files in the MANIFEST file
     make dist       # see below the Distribution Support section

make test
---------

MakeMaker checks for the existence of a file named "test.pl" in the
current directory and if it exists it adds commands to the test target of
the generated Makefile that will execute the script with the proper set of
perl -I options.

MakeMaker also checks for any files matching glob("t/*.t"). It will add
commands to the test target of the generated Makefile that execute all
matching files via the *Note Test/Harness: Test/Harness, module with the -I
switches set correctly.

make install
------------

make alone puts all relevant files into directories that are named by the
macros INST_LIB, INST_ARCHLIB, INST_SCRIPT, INST_MAN1DIR, and
INST_MAN3DIR. All these default to something below ./blib if you are *not*
building below the perl source directory. If you *are* building below the
perl source, INST_LIB and INST_ARCHLIB default to  ../../lib, and
INST_SCRIPT is not defined.

The install target of the generated Makefile copies the files found below
each of the INST_* directories to their INSTALL* counterparts. Which
counterparts are chosen depends on the setting of INSTALLDIRS according to
the following table:

     INSTALLDIRS set to
            	       	        perl   	          site

     INST_ARCHLIB    INSTALLARCHLIB    INSTALLSITEARCH
     INST_LIB        INSTALLPRIVLIB    INSTALLSITELIB
     INST_BIN                  INSTALLBIN
     INST_SCRIPT              INSTALLSCRIPT
     INST_MAN1DIR             INSTALLMAN1DIR
     INST_MAN3DIR             INSTALLMAN3DIR

The INSTALL... macros in turn default to their %Config
($Config{installprivlib}, $Config{installarchlib}, etc.) counterparts.

You can check the values of these variables on your system with

     perl -MConfig -le 'print join $/, map
         sprintf("%20s: %s", $_, $Config{$_}),
         grep /^install/, keys %Config'

And to check the sequence in which the library directories are searched by
perl, run

     perl -le 'print join $/, @INC'

PREFIX attribute
----------------

The PREFIX attribute can be used to set the INSTALL* attributes in one go.
The quickest way to install a module in a non-standard place

     perl Makefile.PL PREFIX=~

This will replace the string specified by $Config{prefix} in all
$Config{install*} values.

Note, that the tilde expansion is done by MakeMaker, not by perl by
default, nor by make.

If the user has superuser privileges, and is not working on AFS (Andrew
File System) or relatives, then the defaults for INSTALLPRIVLIB,
INSTALLARCHLIB, INSTALLSCRIPT, etc. will be appropriate, and this
incantation will be the best:

     perl Makefile.PL; make; make test
     make install

make install per default writes some documentation of what has been done
into the file `$(INSTALLARCHLIB)/perllocal.pod'. This feature can be
bypassed by calling make pure_install.

AFS users
---------

will have to specify the installation directories as these most probably
have changed since perl itself has been installed. They will have to do
this by calling

     perl Makefile.PL INSTALLSITELIB=/afs/here/today \
     	INSTALLSCRIPT=/afs/there/now INSTALLMAN3DIR=/afs/for/manpages
     make

Be careful to repeat this procedure every time you recompile an extension,
unless you are sure the AFS installation directories are still valid.

Static Linking of a new Perl Binary
-----------------------------------

An extension that is built with the above steps is ready to use on systems
supporting dynamic loading. On systems that do not support dynamic
loading, any newly created extension has to be linked together with the
available resources. MakeMaker supports the linking process by creating
appropriate targets in the Makefile whenever an extension is built. You
can invoke the corresponding section of the makefile with

     make perl

That produces a new perl binary in the current directory with all
extensions linked in that can be found in INST_ARCHLIB , SITELIBEXP, and
PERL_ARCHLIB. To do that, MakeMaker writes a new Makefile, on UNIX, this
is called Makefile.aperl (may be system dependent). If you want to force
the creation of a new perl, it is recommended, that you delete this
Makefile.aperl, so the directories are searched-through for linkable
libraries again.

The binary can be installed into the directory where perl normally resides
on your machine with

     make inst_perl

To produce a perl binary with a different name than `perl', either say

     perl Makefile.PL MAP_TARGET=myperl
     make myperl
     make inst_perl

or say

     perl Makefile.PL
     make myperl MAP_TARGET=myperl
     make inst_perl MAP_TARGET=myperl

In any case you will be prompted with the correct invocation of the
`inst_perl' target that installs the new binary into INSTALLBIN.

make inst_perl per default writes some documentation of what has been done
into the file `$(INSTALLARCHLIB)/perllocal.pod'. This can be bypassed by
calling make pure_inst_perl.

Warning: the inst_perl: target will most probably overwrite your existing
perl binary. Use with care!

Sometimes you might want to build a statically linked perl although your
system supports dynamic loading. In this case you may explicitly set the
linktype with the invocation of the Makefile.PL or make:

     perl Makefile.PL LINKTYPE=static    # recommended

or

     make LINKTYPE=static                # works on most systems

Determination of Perl Library and Installation Locations
--------------------------------------------------------

MakeMaker needs to know, or to guess, where certain things are located.
Especially INST_LIB and INST_ARCHLIB (where to put the files during the
make(1) run), PERL_LIB and PERL_ARCHLIB (where to read existing modules
from), and PERL_INC (header files and `libperl*.*').

Extensions may be built either using the contents of the perl source
directory tree or from the installed perl library. The recommended way is
to build extensions after you have run 'make install' on perl itself. You
can do that in any directory on your hard disk that is not below the perl
source tree. The support for extensions below the ext directory of the
perl distribution is only good for the standard extensions that come with
perl.

If an extension is being built below the `ext/' directory of the perl
source then MakeMaker will set PERL_SRC automatically (e.g., `../..').  If
PERL_SRC is defined and the extension is recognized as a standard
extension, then other variables default to the following:

     PERL_INC     = PERL_SRC
     PERL_LIB     = PERL_SRC/lib
     PERL_ARCHLIB = PERL_SRC/lib
     INST_LIB     = PERL_LIB
     INST_ARCHLIB = PERL_ARCHLIB

If an extension is being built away from the perl source then MakeMaker
will leave PERL_SRC undefined and default to using the installed copy of
the perl library. The other variables default to the following:

     PERL_INC     = $archlibexp/CORE
     PERL_LIB     = $privlibexp
     PERL_ARCHLIB = $archlibexp
     INST_LIB     = ./blib/lib
     INST_ARCHLIB = ./blib/arch

If perl has not yet been installed then PERL_SRC can be defined on the
command line as shown in the previous section.

Which architecture dependent directory?
---------------------------------------

If you don't want to keep the defaults for the INSTALL* macros, MakeMaker
helps you to minimize the typing needed: the usual relationship between
INSTALLPRIVLIB and INSTALLARCHLIB is determined by Configure at perl
compilation time. MakeMaker supports the user who sets INSTALLPRIVLIB. If
INSTALLPRIVLIB is set, but INSTALLARCHLIB not, then MakeMaker defaults the
latter to be the same subdirectory of INSTALLPRIVLIB as Configure decided
for the counterparts in %Config , otherwise it defaults to INSTALLPRIVLIB.
The same relationship holds for INSTALLSITELIB and INSTALLSITEARCH.

MakeMaker gives you much more freedom than needed to configure internal
variables and get different results. It is worth to mention, that make(1)
also lets you configure most of the variables that are used in the
Makefile. But in the majority of situations this will not be necessary,
and should only be done, if the author of a package recommends it (or you
know what you're doing).

Using Attributes and Parameters
-------------------------------

The following attributes can be specified as arguments to WriteMakefile()
or as NAME=VALUE pairs on the command line:

C
     Ref to array of *.c file names. Initialised from a directory scan and
     the values portion of the XS attribute hash. This is not currently
     used by MakeMaker but may be handy in Makefile.PLs.

CONFIG
     Arrayref. E.g. [qw(archname manext)] defines ARCHNAME & MANEXT from
     config.sh. MakeMaker will add to CONFIG the following values anyway:
     ar cc cccdlflags ccdlflags dlext dlsrc ld lddlflags ldflags libc
     lib_ext obj_ext ranlib sitelibexp sitearchexp so

CONFIGURE
     CODE reference. The subroutine should return a hash reference. The
     hash may contain further attributes, e.g. {LIBS => ...}, that have to
     be determined by some evaluation method.

DEFINE
     Something like `"-DHAVE_UNISTD_H"'

DIR
     Ref to array of subdirectories containing Makefile.PLs e.g. [ 'sdbm'
     ] in ext/SDBM_File

DISTNAME
     Your name for distributing the package (by tar file). This defaults to
     NAME above.

DL_FUNCS
     Hashref of symbol names for routines to be made available as
     universal symbols.  Each key/value pair consists of the package name
     and an array of routine names in that package.  Used only under AIX
     (export lists) and VMS (linker options) at present.  The routine
     names supplied will be expanded in the same way as XSUB names are
     expanded by the XS() macro.  Defaults to

          {"$(NAME)" => ["boot_$(NAME)" ] }

     e.g.

          {"RPC" => [qw( boot_rpcb rpcb_gettime getnetconfigent )],
           "NetconfigPtr" => [ 'DESTROY'] }

DL_VARS
     Array of symbol names for variables to be made available as universal
     symbols.  Used only under AIX (export lists) and VMS (linker options)
     at present.  Defaults to [].  (e.g. [ qw( Foo_version Foo_numstreams
     Foo_tree ) ])

EXCLUDE_EXT
     Array of extension names to exclude when doing a static build.  This
     is ignored if INCLUDE_EXT is present.  Consult INCLUDE_EXT for more
     details.  (e.g.  [ qw( Socket POSIX ) ] )

     This attribute may be most useful when specified as a string on the
     commandline:  perl Makefile.PL EXCLUDE_EXT='Socket Safe'

EXE_FILES
     Ref to array of executable files. The files will be copied to the
     INST_SCRIPT directory. Make realclean will delete them from there
     again.

NO_VC
     In general any generated Makefile checks for the current version of
     MakeMaker and the version the Makefile was built under. If NO_VC is
     set, the version check is neglected. Do not write this into your
     Makefile.PL, use it interactively instead.

FIRST_MAKEFILE
     The name of the Makefile to be produced. Defaults to the contents of
     MAKEFILE, but can be overridden. This is used for the second Makefile
     that will be produced for the MAP_TARGET.

FULLPERL
     Perl binary able to run this extension.

H
     Ref to array of *.h file names. Similar to C.

INC
     Include file dirs eg: `"-I/usr/5include -I/path/to/inc"'

INCLUDE_EXT
     Array of extension names to be included when doing a static build.
     MakeMaker will normally build with all of the installed extensions
     when doing a static build, and that is usually the desired behavior.
     If INCLUDE_EXT is present then MakeMaker will build only with those
     extensions which are explicitly mentioned. (e.g.  [ qw( Socket POSIX
     ) ])

     It is not necessary to mention DynaLoader or the current extension
     when filling in INCLUDE_EXT.  If the INCLUDE_EXT is mentioned but is
     empty then only DynaLoader and the current extension will be included
     in the build.

     This attribute may be most useful when specified as a string on the
     commandline:  perl Makefile.PL INCLUDE_EXT='POSIX Socket Devel::Peek'

INSTALLARCHLIB
     Used by 'make install', which copies files from INST_ARCHLIB to this
     directory if INSTALLDIRS is set to perl.

INSTALLBIN
     Directory to install binary files (e.g. tkperl) into.

INSTALLDIRS
     Determines which of the two sets of installation directories to
     choose: installprivlib and installarchlib versus installsitelib and
     installsitearch. The first pair is chosen with INSTALLDIRS=perl, the
     second with INSTALLDIRS=site. Default is site.

INSTALLMAN1DIR
     This directory gets the man pages at 'make install' time. Defaults to
     $Config{installman1dir}.

INSTALLMAN3DIR
     This directory gets the man pages at 'make install' time. Defaults to
     $Config{installman3dir}.

INSTALLPRIVLIB
     Used by 'make install', which copies files from INST_LIB to this
     directory if INSTALLDIRS is set to perl.

INSTALLSCRIPT
     Used by 'make install' which copies files from INST_SCRIPT to this
     directory.

INSTALLSITELIB
     Used by 'make install', which copies files from INST_LIB to this
     directory if INSTALLDIRS is set to site (default).

INSTALLSITEARCH
     Used by 'make install', which copies files from INST_ARCHLIB to this
     directory if INSTALLDIRS is set to site (default).

INST_ARCHLIB
     Same as INST_LIB for architecture dependent files.

INST_BIN
     Directory to put real binary files during 'make'. These will be copied
     to INSTALLBIN during 'make install'

INST_EXE
     Old name for INST_SCRIPT. Deprecated. Please use INST_SCRIPT if you
     need to use it.

INST_LIB
     Directory where we put library files of this extension while building
     it.

INST_MAN1DIR
     Directory to hold the man pages at 'make' time

INST_MAN3DIR
     Directory to hold the man pages at 'make' time

INST_SCRIPT
     Directory, where executable files should be installed during 'make'.
     Defaults to "./blib/bin", just to have a dummy location during
     testing. make install will copy the files in INST_SCRIPT to
     INSTALLSCRIPT.

LDFROM
     defaults to "$(OBJECT)" and is used in the ld command to specify what
     files to link/load from (also see dynamic_lib below for how to
     specify ld flags)

LIBPERL_A
     The filename of the perllibrary that will be used together with this
     extension. Defaults to libperl.a.

LIBS
     An anonymous array of alternative library specifications to be
     searched for (in order) until at least one library is found. E.g.

          'LIBS' => ["-lgdbm", "-ldbm -lfoo", "-L/path -ldbm.nfs"]

     Mind, that any element of the array contains a complete set of
     arguments for the ld command. So do not specify

          'LIBS' => ["-ltcl", "-ltk", "-lX11"]

     See ODBM_File/Makefile.PL for an example, where an array is needed. If
     you specify a scalar as in

          'LIBS' => "-ltcl -ltk -lX11"

     MakeMaker will turn it into an array with one element.

LINKTYPE
     'static' or 'dynamic' (default unless usedl=undef in config.sh).
     Should only be used to force static linking (also see linkext below).

MAKEAPERL
     Boolean which tells MakeMaker, that it should include the rules to
     make a perl. This is handled automatically as a switch by MakeMaker.
     The user normally does not need it.

MAKEFILE
     The name of the Makefile to be produced.

MAN1PODS
     Hashref of pod-containing files. MakeMaker will default this to all
     EXE_FILES files that include POD directives. The files listed here
     will be converted to man pages and installed as was requested at
     Configure time.

MAN3PODS
     Hashref of .pm and .pod files. MakeMaker will default this to all
     .pod and any .pm files that include POD directives. The files listed
     here will be converted to man pages and installed as was requested at
     Configure time.

MAP_TARGET
     If it is intended, that a new perl binary be produced, this variable
     may hold a name for that binary. Defaults to perl

MYEXTLIB
     If the extension links to a library that it builds set this to the
     name of the library (see SDBM_File)

NAME
     Perl module name for this extension (DBD::Oracle). This will default
     to the directory name but should be explicitly defined in the
     Makefile.PL.

NEEDS_LINKING
     MakeMaker will figure out, if an extension contains linkable code
     anywhere down the directory tree, and will set this variable
     accordingly, but you can speed it up a very little bit, if you define
     this boolean variable yourself.

NOECHO
     Defaults to `@'. By setting it to an empty string you can generate a
     Makefile that echos all commands. Mainly used in debugging MakeMaker
     itself.

NORECURS
     Boolean.  Attribute to inhibit descending into subdirectories.

OBJECT
     List of object files, defaults to '$(BASEEXT)$(OBJ_EXT)', but can be
     a long string containing all object files, e.g. "tkpBind.o
     tkpButton.o tkpCanvas.o"

OPTIMIZE
     Defaults to `-O'. Set it to `-g' to turn debugging on. The flag is
     passed to subdirectory makes.

PERL
     Perl binary for tasks that can be done by miniperl

PERLMAINCC
     The call to the program that is able to compile perlmain.c. Defaults
     to $(CC).

PERL_ARCHLIB
     Same as above for architecture dependent files

PERL_LIB
     Directory containing the Perl library to use.

PERL_SRC
     Directory containing the Perl source code (use of this should be
     avoided, it may be undefined)

PL_FILES
     Ref to hash of files to be processed as perl programs. MakeMaker will
     default to any found *.PL file (except Makefile.PL) being keys and
     the basename of the file being the value. E.g.

          {'foobar.PL' => 'foobar'}

     The *.PL files are expected to produce output to the target files
     themselves.

PM
     Hashref of .pm files and *.pl files to be installed.  e.g.

          {'name_of_file.pm' => '$(INST_LIBDIR)/install_as.pm'}

     By default this will include *.pm and *.pl. If a lib directory exists
     and is not listed in DIR (above) then any *.pm and *.pl files it
     contains will also be included by default.  Defining PM in the
     Makefile.PL will override PMLIBDIRS.

PMLIBDIRS
     Ref to array of subdirectories containing library files.  Defaults to
     [ 'lib', $(BASEEXT) ]. The directories will be scanned and any files
     they contain will be installed in the corresponding location in the
     library.  A libscan() method can be used to alter the behaviour.
     Defining PM in the Makefile.PL will override PMLIBDIRS.

PREFIX
     Can be used to set the three INSTALL* attributes in one go (except for
     probably INSTALLMAN1DIR, if it is not below PREFIX according to
     %Config).  They will have PREFIX as a common directory node and will
     branch from that node into lib/, lib/ARCHNAME or whatever Configure
     decided at the build time of your perl (unless you override one of
     them, of course).

PREREQ_PM
     Hashref: Names of modules that need to be available to run this
     extension (e.g. Fcntl for SDBM_File) are the keys of the hash and the
     desired version is the value. If the required version number is 0, we
     only check if any version is installed already.

SKIP
     Arryref. E.g. [qw(name1 name2)] skip (do not write) sections of the
     Makefile. Caution! Do not use the SKIP attribute for the neglectible
     speedup. It may seriously damage the resulting Makefile. Only use it,
     if you really need it.

TYPEMAPS
     Ref to array of typemap file names.  Use this when the typemaps are
     in some directory other than the current directory or when they are
     not named *typemap*.  The last typemap in the list takes precedence.
     A typemap in the current directory has highest precedence, even if it
     isn't listed in TYPEMAPS.  The default system typemap has lowest
     precedence.

VERSION
     Your version number for distributing the package.  This defaults to
     0.1.

VERSION_FROM
     Instead of specifying the VERSION in the Makefile.PL you can let
     MakeMaker parse a file to determine the version number. The parsing
     routine requires that the file named by VERSION_FROM contains one
     single line to compute the version number. The first line in the file
     that contains the regular expression

          /\$(([\w\:\']*)\bVERSION)\b.*\=/

     will be evaluated with eval() and the value of the named variable
     *after* the eval() will be assigned to the VERSION attribute of the
     MakeMaker object. The following lines will be parsed o.k.:

          $VERSION = '1.00';
          ( $VERSION ) = '$Revision: 1.207 $ ' =~ /\$Revision:\s+([^\s]+)/;
          $FOO::VERSION = '1.10';

     but these will fail:

          my $VERSION = '1.01';
          local $VERSION = '1.02';
          local $FOO::VERSION = '1.30';

     The file named in VERSION_FROM is added as a dependency to Makefile to
     guarantee, that the Makefile contains the correct VERSION macro after
     a change of the file.

XS
     Hashref of .xs files. MakeMaker will default this.  e.g.

          {'name_of_file.xs' => 'name_of_file.c'}

     The .c files will automatically be included in the list of files
     deleted by a make clean.

XSOPT
     String of options to pass to xsubpp.  This might include `-C++' or
     `-extern'.  Do not include typemaps here; the TYPEMAP parameter
     exists for that purpose.

XSPROTOARG
     May be set to an empty string, which is identical to `-prototypes', or
     `-noprototypes'. See the xsubpp documentation for details. MakeMaker
     defaults to the empty string.

XS_VERSION
     Your version number for the .xs file of this package.  This defaults
     to the value of the VERSION attribute.

Additional lowercase attributes
-------------------------------

can be used to pass parameters to the methods which implement that part of
the Makefile.

clean
          {FILES => "*.xyz foo"}

depend
          {ANY_TARGET => ANY_DEPENDECY, ...}

dist
          {TARFLAGS => 'cvfF', COMPRESS => 'gzip', SUFFIX => 'gz',
          SHAR => 'shar -m', DIST_CP => 'ln', ZIP => '/bin/zip',
          ZIPFLAGS => '-rl', DIST_DEFAULT => 'private tardist' }

     If you specify COMPRESS, then SUFFIX should also be altered, as it is
     needed to tell make the target file of the compression. Setting
     DIST_CP to ln can be useful, if you need to preserve the timestamps on
     your files. DIST_CP can take the values 'cp', which copies the file,
     'ln', which links the file, and 'best' which copies symbolic links and
     links the rest. Default is 'best'.

dynamic_lib
          {ARMAYBE => 'ar', OTHERLDFLAGS => '...', INST_DYNAMIC_DEP => '...'}

installpm
     Deprecated as of MakeMaker 5.23. See `pm_to_blib', *Note
     ExtUtils/MM_Unix: ExtUtils/MM_Unix,.

linkext
          {LINKTYPE => 'static', 'dynamic' or ''}

     NB: Extensions that have nothing but *.pm files had to say

          {LINKTYPE => ''}

     with Pre-5.0 MakeMakers. Since version 5.00 of MakeMaker such a line
     can be deleted safely. MakeMaker recognizes, when there's nothing to
     be linked.

macro
          {ANY_MACRO => ANY_VALUE, ...}

realclean
          {FILES => '$(INST_ARCHAUTODIR)/*.xyz'}

tool_autosplit
          {MAXLEN =Greater_Than_Special_Sequence 8}

Overriding MakeMaker Methods
----------------------------

If you cannot achieve the desired Makefile behaviour by specifying
attributes you may define private subroutines in the Makefile.PL.  Each
subroutines returns the text it wishes to have written to the Makefile. To
override a section of the Makefile you can either say:

     sub MY::c_o { "new literal text" }

or you can edit the default by saying something like:

     sub MY::c_o {
                 my($inherited) = shift->SUPER::c_o(@_);
         $inherited =~ s/old text/new text/;
         $inherited;
     }

If you running experiments with embedding perl as a library into other
applications, you might find MakeMaker not sufficient. You'd better have a
look at ExtUtils::embed which is a collection of utilities for embedding.

If you still need a different solution, try to develop another subroutine,
that fits your needs and submit the diffs to `perl5-porters@nicoh.com' or
`comp.lang.perl.misc' as appropriate.

For a complete description of all MakeMaker methods see *Note
ExtUtils/MM_Unix: ExtUtils/MM_Unix,.

Here is a simple example of how to add a new target to the generated
Makefile:

     sub MY::postamble {
     	'
     $(MYEXTLIB): sdbm/Makefile
     	    cd sdbm && $(MAKE) all
     ';
     }

Hintsfile support
-----------------

MakeMaker.pm uses the architecture specific information from Config.pm. In
addition it evaluates architecture specific hints files in a `hints/'
directory. The hints files are expected to be named like their
counterparts in `PERL_SRC/hints', but with an `.pl' file name extension
(eg. `next_3_2.pl'). They are simply evaled by MakeMaker within the
WriteMakefile() subroutine, and can be used to execute commands as well as
to include special variables. The rules which hintsfile is chosen are the
same as in Configure.

The hintsfile is eval()ed immediately after the arguments given to
WriteMakefile are stuffed into a hash reference $self but before this
reference becomes blessed. So if you want to do the equivalent to override
or create an attribute you would say something like

     $self->{LIBS} = ['-ldbm -lucb -lc'];

Distribution Support
--------------------

For authors of extensions MakeMaker provides several Makefile targets.
Most of the support comes from the ExtUtils::Manifest module, where
additional documentation can be found.

make distcheck
     reports which files are below the build directory but not in the
     MANIFEST file and vice versa. (See ExtUtils::Manifest::fullcheck() for
     details)

make skipcheck
     reports which files are skipped due to the entries in the
     MANIFEST.SKIP file (See ExtUtils::Manifest::skipcheck() for details)

make distclean
     does a realclean first and then the distcheck. Note that this is not
     needed to build a new distribution as long as you are sure, that the
     MANIFEST file is ok.

make manifest
     rewrites the MANIFEST file, adding all remaining files found (See
     ExtUtils::Manifest::mkmanifest() for details)

make distdir
     Copies all the files that are in the MANIFEST file to a newly created
     directory with the name `$(DISTNAME)-$(VERSION)'. If that directory
     exists, it will be removed first.

make disttest
     Makes a distdir first, and runs a `perl Makefile.PL', a make, and a
     make test in that directory.

make tardist
     First does a distdir. Then a command $(PREOP) which defaults to a null
     command, followed by $(TOUNIX), which defaults to a null command under
     UNIX, and will convert files in distribution directory to UNIX format
     otherwise. Next it runs `tar' on that directory into a tarfile and
     deletes the directory. Finishes with a command $(POSTOP) which
     defaults to a null command.

make dist
     Defaults to $(DIST_DEFAULT) which in turn defaults to tardist.

make uutardist
     Runs a tardist first and uuencodes the tarfile.

make shdist
     First does a distdir. Then a command $(PREOP) which defaults to a null
     command. Next it runs `shar' on that directory into a sharfile and
     deletes the intermediate directory again. Finishes with a command
     $(POSTOP) which defaults to a null command.  Note: For shdist to work
     properly a `shar' program that can handle directories is mandatory.

make zipdist
     First does a distdir. Then a command $(PREOP) which defaults to a null
     command. Runs `$(ZIP) $(ZIPFLAGS)' on that directory into a zipfile.
     Then deletes that directory. Finishes with a command $(POSTOP) which
     defaults to a null command.

make ci
     Does a $(CI) and a $(RCS_LABEL) on all files in the MANIFEST file.

Customization of the dist targets can be done by specifying a hash
reference to the dist attribute of the WriteMakefile call. The following
parameters are recognized:

     CI           ('ci -u')
     COMPRESS     ('compress')
     POSTOP       ('@ :')
     PREOP        ('@ :')
     TO_UNIX      (depends on the system)
     RCS_LABEL    ('rcs -q -Nv$(VERSION_SYM):')
     SHAR         ('shar')
     SUFFIX       ('Z')
     TAR          ('tar')
     TARFLAGS     ('cvf')
     ZIP          ('zip')
     ZIPFLAGS     ('-r')

An example:

     WriteMakefile( 'dist' => { COMPRESS=>"gzip", SUFFIX=>"gz" })

SEE ALSO
========

ExtUtils::MM_Unix, ExtUtils::Manifest, ExtUtils::testlib,
ExtUtils::Install, ExtUtils::embed

AUTHORS
=======

Andy Dougherty `<doughera@lafcol.lafayette.edu>', Andreas KE<ouml>nig
`<A.Koenig@franz.ww.TU-Berlin.DE>', Tim Bunce `<Tim.Bunce@ig.co.uk>'.  VMS
support by Charles Bailey `<bailey@genetics.upenn.edu>'. OS/2 support by
Ilya Zakharevich `<ilya@math.ohio-state.edu>'. Contact the makemaker
mailing list `mailto:makemaker@franz.ww.tu-berlin.de', if you have any
questions.


File: pm.info,  Node: ExtUtils/Manifest,  Next: ExtUtils/Miniperl,  Prev: ExtUtils/MakeMaker,  Up: Module List

utilities to write and check a MANIFEST file
********************************************

NAME
====

ExtUtils::Manifest - utilities to write and check a MANIFEST file

SYNOPSIS
========

`require ExtUtils::Manifest;'

`ExtUtils::Manifest::mkmanifest;'

`ExtUtils::Manifest::manicheck;'

`ExtUtils::Manifest::filecheck;'

`ExtUtils::Manifest::fullcheck;'

`ExtUtils::Manifest::skipcheck;'

`ExtUtild::Manifest::manifind();'

`ExtUtils::Manifest::maniread($file);'

`ExtUtils::Manifest::manicopy($read,$target,$how);'

DESCRIPTION
===========

Mkmanifest() writes all files in and below the current directory to a file
named in the global variable $ExtUtils::Manifest::MANIFEST (which defaults
to `MANIFEST') in the current directory. It works similar to

     find . -print

but in doing so checks each line in an existing `MANIFEST' file and
includes any comments that are found in the existing `MANIFEST' file in
the new one. Anything between white space and an end of line within a
`MANIFEST' file is considered to be a comment. Filenames and comments are
seperated by one or more TAB characters in the output. All files that
match any regular expression in a file MANIFEST.SKIP (if such a file
exists) are ignored.

Manicheck() checks if all the files within a `MANIFEST' in the current
directory really do exist. It only reports discrepancies and exits
silently if MANIFEST and the tree below the current directory are in sync.

Filecheck() finds files below the current directory that are not mentioned
in the `MANIFEST' file. An optional file MANIFEST.SKIP will be consulted.
Any file matching a regular expression in such a file will not be reported
as missing in the `MANIFEST' file.

Fullcheck() does both a manicheck() and a filecheck().

Skipcheck() lists all the files that are skipped due to your MANIFEST.SKIP
file.

Manifind() retruns a hash reference. The keys of the hash are the files
found below the current directory.

Maniread($file) reads a named `MANIFEST' file (defaults to `MANIFEST' in
the current directory) and returns a HASH reference with files being the
keys and comments being the values of the HASH.

*Manicopy($read,$target,$how)* copies the files that are the keys in the
HASH *%$read* to the named target directory. The HASH reference *$read* is
typically returned by the maniread() function. This function is useful for
producing a directory tree identical to the intended distribution tree.
The third parameter $how can be used to specify a different methods of
"copying". Valid values are `cp', which actually copies the files, `ln'
which creates hard links, and `best' which mostly links the files but
copies any symbolic link to make a tree without any symbolic link. Best is
the default.

MANIFEST.SKIP
=============

The file MANIFEST.SKIP may contain regular expressions of files that
should be ignored by mkmanifest() and filecheck(). The regular expressions
should appear one on each line. A typical example:

     \bRCS\b
     ^MANIFEST\.
     ^Makefile$
     ~$
     \.html$
     \.old$
     ^blib/
     ^MakeMaker-\d

EXPORT_OK
=========

`&mkmanifest', `&manicheck', `&filecheck', `&fullcheck', `&maniread', and
`&manicopy' are exportable.

GLOBAL VARIABLES
================

`$ExtUtils::Manifest::MANIFEST' defaults to `MANIFEST'. Changing it
results in both a different `MANIFEST' and a different MANIFEST.SKIP file.
This is useful if you want to maintain different distributions for
different audiences (say a user version and a developer version including
RCS).

`$ExtUtils::Manifest::Quiet' defaults to 0. If set to a true value, all
functions act silently.

DIAGNOSTICS
===========

All diagnostic output is sent to `STDERR'.

`Not in MANIFEST:' *file*
     is reported if a file is found, that is missing in the `MANIFEST'
     file which is excluded by a regular expression in the file
     MANIFEST.SKIP.

`No such file:' *file*
     is reported if a file mentioned in a `MANIFEST' file does not exist.

`MANIFEST:' $!
     is reported if `MANIFEST' could not be opened.

`Added to MANIFEST:' *file*
     is reported by mkmanifest() if $Verbose is set and a file is added to
     MANIFEST. $Verbose is set to 1 by default.

SEE ALSO
========

*Note ExtUtils/MakeMaker: ExtUtils/MakeMaker, which has handy targets for
most of the functionality.

AUTHOR
======

Andreas Koenig <`koenig@franz.ww.TU-Berlin.DE'>


File: pm.info,  Node: ExtUtils/Miniperl,  Next: ExtUtils/Mkbootstrap,  Prev: ExtUtils/Manifest,  Up: Module List

write the C code for perlmain.c
*******************************

NAME
====

ExtUtils::Miniperl, writemain - write the C code for perlmain.c

SYNOPSIS
========

`use ExtUtils::Miniperl;'

`writemain(@directories);'

DESCRIPTION
===========

This whole module is written when perl itself is built from a script
called minimod.PL. In case you want to patch it, please patch minimod.PL
in the perl distribution instead.

writemain() takes an argument list of directories containing archive
libraries that relate to perl modules and should be linked into a new perl
binary. It writes to STDOUT a corresponding perlmain.c file that is a
plain C file containing all the bootstrap code to make the modules
associated with the libraries available from within perl.

The typical usage is from within a Makefile generated by
ExtUtils::MakeMaker. So under normal circumstances you won't have to deal
with this module directly.

SEE ALSO
========

*Note ExtUtils/MakeMaker: ExtUtils/MakeMaker,


File: pm.info,  Node: ExtUtils/Mkbootstrap,  Next: ExtUtils/Mksymlists,  Prev: ExtUtils/Miniperl,  Up: Module List

make a bootstrap file for use by DynaLoader
*******************************************

NAME
====

ExtUtils::Mkbootstrap - make a bootstrap file for use by DynaLoader

SYNOPSIS
========

`mkbootstrap'

DESCRIPTION
===========

Mkbootstrap typically gets called from an extension Makefile.

There is no `*.bs' file supplied with the extension. Instead a `*_BS' file
which has code for the special cases, like posix for berkeley db on the
NeXT.

This file will get parsed, and produce a maybe empty
`@DynaLoader::dl_resolve_using' array for the current architecture.  That
will be extended by $BSLOADLIBS, which was computed by
ExtUtils::Liblist::ext(). If this array still is empty, we do nothing,
else we write a .bs file with an `@DynaLoader::dl_resolve_using' array.

The `*_BS' file can put some code into the generated `*.bs' file by
placing it in `$bscode'. This is a handy 'escape' mechanism that may prove
useful in complex situations.

If @DynaLoader::dl_resolve_using contains `-L*' or `-l*' entries then
Mkbootstrap will automatically add a dl_findfile() call to the generated
`*.bs' file.


File: pm.info,  Node: ExtUtils/Mksymlists,  Next: ExtUtils/testlib,  Prev: ExtUtils/Mkbootstrap,  Up: Module List

write linker options files for dynamic extension
************************************************

NAME
====

ExtUtils::Mksymlists - write linker options files for dynamic extension

SYNOPSIS
========

     use ExtUtils::Mksymlists;
     Mksymlists({ NAME     => $name ,
                  DL_VARS  => [ $var1, $var2, $var3 ],
                  DL_FUNCS => { $pkg1 => [ $func1, $func2 ],
                                $pkg2 => [ $func3 ] });

DESCRIPTION
===========

`ExtUtils::Mksymlists' produces files used by the linker under some OSs
during the creation of shared libraries for dynamic extensions.  It is
normally called from a MakeMaker-generated Makefile when the extension is
built.  The linker option file is generated by calling the function
`Mksymlists', which is exported by default from `ExtUtils::Mksymlists'.
It takes one argument, a list of key-value pairs, in which the following
keys are recognized:

NAME
     This gives the name of the extension (*e.g.* Tk::Canvas) for which
     the linker option file will be produced.

DL_FUNCS
     This is identical to the DL_FUNCS attribute available via MakeMaker,
     from which it is usually taken.  Its value is a reference to an
     associative array, in which each key is the name of a package, and
     each value is an a reference to an array of function names which
     should be exported by the extension.  For instance, one might say
     `DL_FUNCS => { Homer::Iliad   => [ qw(trojans greeks) ],
     Homer::Odyssey => [ qw(travellers family suitors) ] }'.  The function
     names should be identical to those in the XSUB code; `Mksymlists'
     will alter the names written to the linker option file to match the
     changes made by xsubpp.  In addition, if none of the functions in a
     list begin with the string *boot_*, `Mksymlists' will add a bootstrap
     function for that package, just as xsubpp does.  (If a *boot_<pkg>*
     function is present in the list, it is passed through unchanged.)  If
     DL_FUNCS is not specified, it defaults to the bootstrap function for
     the extension specified in NAME.

DL_VARS
     This is identical to the DL_VARS attribute available via MakeMaker,
     and, like DL_FUNCS, it is usually specified via MakeMaker.  Its value
     is a reference to an array of variable names which should be exported
     by the extension.

FILE
     This key can be used to specify the name of the linker option file
     (minus the OS-specific extension), if for some reason you do not want
     to use the default value, which is the last word of the NAME
     attribute (*e.g.* for Tk::Canvas, FILE defaults to 'Canvas').

FUNCLIST
     This provides an alternate means to specify function names to be
     exported from the extension.  Its value is a reference to an array of
     function names to be exported by the extension.  These names are
     passed through unaltered to the linker options file.

DLBASE
     This item specifies the name by which the linker knows the extension,
     which may be different from the name of the extension itself (for
     instance, some linkers add an '_' to the name of the extension).  If
     it is not specified, it is derived from the NAME attribute.  It is
     presently used only by OS2.

     When calling `Mksymlists', one should always specify the NAME
     attribute.  In most cases, this is all that's necessary.  In the case
     of unusual extensions, however, the other attributes can be used to
     provide additional information to the linker.

AUTHOR
======

Charles Bailey *<bailey@genetics.upenn.edu>*

REVISION
========

Last revised 14-Feb-1996, for Perl 5.002.


File: pm.info,  Node: ExtUtils/testlib,  Next: Fatal,  Prev: ExtUtils/Mksymlists,  Up: Module List

add blib/* directories to @INC
******************************

NAME
====

ExtUtils::testlib - add blib/* directories to @INC

SYNOPSIS
========

`use ExtUtils::testlib;'

DESCRIPTION
===========

After an extension has been built and before it is installed it may be
desirable to test it bypassing make test. By adding

     use ExtUtils::testlib;

to a test program the intermediate directories used by make are added to
@INC.


File: pm.info,  Node: Fatal,  Next: Fcntl,  Prev: ExtUtils/testlib,  Up: Module List

replace functions with equivalents which succeed or die
*******************************************************

NAME
====

Fatal - replace functions with equivalents which succeed or die

SYNOPSIS
========

     use Fatal qw(open print close);

     sub juggle { . . . }
     import Fatal 'juggle';

DESCRIPTION
===========

Fatal provides a way to conveniently replace functions which normally
return a false value when they fail with equivalents which halt execution
if they are not successful.  This lets you use these functions without
having to test their return values explicitly on each call.   Errors are
reported via die, so you can trap them using `$SIG{__DIE__}' if you wish
to take some action before the program exits.

The do-or-die equivalents are set up simply by calling Fatal's import
routine, passing it the names of the functions to be replaced.  You may
wrap both user-defined functions and CORE operators in this way.

AUTHOR
======

Lionel.Cons@cern.ch


File: pm.info,  Node: Fcntl,  Next: File/Basename,  Prev: Fatal,  Up: Module List

load the C Fcntl.h defines
**************************

NAME
====

Fcntl - load the C Fcntl.h defines

SYNOPSIS
========

     use Fcntl;

DESCRIPTION
===========

This module is just a translation of the C `fnctl.h' file.  Unlike the old
mechanism of requiring a translated `fnctl.ph' file, this uses the h2xs
program (see the Perl source distribution) and your native C compiler.
This means that it has a far more likely chance of getting the numbers
right.

NOTE
====

Only `#define' symbols get translated; you must still correctly pack up
your own arguments to pass as args for locking functions, etc.


File: pm.info,  Node: File/Basename,  Next: File/BasicFlock,  Prev: Fcntl,  Up: Module List

parse file specifications
*************************

NAME
====

Basename - parse file specifications

fileparse - split a pathname into pieces

basename - extract just the filename from a path

dirname - extract just the directory from a path

SYNOPSIS
========

     use File::Basename;

     ($name,$path,$suffix) = fileparse($fullname,@suffixlist)
     fileparse_set_fstype($os_string);
     $basename = basename($fullname,@suffixlist);
     $dirname = dirname($fullname);

     ($name,$path,$suffix) = fileparse("lib/File/Basename.pm","\.pm");
     fileparse_set_fstype("VMS");
     $basename = basename("lib/File/Basename.pm",".pm");
     $dirname = dirname("lib/File/Basename.pm");

DESCRIPTION
===========

These routines allow you to parse file specifications into useful pieces
using the syntax of different operating systems.

fileparse_set_fstype
     You select the syntax via the routine fileparse_set_fstype().  If the
     argument passed to it contains one of the substrings "VMS", "MSDOS",
     or "MacOS", the file specification syntax of that operating system is
     used in future calls to fileparse(), basename(), and dirname().  If
     it contains none of these substrings, UNIX syntax is used.  This
     pattern matching is case-insensitive.  If you've selected VMS syntax,
     and the file specification you pass to one of these routines contains
     a "/", they assume you are using UNIX emulation and apply the UNIX
     syntax rules instead, for that function call only.

     If you haven't called fileparse_set_fstype(), the syntax is chosen by
     examining the builtin variable $^O according to these rules.

fileparse
     The fileparse() routine divides a file specification into three
     parts: a leading path, a file *name*, and a *suffix*.  The path
     contains everything up to and including the last directory separator
     in the input file specification.  The remainder of the input file
     specification is then divided into *name* and *suffix* based on the
     optional patterns you specify in `@suffixlist'.  Each element of this
     list is interpreted as a regular expression, and is matched against
     the end of *name*.  If this succeeds, the matching portion of *name*
     is removed and prepended to *suffix*.  By proper use of
     `@suffixlist', you can remove file types or versions for examination.

     You are guaranteed that if you concatenate path, *name*, and *suffix*
     together in that order, the result will denote the same file as the
     input file specification.

EXAMPLES
========

Using UNIX file syntax:

     ($base,$path,$type) = fileparse('/virgil/aeneid/draft.book7',
     				    '\.book\d+');

would yield

     $base eq 'draft'
     $path eq '/virgil/aeneid/',
     $type eq '.book7'

Similarly, using VMS syntax:

     ($name,$dir,$type) = fileparse('Doc_Root:[Help]Rhetoric.Rnh',
     				   '\..*');

would yield

     $name eq 'Rhetoric'
     $dir  eq 'Doc_Root:[Help]'
     $type eq '.Rnh'

`basename'
     The basename() routine returns the first element of the list produced
     by calling fileparse() with the same arguments.  It is provided for
     compatibility with the UNIX shell command basename(1).

`dirname'
     The dirname() routine returns the directory portion of the input file
     specification.  When using VMS or MacOS syntax, this is identical to
     the second element of the list produced by calling fileparse() with
     the same input file specification.  (Under VMS, if there is no
     directory information in the input file specification, then the
     current default device and directory are returned.)  When using UNIX
     or MSDOS syntax, the return value conforms to the behavior of the
     UNIX shell command dirname(1).  This is usually the same as the
     behavior of fileparse(), but differs in some cases.  For example, for
     the input file specification `lib/', fileparse() considers the
     directory name to be `lib/', while dirname() considers the directory
     name to be .).


File: pm.info,  Node: File/BasicFlock,  Next: File/CheckTree,  Prev: File/Basename,  Up: Module List

file locking with flock
***********************

NAME
====

     File::BasicFlock - file locking with flock

SYNOPSIS
========

     use File::BasicFlock;

     lock($filename);

     lock($filename, 'shared');

     lock($filename, undef, 'nonblocking');

     lock($filename, 'shared', 'nonblocking');

     unlock($filename);

DESCRIPTION
===========

Lock files using the flock() call.  The file to be locked must already
exist.

AUTHOR
======

David Muir Sharnoff, <muir@idiom.com>


File: pm.info,  Node: File/CheckTree,  Next: File/Cmp,  Prev: File/BasicFlock,  Up: Module List

run many filetest checks on a tree
**********************************

NAME
====

validate - run many filetest checks on a tree

SYNOPSIS
========

     use File::CheckTree;

     $warnings += validate( q{
     	/vmunix                 -e || die
     	/boot                   -e || die
     	/bin                    cd
     	    csh                 -ex
     	    csh                 !-ug
     	    sh                  -ex
     	    sh                  !-ug
     	/usr                    -d || warn "What happened to $file?\n"
     });

DESCRIPTION
===========

The validate() routine takes a single multiline string consisting of lines
containing a filename plus a file test to try on it.  (The file test may
also be a "cd", causing subsequent relative filenames to be interpreted
relative to that directory.)  After the file test you may put `|| die' to
make it a fatal error if the file test fails.  The default is `|| warn'.
The file test may optionally have a "!' prepended to test for the opposite
condition.  If you do a cd and then list some relative filenames, you may
want to indent them slightly for readability.  If you supply your own
die() or warn() message, you can use $file to interpolate the filename.

Filetests may be bunched:  "-rwx" tests for all of -r, -w, and -x.  Only
the first failed test of the bunch will produce a warning.

The routine returns the number of warnings issued.


File: pm.info,  Node: File/Cmp,  Next: File/Copy,  Prev: File/CheckTree,  Up: Module List

compare files
*************

NAME
====

File::Cmp - compare files

SYNOPSIS
========

     use File::Cmp;

     $status = cmp_file "filename1", "filename2";

DESCRIPTION
===========

cmp_file() compares the contents of two files.  If they are identical
cmp_file() return a value of 0.  Otherwise it returns a positive nonzero
value.

If one of the two files cannot be opened, cmp_file() returns -1.

BUGS
====

cmp_file() checks to see if files have identical filenames, but maybe it
should also check inode numbers?

It might be nice to have a version that would return the location of the
first difference found.

AUTHOR
======

Joseph N. Hall, joseph@5sigma.com


File: pm.info,  Node: File/Copy,  Next: File/CounterFile,  Prev: File/Cmp,  Up: Module List

Copy files or filehandles
*************************

NAME
====

File::Copy - Copy files or filehandles

SYNOPSIS
========

     use File::Copy;

     copy("file1","file2");
       	copy("Copy.pm",\*STDOUT);'

     use POSIX;
     	use File::Copy cp;

     $n=FileHandle->new("/dev/null","r");
     cp($n,"x");'

DESCRIPTION
===========

The File::Copy module provides a basic function copy which takes two
parameters: a file to copy from and a file to copy to. Either argument may
be a string, a FileHandle reference or a FileHandle glob. Obviously, if
the first argument is a filehandle of some sort, it will be read from, and
if it is a file *name* it will be opened for reading. Likewise, the second
argument will be written to (and created if need be).  Note that passing in
files as handles instead of names may lead to loss of information on some
operating systems; it is recommended that you use file names whenever
possible.

An optional third parameter can be used to specify the buffer size used
for copying. This is the number of bytes from the first file, that wil be
held in memory at any given time, before being written to the second file.
The default buffer size depends upon the file, but will generally be the
whole file (up to 2Mb), or 1k for filehandles that do not reference files
(eg. sockets).

You may use the syntax `use File::Copy "cp"' to get at the "cp" alias for
this function. The syntax is *exactly* the same.

File::Copy also provides the `syscopy' routine, which copies the file
specified in the first parameter to the file specified in the second
parameter, preserving OS-specific attributes and file structure.  For Unix
systems, this is equivalent to the simple copy routine.  For VMS systems,
this calls the `rmscopy' routine (see below).  For OS/2 systems, this
calls the `syscopy' XSUB directly.

Special behavior under VMS
--------------------------

If the second argument to copy is not a file handle for an already opened
file, then copy will perform an RMS copy of the input file to a new output
file, in order to preserve file attributes, indexed file structure, *etc.*
The buffer size parameter is ignored.  If the second argument to copy is a
Perl handle to an opened file, then data is copied using Perl operators,
and no effort is made to preserve file attributes or record structure.

The RMS copy routine may also be called directly under VMS as
`File::Copy::rmscopy' (or `File::Copy::syscopy', which is just an alias
for this routine).

rmscopy($from,$to[,$date_flag])
     The first and second arguments may be strings, typeglobs, or typeglob
     references; they are used in all cases to obtain the *filespec* of
     the input and output files, respectively.  The name and type of the
     input file are used as defaults for the output file, if necessary.

     A new version of the output file is always created, which inherits
     the structure and RMS attributes of the input file, except for owner
     and protections (and possibly timestamps; see below).  All data from
     the input file is copied to the output file; if either of the first
     two parameters to `rmscopy' is a file handle, its position is
     unchanged.  (Note that this means a file handle pointing to the
     output file will be associated with an old version of that file after
     `rmscopy' returns, not the newly created version.)

     The third parameter is an integer flag, which tells `rmscopy' how to
     handle timestamps.  If it is < 0, none of the input file's timestamps
     are propagated to the output file.  If it is > 0, then it is
     interpreted as a bitmask: if bit 0 (the LSB) is set, then timestamps
     other than the revision date are propagated; if bit 1 is set, the
     revision date is propagated.  If the third parameter to `rmscopy' is
     0, then it behaves much like the DCL COPY command: if the name or
     type of the output file was explicitly specified, then no timestamps
     are propagated, but if they were taken implicitly from the input
     filespec, then all timestamps other than the revision date are
     propagated.  If this parameter is not supplied, it defaults to 0.

     Like copy, `rmscopy' returns 1 on success.  If an error occurs, it
     sets $!, deletes the output file, and returns 0.

RETURN
======

Returns 1 on success, 0 on failure. $! will be set if an error was
encountered.

AUTHOR
======

File::Copy was written by Aaron Sherman *<ajs@ajs.com>* in 1995.  The
VMS-specific code was added by Charles Bailey
*<bailey@genetics.upenn.edu>* in March 1996.


File: pm.info,  Node: File/CounterFile,  Next: File/Find,  Prev: File/Copy,  Up: Module List

Persistent counter class
************************

NAME
====

File::CounterFile - Persistent counter class

SYNOPSIS
========

     use File::CounterFile;
     $c = new File::CounterFile "COUNTER", "aa00";

     $id = $c->inc;
     open(F, ">F$id");

DESCRIPTION
===========

This module implements a persistent counter class.  Each counter is
represented by a separate file in the file system.  File locking is
applied, so multiple processes might try to access the same counters at
the same time without risk of counter destruction.

You give the file name as the first parameter to the object constructor
(new).  The file is created if it does not exist.

If the file name does not start with "/" or ".", then it is interpreted as
a file relative to `$File::CounterFile::DEFAULT_DIR'.  The default value
for this variable is initialized from the environment variable `TMPDIR',
or `/usr/tmp' is no environment variable is defined.  You may want to
assign a different value to this variable before creating counters.

If you pass a second parameter to the constructor, that sets the initial
value for a new counter.  This parameter only takes effect when the file
is created (i.e. it does not exist before the call).

When you call the `inc()' method, you increment the counter value by one.
When you call `dec()' the counter value is decrementd.  In both cases the
new value is returned.  The `dec()' method only works for numerical
counters (digits only).

You can peek at the value of the counter (without incrementing it) by
using the `value()' method.

The counter can be locked and unlocked with the `lock()' and `unlock()'
methods.  Incrementing and value retrieval is faster when the counter is
locked, because we do not have to update the counter file all the time.
You can query whether the counter is locked with the `locked()' method.

There is also an operator overloading interface to the File::CounterFile
object.  This means that you might use the `++' operator for incrementing
the counter, `--' operator for decrementing and you can interpolate
counters diretly into strings.

BUGS
====

It uses flock(2) to lock the counter file.  This does not work on all
systems.  Perhaps we should use the File::Lock module?

INSTALLATION
============

Copy this file to the `File' subdirectory of your Perl 5 library directory
(often `/usr/local/lib/perl5').

COPYRIGHT
=========

Copyright (c) 1995-1996 Gisle Aas. All rights reserved.

This library is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

AUTHOR
======

Gisle Aas <aas@sn.no>


File: pm.info,  Node: File/Find,  Next: File/Flock,  Prev: File/CounterFile,  Up: Module List

traverse a file tree
********************

NAME
====

find - traverse a file tree

finddepth - traverse a directory structure depth-first

SYNOPSIS
========

     use File::Find;
     find(\&wanted, '/foo','/bar');
     sub wanted { ... }
     
     use File::Find;
     finddepth(\&wanted, '/foo','/bar');
     sub wanted { ... }

DESCRIPTION
===========

The wanted() function does whatever verifications you want.
$File::Find::dir contains the current directory name, and $_ the current
filename within that directory.  $File::Find::name contains
`"$File::Find::dir/$_"'.  You are chdir()'d to $File::Find::dir when the
function is called.  The function may set $File::Find::prune to prune the
tree.

File::Find assumes that you don't alter the $_ variable.  If you do then
make sure you return it to its original value before exiting your function.

This library is primarily for the find2perl tool, which when fed,

     find2perl / -name .nfs\* -mtime +7 \
     	-exec rm -f {} \; -o -fstype nfs -prune

produces something like:

     sub wanted {
         /^\.nfs.*$/ &&
         (($dev,$ino,$mode,$nlink,$uid,$gid) = lstat($_)) &&
         int(-M _) > 7 &&
         unlink($_)
         ||
         ($nlink || (($dev,$ino,$mode,$nlink,$uid,$gid) = lstat($_))) &&
         $dev < 0 &&
         ($File::Find::prune = 1);
     }

Set the variable $File::Find::dont_use_nlink if you're using AFS, since
AFS cheats.

`finddepth' is just like `find', except that it does a depth-first search.

Here's another interesting wanted function.  It will find all symlinks
that don't resolve:

     sub wanted {
     	-l && !-e && print "bogus link: $File::Find::name\n";
     }


File: pm.info,  Node: File/Flock,  Next: File/Listing,  Prev: File/Find,  Up: Module List

file locking with flock
***********************

NAME
====

     File::Flock - file locking with flock

SYNOPSIS
========

     use File::Flock;

     lock($filename);

     lock($filename, 'shared');

     lock($filename, undef, 'nonblocking');

     lock($filename, 'shared', 'nonblocking');

     unlock($filename);

DESCRIPTION
===========

Lock files using the flock() call.  If the file to be locked does not
exist, then the file is created.  If the file was created then it will be
removed when it is unlocked assuming it's still an empty file.

AUTHOR
======

David Muir Sharnoff, <muir@idiom.com>


File: pm.info,  Node: File/Listing,  Next: File/Path,  Prev: File/Flock,  Up: Module List

parse directory listing
***********************

NAME
====

parse_dir - parse directory listing

SYNOPSIS
========

     use File::Listing;
     for (parse_dir(`ls -l`)) {
         ($name, $type, $size, $mtime, $mode) = @$_;
         next if $type ne 'f'; # plain file
         #...
     }

     # directory listing can also be read from a file
     open(LISTING, "zcat ls-lR.gz|");
     $dir = parse_dir(\*LISTING, '+0000');

DESCRIPTION
===========

The parse_dir() routine can be used to parse directory listings. Currently
it only understand Unix `'ls -l'' and `'ls -lR'' format.  It should
eventually be able to most things you might get back from a ftp server
file listing (LIST command), i.e. VMS listings, NT listings, DOS
listings,...

The first parameter to parse_dir() is the directory listing to parse.  It
can be a scalar, a reference to an array of directory lines or a glob
representing a filehandle to read the directory listing from.

The second parameter is the time zone to use when parsing time stamps in
the listing. If this value is undefined, then the local time zone is
assumed.

The third parameter is the type of listing to assume.  The values will be
strings like 'unix', 'vms', 'dos'.  Currently only 'unix' is implemented
and this is also the default value.  Ideally, the listing type should be
determined automatically.

The fourth parameter specify how unparseable lines should be treated.
Values can be 'ignore', 'warn' or a code reference.  Warn means that the
perl warn() function will be called.  If a code reference is passed, then
this routine will be called and the return value from it will be
incorporated in the listing.  The default is 'ignore'.

Only the first parameter is mandatory.  The parse_dir() prototype is
($;$$$).

The return value from parse_dir() is a list of directory entries.  In
scalar context the return value is a reference to the list.  The directory
entries are represented by an array consisting of [ $filename, $filetype,
$filesize, $filetime, $filemode ].  The $filetype value is one of the
letters 'f', 'd', 'l' or '?'.  The $filetime value is converted to seconds
since Jan 1, 1970.  The $filemode is a bitmask like the mode returned by
stat().

CREDITS
=======

Based on lsparse.pl (from Lee McLoughlin's ftp mirror package) and
Net::FTP's parse_dir (Graham Barr).


File: pm.info,  Node: File/Path,  Next: File/PathConvert,  Prev: File/Listing,  Up: Module List

create or remove a series of directories
****************************************

NAME
====

File::Path - create or remove a series of directories

SYNOPSIS
========

`use File::Path'

`mkpath(['/foo/bar/baz', 'blurfl/quux'], 1, 0711);'

`rmtree(['foo/bar/baz', 'blurfl/quux'], 1, 1);'

DESCRIPTION
===========

The `mkpath' function provides a convenient way to create directories,
even if your mkdir kernel call won't create more than one level of
directory at a time.  `mkpath' takes three arguments:

   * the name of the path to create, or a reference to a list of paths to
     create,

   * a boolean value, which if TRUE will cause `mkpath' to print the name
     of each directory as it is created (defaults to FALSE), and

   * the numeric mode to use when creating the directories (defaults to
     0777)

It returns a list of all directories (including intermediates, determined
using the Unix '/' separator) created.

Similarly, the `rmtree' function provides a convenient way to delete a
subtree from the directory structure, much like the Unix command `rm -r'.
`rmtree' takes three arguments:

   * the root of the subtree to delete, or a reference to a list of roots.
     All of the files and directories below each root, as well as the
     roots themselves, will be deleted.

   * a boolean value, which if TRUE will cause `rmtree' to print a message
     each time it examines a file, giving the name of the file, and
     indicating whether it's using rmdir or unlink to remove it, or that
     it's skipping it.  (defaults to FALSE)

   * a boolean value, which if TRUE will cause `rmtree' to skip any files
     to which you do not have delete access (if running under VMS) or
     write access (if running under another OS).  This will change in the
     future when a criterion for 'delete permission' under OSs other than
     VMS is settled. (defaults to FALSE)

It returns the number of files successfully deleted. Symlinks are treated
as ordinary files.

AUTHORS
=======

Tim Bunce <`Tim.Bunce@ig.co.uk'> Charles Bailey
<`bailey@genetics.upenn.edu'>

REVISION
========

This module was last revised 14-Feb-1996, for perl 5.002. $VERSION is 1.01.


File: pm.info,  Node: File/PathConvert,  Next: File/Recurse,  Prev: File/Path,  Up: Module List

make an canonicalized absolute path name
****************************************

NAME
====

realpath - make an canonicalized absolute path name

abs2rel - make a relative path from an absolute path

rel2abs - make an absolute path from a relative path

SYNOPSIS
========

`use File::PathConvert;'

`$path = realpath($path);'

`$path = abs2rel($path);' .br `$path = abs2rel($path, $base);'

`$path = rel2abs($path);' .br `$path = rel2abs($path, $base);'

DESCRIPTION
===========

The PathConvert module provides three functions.

realpath
     realpath make a canonicalized absolute pathname.  The realpath
     resolves all symbolic links, extra ``/'' characters and references to
     /./ and /../ in the path.  The realpath will resolve both absolute
     and relative paths.  realpath return resolved name on success else
     undef and set valiable $resolved to pathname which caused the problem.

     All but the last component of the path must exist.

     This implementation based on 4.4BSD realpath(3).

abs2rel
     abs2rel make a relative path from an absolute path.  By default, the
     base is current directory.  If you specify second parameter, it's
     assumed the base.

     Returned path may include symbolic links.  abs2rel doesn't check
     whether any path exist or not.

rel2abs
     rel2abs make a absolute path from an relative path.  By default, the
     base directory is current directory.  If you specify second
     parameter, it's assumed the base.

     Returned path may include symbolic links.  abs2rel doesn't check
     whether any path exist or not.

EXAMPLES
========

realpath
          If '/sys' is symbolic link to '/usr/src/sys',

          chdir('/usr');
          $path = realpath('../sys/kern');

     or in anywhere ...

          $path = realpath('/sys/kern');

     would yield

          $path eq '/usr/src/sys/kern'

abs2rel
          chdir('/usr/local/lib');
          $path = abs2rel('/usr/src/sys');

     or in anywhere ...

          $path = abs2rel('/usr/src/sys', '/usr/local/lib');

     would yield

          $path eq '../../src/sys'

     Similarly,

          $path1 = abs2rel('/usr/src/sys', '/usr');
          $path2 = abs2rel('/usr/src/sys', '/usr/src/sys');

     would yield

          $path1 eq 'src/sys'
          $path2 eq '.'

     If the base directory includes symbolic links, abs2rel produce wrong
     path.  For example, '/sys' is a symbolic link to '/usr/src/sys',

          $path = abs2rel('/usr/local/lib', '/sys');

     would yield

          $path eq '../usr/local/lib'		# It's wrong!!

     You should convert the base directory into a real path in advance.

          $path = abs2rel('/sys/kern', realpath('/sys'));

     would yield

          $path eq '../../../sys/kern'	# It's correct but ...

     It's correct but a little redundant. If you wish get a simple answer
     'kern', do the following.

          $path = abs2rel(realpath('/sys/kern'), realpath('/sys'));

     realpath() make the result correct but don't forget realpath require
     that all but the last component of the path exist.

rel2abs
          chdir('/usr/local/lib');
          $path = rel2abs('../../src/sys');

     or in anywhere ...

          $path = rel2abs('../../src/sys', '/usr/local/lib');

     would yield

          $path eq '/usr/src/sys'

     Similarly,

          $path = rel2abs('src/sys', '/usr');
          $path = rel2abs('.', '/usr/src/sys');

     would yield

          $path eq '/usr/src/sys'

AUTHOR
======

Shigio Yamaguchi <shigio@ca2.so-net.or.jp>


File: pm.info,  Node: File/Recurse,  Next: File/Slurp,  Prev: File/PathConvert,  Up: Module List

Recurse over files, performing some function.
*********************************************

NAME
====

File::Recurse - Recurse over files, performing some function.

SYNOPSIS
========

     use File::Recurse;
     use File::Copy;

     recurse { print } "/tmp";
     recurse {copy($_,"elsewhere") if -f $_} "dir";
     recurse(\&func, "/");

DESCRIPTION
===========

The `File::Recurse' module is designed for performing an operation on a
tree of directories and files. The basic usage is simmilar to the
`find.pl' library. Once one uses the File::Recurse module, you need only
call the `recurse' function in order to perform recursive directory
operations.

The function takes two parameters a function reference and a directory.
The function referenced by the first parameter should expect to take one
parameter: the full path to the file currently being operated on. This
function is called once for every file and directory under the directory
named by the second parameter.

For example:

     recurse(\&func, "/");

would start at the top level of the filesystem and call "func" for every
file and directory found (not including "/").

Perl allows a second form of calling this function which can be useful for
situations where you want to do something simple in the function. In these
cases, you can define an anonymous function by using braces like so:

     recurse {print $_[0]} "/";

This would print every file and directory in the filesystem. However, as
an added convenience you can access the pathname in the variable $_. So
the above could be rewritten as:

     recurse { print } "/";

Context
-------

There is an optional third parameter which can be any scalar value
(including a reference). This value is ignored by recurse, but will be
passed as the second parameter to the user-defined function. This can be
useful for building library routines that use recurse, so that they do not
have to pass state to the function as global variables.

Controling Recursion
--------------------

If you want to control how recursion happens, you have several options.
First, there are some global variables that affect the overall operation
of the recurse routine:

`$MAX_DEPTH'
     This variable controls how far down a tree of directories recurse
     will go before it assumes that something bad has happened. Default:
     100.

`$FOLLOW_SYMLINKS'
     This variable tells recurse if it should descend into directories
     that are symbolic links. Default: 0.

Normally, the return value of the function called is not used, but if it
is -1 or -2, there is a special action taken.

If the function returns -1 and the current filename refers to a directory,
recurse will *not* descend into that directory. This can be used to prune
searches and focus only on those directories which should be followed.

If the function returns -2, the search is terminated, and recurse will
return. This can be used to bail when a problem occurs, and you don't want
to exit the program, or to end the search for some file once it is found.

SEE ALSO
========

*Note File/Tools: File/Tools,

AUTHOR
======

Written in 1996 by Aaron Sherman, ajs@ajs.com


File: pm.info,  Node: File/Slurp,  Next: File/Tools,  Prev: File/Recurse,  Up: Module List

single call read & write file routines; read directories
********************************************************

NAME
====

     File::Slurp -- single call read & write file routines; read directories

SYNOPSIS
========

     use File::Slurp;

     $all_of_it = read_file($filename);
     @all_lines = read_file($filename);

     write_file($filename, @contents)

     overwrite_file($filename, @new_contnts);

     append_file($filename, @additional_contents);

     @files = read_dir($directory);

DESCRIPTION
===========

These are quickie routines that are meant to save a couple of lines of
code over and over again.  They do not do anything fancy.

read_file() does what you would expect.  If you are using its output in
array context, then it returns an array of lines.  If you are calling it
from scalar context, then returns the entire file in a single string.

It croaks()s if it can't open the file.

write_file() creates or overwrites files.

append_file() appends to a file.

overwrite_file() does an in-place update of an existing file or creates a
new file if it didn't already exist.  Write_file will also replace a file.
The difference is that the first that that write_file() does is to
trucate the file whereas the last thing that overwrite_file() is to
trucate the file.  Overwrite_file() should be used in situations where you
have a file that always needs to have contents, even in the middle of an
update.

read_dir() returns all of the entries in a directory except for "." and
"..".  It croaks if it cannot open the directory.

AUTHOR
======

David Muir Sharnoff <muir@idiom.com>


File: pm.info,  Node: File/Tools,  Next: FileCache,  Prev: File/Slurp,  Up: Module List

This module is a wrapper for the various File moudles.
******************************************************

NAME
====

File::Tools - This module is a wrapper for the various File moudles.

SYNOPSIS
========

     use File::Tools;
     copy("x", *STDOUT);
     recurse { print } "/etc";

DESCRIPTION
===========

Provides the routines that are defined in File::Recurse and File::Copy.

Other modules will be added at a later date, but File::Tools will always
encapsulate them.

SEE ALSO
========

*Note File/Copy: File/Copy, and *Note File/Recurse: File/Recurse,

AUTHOR
======

Written in 1996 by Aaron Sherman


File: pm.info,  Node: FileCache,  Next: FileHandle,  Prev: File/Tools,  Up: Module List

keep more files open than the system permits
********************************************

NAME
====

FileCache - keep more files open than the system permits

SYNOPSIS
========

     cacheout $path;
     print $path @data;

DESCRIPTION
===========

The `cacheout' function will make sure that there's a filehandle open for
writing available as the pathname you give it.  It automatically closes
and re-opens files if you exceed your system file descriptor maximum.

BUGS
====

`sys/param.h' lies with its `NOFILE' define on some systems, so you may
have to set $cacheout::maxopen yourself.


File: pm.info,  Node: FileHandle,  Next: Filter/Util/Call,  Prev: FileCache,  Up: Module List

supply object methods for filehandles
*************************************

NAME
====

FileHandle - supply object methods for filehandles

SYNOPSIS
========

     use FileHandle;

     $fh = new FileHandle;
     if ($fh->open "< file") {
         print <$fh>;
         $fh->close;
     }

     $fh = new FileHandle "> FOO";
     if (defined $fh) {
         print $fh "bar\n";
         $fh->close;
     }

     $fh = new FileHandle "file", "r";
     if (defined $fh) {
         print <$fh>;
         undef $fh;       # automatically closes the file
     }

     $fh = new FileHandle "file", O_WRONLY|O_APPEND;
     if (defined $fh) {
         print $fh "corge\n";
         undef $fh;       # automatically closes the file
     }

     $pos = $fh->getpos;
     $fh->setpos $pos;

     $fh->setvbuf($buffer_var, _IOLBF, 1024);

     ($readfh, $writefh) = FileHandle::pipe;

     autoflush STDOUT 1;

DESCRIPTION
===========

`FileHandle::new' creates a FileHandle, which is a reference to a newly
created symbol (see the Symbol package).  If it receives any parameters,
they are passed to `FileHandle::open'; if the open fails, the FileHandle
object is destroyed.  Otherwise, it is returned to the caller.

`FileHandle::new_from_fd' creates a FileHandle like new does.  It requires
two parameters, which are passed to `FileHandle::fdopen'; if the fdopen
fails, the FileHandle object is destroyed.  Otherwise, it is returned to
the caller.

`FileHandle::open' accepts one parameter or two.  With one parameter, it
is just a front end for the built-in open function.  With two parameters,
the first parameter is a filename that may include whitespace or other
special characters, and the second parameter is the open mode, optionally
followed by a file permission value.

If `FileHandle::open' receives a Perl mode string (">", "+<", etc.) or a
POSIX fopen() mode string ("w", "r+", etc.), it uses the basic Perl open
operator.

If `FileHandle::open' is given a numeric mode, it passes that mode and the
optional permissions value to the Perl sysopen operator.  For convenience,
`FileHandle::import' tries to import the O_XXX constants from the Fcntl
module.  If dynamic loading is not available, this may fail, but the rest
of FileHandle will still work.

`FileHandle::fdopen' is like open except that its first parameter is not a
filename but rather a file handle name, a FileHandle object, or a file
descriptor number.

If the C functions fgetpos() and fsetpos() are available, then
`FileHandle::getpos' returns an opaque value that represents the current
position of the FileHandle, and `FileHandle::setpos' uses that value to
return to a previously visited position.

If the C function setvbuf() is available, then `FileHandle::setvbuf' sets
the buffering policy for the FileHandle.  The calling sequence for the
Perl function is the same as its C counterpart, including the macros
`_IOFBF', `_IOLBF', and `_IONBF', except that the buffer parameter
specifies a scalar variable to use as a buffer.  WARNING: A variable used
as a buffer by `FileHandle::setvbuf' must not be modified in any way until
the FileHandle is closed or until `FileHandle::setvbuf' is called again,
or memory corruption may result!

See *Note Perlfunc: (perl.info)perlfunc, for complete descriptions of each
of the following supported FileHandle methods, which are just front ends
for the corresponding built-in functions:

close     fileno     getc     gets     eof     clearerr     seek     tell

See *Note Perlvar: (perl.info)perlvar, for complete descriptions of each
of the following supported FileHandle methods:

     autoflush
     output_field_separator
     output_record_separator
     input_record_separator
     input_line_number
     format_page_number
     format_lines_per_page
     format_lines_left
     format_name
     format_top_name
     format_line_break_characters
     format_formfeed

Furthermore, for doing normal I/O you might need these:

$fh->print
     See `print', *Note Perlfunc: (perl.info)perlfunc,.

$fh->printf
     See `printf', *Note Perlfunc: (perl.info)perlfunc,.

$fh->getline
     This works like <$fh> described in `"I', *Note Perlop:
     (perl.info)perlop, except that it's more readable and can be safely
     called in an array context but still returns just one line.

$fh->getlines
     This works like <$fh> when called in an array context to read all the
     remaining lines in a file, except that it's more readable.  It will
     also croak() if accidentally called in a scalar context.

SEE ALSO
========

*Note Perlfunc: (perl.info)perlfunc,, `"I', *Note Perlop:
(perl.info)perlop,, `"FileHandle"', *Note POSIX: POSIX,

BUGS
====

Due to backwards compatibility, all filehandles resemble objects of class
FileHandle, or actually classes derived from that class.  They actually
aren't.  Which means you can't derive your own class from FileHandle and
inherit those methods.


File: pm.info,  Node: Filter/Util/Call,  Next: Filter/Util/Exec,  Prev: FileHandle,  Up: Module List

Perl Source Filter Utility Module
*********************************

NAME
====

Filter::Util::Call - Perl Source Filter Utility Module

DESCRIPTION
===========

This module provides you with the framework to write *Source Filters* in
Perl.

A *Perl Source Filter* is implemented as a Perl module. The structure of
the module can take one of two broadly similar formats. To distinguish
between them, the first will be referred to as *method filter* and the
second as *closure filter*.

Here is a skeleton for the *method filter*:

     package MyFilter ;
     
     use Filter::Util::Call ;

     sub import
     {
         my($type, @arguments) = @_ ;
         filter_add([]) ;
     }
     
     sub filter
     {
         my($self) = @_ ;
         my($status) ;
     
         $status = filter_read() ;
         $status ;
     }
     
     1 ;

and this is the equivalent skeleton for the *closure filter*:

     package MyFilter ;
     
     use Filter::Util::Call ;

     sub import
     {
         my($type, @arguments) = @_ ;
     
         filter_add(
             sub
             {
                 my($status) ;
                 $status = filter_read() ;
                 $status ;
             } )
     }
     
     1 ;

To make use of either of the two filter modules above, place the line
below in a Perl source file.

     use MyFilter;

In fact, the skeleton modules shown above are fully functional *Source
Filters*, albeit fairly useless ones. All they does is filter the source
stream without modifying it at all.

As you can see both modules have a broadly similar structure. They both
make use of the `Filter::Util::Call' module and both have an import
method. The difference between them is that the *method filter* requires a
*filter* method, whereas the *closure filter* gets the equivalent of a
*filter* method with the anonymous sub passed to *filter_add*.

To make proper use of the *closure filter* shown above you need to have a
good understanding of the concept of a *closure*. See *Note Perlref:
(perl.info)perlref, for more details on the mechanics of *closures*.

use Filter::Util::Call
----------------------

The following functions are exported by `Filter::Util::Call':

     filter_add()
     filter_read()
     filter_read_exact()
     filter_del()

import()
--------

The import method is used to create an instance of the filter. It is
called indirectly by Perl when it encounters the `use MyFilter' line in a
source file (See `import', *Note Perlfunc: (perl.info)perlfunc, for more
details on import).

It will always have at least one parameter automatically passed by Perl -
this corresponds to the name of the package. In the example above it will
be `"MyFilter"'.

Apart from the first parameter, import can accept an optional list of
parameters. These can be used to pass parameters to the filter. For
example:

     use MyFilter qw(a b c) ;

will result in the `@_' array having the following values:

     @_ [0] => "MyFilter"
     @_ [1] => "a"
     @_ [2] => "b"
     @_ [3] => "c"

Before terminating, the import function must explicitly install the filter
by calling `filter_add'.

*filter_add()*

The function, `filter_add', actually installs the filter. It takes one
parameter which should be a reference. The kind of reference used will
dictate which of the two filter types will be used.

If a CODE reference is used then a *closure filter* will be assumed.

If a CODE reference is not used, a *method filter* will be assumed.  In a
*method filter*, the reference can be used to store context information.
The reference will be *blessed* into the package by `filter_add'.

See the filters at the end of this documents for examples of using context
information using both *method filters* and *closure filters*.

filter() and anonymous sub
--------------------------

Both the `filter' method used with a *method filter* and the anonymous sub
used with a *closure filter* is where the main processing for the filter
is done.

The big difference between the two types of filter is that the *method
filter* uses the object passed to the method to store any context data,
whereas the *closure filter* uses the lexical variables that are
maintained by the closure.

Note that the single parameter passed to the *method filter*, `$self', is
the same reference that was passed to `filter_add' blessed into the
filter's package. See the example filters later on for details of using
`$self'.

Here is a list of the common features of the anonymous sub and the
`filter()' method.

$_
     Although $_ doesn't actually appear explicitly in the sample filters
     above, it is implicitly used in a number of places.

     Firstly, when either `filter' or the anonymous sub are called, a local
     copy of $_ will automatically be created. It will always contain the
     empty string at this point.

     Next, both filter_read and `filter_read_exact' will append any source
     data that is read to the end of $_.

     Finally, when `filter' or the anonymous sub are finished processing,
     they are expected to return the filtered source using $_.

     This implicit use of $_ greatly simplifies the filter.

$status
     The status value that is returned by the user's `filter' method or
     anonymous sub and the filter_read and `read_exact' functions take the
     same set of values, namely:

          < 0  Error
          = 0  EOF
          > 0  OK

filter_read and *filter_read_exact*
     These functions are used by the filter to obtain either a line or
     block from the next filter in the chain or the actual source file if
     there aren't any other filters.

     The function filter_read takes two forms:

          $status = filter_read() ;
          $status = filter_read($size) ;

     The first form is used to request a *line*, the second requests a
     *block*.

     In line mode, filter_read will append the next source line to the end
     of the $_ scalar.

     In block mode, filter_read will append a block of data which is <=
     `$size' to the end of the $_ scalar. It is important to emphasise the
     that filter_read will not necessarily read a block which is
     *precisely* `$size' bytes.

     If you need to be able to read a block which has an exact size, you
     can use the function `filter_read_exact'. It works identically to
     filter_read in block mode, except it will try to read a block which
     is exactly `$size' bytes in length. The only circumstances when it
     will not return a block which is `$size' bytes long is on EOF or
     error.

     It is *very* important to check the value of $status after *every*
     call to filter_read or `filter_read_exact'.

filter_del
     The function, filter_del, is used to disable the current filter. It
     does not affect the running of the filter. All it does is tell Perl
     not to call filter any more.

     See `Example 4: Using filter_del' in this node for details.

EXAMPLES
========

Here are a few examples which illustrate the key concepts - as such most
of them are of little practical use.

The `examples' sub-directory has copies of all these filters implemented
both as *method filters* and as *closure filters*.

Example 1: A simple filter.
---------------------------

Below is a *method filter* which is hard-wired to replace all occurrences
of the string `"Joe"' to `"Jim"'. Not particularly useful, but it is the
first example and I wanted to keep it simple.

     package Joe2Jim ;
     
     use Filter::Util::Call ;

     sub import
     {
         my($type) = @_ ;
     
         filter_add(bless []) ;
     }
     
     sub filter
     {
         my($self) = @_ ;
         my($status) ;
     
         s/Joe/Jim/g
             if ($status = filter_read()) > 0 ;
         $status ;
     }
     
     1 ;

Here is an example of using the filter:

     use Joe2Jim ;
     print "Where is Joe?\n" ;

And this is what the script above will print:

     Where is Jim?

Example 2: Using the context
----------------------------

The previous example was not particularly useful. To make it more general
purpose we will make use of the context data and allow any arbitrary
*from* and to strings to be used. This time we will use a *closure
filter*. To reflect its enhanced role, the filter is called `Subst'.

     package Subst ;
     
     use Filter::Util::Call ;
     use Carp ;
     
     sub import
     {
         croak("usage: use Subst qw(from to)")
             unless @_ == 3 ;
         my ($self, $from, $to) = @_ ;
         filter_add(
             sub
             {
                 my ($status) ;
                 s/$from/$to/
                     if ($status = filter_read()) > 0 ;
                 $status ;
             })
     }
     1 ;

and is used like this:

     use Subst qw(Joe Jim) ;
     print "Where is Joe?\n" ;

Example 3: Using the context within the filter
----------------------------------------------

Here is a filter which a variation of the `Joe2Jim' filter. As well as
substituting all occurrences of `"Joe"' to `"Jim"' it keeps a count of the
number of substitutions made in the context object.

Once EOF is detected ($status is zero) the filter will insert an extra
line into the source stream. When this extra line is executed it will
print a count of the number of substitutions actually made.  Note that
$status is set to 1 in this case.

     package Count ;
     
     use Filter::Util::Call ;
     
     sub filter
     {
         my ($self) = @_ ;
         my ($status) ;
     
         if (($status = filter_read()) > 0 ) {
             s/Joe/Jim/g ;
     	    ++ $$self ;
         }
     	elsif ($$self >= 0) { # EOF
             $_ = "print q[Made ${$self} substitutions\n]" ;
             $status = 1 ;
     	    $$self = -1 ;
         }

     $status ;
         }
     
         sub import
         {
     my ($self) = @_ ;
     my ($count) = 0 ;
     filter_add(\$count) ;
         }
     
         1 ;

Here is a script which uses it:

     use Count ;
     print "Hello Joe\n" ;
     print "Where is Joe\n" ;

Outputs:

     Hello Jim
     Where is Jim
     Made 2 substitutions

Example 4: Using filter_del
---------------------------

Another variation on a theme. This time we will modify the `Subst' filter
to allow a starting and stopping pattern to be specified as well as the
*from* and to patterns. If you know the *vi* editor, it is the equivalent
of this command:

     :/start/,/stop/s/from/to/

When used as a filter we want to invoke it like this:

     use NewSubst qw(start stop from to) ;

Here is the module.

     package NewSubst ;
     
     use Filter::Util::Call ;
     use Carp ;
     
     sub import
     {
         my ($self, $start, $stop, $from, $to) = @_ ;
         my ($found) = 0 ;
         croak("usage: use Subst qw(start stop from to)")
             unless @_ == 5 ;
     
         filter_add(
             sub
             {
                 my ($status) ;
     
                 if (($status = filter_read()) > 0) {
     
                     $found = 1
                         if $found == 0 and /$start/ ;
     
                     if ($found) {
                         s/$from/$to/ ;
                         filter_del() if /$stop/ ;
                     }
     
                 }
                 $status ;
             } )
     
     }
     
     1 ;

AUTHOR
======

Paul Marquess

DATE
====

26th January 1996


File: pm.info,  Node: Filter/Util/Exec,  Next: Filter/cpp,  Prev: Filter/Util/Call,  Up: Module List

exec source filter
******************

NAME
====

Filter::Util::Exec - exec source filter

DESCRIPTION
===========

This module is provides the interface to allow the creation of *Source
Filters* which use a Unix coprocess.

See *Note Filter/exec: Filter/exec,, *Note Filter/cpp: Filter/cpp, and
*Note Filter/sh: Filter/sh, for examples of the use of this module.

AUTHOR
======

Paul Marquess

DATE
====

11th December 1995.


File: pm.info,  Node: Filter/cpp,  Next: Filter/decrypt,  Prev: Filter/Util/Exec,  Up: Module List

cpp source filter
*****************

NAME
====

Filter::cpp - cpp source filter

SYNOPSIS
========

     use Filter::cpp ;

DESCRIPTION
===========

This source filter pipes the current source file through the C
pre-processor (cpp) if it is available.

As with all source filters its scope is limited to the current source file
only. Every file you want to be processed by the filter must have a

     use Filter::cpp ;

near the top.

Here is an example script which uses the filter:

     use Filter::cpp ;

     #define FRED 1
     $a = 2 + FRED ;
     print "a = $a\n" ;
     #ifdef FRED
     print "Hello FRED\n" ;
     #else
     print "Where is FRED\n" ;
     #endif

And here is what it will output:

     a = 3
     Hello FRED

AUTHOR
======

Paul Marquess

DATE
====

11th December 1995.


File: pm.info,  Node: Filter/decrypt,  Next: Filter/exec,  Prev: Filter/cpp,  Up: Module List

template for a decrypt source filter
************************************

NAME
====

Filter::decrypt - template for a decrypt source filter

SYNOPSIS
========

     use Filter::decrypt ;

DESCRIPTION
===========

This is a sample decrypting source filter.

Although this is a fully functional source filter and it does implement a
*very* simple decrypt algorithm, it is *not* intended to be used as it is
supplied. Consider it to be a template which you can combine with a proper
decryption algorithm to develop your own decryption filter.

WARNING
=======

It is important to note that a decryption filter can *never* provide
complete security against attack. At some point the parser within Perl
needs to be able to scan the original decrypted source. That means that at
some stage fragments of the source will exist in a memory buffer.

The best you can hope to achieve by decrypting your Perl source using a
source filter is to make it impractical to crack.

Given that proviso, there are a number of things you can do to make life
more difficult for the prospective cracker.

  1. Strip the Perl binary to remove all symbols.

  2. Build the decrypt extension using static linking. If the extension is
     provided as a dynamic module, there is nothing to stop someone from
     linking it at run time with a modified Perl binary.

  3. Do not build Perl with `-DDEBUGGING'. If you do then your source can
     be retrieved with the `-Dp' command line option.

     The sample filter contains logic to detect the DEBUGGING option.

  4. Do not build Perl with C debugging support enabled.

  5. Do not implement the decryption filter as a sub-process (like the cpp
     source filter). It is possible to peek into the pipe that connects to
     the sub-process.

  6. Do not use the decrypt filter as-is. The algorithm used in this filter
     has been purposefully left simple.

     If you feel that the source filtering mechanism is not secure enough
you could try using the unexec/undump method. See the Perl FAQ for further
details.

AUTHOR
======

Paul Marquess

DATE
====

19th December 1995


File: pm.info,  Node: Filter/exec,  Next: Filter/sh,  Prev: Filter/decrypt,  Up: Module List

exec source filter
******************

NAME
====

Filter::exec - exec source filter

SYNOPSIS
========

     use Filter::exec qw(command parameters) ;

DESCRIPTION
===========

This filter pipes the current source file through the program which
corresponds to the command parameter.

As with all source filters its scope is limited to the current source file
only. Every file you want to be processed by the filter must have a

     use Filter::exec qw(command ) ;

near the top.

Here is an example script which uses the filter:

     use Filter::exec qw(tr XYZ PQR) ;
     $a = 1 ;
     print "XYZ a = $a\n" ;

And here is what it will output:

     PQR = 1

WARNING
=======

You should be *very* careful when using this filter. Because of the way
the filter is implemented it is possible to end up with deadlock.

Be especially careful when stacking multiple instances of the filter in a
single source file.

AUTHOR
======

Paul Marquess

DATE
====

11th December 1995.


File: pm.info,  Node: Filter/sh,  Next: Filter/tee,  Prev: Filter/exec,  Up: Module List

sh source filter
****************

NAME
====

Filter::sh - sh source filter

SYNOPSIS
========

     use Filter::sh 'command' ;

DESCRIPTION
===========

This filter pipes the current source file through the program which
corresponds to the command parameter using the Bourne shell.

As with all source filters its scope is limited to the current source file
only. Every file you want to be processed by the filter must have a

     use Filter::sh 'command' ;

near the top.

Here is an example script which uses the filter:

     use Filter::sh 'tr XYZ PQR' ;
     $a = 1 ;
     print "XYZ a = $a\n" ;

And here is what it will output:

     PQR = 1

WARNING
=======

You should be *very* careful when using this filter. Because of the way
the filter is implemented it is possible to end up with deadlock.

Be especially careful when stacking multiple instances of the filter in a
single source file.

AUTHOR
======

Paul Marquess

DATE
====

11th December 1995.


File: pm.info,  Node: Filter/tee,  Next: FindBin,  Prev: Filter/sh,  Up: Module List

tee source filter
*****************

NAME
====

Filter::tee - tee source filter

SYNOPSIS
========

     use Filter::tee 'filename' ;
     use Filter::tee '>filename' ;
     use Filter::tee '>>filename' ;

DESCRIPTION
===========

This filter copies all text from the line after the use in the current
source file to the file specified by the parameter `filename'.

By default and when the filename is prefixed with a '>' the output file
will be emptied first if it already exists.

If the output filename is prefixed with '>>' it will be opened for
appending.

This filter is useful as a debugging aid when developing other source
filters.

AUTHOR
======

Paul Marquess

DATE
====

20th June 1995.


File: pm.info,  Node: FindBin,  Next: Font/AFM,  Prev: Filter/tee,  Up: Module List

Locate directory of original perl script
****************************************

NAME
====

FindBin - Locate directory of original perl script

SYNOPSIS
========

     use FindBin;
     use lib "$FindBin::Bin/../lib";

     or

     use FindBin qw($Bin);
     use lib "$Bin/../lib";

DESCRIPTION
===========

Locates the full path to the script bin directory to allow the use of
paths relative to the bin directory.

This allows a user to setup a directory tree for some software with
directories <root>/bin and <root>/lib and then the above example will allow
the use of modules in the lib directory without knowing where the software
tree is installed.

If perl is invoked using the -e option or the perl script is read from
`STDIN' then FindBin sets both `$Bin' and `$RealBin' to the current
directory.

EXPORTABLE VARIABLES
====================

     $Bin         - path to bin directory from where script was invoked
     $Script      - basename of script from which perl was invoked
     $RealBin     - $Bin with all links resolved
     $RealScript  - $Script with all links resolved

KNOWN BUGS
==========

if perl is invoked as

     perl filename

and *filename* does not have executable rights and a program called
*filename* exists in the users `$ENV{PATH}' which satisfies both -x and -T
then FindBin assumes that it was invoked via the `$ENV{PATH}'.

Workaround is to invoke perl as

     perl ./filename

AUTHORS
=======

Graham Barr <`bodg@tiuk.ti.com'> Nick Ing-Simmons <`nik@tiuk.ti.com'>

COPYRIGHT
=========

Copyright (c) 1995 Graham Barr & Nick Ing-Simmons. All rights reserved.
This program is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

REVISION
========

$Revision: 1.4 $


File: pm.info,  Node: Font/AFM,  Next: GD,  Prev: FindBin,  Up: Module List

Interface to Adobe Font Metrics files
*************************************

NAME
====

Font::AFM - Interface to Adobe Font Metrics files

SYNOPSIS
========

     use Font::AFM;
     $h = new Font::AFM "Helvetica";
     $copyright = $h->Notice;
     $w = $h->Wx->{"aring"};
     $w = $h->stringwidth("Gisle", 10);
     $h->dump;  # for debugging

DESCRIPTION
===========

This module implements the Font::AFM class. Objects of this class are
initialised from an AFM-file and allows you to obtain information about
the font and the metrics of the various glyphs in the font.

All measurements in AFM files are given in terms of units equal to 1/1000
of the scale factor of the font being used. To compute actual sizes in a
document, these amounts should be multiplied by (scale factor of
font)/1000.

The following methods are available:

new($fontname)
     Object constructor. Takes the name of the font as argument. It will
     croak if the font can not be found.

latin1_wx_table()
     Returns a 256 element array, where each element contains the width of
     the corresponding character in the iso-8859-1 character set.

stringwidth($string, [$fontsize])
     Returns the width of the string passed as argument. The string is
     assumed to be encoded in the iso-8859-1 character set.  A second
     argument can be used to scale the width according to the font size.

FontName
     The name of the font as presented to the PostScript language
     `findfont' operator, for instance "Times-Roman".

FullName
     Unique, human-readable name for an individual font, for instance
     "Times Roman".

FamilyName
     Human-readable name for a group of fonts that are stylistic variants
     of a single design. All fonts that are member of such a group should
     have exactly the same FamilyName. Example of a family name is "Times".

Weight
     Human-readable name for the weight, or "boldness", attribute of a
     font.  Exampes are `Roman', `Bold', `Light'.

ItalicAngle
     Angle in degrees counterclockwise from the vertical of the dominant
     vertical strokes of the font.

IsFixedPitch
     If the value is `true', it indicated that the font is a fixed-pitch
     (monospaced) font.

FontBBox
     A string of four numbers giving the lower-left x, lower-left y,
     upper-right x, and upper-right y of the font bounding box. The font
     bounding box is the smallest rectangle enclosing the shape that would
     result if all the characters of the font were placed with their
     origins coincident, and then painted.

UnderlinePosition
     Recommended distance from the baseline for positioning underline
     stokes. This number is the y coordinate of the center of the stroke.

UnderlineThickness
     Recommended stroke width for underlining.

Version
     Version number of the font.

Notice
     Trademark or copyright notice, if applicable.

Comment
     Comments found in the AFM file.

EncodingScheme
     The name of the standard encoding scheme for the font. Most Adobe
     fonts use the `AdobeStandardEncoding'. Special fonts might state
     `FontSpecific'.

CapHeight
     Usually the y-value of the top of the capital H.

XHeight
     Typically the y-value of the top of the lowercase x.

Ascender
     Typically the y-value of the top of the lowercase d.

Descender
     Typically the y-value of the bottom of the lowercase p.

Wx
     Returns a hash table that maps from glyph names to the width of that
     glyph.

BBox
     Returns a hash table that maps from glyph names to bounding box
     information.  The bounding box consist of 4 numbers: llx, lly, urx,
     ury.

dump
     Dumps the content of the Font::AFM object to STDOUT.  Might sometimes
     be useful for debugging.

The AFM specification can be found at:

     ftp://ftp.adobe.com/pub/adobe/DeveloperSupport/TechNotes/PSfiles/5004.AFM_Spec.ps

ENVIRONMENT
===========

METRICS
     Contains the path to seach for AFM-files.  Format is as for the PATH
     environment variable. The default path built into this library is:

          /usr/lib/afm:/usr/local/lib/afm:/usr/openwin/lib/fonts/afm/:.

BUGS
====

Kerning data and composite character data is not yet parsed.  Ligature
data is not parsed.

COPYRIGHT
=========

Copyright 1995 Gisle Aas. All rights reserved.

This program is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.


File: pm.info,  Node: GD,  Next: GDBM_File,  Prev: Font/AFM,  Up: Module List

Interface to Gd Graphics Library
********************************

NAME
====

GD.pm - Interface to Gd Graphics Library

DESCRIPTION
===========

*GD.pm* is a port of Thomas Boutell's gd graphics library (see below).  GD
allows you to create color drawings using a large number of graphics
primitives, and emit the drawings as GIF files.

GD defines the following three classes:

`GD::Image'
     An image class, which holds the image data and accepts graphic
     primitive method calls.

`GD::Font'
     A font class, which holds static font information and used for text
     rendering.

`GD::Polygon'
     A simple polygon object, used for storing lists of vertices prior to
     rendering a polygon into an image.

A Simple Example:

     #!/usr/local/bin/perl

     use GD;
     
     # create a new image
     $im = new GD::Image(100,100);

     # allocate some colors
     $white = $im->colorAllocate(255,255,255);
     $black = $im->colorAllocate(0,0,0);
     $red = $im->colorAllocate(255,0,0);
     $blue = $im->colorAllocate(0,0,255);

     # make the background transparent and interlaced
     $im->transparent($white);
     $im->interlaced('true');

     # Put a black frame around the picture
     $im->rectangle(0,0,99,99,$black);

     # Draw a blue oval
     $im->arc(50,50,95,75,0,360,$blue);

     # And fill it with red
     $im->fill(50,50,$red);

     # Convert the image to GIF and print it on standard output
     print $im->gif;

Notes:

  1. To create a new, empty image, send a new() message to GD::Image,
     passing it the width and height of the image you want to create.  An
     image object will be returned.  Other class methods allow you to
     initialize an image from a preexisting GIF, GD or XBM file.

  2. Next you will ordinarily add colors to the image's color table.
     colors are added using a colorAllocate() method call.  The three
     parameters in each call are the red, green and blue (rgb) triples for
     the desired color.  The method returns the index of that color in the
     image's color table.  You should store these indexes for later use.

  3. Now you can do some drawing!  The various graphics primitives are
     described below.  In this example, we do some text drawing, create an
     oval, and create and draw a polygon.

  4. Polygons are created with a new() message to GD::Polygon.  You can
     add points to the returned polygon one at a time using the addPt()
     method. The polygon can then be passed to an image for rendering.

  5. When you're done drawing, you can convert the image into GIF format
     by sending it a gif() message.  It will return a (potentially large)
     scalar value containing the binary data for the image.  Ordinarily
     you will print it out at this point or write it to a file.

Method Calls
============

Creating and Saving Images
--------------------------

new
     `GD::Image::new(width,height)' *class method*

     To create a new, blank image, send a new() message to the GD::Image
     class.  For example:

          $myImage = new GD::Image(100,100) || die;

     This will create an image that is 100 x 100 pixels wide.  If you don't
     specify the dimensions, a default of 64 x 64 will be chosen. If
     something goes wrong (e.g. insufficient memory), this call will
     return undef.

`newFromGif'
     `GD::Image::newFromGif(FILEHANDLE)' *class method*

     This will create an image from a GIF file read in through the provided
     filehandle.  The filehandle must previously have been opened on a
     valid GIF file or pipe.  If successful, this call will return an
     initialized image which you can then manipulate as you please.  If it
     fails, which usually happens if the thing at the other end of the
     filehandle is not a valid GIF file, the call returns undef.  Notice
     that the call doesn't automatically close the filehandle for you.

     To get information about the size and color usage of the information,
     you can call the image query methods described below.

          Example usage:

          open (GIF,"barnswallow.gif") || die;
          $myImage = newFromGif GD::Image(GIF) || die;
          close GIF;

`newFromXbm'
     `GD::Image::newFromXbm(FILEHANDLE)' *class method*

     This works in exactly the same way as `newFromGif', but reads the
     contents of an X Bitmap file:

          open (XBM,"coredump.xbm") || die;
          $myImage = newFromXbm GD::Image(XBM) || die;
          close XBM;

`newFromGd'
     `GD::Image::newFromGd(FILEHANDLE)' *class method*

     This works in exactly the same way as `newFromGif', but reads the
     contents of a GD file.  GD is Tom Boutell's disk-based storage format,
     intended for the rare case when you need to read and write the image
     to disk quickly.  It's not intended for regular use, because, unlike
     GIF or JPEG, no image compression is performed and these files can
     become *BIG*.

          open (GDF,"godzilla.gd") || die;
          $myImage = newFromGd GD::Image(GDF) || die;
          close GDF;

`gif'
     `GD::Image::gif' *object method*

     This returns the image data in GIF format.  You can then print it,
     pipe it to a display program, or write it to a file.  Example:

          $gif_data = $myImage->gif;
          open (DISPLAY,"| display -") || die;
          print DISPLAY $gif_data;
          close DISPLAY;

`gd'
     `GD::Image::gd' *object method*

     This returns the image data in GD format.  You can then print it,
     pipe it to a display program, or write it to a file.  Example:

          print MYOUTFILE $myImage->gd;

Color Control
-------------

`colorAllocate'
     `GD::Image::colorAllocate(red,green,blue)' *object method*

     This allocates a color with the specified red, green and blue
     components and returns its index in the color table, if specified.
     The first color allocated in this way becomes the image's background
     color.  (255,255,255) is white (all pixels on).  (0,0,0) is black (all
     pixels off).  (255,0,0) is fully saturated red.  (127,127,127) is 50%
     gray.  You can find plenty of examples in /usr/X11/lib/X11/rgb.txt.

     If no colors are allocated, then this function returns -1.

     Example:

          $white = $myImage->colorAllocate(0,0,0); #background color
          $black = $myImage->colorAllocate(255,255,255);
          $peachpuff = $myImage->colorAllocate(255,218,185);

`colorDeallocate'
     `GD::Image::colorDeallocate(colorIndex)' *object method*

     This marks the color at the specified index as being ripe for
     reallocation.  The next time colorAllocate is used, this entry will be
     replaced.  You can call this method several times to deallocate
     multiple colors.  There's no function result from this call.

     Example:

          $myImage->colorDeallocate($peachpuff);
          $peachy = $myImage->colorAllocate(255,210,185);

`colorClosest'
     `GD::Image::colorClosest(red,green,blue)' *object method*

     This returns the index of the color closest in the color table to the
     red green and blue components specified.  If no colors have yet been
     allocated, then this call returns -1.

     Example:

          $apricot = $myImage->colorClosest(255,200,180);

`colorExact'
     `GD::Image::colorExact(red,green,blue)' *object method*

     This returns the index of a color that exactly matches the specified
     red green and blue components.  If such a color is not in the color
     table, this call returns -1.

          $rosey = $myImage->colorExact(255,100,80);
          warn "Everything's coming up roses.\n" if $rosey >= 0;

`colorsTotal'
     `GD::Image::colorsTotal)' *object method*

     This returns the total number of colors allocated in the object.

          $maxColors = $myImage->colorsTotal;

`getPixel'
     `GD::Image::getPixel(x,y)' *object method*

     This returns the color table index underneath the specified point.
     It can be combined with rgb() to obtain the rgb color underneath the
     pixel.

     Example:

          $index = $myImage->getPixel(20,100);
          ($r,$g,$b) = $myImage->rgb($index);

`rgb'
     `GD::Image::rgb(colorIndex)' *object method*

     This returns a list containing the red, green and blue components of
     the specified color index.

     Example:

          @RGB = $myImage->rgb($peachy);

`transparent'
     `GD::Image::transparent(colorIndex)' *object method*

     This marks the color at the specified index as being transparent.
     Portions of the image drawn in this color will be invisible.  This is
     useful for creating paintbrushes of odd shapes, as well as for making
     GIF backgrounds transparent for displaying on the Web.  Only one
     color can be transparent at any time. To disable transparency,
     specify -1 for the index.

     If you call this method without any parameters, it will return the
     current index of the transparent color, or -1 if none.

     Example:

          open(GIF,"test.gif");
          $im = newFromGif GD::Image(GIF);
          $white = $im->colorClosest(255,255,255); # find white
          $im->transparent($white);
          print $im->gif;

Special Colors
--------------

GD implements a number of special colors that can be used to achieve
special effects.  They are constants defined in the GD:: namespace, but
automatically exported into your namespace when the GD module is loaded.

`setBrush'
`gdBrushed'
     `GD::Image::setBrush( )' and `GD::gdBrushed'

     You can draw lines and shapes using a brush pattern.  Brushes are
     just images that you can create and manipulate in the usual way. When
     you draw with them, their contents are used for the color and shape of
     the lines.

     To make a brushed line, you must create or load the brush first, then
     assign it to the image using `setBrush'.  You can then draw in that
     with that brush using the `gdBrushed' special color.  It's often
     useful to set the background of the brush to transparent so that the
     non-colored parts don't overwrite other parts of your image.

     Example:

          # Create a brush at an angle
          $diagonal_brush = new GD::Image(5,5);
          $white = $diagonal_brush->allocateColor(255,255,255);
          $black = $diagonal_brush->allocateColor(0,0,0);
          $diagonal_brush->transparent($white);
          $diagonal_brush->line(0,4,4,0,$black); # NE diagonal

          # Set the brush
          $myImage->setBrush($diagonal_brush);
          
          # Draw a circle using the brush
          $myImage->arc(50,50,25,25,0,360,gdBrushed);

`setStyle'
`gdStyled'
     `GD::Image::setStyle(@colors)' and `GD::gdStyled'

     Styled lines consist of an arbitrary series of repeated colors and are
     useful for generating dotted and dashed lines.  To create a styled
     line, use `setStyle' to specify a repeating series of colors.  It
     accepts an array consisting of one or more color indexes.  Then draw
     using the `gdStyled' special color.  Another special color,
     `gdTransparent' can be used to introduce holes in the line, as the
     example shows.

     Example:

          # Set a style consisting of 4 pixels of yellow,
          # 4 pixels of blue, and a 2 pixel gap
          $myImage->setStyle($yellow,$yellow,$yellow,$yellow,
          		   $blue,$blue,$blue,$blue,
          		   gdTransparent,gdTransparent);
          $myImage->arc(50,50,25,25,0,360,gdStyled);

     To combine the `gdStyled' and `gdBrushed' behaviors, you can specify
     `gdStyledBrushed'.  In this case, a pixel from the current brush
     pattern is rendered wherever the color specified in setStyle() is
     neither gdTransparent nor 0.

`gdTiled'
     Draw filled shapes and flood fills using a pattern.  The pattern is
     just another image.  The image will be tiled multiple times in order
     to fill the required space, creating wallpaper effects.  You must call
     `setTile' in order to define the particular tile pattern you'll use
     for drawing when you specify the gdTiled color.  details.

`gdStyled'
     The gdStyled color is used for creating dashed and dotted lines.  A
     styled line can contain any series of colors and is created using the
     `setStyled' command.

Drawing Commands
----------------

`setPixel'
     `GD::Image::setPixel(x,y,color)' *object method*

     This sets the pixel at (x,y) to the specified color index.  No value
     is returned from this method.  The coordinate system starts at the
     upper left at (0,0) and gets larger as you go down and to the right.
     You can use a real color, or one of the special colors gdBrushed,
     gdStyled and gdStyledBrushed can be specified.

     Example:

          # This assumes $peach already allocated
          $myImage->setPixel(50,50,$peach);

`line'
     `GD::Image::line(x1,y1,x2,y2,color)' *object method*

     This draws a line from (x1,y1) to (x2,y2) of the specified color.  You
     can use a real color, or one of the special colors gdBrushed,
     gdStyled and gdStyledBrushed.

     Example:

          # Draw a diagonal line using the currently defind
          # paintbrush pattern.
          $myImage->line(0,0,150,150,gdBrushed);

`dashedLine'
     `GD::Image::dashedLine(x1,y1,x2,y2,color)' *object method*

     This draws a dashed line from (x1,y1) to (x2,y2) in the specified
     color.  A more powerful way to generate arbitrary dashed and dotted
     lines is to use the setStyle() method described below and to draw with
     the special color gdStyled.

     Example:

          $myImage->dashedLine(0,0,150,150,$blue);

`rectangle'
     `GD::Image::rectangle(x1,y1,x2,y2,color)' *object method*

     This draws a rectangle with the specified color.  (x1,y1) and (x2,y2)
     are the upper left and lower right corners respectively.  Both real
     color indexes and the special colors gdBrushed, gdStyled and
     gdStyledBrushed are accepted.

     Example:

          $myImage->rectangle(10,10,100,100,$rose);

`filledRectangle'
     `GD::Image::filledRectangle(x1,y1,x2,y2,color)' *object method*

     This draws a rectangle filed with the specified color.  You can use a
     real color, or the special fill color gdTiled to fill the polygon
     with a pattern.

     Example:

          # read in a fill pattern and set it
          open(GIF,"happyface.gif") || die;
          $tile = newFromGif GD::Image(GIF);
          $myImage->setTile($tile);

          # draw the rectangle, filling it with the pattern
          $myImage->filledRectangle(10,10,150,200,gdTiled);

`polygon'
     `GD::Image::polygon(polygon,color)' *object method*

     This draws a polygon with the specified color.  The polygon must be
     created first (see below).  The polygon must have at least three
     vertices.  If the last vertex doesn't close the polygon, the method
     will close it for you.  Both real color indexes and the special
     colors gdBrushed, gdStyled and gdStyledBrushed can be specified.

     Example:

          $poly = new GD::Polygon;
          $poly->addPt(50,0);
          $poly->addPt(99,99);
          $poly->addPt(0,99);
          $myImage->polygon($poly,$blue);

`filledPolygon'
     `GD::Image::filledPolygon(poly,color)' *object method*

     This draws a polygon filled with the specified color.  You can use a
     real color, or the special fill color gdTiled to fill the polygon
     with a pattern.

     Example:

          # make a polygon
          $poly = new GD::Polygon;
          $poly->addPt(50,0);
          $poly->addPt(99,99);
          $poly->addPt(0,99);

          # draw the polygon, filling it with a color
          $myImage->filledPolygon($poly,$peachpuff);

`arc'
     `GD::Image::arc(cx,cy,width,height,start,end,color)' *object method*

     This draws arcs and ellipses.  (cx,cy) are the center of the arc, and
     (width,height) specify the width and height, respectively.  The
     portion of the ellipse covered by the arc are controlled by start and
     end, both of which are given in degrees from 0 to 360.  Zero is at the
     top of the ellipse, and angles increase clockwise.  To specify a
     complete ellipse, use 0 and 360 as the starting and ending angles.  To
     draw a circle, use the same value for width and height.

     You can specify a normal color or one of the special colors gdBrushed,
     gdStyled, or gdStyledBrushed.

     Example:

          # draw a semicircle centered at 100,100
          $myImage->arc(100,100,50,50,0,180,$blue);

`fill'
     `GD::Image::fill(x,y,color)' *object method*

     This method flood-fills regions with the specified color.  The color
     will spread through the image, starting at point (x,y), until it is
     stopped by a pixel of a different color from the starting pixel (this
     is similar to the "paintbucket" in many popular drawing toys).  You
     can specify a normal color, or the special color gdTiled, to
     flood-fill with patterns.

     Example:

          # Draw a rectangle, and then make its interior blue
          $myImage->rectangle(10,10,100,100,$black);
          $myImage->fill(50,50,$blue);

`GD::Image::fillToBorder(x,y,bordercolor,color)' *object method*
     Like `fill', this method flood-fills regions with the specified color,
     starting at position (x,y).  However, instead of stopping when it
     hits a pixel of a different color than the starting pixel, flooding
     will only stop when it hits the color specified by bordercolor.  You
     must specify a normal indexed color for the bordercolor.  However,
     you are free to use the gdTiled color for the fill.

     Example:

          # This has the same effect as the previous example
          $myImage->rectangle(10,10,100,100,$black);
          $myImage->fillToBorder(50,50,$black,$blue);

Image Copying Commands
----------------------

Two methods are provided for copying a rectangular region from one image
to another.  One method copies a region without resizing it.  The other
allows you to stretch the region during the copy operation.

With either of these methods it is important to know that the routines
will attempt to flesh out the destination image's color table to match the
colors that are being copied from the source.  If the destination's color
table is already full, then the routines will attempt to find the best
match, with varying results.

copy
     `GD::Image::copy(sourceImage,dstX,dstY,srcX,srcY,width,height)'
     *object method*

     This is the simpler of the two copy operations, copying the specified
     region from the source image to the destination image (the one
     performing the method call).  (srcX,srcY) specify the upper left
     corner of a rectangle in the source image, and (width,height) give the
     width and height of the region to copy.  (dstX,dstY) control where in
     the destination image to stamp the copy.  You can use the same image
     for both the source and the destination, but the source and
     destination regions must not overlap or strange things will happen.

     Example:

          $myImage = new GD::Image(100,100);
          ... various drawing stuff ...
          $srcImage = new GD::Image(50,50);
          ... more drawing stuff ...
          # copy a 25x25 pixel region from $srcImage to
          # the rectangle starting at (10,10) in $myImage
          $myImage->copy($srcImage,10,10,0,0,25,25);

`copyResized'










     `GD::Image::copyResized(sourceImage,dstX,dstY,srcX,srcY,destW,destH,srcW,srcH)'
     *object method*

     This method is similar to copy() but allows you to choose different
     sizes for the source and destination rectangles.  The source and
     destination rectangle's are specified independently by (srcW,srcH) and
     (destW,destH) respectively.  copyResized() will stretch or shrink the
     image to accomodate the size requirements.

     Example:

          $myImage = new GD::Image(100,100);
          ... various drawing stuff ...
          $srcImage = new GD::Image(50,50);
          ... more drawing stuff ...
          # copy a 25x25 pixel region from $srcImage to
          # a larger rectangle starting at (10,10) in $myImage
          $myImage->copyResized($srcImage,10,10,0,0,50,50,25,25);

Character and String Drawing
----------------------------

Gd allows you to draw characters and strings, either in normal horizontal
orientation or rotated 90 degrees.  These routines use a GD::Font object,
described in more detail below.  There are four built-in fonts, available
in global variables gdLargeFont, gdMediumBoldFont, gdSmallFont and
gdTinyFont.  Currently there is no way of dynamically creating your own
fonts.

`string'
     `GD::Image::string(font,x,y,string,color)' *Object Method*

     This method draws a string startin at position (x,y) in the specified
     font and color.  Your choices of fonts are gdSmallFont,
     gdMediumBoldFont, gdTinyFont and gdLargeFont.

     Example:

          $myImage->string(gdSmallFont,2,10,"Peachy Keen",$peach);

`stringUp'
     `GD::Image::stringUp(font,x,y,string,color)' *Object Method*

     Just like the previous call, but draws the text rotated
     counterclockwise 90 degrees.

`char'
`charUp'
     `GD::Image::char(font,x,y,char,color)' *Object Method*
     `GD::Image::charUp(font,x,y,char,color)' *Object Method*

     These methods draw single characters at position (x,y) in the
     specified font and color.  They're carry-overs from the C interface,
     where there is a distinction between characters and strings.  Perl is
     insensible to such subtle distinctions.

Miscellaneous Image Methods
---------------------------

`interlaced'
     `GD::Image::interlaced( )' `GD::Image::interlaced(1)' *Object method*

     This method sets or queries the image's interlaced setting.  Interlace
     produces a cool venetian blinds effect on certain viewers.  Provide a
     true parameter to set the interlace attribute.  Provide undef to
     disable it.  Call the method without parameters to find out the
     current setting.

c<getBounds>
     `GD::Image::getBounds( )' *Object method*

     This method will return a two-member list containing the width and
     height of the image.  You query but not not change the size of the
     image once it's created.

Polygon Methods
---------------

A few primitive polygon creation and manipulation methods are provided.
They aren't part of the Gd library, but I thought they might be handy to
have around (they're borrowed from my qd.pl Quickdraw library).

c<new>
     `GD::Polygon::new' *class method*

     Create an empty polygon with no vertices.

          $poly = new GD::Polygon;

`addPt'
     `GD::Polygon::addPt(x,y)' *object method*

     Add point (x,y) to the polygon.

          $poly->addPt(0,0);
          $poly->addPt(0,50);
          $poly->addPt(25,25);
          $myImage->fillPoly($poly,$blue);

`getPt'
     `GD::Polygon::getPt(index)' *object method*

     Retrieve the point at the specified vertex.

          ($x,$y) = $poly->getPt(2);

`setPt'
     `GD::Polygon::setPt(index,x,y)' *object method*

     Change the value of an already existing vertex.  It is an error to set
     a vertex that isn't already defined.

          $poly->setPt(2,100,100);

`deletePt'
     `GD::Polygon:deletePt(index)' *object method*

     Delete the specified vertex, returning its value.

          ($x,$y) = $poly->deletePt(1);

length
     `GD::Polygon::length' *object method*

     Return the number of vertices in the polygon.

          $points = $poly->length;

`vertices'
     `GD::Polygon::vertices' *object method*

     Return a list of all the verticies in the polygon object.  Each
     membver of the list is a reference to an (x,y) array.

          @vertices = $poly->vertices;
          foreach $v (@vertices)
             print join(",",@$v),"\n";
          }

`bounds'
     `GD::Polygon::bounds' *object method*

     Return the smallest rectangle that completely encloses the polygon.
     The return value is an array containing the (left,top,right,bottom) of
     the rectangle.

          ($left,$top,$right,$bottom) = $poly->bounds;

`offset'
     `GD::Polygon::offset(dx,dy)' *object method*

     Offset all the vertices of the polygon by the specified horizontal
     (dh) and vertical (dy) amounts.  Positive numbers move the polygon
     down and to the right.

          $poly->offset(10,30);

map
     `GD::Polygon::map(srcL,srcT,srcR,srcB,destL,dstT,dstR,dstB)' *object
     method*

     Map the polygon from a source rectangle to an equivalent position in a
     destination rectangle, moving it and resizing it as necessary.  See
     polys.pl for an example of how this works.  Both the source and
     destination rectangles are given in (left,top,right,bottom)
     coordinates.  For convenience, you can use the polygon's own bounding
     box as the source rectangle.

          # Make the polygon really tall
          $poly->map($poly->bounds,0,0,50,200);

Font Utilities
--------------

Gd's support for fonts is minimal.  Basically you have access to
gdSmallFont and gdLargeFont for drawing, and not much else.  However, for
future compatibility, I've made the fonts into perl objects of type
GD::Font that you can query and, perhaps someday manipulate.

`gdSmallFont'
     `GD::Font::gdSmallFont' *constant*

     This is the basic small font, "borrowed" from a well known public
     domain 6x12 font.

`gdLargeFont'
     `GD::Font::gdLargeFont' *constant*

     This is the basic large font, "borrowed" from a well known public
     domain 8x16 font.

`gdMediumBoldFont'
     `GD::Font::gdMediumBoldFont' *constant*

     This is a bold font intermediate in size between the small and large
     fonts, borrowed from a public domain 7x13 font;

`gdTinyFont'
     `GD::Font::gdTinyFont' *constant*

     This is a tiny, almost unreadable font, 5x8 pixels wide.

`nchars'
     `GD::Font::nchars'	*object method*

     This returns the number of characters in the font.

          print "The large font contains ",gdLargeFont->nchars," characters\n";

`offset'
     `GD::Font::offset' 	*object method*

     This returns the ASCII value of the first character in the font

`width'
`height'
     `GD::Font::width' `GD::Font::height'	*object methods*

     These return the width and height of the font.

          ($w,$h) = (gdLargeFont->width,gdLargeFont->height);

Obtaining the C-language version of gd
======================================

libgd, the C-language version of gd, can be obtained at URL
http://www.boutell.com/gd/gd.html.  Directions for installing and using it
can be found at that site.  Please do not contact me for help with libgd.

Copyright Information
=====================

The GD.pm interface is copyright 1995, Lincoln D. Stein.  You are free to
use it for any purpose, commercial or noncommercial, provided that if you
redistribute the source code this statement of copyright remains attached.
The gd library is covered separately under a 1994 copyright by Quest
Protein Database Center, Cold Spring Harbor Labs and Thomas Boutell.  For
usage information see the gd documentation at URL

     http://www.boutell.com/gd/gd.html

The latest versions of GD.pm are available at

     http://www.genome.wi.mit.edu/ftp/pub/software/WWW/GD.html
     ftp://ftp-genome.wi.mit.edu/pub/software/WWW/GD.pm.tar.gz


File: pm.info,  Node: GDBM_File,  Next: Getopt/Long,  Prev: GD,  Up: Module List

Perl5 access to the gdbm library.
*********************************

NAME
====

GDBM_File - Perl5 access to the gdbm library.

SYNOPSIS
========

     use GDBM_File ;
     tie %hash, 'GDBM_File', $filename, &GDBM_WRCREAT, 0640);
     # Use the %hash array.
     untie %hash ;

DESCRIPTION
===========

*GDBM_File* is a module which allows Perl programs to make use of the
facilities provided by the GNU gdbm library.  If you intend to use this
module you should really have a copy of the gdbm manualpage at hand.

Most of the libgdbm.a functions are available through the GDBM_File
interface.

AVAILABILITY
============

Gdbm is available from any GNU archive.  The master site is
`prep.ai.mit.edu', but your are strongly urged to use one of the many
mirrors.   You can obtain a list of mirror sites by issuing the
command	`finger fsf@prep.ai.mit.edu'.

BUGS
====

The available functions and the gdbm/perl interface need to be documented.

SEE ALSO
========

`perl(1)' in this node, `DB_File(3)' in this node.


File: pm.info,  Node: Getopt/Long,  Next: Getopt/Mixed,  Prev: GDBM_File,  Up: Module List

extended processing of command line options
*******************************************

NAME
====

GetOptions - extended processing of command line options

SYNOPSIS
========

     use Getopt::Long;
     $result = GetOptions (...option-descriptions...);

DESCRIPTION
===========

The Getopt::Long module implements an extended getopt function called
GetOptions(). This function adheres to the POSIX syntax for command line
options, with GNU extensions. In general, this means that options have
long names instead of single letters, and are introduced with a double
dash "-". Support for bundling of command line options, as was the case
with the more traditional single-letter approach, is provided but not
enabled by default. For example, the UNIX "ps" command can be given the
command line "option"

     -vax

which means the combination of -v, -a and -x. With the new syntax *-vax*
would be a single option, probably indicating a computer architecture.

Command line options can be used to set values. These values can be
specified in one of two ways:

     --size 24
     --size=24

GetOptions is called with a list of option-descriptions, each of which
consists of two elements: the option specifier and the option linkage.
The option specifier defines the name of the option and, optionally, the
value it can take. The option linkage is usually a reference to a variable
that will be set when the option is used. For example, the following call
to GetOptions:

     &GetOptions("size=i" => \$offset);

will accept a command line option "size" that must have an integer value.
With a command line of "-size 24" this will cause the variable $offset to
get the value 24.

Alternatively, the first argument to GetOptions may be a reference to a
HASH describing the linkage for the options. The following call is
equivalent to the example above:

     %optctl = ("size" => \$offset);
     &GetOptions(\%optctl, "size=i");

Linkage may be specified using either of the above methods, or both.
Linkage specified in the argument list takes precedence over the linkage
specified in the HASH.

The command line options are taken from array @ARGV. Upon completion of
GetOptions, @ARGV will contain the rest (i.e. the non-options) of the
command line.

Each option specifier designates the name of the option, optionally
followed by an argument specifier. Values for argument specifiers are:

<none>
     Option does not take an argument.  The option variable will be set to
     1.

!
     Option does not take an argument and may be negated, i.e. prefixed by
     "no". E.g. "foo!" will allow *-foo* (with value 1) and *-nofoo* (with
     value 0).  The option variable will be set to 1, or 0 if negated.

=s
     Option takes a mandatory string argument.  This string will be
     assigned to the option variable.  Note that even if the string
     argument starts with - or *-*, it will not be considered an option on
     itself.

:s
     Option takes an optional string argument.  This string will be
     assigned to the option variable.  If omitted, it will be assigned ""
     (an empty string).  If the string argument starts with - or *-*, it
     will be considered an option on itself.

=i
     Option takes a mandatory integer argument.  This value will be
     assigned to the option variable.  Note that the value may start with
     - to indicate a negative value.

:i
     Option takes an optional integer argument.  This value will be
     assigned to the option variable.  If omitted, the value 0 will be
     assigned.  Note that the value may start with - to indicate a negative
     value.

=f
     Option takes a mandatory real number argument.  This value will be
     assigned to the option variable.  Note that the value may start with
     - to indicate a negative value.

:f
     Option takes an optional real number argument.  This value will be
     assigned to the option variable.  If omitted, the value 0 will be
     assigned.

A lone dash - is considered an option, the corresponding option name is
the empty string.

A double dash on itself *-* signals end of the options list.

Linkage specification
---------------------

The linkage specifier is optional. If no linkage is explicitly specified
but a ref HASH is passed, GetOptions will place the value in the HASH. For
example:

     %optctl = ();
     &GetOptions (\%optctl, "size=i");

will perform the equivalent of the assignment

     $optctl{"size"} = 24;

For array options, a reference to an array is used, e.g.:

     %optctl = ();
     &GetOptions (\%optctl, "sizes=i@");

with command line "-sizes 24 -sizes 48" will perform the equivalent of the
assignment

     $optctl{"sizes"} = [24, 48];

For hash options (an option whose argument looks like "name=value"), a
reference to a hash is used, e.g.:

     %optctl = ();
     &GetOptions (\%optctl, "define=s%");

with command line "-define foo=hello -define bar=world" will perform the
equivalent of the assignment

     $optctl{"define"} = {foo=>'hello', bar=>'world')

If no linkage is explicitly specified and no ref HASH is passed,
GetOptions will put the value in a global variable named after the option,
prefixed by "opt_". To yield a usable Perl variable, characters that are
not part of the syntax for variables are translated to underscores. For
example, "-fpp-struct-return" will set the variable
$opt_fpp_struct_return. Note that this variable resides in the namespace
of the calling program, not necessarily *main*.  For example:

     &GetOptions ("size=i", "sizes=i@");

with command line "-size 10 -sizes 24 -sizes 48" will perform the
equivalent of the assignments

     $opt_size = 10;
     @opt_sizes = (24, 48);

A lone dash - is considered an option, the corresponding Perl identifier
is $opt_ .

The linkage specifier can be a reference to a scalar, a reference to an
array, a reference to a hash or a reference to a subroutine.

If a REF SCALAR is supplied, the new value is stored in the referenced
variable. If the option occurs more than once, the previous value is
overwritten.

If a REF ARRAY is supplied, the new value is appended (pushed) to the
referenced array.

If a REF HASH is supplied, the option value should look like "key" or
"key=value" (if the "=value" is omitted then a value of 1 is implied).  In
this case, the element of the referenced hash with the key "key" is
assigned "value".

If a REF CODE is supplied, the referenced subroutine is called with two
arguments: the option name and the option value.  The option name is
always the true name, not an abbreviation or alias.

Aliases and abbreviations
-------------------------

The option name may actually be a list of option names, separated by "|"s,
e.g. "foo|bar|blech=s". In this example, "foo" is the true name op this
option. If no linkage is specified, options "foo", "bar" and "blech" all
will set $opt_foo.

Option names may be abbreviated to uniqueness, depending on configuration
variable $Getopt::Long::autoabbrev.

Non-option call-back routine
----------------------------

A special option specifier, <>, can be used to designate a subroutine to
handle non-option arguments. GetOptions will immediately call this
subroutine for every non-option it encounters in the options list.  This
subroutine gets the name of the non-option passed.  This feature requires
$Getopt::Long::order to have the value $PERMUTE.  See also the examples.

Option starters
---------------

On the command line, options can start with - (traditional), *-* (POSIX)
and + (GNU, now being phased out). The latter is not allowed if the
environment variable *POSIXLY_CORRECT* has been defined.

Options that start with "-" may have an argument appended, separated with
an "=", e.g. "-foo=bar".

Return value
------------

A return status of 0 (false) indicates that the function detected one or
more errors.

COMPATIBILITY
=============

Getopt::Long::GetOptions() is the successor of *newgetopt.pl* that came
with Perl 4. It is fully upward compatible.  In fact, the Perl 5 version
of newgetopt.pl is just a wrapper around the module.

If an "@" sign is appended to the argument specifier, the option is
treated as an array. Value(s) are not set, but pushed into array
@opt_name. If explicit linkage is supplied, this must be a reference to an
ARRAY.

If an "%" sign is appended to the argument specifier, the option is
treated as a hash. Value(s) of the form "name=value" are set by setting
the element of the hash %opt_name with key "name" to "value" (if the
"=value" portion is omitted it defaults to 1). If explicit linkage is
supplied, this must be a reference to a HASH.

If configuration variable $Getopt::Long::getopt_compat is set to a
non-zero value, options that start with "+" or "-" may also include their
arguments, e.g. "+foo=bar". This is for compatiblity with older
implementations of the GNU "getopt" routine.

If the first argument to GetOptions is a string consisting of only
non-alphanumeric characters, it is taken to specify the option starter
characters. Everything starting with one of these characters from the
starter will be considered an option. *Using a starter argument is
strongly deprecated.*

For convenience, option specifiers may have a leading - or *-*, so it is
possible to write:

     GetOptions qw(-foo=s --bar=i --ar=s);

EXAMPLES
========

If the option specifier is "one:i" (i.e. takes an optional integer
argument), then the following situations are handled:

     -one -two		-> $opt_one = '', -two is next option
     -one -2		-> $opt_one = -2

Also, assume specifiers "foo=s" and "bar:s" :

     -bar -xxx		-> $opt_bar = '', '-xxx' is next option
     -foo -bar		-> $opt_foo = '-bar'
     -foo --		-> $opt_foo = '--'

In GNU or POSIX format, option names and values can be combined:

     +foo=blech		-> $opt_foo = 'blech'
     --bar=		-> $opt_bar = ''
     --bar=--		-> $opt_bar = '--'

Example of using variable references:

     $ret = &GetOptions ('foo=s', \$foo, 'bar=i', 'ar=s', \@ar);

With command line options "-foo blech -bar 24 -ar xx -ar yy" this will
result in:

     $bar = 'blech'
     $opt_bar = 24
     @ar = ('xx','yy')

Example of using the <> option specifier:

     @ARGV = qw(-foo 1 bar -foo 2 blech);
     &GetOptions("foo=i", \$myfoo, "<>", \&mysub);

Results:

     &mysub("bar") will be called (with $myfoo being 1)
     &mysub("blech") will be called (with $myfoo being 2)

Compare this with:

     @ARGV = qw(-foo 1 bar -foo 2 blech);
     &GetOptions("foo=i", \$myfoo);

This will leave the non-options in @ARGV:

     $myfoo -> 2
     @ARGV -> qw(bar blech)

CONFIGURATION VARIABLES
=======================

The following variables can be set to change the default behaviour of
GetOptions():

$Getopt::Long::autoabbrev
     Allow option names to be abbreviated to uniqueness.  Default is 1
     unless environment variable POSIXLY_CORRECT has been set.

$Getopt::Long::getopt_compat
     Allow '+' to start options.  Default is 1 unless environment variable
     POSIXLY_CORRECT has been set.

$Getopt::Long::order
     Whether non-options are allowed to be mixed with options.  Default is
     $REQUIRE_ORDER if environment variable POSIXLY_CORRECT has been set,
     $PERMUTE otherwise.

     $PERMUTE means that

          -foo arg1 -bar arg2 arg3

     is equivalent to

          -foo -bar arg1 arg2 arg3

     If a non-option call-back routine is specified, @ARGV will always be
     empty upon succesful return of GetOptions since all options have been
     processed, except when *-* is used:

          -foo arg1 -bar arg2 -- arg3

     will call the call-back routine for arg1 and arg2, and terminate
     leaving arg2 in @ARGV.

     If $Getopt::Long::order is $REQUIRE_ORDER, options processing
     terminates when the first non-option is encountered.

          -foo arg1 -bar arg2 arg3

     is equivalent to

          -foo -- arg1 -bar arg2 arg3

     $RETURN_IN_ORDER is not supported by GetOptions().

$Getopt::Long::bundling
     Setting this variable to a non-zero value will allow single-character
     options to be bundled. To distinguish bundles from long option names,
     long options must be introduced with *-* and single-character options
     (and bundles) with -. For example,

          ps -vax --vax

     would be equivalent to

          ps -v -a -x --vax

     provided "vax", "v", "a" and "x" have been defined to be valid
     options.

     Bundled options can also include a value in the bundle; this value has
     to be the last part of the bundle, e.g.

          scale -h24 -w80

     is equivalent to

          scale -h 24 -w 80

     *Note:* Using option bundling can easily lead to unexpected results,
     especially when mixing long options and bundles. Caveat emptor.

$Getopt::Long::ignorecase
     Ignore case when matching options. Default is 1. When bundling is in
     effect, case is ignored on single-character options only if
     $Getopt::Long::ignorecase is greater than 1.

$Getopt::Long::passthrough
     Unknown options are passed through in @ARGV instead of being flagged
     as errors. This makes it possible to write wrapper scripts that
     process only part of the user supplied options, and passes the
     remaining options to some other program.

     This can be very confusing, especially when $Getopt::Long::order is
     set to $PERMUTE.

$Getopt::Long::VERSION
     The version number of this Getopt::Long implementation in the format
     `major'.`minor'. This can be used to have Exporter check the version,
     e.g.

          use Getopt::Long 2.00;

     You can inspect $Getopt::Long::major_version and
     $Getopt::Long::minor_version for the individual components.

$Getopt::Long::error
     Internal error flag. May be incremented from a call-back routine to
     cause options parsing to fail.

$Getopt::Long::debug
     Enable copious debugging output. Default is 0.


File: pm.info,  Node: Getopt/Mixed,  Next: Getopt/Regex,  Prev: Getopt/Long,  Up: Module List

getopt processing with both long and short options
**************************************************

NAME
====

Getopt::Mixed - getopt processing with both long and short options

SYNOPSIS
========

     use Getopt::Mixed;
     Getopt::Mixed::getOptions(...option-descriptions...);
     ...examine $opt_* variables...

or

     use Getopt::Mixed "nextOption";
     Getopt::Mixed::init(...option-descriptions...);
     while (($option, $value) = nextOption()) {
         ...process option...
     }
     Getopt::Mixed::cleanup();

DESCRIPTION
===========

This package is my response to the standard modules Getopt::Std and
Getopt::Long.  `Std' doesn't support long options, and `Long' doesn't
support short options.  I wanted both, since long options are easier to
remember and short options are faster to type.

This package is intended to be the "Getopt-to-end-all-Getop's".  It
combines (I hope) flexibility and simplicity.  It supports both short
options (introduced by -) and long options (introduced by `--').  Short
options which do not take an argument can be grouped together.  Short
options which do take an argument must be the last option in their group,
because everything following the option will be considered to be its
argument.

There are two methods for using Getopt::Mixed:  the simple method and the
flexible method.  Both methods use the same format for option descriptions.

Option Descriptions
-------------------

The option-description arguments required by init and `getOptions' are
strings composed of individual option descriptions.  Several option
descriptions can appear in the same string if they are separated by
whitespace.

Each description consists of the option name and an optional trailing
argument specifier.  Option names may consist of any characters but
whitespace, =, `:', and `>'.

Values for argument specifiers are:

     <none>   option does not take an argument
     =s :s    option takes a mandatory (=) or optional (:) string argument
     =i :i    option takes a mandatory (=) or optional (:) integer argument
     =f :f    option takes a mandatory (=) or optional (:) real number argument
     >new     option is a synonym for option `new'

The `>' specifier is not really an argument specifier.  It defines an
option as being a synonym for another option.  For example, "a=i apples>a"
would define -a as an option that requires an integer argument and
*-apples* as a synonym for -a.  Only one level of synonyms is supported,
and the root option must be listed first.  For example, "apples>a a=i" and
"a=i apples>a oranges>apples" are illegal; use "a=i apples>a oranges>a" if
that's what you want.

For example, in the option description:      "a b=i c:s apple baker>b
charlie:s"          -a and -apple do not take arguments          -b takes
a mandatory integer argument          -baker is a synonym for -b
-c and -charlie take an optional string argument

If the first argument to init or `getOptions' is entirely non-alphanumeric
characters with no whitespace, it represents the characters which can
begin options.

User Interface
--------------

From the user's perspective, short options are introduced by a dash (-)
and long options are introduced by a double dash (`--').  Short options
may be combined ("-a -b" can be written "-ab"), but an option that takes
an argument must be the last one in its group, because anything following
it is considered part of the argument.  A double dash by itself marks the
end of the options; all arguments following it are treated as normal
arguments, not options.  A single dash by itself is treated as a normal
argument, *not* an option.

Long options may be abbreviated.  An option *-all-the-time* could be
abbreviated *-all*, *-a-tim*, or even *-a*.  Note that *-time* would not
work; the abbreviation must start at the beginning of the option name.  If
an abbreviation is ambiguous, an error message will be printed.

In the following examples, -i and *-int* take integer arguments, *-f* and
*-float* take floating point arguments, and -s and *-string* take string
arguments.  All other options do not take an argument.

     -i24            -f24.5               -sHello
     -i=24 --int=-27 -f=24.5 --float=0.27 -s=Hello --string=Hello

If the argument is required, it can also be separated by whitespace:

     -i 24 --int -27 -f 24.5 --float 0.27 -s Hello --string Hello

Note that if the option is followed by =, whatever follows the = *is* the
argument, even if it's the null string.  In the example

     -i= 24 -f= 24.5 -s= Hello

-i and *-f* will cause an error, because the null string is not a number,
but -s is perfectly legal; its argument is the null string, not "Hello".

Remember that optional arguments *cannot* be separated from the option by
whitespace.

The Simple Method
-----------------

The simple method is

     use Getopt::Mixed;
     Getopt::Mixed::getOptions(...option-descriptions...);

You then examine the `$opt_*' variables to find out what options were
specified and the `@ARGV' array to see what arguments are left.

If -a is an option that doesn't take an argument, then `$opt_a' will be
set to 1 if the option is present, or left undefined if the option is not
present.

If *-b* is an option that takes an argument, then `$opt_b' will be set to
the value of the argument if the option is present, or left undefined if
the option is not present.  If the argument is optional but not supplied,
`$opt_b' will be set to the null string.

Note that even if you specify that an option *requires* a string argument,
you can still get the null string (if the user specifically enters it).
If the option requires a numeric argument, you will never get the null
string (because it isn't a number).

When converting the option name to a Perl identifier, any non-word
characters in the name will be converted to underscores (`_').

If the same option occurs more than once, only the last occurrence will be
recorded.  If that's not acceptable, you'll have to use the flexible
method instead.

The Flexible Method
-------------------

The flexible method is

     use Getopt::Mixed "nextOption";
     Getopt::Mixed::init(...option-descriptions...);
     while (($option, $value, $pretty) = nextOption()) {
         ...process option...
     }
     Getopt::Mixed::cleanup();

This lets you process arguments one at a time.  You can then handle
repeated options any way you want to.  It also lets you see option names
with non-alphanumeric characters without any translation.  This is also
the only method that lets you find out what order the options and other
arguments were in.

First, you call Getopt::Mixed::init with the option descriptions.  Then,
you keep calling nextOption until it returns an empty list.  Finally, you
call Getopt::Mixed::cleanup when you're done.  The remaining (non-option)
arguments will be found in @ARGV.

Each call to nextOption returns a list of the next option, its value, and
the option as the user typed it.  The value will be undefined if the
option does not take an argument.  The option is stripped of its starter
(e.g., you get "a" and "foo", not "-a" or "-foo").  If you want to print
an error message, use the third element, which does include the option
starter.

OTHER FUNCTIONS
===============

Getopt::Mixed provides one other function you can use.  `abortMsg' prints
its arguments on STDERR, plus your program's name and a newline.  It then
exits with status 1.  For example, if `foo.pl' calls `abortMsg' like this:

     Getopt::Mixed::abortMsg("Error");

The output will be:

     foo.pl: Error

CUSTOMIZATION
=============

There are several customization variables you can set.  All of these
variables should be set *after* calling Getopt::Mixed::init and *before*
calling nextOption.

If you set any of these variables, you *must* check the version number
first.  The easiest way to do this is like this:

     use Getopt::Mixed 1.006;

If you are using the simple method, and you want to set these variables,
you'll need to call init before calling getOptions, like this:

     use Getopt::Mixed 1.006;
     Getopt::Mixed::init(...option-descriptions...);
     ...set configuration variables...
     Getopt::Mixed::getOptions();      # IMPORTANT: no parameters

$order
     $order can be set to $REQUIRE_ORDER, $PERMUTE, or $RETURN_IN_ORDER.
     The default is $REQUIRE_ORDER if the environment variable
     POSIXLY_CORRECT has been set, $PERMUTE otherwise.

     $REQUIRE_ORDER means that no options can follow the first argument
     which isn't an option.

     $PERMUTE means that all options are treated as if they preceded all
     other arguments.

     $RETURN_IN_ORDER means that all arguments maintain their ordering.
     When nextOption is called, and the next argument is not an option, it
     returns the null string as the option and the argument as the value.
     nextOption never returns the null list until all the arguments have
     been processed.

$ignoreCase
     Ignore case when matching options.  Default is 1 unless the option
     descriptions contain an upper-case letter.

$optionStart
     A string of characters that can start options.  Default is "-".

$badOption
     A reference to a function that is called when an unrecognized option
     is encountered.  The function receives three arguments.  $_[0] is the
     position in @ARGV where the option came from.  $_[1] is the option as
     the user typed it (including the option start character).  $_[2] is
     either undef or a string describing the reason the option was not
     recognized (Currently, the only possible value is 'ambiguous', for a
     long option with several possible matches).  The option has already
     been removed from @ARGV.  To put it back, you can say:

          splice(@ARGV,$_[0],0,$_[1]);

     The function can do anything you want to @ARGV.  It should return
     whatever you want nextOption to return.

     The default is a function that prints an error message and exits the
     program.

$checkArg
     A reference to a function that is called to make sure the argument
     type is correct.  The function receives four arguments.  $_[0] is the
     position in @ARGV where the option came from.  $_[1] is the text
     following the option, or undefined if there was no text following the
     option.  $_[2] is the name of the option as the user typed it
     (including the option start character), suitable for error messages.
     $_[3] is the argument type specifier.

     The function can do anything you want to @ARGV.  It should return the
     value for this option.

     The default is a function that prints an error message and exits the
     program if the argument is not the right type for the option.  You can
     also adjust the behavior of the default function by changing
     $intRegexp or $floatRegexp.

$intRegexp
     A regular expression that matches an integer.  Default is
     '^[-+]?\d+$', which matches a string of digits preceded by an
     optional sign.  Unlike the other configuration variables, this cannot
     be changed after nextOption is called, because the pattern is compiled
     only once.

$floatRegexp
     A regular expression that matches a floating point number.  Default is
     '^[-+]?(\d*\.?\d+|\d+\.)$', which matches the following formats:
     "123", "123.", "123.45", and ".123" (plus an optional sign).  It does
     not match exponential notation.  Unlike the other configuration
     variables, this cannot be changed after nextOption is called, because
     the pattern is compiled only once.

$typeChars
     A string of the characters which are legal argument types.  The
     default is 'sif', for String, Integer, and Floating point arguments.
     The string should consist only of letters.  Upper case letters are
     discouraged, since this will hamper the case-folding of options.  If
     you change this, you should set $checkType to a function that will
     check arguments of your new type.  Unlike the other configuration
     variables, this must be set *before* calling init(), and cannot be
     changed afterwards.

$checkType
     If you add new types to $typeChars, you should set this to a function
     which will check arguments of the new types.

BUGS
====

   * This document should be expanded.

   * A long option must be at least two characters long.  Sorry.

   * The ! argument specifier of Getopt::Long is not supported, but you
     could have options *-foo* and *-nofoo* and then do something like:

          $opt_foo = 0 if $opt_nofoo;

   * The `@' argument specifier of Getopt::Long is not supported.  If you
     want your values pushed into an array, you'll have to use nextOption
     and do it yourself.

LICENSE
=======

Getopt::Mixed is distributed under the terms of the GNU General Public
License as published by the Free Software Foundation; either version 2, or
(at your option) any later version.

This means it is distributed in the hope that it will be useful, but
*without any warranty*; without even the implied warranty of
*merchantability* or *fitness for a particular purpose*.  See the GNU
General Public License for more details.

Since Perl scripts are only compiled at runtime, and simply calling
Getopt::Mixed does *not* bring your program under the GPL, the only real
restriction is that you can't use Getopt::Mixed in an binary-only
distribution produced with dump (unless you also provide source code).

AUTHOR
======

Christopher J. Madsen <`ac608@yfn.ysu.edu'>

Thanks are also due to Andreas Koenig for helping Getopt::Mixed conform to
the standards for Perl modules and for answering a bunch of questions.
Any remaining deficiencies are my fault.


File: pm.info,  Node: Getopt/Regex,  Next: Getopt/Std,  Prev: Getopt/Mixed,  Up: Module List

SYNOPSIS
========

     use Getopt::Regex;
     GetOptions(\@ARGV,[$regex,$ref,$takesarg],...);

*\@ARGV* - reference to array of command line arguments *$regex* - regular
expression for identifying the option *$ref* - reference to a variable to
be set or a function which is passed the argument if it exists.
*$takesarg* - if 1 subsequent command line argument is taken as its
argument

DESCRIPTION
===========

This package provides a flexible yet simple method for handling command
line options. It does not stamp over the callers namespace or, currently,
inforce any particular standard for the options - the user can do this if
they want. By using anonymous closures sophisticated option specifications
can be constructed.

The function *GetOptions*, exported from the package takes a reference to
the argument list followed by a set of option specifications which are
references to arrays containing at least a regular expression to match for
the option and a reference to a variable to be set or a function to be
called. A third optional argument for each option, if set to 1, pulles off
the following command line argument as an argument for that option.

The simplest use is to set a boolean variable if an argument is set

     GetOptions(\@ARGV,['-[v|V]',\$bool,0]);

If the option '-v' or '-V' occurs $bool will be set to 1, otherwise it is
left unchanged.

A subsequent command line argument may be used as as an option argument as
follows

     GetOptions(\@ARGV,['-f',\$fname,1]);
     
     will set $fname to fname if '-f fname' is specified on the command line.

Processed arguments are removed from the argument list.  Only the first
occurance of an argument is processed, if a variable is being set as in
the above examples

More complex argument specifications are possible using anonymous
functions as arguments. If the option takes an argument, the argument is
passed to the function.  Parts of the regular expression may also be used
in the anonymous closure being executed. e.g.

     GetOptions(\@ARGV,
      ['-D(.+)=(.+)',sub { diagnostic $1,$2; }    ,0],
      ['-D(.+)',     sub { diagnostic $1; $_[0]; },1]);

The first option specification will match options in the format
'-DDIAGNOSTIC=VALUE',the second will match occurances of the format
'-DDIAGNOSTIC VALUE'.  As can be seen use of the regex matching variables
can be made in handling the options.

When *GetOptions* is called with a function reference the function is
called for all matching occurances of the regular expression, and the
proceesed options are removed from the argument list.

Another useful example is

     GetOptions(\@ARGV,['-(no-)*optimization',0,sub { $optimization=!$1; }]);

which identifies the option statements '-optimization' or
'-no-optimization' setting $optimization true or false approptiately.

The option '-' ends the search for matching options - further arguments
are not searched.

NOTE
====

Requires at least Perl 5.000 or Perl 5.001m if anonymous closures are used.

HISTORY
=======

$Log: Options.pm,v $ Revision 1.3  1995/12/16 09:48:28  willijar Rename
package to be more consistant with guidlines

Revision 1.2  1995/12/12 22:01:35  willijar Removed unnecessary default
argument. Extended pod documentation.

Revision 1.1  1995/12/10 15:57:06  willijar Initial revision

BUGS
====

Please let me know.

TODO
====

Possibly integrate default behaviour of other option functions in this
package.

AUTHOR
======

John A.R. Williams, <J.A.R.Williams@aston.ac.uk>


File: pm.info,  Node: Getopt/Std,  Next: HTML/AsSubs,  Prev: Getopt/Regex,  Up: Module List

Process single-character switches with switch clustering
********************************************************

NAME
====

getopt - Process single-character switches with switch clustering

getopts - Process single-character switches with switch clustering

SYNOPSIS
========

     use Getopt::Std;
     getopt('oDI');  # -o, -D & -I take arg.  Sets opt_* as a side effect.
     getopts('oif:');  # -o & -i are boolean flags, -f takes an argument
     		      # Sets opt_* as a side effect.

DESCRIPTION
===========

The getopt() functions processes single-character switches with switch
clustering.  Pass one argument which is a string containing all switches
that take an argument.  For each switch found, sets $opt_x (where x is the
switch name) to the value of the argument, or 1 if no argument.  Switches
which take an argument don't care whether there is a space between the
switch and the argument.


File: pm.info,  Node: HTML/AsSubs,  Next: HTML/Element,  Prev: Getopt/Std,  Up: Module List

functions that construct a HTML syntax tree
*******************************************

NAME
====

HTML::AsSubs - functions that construct a HTML syntax tree

SYNOPSIS
========

     use HTML::AsSubs;
     $h = body(
     	   h1("This is the heading"),
     	   p("This is the first paragraph which contains a ",
     	     a({href=>'link.html'}, "link"),
     	     " and an ",
     	     img({src=>'img.gif', alt=>'image'}),
     	     "."
     	    ),
     	  );
     print $h->as_HTML;

DESCRIPTION
===========

This module exports functions that can be used to construct various HTML
elements. The functions are named after the tags of the correponding HTML
element and are all written in lower case. If the first argument is a
*hash* then it will be used to initialize the attributes of this element.
The remaining arguments are regarded as content.

ACKNOWLEDGEMENT
===============

This module was inspired by the following message:

     Date: Tue, 4 Oct 1994 16:11:30 +0100
     Subject: Wow! I have a large lightbulb above my head!

     Take a moment to consider these lines:

     %OVERLOAD=( '""' => sub { join("", @{$_[0]}) } );

     sub html { my($type)=shift; bless ["<$type>", @_, "</$type>"]; }

     :-)  I *love* Perl 5!  Thankyou Larry and Ilya.

     Regards,
     Tim Bunce.

     p.s. If you didn't get it, think about recursive data types: html(html())
     p.p.s. I'll turn this into a much more practical example in a day or two.
     p.p.p.s. It's a pity that overloads are not inherited. Is this a bug?

BUGS
====

The exported link() function overrides the builtin link() function.  The
exported tr() function must be called using &tr(...) syntax because it
clashes with the builtin tr/../../ operator.

SEE ALSO
========

*Note HTML/Element: HTML/Element,


File: pm.info,  Node: HTML/Element,  Next: HTML/Entities,  Prev: HTML/AsSubs,  Up: Module List

Class for objects that represent HTML elements
**********************************************

NAME
====

HTML::Element - Class for objects that represent HTML elements

SYNOPSIS
========

     require HTML::Element;
     $a = new HTML::Element 'a', href => 'http://www.oslonett.no/';
     $a->push_content("Oslonett AS");

     $tag = $a->tag;
     $tag = $a->starttag;
     $tag = $a->endtag;
     $ref = $a->attr('href');

     $links = $a->extract_links();

     print $a->as_HTML;

DESCRIPTION
===========

Objects of the HTML::Element class can be used to represent elements of
HTML.  These objects have attributes and content.  The content is an array
of text segments and other HTML::Element objects.  Thus a tree of
HTML::Element objects as nodes can represent the syntax tree for a HTML
document.

The following methods are available:

$h = HTML::Element->new('tag', 'attrname' => 'value',...)
---------------------------------------------------------

The object constructor.  Takes a tag name as argument. Optionally, allows
you to specify initial attributes at object creation time.

$h->tag()
---------

Returns (optionally sets) the tag name for the element.  The tag is always
converted to lower case.

$h->starttag()
--------------

Returns the complete start tag for the element.  Including leading "<",
trailing ">" and attributes.

$h->endtag()
------------

Returns the complete end tag.  Includes leading "</" and the trailing ">".

$h->parent([$newparent])
------------------------

Returns (optionally sets) the parent for this element.

$h->implicit([$bool])
---------------------

Returns (optionally sets) the implicit attribute.  This attribute is used
to indicate that the element was not originally present in the source, but
was inserted in order to conform to HTML strucure.

$h->is_inside('tag',...)
------------------------

Returns true if this tag is contained inside one of the specified tags.

$h->pos()
---------

Returns (and optionally sets) the current position.  The position is a
reference to a HTML::Element object that is part of the tree that has the
current object as root.  This restriction is not enforced when setting
pos(), but unpredictable things will happen if this is not true.

$h->attr('attr', [$value])
--------------------------

Returns (and optionally sets) the value of some attribute.

$h->content()
-------------

Returns the content of this element.  The content is represented as a
reference to an array of text segments and references to other
HTML::Element objects.

$h->is_empty()
--------------

Returns true if there is no content.

$h->insert_element($element, $implicit)
---------------------------------------

Inserts a new element at current position and updates pos() to point to
the inserted element.  Returns $element.

$h->push_content($element_or_text,...)
--------------------------------------

Adds to the content of the element.  The content should be a text segment
(scalar) or a reference to a HTML::Element object.

$h->delete_content()
--------------------

Clears the content.

$h->delete()
------------

Frees memory associated with the element and all children.  This is needed
because perl's reference counting does not work since we use circular
references.

$h->traverse(\&callback, [$ignoretext])
---------------------------------------

Traverse the element and all of its children.  For each node visited, the
callback routine is called with the node, a startflag and the depth as
arguments.  If the $ignoretext parameter is true, then the callback will
not be called for text content.  The flag is 1 when we enter a node and 0
when we leave the node.

If the returned value from the callback is false then we will not traverse
the children.

$h->extract_links([@wantedTypes])
---------------------------------

Returns links found by traversing the element and all of its children.
The return value is a reference to an array.  Each element of the array is
an array with 2 values; the link value and a reference to the
corresponding element.

You might specify that you just want to extract some types of links.  For
instance if you only want to extract <a href="..."> and <img src="...">
links you might code it like this:

     for (@{ $e->extract_links(qw(a img)) }) {
         ($link, $linkelem) = @$_;
         ...
     }

$h->dump()
----------

Prints the element and all its children to STDOUT.  Mainly useful for
debugging.  The structure of the document is shown by indentation (no end
tags).

$h->as_HTML()
-------------

Returns a string (the HTML document) that represents the element and its
children.

BUGS
====

If you want to free the memory assosiated with a tree built of
HTML::Element nodes then you will have to delete it explicitly.  The
reason for this is that perl currently has no proper garbage collector,
but depends on reference counts in the objects.  This scheme fails because
the parse tree contains circular references (parents have references to
their children and children have a reference to their parent).

SEE ALSO
========

*Note HTML/AsSubs: HTML/AsSubs,

COPYRIGHT
=========

Copyright 1995,1996 Gisle Aas.  All rights reserved.

This library is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

AUTHOR
======

Gisle Aas <aas@sn.no>


File: pm.info,  Node: HTML/Entities,  Next: HTML/FormatPS,  Prev: HTML/Element,  Up: Module List

Expand HTML entities in a string
********************************

NAME
====

decode - Expand HTML entities in a string

encode - Encode chars in a string using HTML entities

SYNOPSIS
========

     use HTML::Entities;

     $a = "V&aring;re norske tegn b&oslash;r &#230res";
     decode_entities($a);
     encode_entities($a, "\200-\377");

DESCRIPTION
===========

The decode_entities() routine replaces valid HTML entities found in the
string with the corresponding ISO-8859/1 character.

The encode_entities() routine replaces the characters specified by the
second argument with their entity representation.  The default set of
characters to expand are control chars, high-bit chars and the '<', '&',
'>' and '"' character.

Both routines modify the string passed in as the first argument and return
it.

If you prefer not to import these routines into your namespace you can
call them as:

     use HTML::Entities ();
     $encoded = HTML::Entities::encode($a);
     $decoded = HTML::Entities::decode($a);

The module can also export the %char2entity and the %entity2char hashes
which contains the mapping from all characters to the corresponding
entities.

COPYRIGHT
=========

Copyright 1995, 1996 Gisle Aas. All rights reserved.

This library is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

AUTHOR
======

Gisle Aas <aas@sn.no>


File: pm.info,  Node: HTML/FormatPS,  Next: HTML/FormatText,  Prev: HTML/Entities,  Up: Module List

Format HTML as postscript
*************************

NAME
====

HTML::FormatPS - Format HTML as postscript

SYNOPSIS
========

     require HTML::FormatPS;
     $html = parse_htmlfile("test.html");
     $formatter = new HTML::FormatPS
     		   FontFamily => 'Helvetica',
     		   PaperSize  => 'Letter';
     print $formatter->format($html);

DESCRIPTION
===========

The HTML::FormatPS is a formatter that outputs PostScript code.
Formatting of HTML tables and forms is not implemented.

You might specify the following parameters when constructing the formatter:

PaperSize
     What kind of paper should we format for.  The value can be one of
     these: A3, A4, A5, B4, B5, Letter, Legal, Executive, Tabloid,
     Statement, Folio, 10x14, Quarto.

     The default is "A4".

PaperWidth
     The width of the paper in points.  Setting PaperSize also defines this
     value.

PaperHeight
     The height of the paper in points.  Setting PaperSize also defines
     this value.

LeftMargin
     The left margin in points.

RightMargin
     The right margin in points.

HorizontalMargin
     Both left and right margin at the same time.  The default value is 4
     cm.

TopMargin
     The top margin in points.

BottomMargin
     The bottom margin in points.

VerticalMargin
     Both top and bottom margin at the same time.  The default value is 2
     cm.

PageNo
     The parameter determines if we should put page numbers on the pages.
     The default is yes, so you have to set this value to 0 in order to
     suppress page numbers.

FontFamily
     The parameter specifies which family of fonts to use for the
     formatting.  Legal values are "Courier", "Helvetica" and "Times".
     The default is "Times".

FontScale
     All fontsizes might be scaled by this factor.

Leading
     How much space between lines.  This is a factor of the fontsize used
     for that line.  Default is 0.1.

SEE ALSO
========

*Note HTML/Formatter: HTML/Formatter,

COPYRIGHT
=========

Copyright (c) 1995 Gisle Aas. All rights reserved.

This library is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

AUTHOR
======

Gisle Aas <aas@oslonett.no>


File: pm.info,  Node: HTML/FormatText,  Next: HTML/Formatter,  Prev: HTML/FormatPS,  Up: Module List

Format HTML as text
*******************

NAME
====

HTML::FormatText - Format HTML as text

SYNOPSIS
========

     require HTML::FormatText;
     $html = parse_htmlfile("test.html");
     $formatter = new HTML::FormatText;
     print $formatter->format($html);

DESCRIPTION
===========

The HTML::FormatText is a formatter that outputs plain latin1 text.  All
character attributes (bold/italic/underline) are ignored.  Formatting of
HTML tables and forms is not implemented.

SEE ALSO
========

*Note HTML/Formatter: HTML/Formatter,

COPYRIGHT
=========

Copyright (c) 1995 Gisle Aas. All rights reserved.

This library is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

AUTHOR
======

Gisle Aas <aas@oslonett.no>


File: pm.info,  Node: HTML/Formatter,  Next: HTML/HeadParser,  Prev: HTML/FormatText,  Up: Module List

Base class for HTML formatters
******************************

NAME
====

HTML::Formatter - Base class for HTML formatters

DESCRIPTION
===========

HTML formatters are able to format a HTML syntax tree into various
printable formats.  Different formatters produce output for different
output media.  Common for all formatters are that they will return the
formatted output when the format() method is called.  Format() takes a
HTML::Element as parameter.

SEE ALSO
========

*Note HTML/FormatText: HTML/FormatText,, *Note HTML/FormatPS:
HTML/FormatPS,, *Note HTML/Element: HTML/Element,

COPYRIGHT
=========

Copyright (c) 1995 Gisle Aas. All rights reserved.

This library is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

AUTHOR
======

Gisle Aas <aas@oslonett.no>


File: pm.info,  Node: HTML/HeadParser,  Next: HTML/LinkExtor,  Prev: HTML/Formatter,  Up: Module List

Parse <HEAD> section of a HTML document
***************************************

NAME
====

HTML::HeadParser - Parse <HEAD> section of a HTML document

SYNOPSIS
========

     require HTML::HeadParser;
     $p = HTML::HeadParser->new;
     $p->parse($text) and  print "not finished";

     $p->header('Title')          # to access <title>....</title>
     $p->header('Content-Base')   # to access <base href="http://...">
     $p->header('Foo')            # to access <meta http-equiv="Foo" content="...">

DESCRIPTION
===========

The *HTML::HeadParser* is a specialized (and lightweight) *HTML::Parser*
that will only parse the <HEAD>...</HEAD> section of a HTML document.  The
parse() and parse_file() methods will return a FALSE value as soon as a
<BODY> element is found, and should not be called again after this.

The *HTML::HeadParser* constructor takes a *HTTP::Headers* object
reference as argument.  The parser will update this header object as the
various head elements are recognized.

The following header fields are initialized from elements found in the
`lt' in this nodehead> section of a HTML document:

Content-Base:
     The *Content-Base* header is initialized from the <base href="...">
     element.

Title:
     The *Title* header is initialized from the <title>...</title> element.

Isindex:
     The *Isindex* header will be added if there is a <isindex> element in
     the <head>.  The header value is initialized from the *prompt*
     attribute if it is present.

*http-equiv*
     Any other header field can be initialized from a <meta
     http-equiv="header" content="..."> element.

EXAMPLES
========

     $h = HTTP::Headers->new;
     $p = HTML::HeadParser->new($h);
     $p->parse(<<EOT);
     <title>Stupid example</title>
     <base href="http://www.sn.no/libwww-perl/">
     Normal text starts here.
     EOT
     undef $p;
     print $h->title;   # should print "Stupid example"

SEE ALSO
========

*Note HTML/Parser: HTML/Parser,, *Note HTTP/Headers: HTTP/Headers,

COPYRIGHT
=========

Copyright 1996 Gisle Aas. All rights reserved.

This library is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

AUTHOR
======

Gisle Aas <aas@sn.no>


File: pm.info,  Node: HTML/LinkExtor,  Next: HTML/Parse,  Prev: HTML/HeadParser,  Up: Module List

Extract links from an HTML document
***********************************

NAME
====

HTML::LinkExtor - Extract links from an HTML document

SYNPOSIS
========

     require HTML::LinkExtor;
     $p = HTML::LinkExtor->new(\&cb, "http://www.sn.no/");
     sub cb {
         my($tag, %links);
         print "$tag @{[%links]}\n";
     }
     $p->parse_file("index.html");

DESCRIPTION
===========

The *HTML::LinkExtor* (link extractor) is an HTML parser that takes a
callback routine as parameter.  This routine is then called as the various
link attributes are recognized.

The *HTML::LinkExtor* is a subclass of *HTML::Parser*. This means that the
document should be given to the parser by calling the $p->parse() or
$p->parse_file() methods.

$p = HTML::LinkExtor->new([$callback[, $base]])
-----------------------------------------------

The constructor takes two optional argument. The first is a reference to a
callback routine. It will be called as links are found. If a callback is
not provided, then links are just accumulated internally and can be
retrieved by calling the $p->links() method. The $base is an optional base
URL used to absolutize all URLs found.

The callback is called with the lowercase tag name as first argument, and
then all link attributes as separate key/value pairs.  All non-link
attributes are removed.

@links = $p->links
------------------

Return links found in the document as an array.  Each array element
contains an anonymous array with the follwing values:

     [$tag, $attr => $url1, $attr2 => $url2,...]

Note that $p->links will always be empty if a callback routine was
provided when the *Note HTML/LinkExtor: HTML/LinkExtor, was created.

EXAMPLE
=======

This is an example showing how you can extract links as a document is
received using LWP:

     use LWP::UserAgent;
     use HTML::LinkExtor;
     use URI::URL;

     $url = "http://www.sn.no/";  # for instance
     $ua = new LWP::UserAgent;

     # Set up a callback that collect image links
     my @imgs = ();
     sub callback {
        my($tag, %attr) = @_;
        return if $tag ne 'img';  # we only look closer at <img ...>
        push(@imgs, values %attr);
     }

     # Make the parser.  Unfortunately, we don't know the base yet (it might
     # be diffent from $url)
     $p = HTML::LinkExtor->new(\&callback);

     # Request document and parse it as it arrives
     $res = $ua->request(HTTP::Request->new(GET => $url), sub {$p->parse($_[0])});

     # Expand all image URLs to absolute ones
     my $base = $res->base;
     @imgs = map { $_ = url($_, $base)->abs; } @imgs;

     # Print them out
     print join("\n", @imgs), "\n";

SEE ALSO
========

*Note HTML/Parser: HTML/Parser,

AUTHOR
======

Gisle Aas <aas@sn.no>


File: pm.info,  Node: HTML/Parse,  Next: HTML/Parser,  Prev: HTML/LinkExtor,  Up: Module List

Parse HTML text
***************

NAME
====

parse_html - Parse HTML text

parse_htmlfile - Parse HTML text from file

SYNOPSIS
========

     use HTML::Parse;
     $h = parse_htmlfile("test.html");
     print $h->dump;
     $h = parse_html("<p>Some more <i>italic</i> text", $h);
     $h->delete;

     print parse_htmlfile("index.html")->as_HTML;  # tidy up markup in a file

DESCRIPTION
===========

*Disclaimer: This module is provided for backwards compatibility with
earlier versions of this library.  New code will probably prefer to use
the HTML::Parser and HTML::TreeBuilder modules directly.*

The `HTML::Parse' module provides functions to parse HTML documents.
There are two functions exported by this module:

parse_html($html, [$obj])
     This function is really just a synonym for $obj->parse($html) and $obj
     is assumed to be a subclass of `HTML::Parser'.  Refer to *Note
     HTML/Parser: HTML/Parser, for more documentation.

     The $obj will default to a internally created `HTML::TreeBuilder'
     object.  This class implements a parser that builds (and is) a HTML
     syntax tree with HTML::Element objects as nodes.

     The return value from parse_html() is $obj.

parse_htmlfile($file, [$obj])
     Same as parse_html(), but obtains HTML text from the named file.

     Returns undef if the file could not be opened, or $obj otherwise.

When a `HTML::TreeBuilder' object is created, the following variables
control how parsing takes place:

$HTML::Parse::IMPLICIT_TAGS
     Setting this variable to true will instruct the parser to try to
     deduce implicit elements and implicit end tags.  If this variable is
     false you get a parse tree that just reflects the text as it stands.
     Might be useful for quick & dirty parsing.  Default is true.

     Implicit elements have the implicit() attribute set.

$HTML::Parse::IGNORE_UNKNOWN
     This variable contols whether unknow tags should be represented as
     elements in the parse tree.  Default is true.

$HTML::Parse::IGNORE_TEXT
     Do not represent the text content of elements.  This saves space if
     all you want is to examine the structure of the document.  Default is
     false.

$HTML::Parse::WARN
     Call warn() with an apropriate message for syntax errors.  Default is
     false.

SEE ALSO
========

*Note HTML/Parser: HTML/Parser,, *Note HTML/TreeBuilder:
HTML/TreeBuilder,, *Note HTML/Element: HTML/Element,

COPYRIGHT
=========

Copyright 1995-1996 Gisle Aas. All rights reserved.

This library is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

AUTHOR
======

Gisle Aas <aas@sn.no>


File: pm.info,  Node: HTML/Parser,  Next: HTML/QuickCheck,  Prev: HTML/Parse,  Up: Module List

SGML parser class
*****************

NAME
====

HTML::Parser - SGML parser class

SYNOPSIS
========

     require HTML::Parser;
     $p = HTML::Parser->new;  # should really a be subclass
     $p->parse($chunk1);
     $p->parse($chunk2);
     #...
     $p->eof;                 # signal end of document

     # Parse directly from file
     $p->parse_file("foo.html");
     # or
     open(F, "foo.html") || die;
     $p->parse_file(\*F);

DESCRIPTION
===========

The `HTML::Parser' will tokenize a HTML document when the $p->parse()
method is called.  The document to parse can be supplied in arbitrary
chunks.  Call $p->eof() the end of the document to flush any remaining
text.  The return value from parse() is a reference to the parser object.

The $p->parse_file() method can be called to parse text from a file.  The
argument can be a filename or an already opened file handle. The return
value from parse_file() is a reference to the parser object.

In order to make the parser do anything interesting, you must make a
subclass where you override one or more of the following methods as
appropriate:

$self->declaration($decl)
     This method is called when a *markup declaration* has been
     recognized.  For typical HTML documents, the only declaration you are
     likely to find is <!DOCTYPE ...>.  The initial "<!" and ending ">" is
     not part of the string passed as argument.  Comments are removed and
     entities have *not* been expanded yet.

$self->start($tag, $attr, $attrseq, $origtext)
     This method is called when a complete start tag has been recognized.
     The first argument is the tag name (in lower case) and the second
     argument is a reference to a hash that contain all attributes found
     within the start tag.  The attribute keys are converted to lower case.
     Entities found in the attribute values are already expanded.  The
     third argument is a reference to an array with the lower case
     attribute keys in the original order.  The fourth argument is the
     original HTML text.

$self->end($tag)
     This method is called when an end tag has been recognized.  The
     argument is the lower case tag name.

$self->text($text)
     This method is called when plain text in the document is recognized.
     The text is passed on unmodified and might contain multiple lines.
     Note that for efficiency reasons entities in the text are *not*
     expanded.  You should call HTML::Entities::decode($text) before you
     process the text any further.

$self->comment($comment)
     This method is called as comments are recognized.  The leading and
     trailing "-" sequences have been stripped off the comment text.

The default implementation of these methods does nothing, *i.e.,* the
tokens are just ignored.

There is really nothing in the basic parser that is HTML specific, so it
is likely that the parser can parse many kinds of SGML documents, but SGML
has many obscure features (not implemented by this module) that prevent us
from renaming this module as `SGML::Parse'.

BUGS
====

You can instruct the parser to parse comments the way Netscape does it by
calling the netscape_buggy_comment() method with a TRUE argument.  This
means that comments will always be terminated by the first occurence of
"->".

SEE ALSO
========

*Note HTML/TreeBuilder: HTML/TreeBuilder,, *Note HTML/HeadParser:
HTML/HeadParser,, *Note HTML/Entities: HTML/Entities,

COPYRIGHT
=========

Copyright 1996 Gisle Aas. All rights reserved.

This library is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

AUTHOR
======

Gisle Aas <aas@sn.no>


File: pm.info,  Node: HTML/QuickCheck,  Next: HTML/Stream,  Prev: HTML/Parser,  Up: Module List

a simple and fast HTML syntax checking package for perl 4 and perl 5
********************************************************************

NAME
====

HTMLQuickCheck.pm - a simple and fast HTML syntax checking package for
perl 4 and perl 5

SYNOPSIS          require 'HTMLQuickCheck.pm';
==============================================

     &HTML'QuickCheck'OK($html_text) || die "Bad HTML: $HTML'QuickCheck'Error";

     or for perl 5:
     HTML::QuickCheck::OK($html_text) ||
             die "Bad HTML: $HTML::QuickCheck::Error";

DESCRIPTION
===========

The objective of the package is to provide a fast and essential HTML check
(esp. for CGI scripts where response time is important) to prevent a piece
of user input HTML code from messing up the rest of a file, i.e., to
minimize and localize any possible damage created by including a piece of
user input HTML text in a dynamic document.

HTMLQuickCheck checks for unmatched < and >, unmatched tags and improper
nesting, which could ruin the rest of the document.  Attributes and
elements with optional end tags are not checked, as they should not cause
disasters with any decent browsers (they should ignore any unrecognized
tags and attributes according to the standard).  A piece of HTML that
passes HTMLQuickCheck may not necessarily be valid HTML, but it would be
very unlikely to screw others but itself. A valid piece of HTML that
doesn't pass the HTMLQuickCheck is however very likely to screw many
browsers(which are obviously broken in terms of strict conformance).

HTMLQuickCheck currently supports HTML 1.0, 2.x (draft), 3.0 (draft) and
netscape extensions (1.1).

EXAMPLE
=======

     htmlchk, a simple html checker:

     #!/usr/local/bin/perl
     require 'HTMLQuickCheck.pm';
     undef $/;
     print &HTML'QuickCheck'OK(<>) ? "HTML OK\n" :
             "Bad HTML:\n", $HTML'QuickCheck'Error;
     __END__

     Usage:
     htmlchk [html_file]

AUTHOR
======

Luke Y. Lu <ylu@mail.utexas.edu>

SEE ALSO
========

HTML docs at <URL:http://www.w3.org/hypertext/WWW/MarkUp/MarkUp.html>;
HTML validation service at <URL:http://www.halsoft.com/html/>; perlSGML
package at <URL:http://www.oac.uci.edu/indiv/ehood/perlSGML.html>; weblint
at <URL:http://www.khoros.unm.edu/staff/neilb/weblint.html>

BUGS
====

Please report them to the author.


File: pm.info,  Node: HTML/Stream,  Next: HTML/TreeBuilder,  Prev: HTML/QuickCheck,  Up: Module List

HTML output stream class, and some markup utilities
***************************************************

NAME
====

HTML::Stream - HTML output stream class, and some markup utilities

DESCRIPTION
===========

This module provides you with an object-oriented (and subclassable) way of
outputting HTML.  Basically, you open up an "HTML stream" on an existing
filehandle, and then do all of your output to the HTML stream (you can
intermix HTML-stream-output and ordinary-print-output, if you like).

Here's small sample of the different ways you can use this module:

     use HTML::Stream;
     $HTML = new HTML::Stream \*STDOUT;
     
     # The vanilla interface...
     tag  $HTML 'A', HREF=>"$href";
     tag  $HTML 'IMG', SRC=>"logo.gif", ALT=>"LOGO";
     text $HTML "My caption!";
     tag  $HTML '_A';
     text $HTML $a_lot_of_text;

     # The chocolate interface (with whipped cream)...
     $HTML -> A(HREF=>"$href")
           -> IMG(SRC=>"logo.gif", ALT=>"LOGO")
           -> t("My caption!")
           -> _A
           -> t($a_lot_of_text);

     # The strawberry interface...
     output $HTML [A, HREF=>"$href"],
                  [IMG, SRC=>"logo.gif", ALT=>"LOGO"],
                  "My caption!",
                  [_A];
     output $HTML $a_lot_of_text;

Function interface
------------------

Let's start out with the simple stuff.  This module provides a collection
of non-OO utility functions for escaping HTML text and producing HTML
tags, like this:

     use HTML::Stream qw(:funcs);        # imports functions from @EXPORT_OK
     
     print html_tag(A, HREF=>$url);
     print '&copy; 1996 by', html_escape($myname), '!';
     print html_tag('/A');

By the way: that last line could be rewritten as:

     print html_tag(_A);

And if you need to get a parameter in your tag that doesn't have an
associated value, supply the *undefined* value (*not* the empty string!):

     print html_tag(TD, NOWRAP=>undef, ALIGN=>'LEFT');
     
          <TD NOWRAP ALIGN=LEFT>
     
     print html_tag(IMG, SRC=>'logo.gif', ALT=>'');
     
          <IMG SRC="logo.gif" ALT="">

There are also some routines for reversing the process, like:

     $text = "This <i>isn't</i> &quot;fun&quot;...";
     print html_unmarkup($text);
     
          This isn't &quot;fun&quot;...
     
     print html_unescape($text);
     
          This isn't "fun"...

*Yeah, yeah, yeah*, I hear you cry.  *We've seen this stuff before.* But
wait!  There's more...

OO interface, vanilla
---------------------

Using the function interface can be tedious... so we also provide an
*"HTML output stream"* class.  Messages to an instance of that class
generally tell that stream to output some HTML.  Here's the above example,
rewritten using HTML streams:

     use HTML::Stream;
     $HTML = new HTML::Stream \*STDOUT;
     
     tag  $HTML 'A', HREF=>$url;
     ent  $HTML 'copy';
     text $HTML " 1996 by $myname!";
     tag  $HTML '_A';

Or, if indirect-object syntax ain't your thang:

     $HTML->tag(A, HREF=>$url);
     $HTML->ent('copy');
     $HTML->text(" 1996 by $myname!");
     $HTML->tag(_A);

As you've probably guessed:

     ent()      Outputs an HTML entity, like C<&copy;>.
     tag()      Outputs an ordinary tag, like <A>, possibly with parameters.
                The parameters will all be HTML-escaped automatically.
     text()     Outputs some text, which will be HTML-escaped.

It you're *not* using indirect-object syntax, you might prefer to use
`t()' and `e()' instead of `text()' and `ent()': they are absolutely
identical... just shorter to type:

     $HTML -> tag(A, HREF=>$url);
     $HTML -> e('copy');
     $HTML -> t(" 1996 by $myname!");
     $HTML -> tag(_A);

Now, it wouldn't be nice to give you those `text()' and `ent()' shortcuts
without giving you one for `tag()', would it?  Of course not...

OO interface, chocolate
-----------------------

The known HTML tags are even given their own *tag-methods,* compiled on
demand... so the above could be written like this:

     $HTML -> A(HREF=>$url);
     $HTML -> e('copy');
     $HTML -> t(" 1996 by $myname!");
     $HTML -> _A;

As you've probably guessed:

     A(HREF=>$url)   ==   tag(A, HREF=>$url)   ==   <A HREF="/the/url">
     _A              ==   tag(_A)              ==   </A>

All such "tag-methods" use the tagname in *all-uppercase*.  A `"_"' prefix
on any tag-method means that an end-tag is desired.  The `"_"' was chosen
for several reasons: (1) it's short and easy to type, (2) it doesn't
produce much visual clutter to look at, (3) `_TAG' looks a little like
`/TAG' because of the straight line.

   * *I know, I know... it looks like a private method.  You get used to
     it.  Really.*

I should stress that this module will only auto-create tag methods for
*known* HTML tags.  So you're protected from typos like this (which will
cause a fatal exception at run-time):

     $HTML -> IMGG(SRC=>$src);

(You're not yet protected from illegal tag parameters, but it's a start,
ain't it?)

If you need to make a tag known (sorry, but this is currently a *global*
operation, and not stream-specific), do this:

     HTML::Stream->accept_tag('MARQUEE');     # for you MSIE fans...

*There is no corresponding "reject_tag"*.  I thought and thought about it,
and could not convince myself that such a method would do anything more
useful that cause other people's modules to suddenly stop working because
some bozo function decided to reject the `FONT' tag.

OO interface, with whipped cream
--------------------------------

In the grand tradition of C++, output method chaining is supported in both
the Vanilla Interface and the Chocolate Interface.  So you can (and
probably should) say:

     $HTML -> A(HREF=>$url)
           -> e('copy') -> t("1996 by $myname!")
           -> _A;

But wait... there's one more flavor...

OO interface, strawberry
------------------------

I was jealous of the compact syntax of HTML::AsSubs, but I didn't want to
worry about clogging the namespace with a lot of functions like p(), a(),
etc. (especially when markup-functions like tr() conflict with existing
Perl functions).  So I came up with this:

     output $HTML [A, HREF=>$url], "Here's my $caption", [_A];

Conceptually, arrayrefs are sent to `html_tag()', and strings to
`html_escape()'.

Newlines
--------

As special cases, some tag-methods (like `P', `_P', and `BR') all cause
newlines to be output before and/or after the tag, so your HTML is a little
more readable when you do stuff like "view source" on a browser.  So:

     $HTML -> HTML
           -> HEAD
           -> TITLE -> t("Hello!") -> _TITLE
           -> _HEAD
           -> BODY(BGCOLOR=>'#808080');

Actually produces:

     <HTML><HTML>
     <HEAD>
     <TITLE>Hello!</TITLE>
     </HEAD>
     <BODY BGCOLOR="#808080">

(This will improve slightly as time goes on).  You can also output newline
explicitly via the special `nl' method in the Chocolate Interface:

     $HTML->nl;     # one newline
     $HTML->nl(6);  # six newlines

Entities
--------

As shown above, You can use the `ent()' (or `e()') method to output an
entity:

     $HTML->t('Copyright ')->e('copy')->t(' 1996 by Me!');

But this can be a pain, particularly for Europeans:

     $HTML -> t('Copyright ')
           -> e('copy')
           -> t(' 1996 by Fran') -> e('ccedil') -> t('ois, Inc.!');

Sooooooooo...

Changing the way text is escaped
--------------------------------

The default "autoescape" behavior of an HTML stream can be a drag if
you've got a lot character entities that you want to output.  So here's
how you can use the `autoescape()' method to change the way an
HTML::Stream works at any time:

     $HTML->autoescape('ALL');        # escapes [<>"&] - the default
     $HTML->autoescape('NON_ENT');    # escapes [<>"] only, and not [&]

If you can also install your own autoescape function (note that you might
very well want to install it for just a little bit only, and then
de-install it):

     sub my_autoescape {
         my $text = shift;
     	$text = HTML::Stream::html_escape_all($text);   # start with default
         $text =~ s/\(c\)/&copy;/ig;        # (C) becomes copyright
         $text =~ s/\\,(c)/\&$1cedil;/ig;   # \,c becomes a cedilla
      	$text;
     }

     # Start using my autoescape:
     my $oldesc = $HTML->autoescape(\&my_autoescape);      # use sub refs ONLY!
     $HTML-> ADDRESS;
     $HTML-> IMG(SRC=>'logo.gif', ALT=>'Fran\,cois, Inc');
     output $HTML 'Copyright (C) 1996 by Fran\,cois, Inc.!';
     $HTML->_ADDRESS;
     
     # Stop using my autoescape:
     $HTML->autoescape($oldesc);

By the way, the following are equivalent:

     $HTML->autoescape('ALL')
     $HTML->autoescape(\&HTML::Stream::escape_all);

No arguments to `autoescape()' returns the current autoescape function.

Outputting HTML to things besides filehandles
---------------------------------------------

As of Revision 1.21, you no longer need to supply new() with a filehandle:
*any object that responds to a print() method will do*.  Of course, this
includes *blessed* FileHandles.

If you supply a GLOB reference (like `\*STDOUT') or a string (like
`"Module::FH"'), HTML::Stream will automatically create an invisible
object for talking to that filehandle (I don't dare bless it into a
FileHandle, since it'd get closed when the HTML::Stream is destroyed, and
you might not like that).

You say you want to print to a string?  For kicks and giggles, try this:

     package StringHandle;
     sub new {
     	my $self = '';
     	bless \$self, shift;
     }
     sub print {
         my $self = shift;
         $$self .= join('', @_);
     }
     
     
     package main;
     use HTML::Stream;
     
     my $SH = new StringHandle;
     my $HTML = new HTML::Stream $SH;
     $HTML -> H1 -> "<Hello & welcome!>" -> _H1;
     print "PRINTED STRING: ", $$SH, "\n";

Subclassing
-----------

This is where you can make your application-specific HTML-generating code
*much* easier to look at.  Consider this:

     package MY::HTML;
     @ISA = qw(HTML::Stream);
     
     sub Aside {
     	$_[0] -> FONT(SIZE=>-1) -> I;
     }
     sub _Aside {
     	$_[0] -> _I -> _FONT;
     }

Now, you can do this:

     my $HTML = new MY::HTML \*STDOUT;
     
     $HTML -> Aside
           -> t("Don't drink the milk, it's spoiled... pass it on...")
           -> _Aside;

If you're defining these markup-like, chocolate-interface-style functions,
I recommend using mixed case with a leading capital.  You probably
shouldn't use all-uppercase, since that's what this module uses for real
HTML tags.

PERFORMANCE
===========

Slower than I'd like.  Both the output() method and the various "tag"
methods seem to run about 5 times slower than the old
just-hardcode-the-darn stuff approach.  That is, in general, this:

     ### Approach #1...
     tag  $HTML 'A', HREF=>"$href";
     tag  $HTML 'IMG', SRC=>"logo.gif", ALT=>"LOGO";
     text $HTML "My caption!";
     tag  $HTML '_A';
     text $HTML $a_lot_of_text;

And this:

     ### Approach #2...
     output $HTML [A, HREF=>"$href"],
     	         [IMG, SRC=>"logo.gif", ALT=>"LOGO"],
     		 "My caption!",
     		 [_A];
     output $HTML $a_lot_of_text;

And this:

     ### Approach #3...
     $HTML -> A(HREF=>"$href")
     	  -> IMG(SRC=>"logo.gif", ALT=>"LOGO")
     	  -> t("My caption!")
     	  -> _A
           -> t($a_lot_of_text);

Each run about 5x slower than this:

     ### Approach #4...
     print '<A HREF="', html_escape($href), '>',
           '<IMG SRC="logo.gif" ALT="LOGO">',
       	  "My caption!",
           '</A>';
     print html_escape($a_lot_of_text);

Of course, I'd much rather use any of first three *(especially #3)* if I
had to get something done right in a hurry.  Or did you not notice the
typo in approach #4?  `;-)'

(BTW, thanks to Benchmark:: for allowing me to... er... benchmark stuff.)

WHY IN THE WORLD DID I WRITE THIS?
==================================

I was just mucking about with different ways of generating large HTML
documents, seeing which ways I liked the most/least.

VERSION
=======

$Revision: 1.24 $

AUTHOR
======

Eryq, eryq@rhine.gsfc.nasa.gov .

Enjoy.


File: pm.info,  Node: HTML/TreeBuilder,  Next: HTTP/Daemon,  Prev: HTML/Stream,  Up: Module List

Parser that builds a HTML syntax tree
*************************************

NAME
====

HTML::TreeBuilder - Parser that builds a HTML syntax tree

SYNOPSIS
========

     $h = new HTML::TreeBuilder;
     $h->parse($document);
     #...

     print $h->as_HTML;  # or any other HTML::Element method

DESCRIPTION
===========

This is a parser that builds (and actually itself is) a HTML syntax tree.

Objects of this class inherit the methods of both `HTML::Parser' and
`HTML::Element'.  After parsing has taken place it can be regarded as the
syntax tree itself.

The following method all control how parsing takes place.  You can set the
attributes by passing a TRUE or FALSE value as argument.

$p->implicit_tags
     Setting this attribute to true will instruct the parser to try to
     deduce implicit elements and implicit end tags.  If it is false you
     get a parse tree that just reflects the text as it stands.  Might be
     useful for quick & dirty parsing.  Default is true.

     Implicit elements have the implicit() attribute set.

$p->ignore_unknown
     This attribute controls whether unknown tags should be represented as
     elements in the parse tree.  Default is true.

$p->ignore_text
     Do not represent the text content of elements.  This saves space if
     all you want is to examine the structure of the document.  Default is
     false.

$p->warn
     Call warn() with an appropriate message for syntax errors.  Default is
     false.

SEE ALSO
========

*Note HTML/Parser: HTML/Parser,, *Note HTML/Element: HTML/Element,

COPYRIGHT
=========

Copyright 1995-1996 Gisle Aas. All rights reserved.

This library is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

AUTHOR
======

Gisle Aas <aas@sn.no>


File: pm.info,  Node: HTTP/Daemon,  Next: HTTP/Date,  Prev: HTML/TreeBuilder,  Up: Module List

a simple http server class
**************************

NAME
====

HTTP::Daemon - a simple http server class

SYNOPSIS
========

     use HTTP::Daemon;
     use HTTP::Status;

     $d = new HTTP::Daemon;
     print "Please contact me at: <URL:", $d->url, ">\n";
     while ($c = $d->accept) {
         $r = $c->get_request;
         if ($r) {
     	  if ($r->method eq 'GET' and $r->url->path eq "/xyzzy") {
                 # this is *not* recommened practice
     	      $c->send_file_response("/etc/passwd");
     	  } else {
     	      $c->send_error(RC_FORBIDDEN)
     	  }
         }
         $c = undef;  # close connection
     }

DESCRIPTION
===========

Instances of the *HTTP::Daemon* class are HTTP/1.1 servers that listens on
a socket for incoming requests. The *HTTP::Daemon* is a sub-class of
IO::Socket::INET, so you can do socket operations directly on it.

The accept() method will return when a connection from a client is
available. The returned value will be a reference to a object of the
*HTTP::Daemon::ClientConn* class which is another IO::Socket::INET
subclass. Calling the get_request() method on this object will read data
from the client and return an *HTTP::Request* object reference.

This HTTP daemon does not fork(2) for you.  Your application, i.e. the
user of the *HTTP::Daemon* is reponsible for forking if that is desirable.
Also note that the user is responsible for generating responses that
conforms to the HTTP/1.1 protocol.  The *HTTP::Daemon::ClientConn* provide
some methods that make this easier.

METHODS
=======

The following is a list of methods that are new (or enhanced) relative to
the IO::Socket::INET base class.

$d = new HTTP::Daemon
     The object constructor takes the same parameters as the
     IO::Socket::INET constructor.  It can also be called without
     specifying any parameters. The daemon will then set up a listen queue
     of 5 connections and allocate some random port number.  A server that
     want to bind to some specific address on the standard HTTP port will
     be constructed like this:

          $d = new HTTP::Daemon
                LocalAddr => 'www.someplace.com',
                LocalPort => 80;

$c = $d->accept
     Same as *IO::Socket::accept* but will return an
     *HTTP::Daemon::ClientConn* reference.  It will return undef if you
     have specified a timeout and no connection is made within that time.

$d->url
     Returns a URL string that can be used to access the server root.

The *HTTP::Daemon::ClientConn* is also a IO::Socket::INET subclass.
Instances of this class are returned by the accept() method of the
*HTTP::Daemon*.  The following additional methods are provided:

$c->get_request
     Will read data from the client and turn it into a *HTTP::Request*
     object which is then returned. Will return undef if reading of the
     request failed.  If it fails, then the *HTTP::Daemon::ClientConn*
     object ($c) should be discarded.

     The $c->get_request method support HTTP/1.1 content bodies, including
     *chunked* transfer encoding with footer and *multipart/** types.

$c->send_status_line( [$code, [$mess, [$proto]]] )
     Sends the status line back to the client.

$c->send_basic_header( [$code, [$mess, [$proto]]] )
     Sends the status line and the "Date:" and "Server:" headers back to
     the client.

$c->send_response( [$res] )
     Takes a *HTTP::Response* object as parameter and send it back to the
     client as the response.

$c->send_redirect( $loc, [$code, [$entity_body]] )
     Sends a redirect response back to the client.  The location ($loc) can
     be an absolute or a relative URL. The $code must be one the redirect
     status codes, and it defaults to "301 Moved Permanently"

$c->send_error( [$code, [$error_message]] )
     Send an error response back to the client.  If the $code is missing a
     "Bad Request" error is reported.  The $error_message is a string that
     is incorporated in the body of the HTML entity body.

$c->send_file_response($filename)
     Send back a response with the specified $filename as content.  If the
     file happen to be a directory we will generate a HTML index for it.

$c->send_file($fd);
     Copies the file back to the client.  The file can be a string (which
     will be interpreted as a filename) or a reference to a glob.

$c->daemon
     Return a reference to the corresponding *HTTP::Daemon* object.

SEE ALSO
========

*Note IO/Socket: IO/Socket,, *Note Apache: Apache,

COPYRIGHT
=========

Copyright 1996, Gisle Aas

This library is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.


File: pm.info,  Node: HTTP/Date,  Next: HTTP/Headers,  Prev: HTTP/Daemon,  Up: Module List

date conversion routines
************************

NAME
====

time2str, str2time - date conversion routines

SYNOPSIS
========

     use HTTP::Date;

     $stringGMT = time2str(time);   # Format as GMT ASCII time
     $time = str2time($stringGMT);  # convert ASCII date to machine time

DESCRIPTION
===========

This module provides two functions that deal with the HTTP date format.

time2str([$time])
-----------------

The time2str() function converts a machine time (seconds since epoch) to a
string.  If the function is called without an argument, it will use the
current time.

The string returned is in the format defined by the HTTP/1.0
specification.  This is a fixed length subset of the format defined by RFC
1123, represented in Universal Time (GMT).  An example of this format is:

     Thu, 03 Feb 1994 17:09:00 GMT

str2time($str [, $zone])
------------------------

The str2time() function converts a string to machine time.  It returns
undef if the format is unrecognized, or the year is not between 1970 and
2038.  The function is able to parse the following formats:

     "Wed, 09 Feb 1994 22:23:32 GMT"       -- HTTP format
     "Thu Feb  3 17:03:55 GMT 1994"        -- ctime(3) format
     'Thu Feb  3 00:00:00 1994',           -- ANSI C asctime() format
     "Tuesday, 08-Feb-94 14:15:29 GMT"     -- old rfc850 HTTP format
     "Tuesday, 08-Feb-1994 14:15:29 GMT"   -- broken rfc850 HTTP format

     "03/Feb/1994:17:03:55 -0700"   -- common logfile format
     "09 Feb 1994 22:23:32 GMT"     -- HTTP format (no weekday)
     "08-Feb-94 14:15:29 GMT"       -- rfc850 format (no weekday)
     "08-Feb-1994 14:15:29 GMT"     -- broken rfc850 format (no weekday)

     "1994-02-03 14:15:29 -0100"    -- ISO 8601 format
     "1994-02-03 14:15:29"          -- zone is optional
     "1994-02-03"                   -- only date
     "1994-02-03T14:15:29"          -- Use T as separator
     "19940203T141529Z"             -- ISO 8601 compact format
     "19940203"                     -- only date

     "08-Feb-94"     -- old rfc850 HTTP format    (no weekday, no time)
     "08-Feb-1994"   -- broken rfc850 HTTP format (no weekday, no time)
     "09 Feb 1994"   -- proposed new HTTP format  (no weekday, no time)
     "03/Feb/1994"   -- common logfile format     (no time, no offset)

     "Feb  3  1994"  -- Unix 'ls -l' format
     "Feb  3 17:03"  -- Unix 'ls -l' format

The parser ignores leading and trailing whitespace.  It also allow the
seconds to be missing and the month to be numerical in most formats.

The str2time() function takes an optional second argument that specifies
the default time zone to use when converting the date.  This zone
specification should be numerical (like "-0800" or "+0100") or "GMT".
This parameter is ignored if the zone is specified in the date string
itself.  It this parameter is missing, and the date string format does not
contain any zone specification then the local time zone is assumed.

If the year is missing, then we assume that the date is the first matching
date *before* current time.

BUGS
====

Non-numerical time zones (like MET, PST) are all treated like GMT.  Do not
use them.  HTTP does not use them.

The str2time() function has been told how to parse far too many formats.
This makes the module name misleading :-)


File: pm.info,  Node: HTTP/Headers,  Next: HTTP/Message,  Prev: HTTP/Date,  Up: Module List

Class encapsulating HTTP Message headers
****************************************

NAME
====

HTTP::Headers - Class encapsulating HTTP Message headers

SYNOPSIS
========

     require HTTP::Headers;
     $request = new HTTP::Headers;

DESCRIPTION
===========

The `HTTP::Headers' class encapsulates HTTP-style message headers.  The
headers consist of attribute-value pairs, which may be repeated, and which
are printed in a particular order.

Instances of this class are usually created as member variables of the
`HTTP::Request' and `HTTP::Response' classes, internal to the library.

METHODS
=======

$h = new HTTP::Headers
----------------------

Constructs a new `HTTP::Headers' object.  You might pass some initial
attribute-value pairs as parameters to the constructor.  *E.g.*:

     $h = new HTTP::Headers
         Date         => 'Thu, 03 Feb 1994 00:00:00 GMT',
         Content_Type => 'text/html; version=3.2',
         Content_Base => 'http://www.sn.no/';

$h->header($field [=> $val],...)
--------------------------------

Get or set the value of a header.  The header field name is not case
sensitive.  To make the life easier for perl users who wants to avoid
quoting before the => operator, you can use '_' as a synonym for '-' in
header names.

The value argument may be a scalar or a reference to a list of scalars. If
the value argument is not defined, then the header is not modified.

The header() method accepts multiple ($field => $value) pairs.

The list of previous values for the last $field is returned.  Only the
first header value is returned in scalar context.

     $header->header(MIME_Version => '1.0',
     		 User_Agent   => 'My-Web-Client/0.01');
     $header->header(Accept => "text/html, text/plain, image/*");
     $header->header(Accept => [qw(text/html text/plain image/*)]);
     @accepts = $header->header('Accept');

$h->scan(\&doit)
----------------

Apply a subroutine to each header in turn.  The callback routine is called
with two parameters; the name of the field and a single value.  If the
header has more than one value, then the routine is called once for each
value.  The field name passed to the callback routine has case as
suggested by HTTP Spec, and the headers will be visited in the recommended
"Good Practice" order.

$h->as_string([$endl])
----------------------

Return the header fields as a formatted MIME header.  Since it internally
uses the `scan()' method to build the string, the result will use case as
suggested by HTTP Spec, and it will follow recommended "Good Practice" of
ordering the header fieds.  Long header values are not folded.

The optional parameter specifies the line ending sequence to use.  The
default is `"\n"'.  Embedded "\n" characters in the header will be
substitued with this line ending sequence.

$h->push_header($field, $val)
-----------------------------

Add a new field value of the specified header.  The header field name is
not case sensitive.  The field need not already have a value. Previous
values for the same field are retained.  The argument may be a scalar or a
reference to a list of scalars.

     $header->push_header(Accept => 'image/jpeg');

$h->remove_header($field,...)
-----------------------------

This function removes the headers with the specified names.

$h->clone
---------

Returns a copy of this HTTP::Headers object.

CONVENIENCE METHODS
===================

The most frequently used headers can also be accessed through the
following convenience methods.  These methods can both be used to read and
to set the value of a header.  The header value is set if you pass an
argument to the method.  The old header value is always returned.

Methods that deal with dates/times always convert their value to system
time (seconds since Jan 1, 1970) and they also expect this kind of value
when the header value is set.

$h->date
--------

This header represents the date and time at which the message was
originated. *E.g.*:

     $h->date(time);  # set current date

$h->expires
-----------

This header gives the date and time after which the entity should be
considered stale.

$h->if_modified_since
---------------------

This header is used to make a request conditional.  If the requested
resource has not been modified since the time specified in this field,
then the server will return a `"304 Not Modified"' response instead of the
document itself.

$h->last_modified
-----------------

This header indicates the date and time at which the resource was last
modified. *E.g.*:

     # check if document is more than 1 hour old
     if ($h->last_modified < time - 60*60) {
     	...
     }

$h->content_type
----------------

The Content-Type header field indicates the media type of the message
content. *E.g.*:

     $h->content_type('text/html');

The value returned will be converted to lower case, and potential
parameters will be chopped off and returned as a separate value if in an
array context.  This makes it safe to do the following:

     if ($h->content_type eq 'text/html') {
        # we enter this place even if the real header value happens to
        # be 'TEXT/HTML; version=3.0'
        ...
     }

$h->content_encoding
--------------------

The Content-Encoding header field is used as a modifier to the media type.
When present, its value indicates what additional encoding mechanism has
been applied to the resource.

$h->content_length
------------------

A decimal number indicating the size in bytes of the message content.

$h->title
---------

The title of the document.  In libwww-perl this header will be initialized
automatically from the <TITLE>...</TITLE> element of HTML documents.
*This header is no longer part of the HTTP standard.*

$h->user_agent
--------------

This header field is used in request messages and contains information
about the user agent originating the request.  *E.g.*:

     $h->user_agent('Mozilla/1.2');

$h->server
----------

The server header field contains information about the software being used
by the originating server program handling the request.

$h->from
--------

This header should contain an Internet e-mail address for the human user
who controls the requesting user agent.  The address should be
machine-usable, as defined by RFC822.  E.g.:

     $h->from('Gisle Aas <aas@sn.no>');

$h->referer
-----------

Used to specify the address (URI) of the document from which the requested
resouce address was obtained.

$h->www_authenticate
--------------------

This header must be included as part of a "401 Unauthorized" response.
The field value consist of a challenge that indicates the authentication
scheme and parameters applicable to the requested URI.

$h->authorization
-----------------

A user agent that wishes to authenticate itself with a server, may do so
by including this header.

$h->authorization_basic
-----------------------

This method is used to get or set an authorization header that use the
"Basic Authentication Scheme".  In array context it will return two
values; the user name and the password.  In scalar context it will return
*"uname:password"* as a single string value.

When used to set the header value, it expects two arguments.  *E.g.*:

     $h->authorization_basic($uname, $password);


File: pm.info,  Node: HTTP/Message,  Next: HTTP/Negotiate,  Prev: HTTP/Headers,  Up: Module List

Class encapsulating HTTP messages
*********************************

NAME
====

HTTP::Message - Class encapsulating HTTP messages

DESCRIPTION
===========

A `HTTP::Message' object contains some headers and a content (body).  The
class is abstract, i.e. it only used as a base class for `HTTP::Request'
and `HTTP::Response' and should never instantiated as itself.

METHODS
=======

$mess = new HTTP::Message;
--------------------------

This is the object constructor.  It should only be called internally by
this library.  External code should construct `HTTP::Request' or
`HTTP::Response' objects.

$mess->clone()
--------------

Returns a copy of the object.

$mess->protocol([$proto])
-------------------------

Sets the HTTP protocol used for the message.  The protocol() is a string
like "HTTP/1.0" or "HTTP/1.1".

$mess->content([$content])
--------------------------

The content() method sets the content if an argument is given.  If no
argument is given the content is not touched.  In either case the previous
content is returned.

$mess->add_content($data)
-------------------------

The add_content() methods appends more data to the end of the previous
content.

$mess->content_ref
------------------

The content_ref() method will return a reference to content string.  It
can be more efficient to access the content this way if the content is
huge, and it can be used for direct manipulation of the content, for
instance:

     ${$res->content_ref} =~ s/\bfoo\b/bar/g;

HEADER METHODS
==============

All unknown `HTTP::Message' methods are delegated to the `HTTP::Headers'
object that is part of every message.  This allows convenient access to
these methods.  Refer to *Note HTTP/Headers: HTTP/Headers, for details of
these methods:

     $mess->header($field => $val);
     $mess->scan(&doit);
     $mess->push_header($field => $val);
     $mess->remove_header($field);

     $mess->date;
     $mess->expires;
     $mess->if_modified_since;
     $mess->last_modified;
     $mess->content_type;
     $mess->content_encoding;
     $mess->content_length;
     $mess->title;
     $mess->user_agent;
     $mess->server;
     $mess->from;
     $mess->referer;
     $mess->www_authenticate;
     $mess->authorization;
     $mess->authorization_basic;

$mess->headers_as_string([$endl])
---------------------------------

Call the HTTP::Headers->as_string() method for the headers in the message.


File: pm.info,  Node: HTTP/Negotiate,  Next: HTTP/Request,  Prev: HTTP/Message,  Up: Module List

choose a variant of a document to serve (HTTP content negotiation)
******************************************************************

NAME
====

choose - choose a variant of a document to serve (HTTP content negotiation)

SYNOPSIS
========

     use HTTP::Negotiate;

     #  ID       QS     Content-Type   Encoding Char-Set        Lang   Size
     $variants =
      [['var1',  1.000, 'text/html',   undef,   'iso-8859-1',   'en',   3000],
       ['var2',  0.950, 'text/plain',  'gzip',  'us-ascii',     'no',    400],
       ['var3',  0.3,   'image/gif',   undef,   undef,          undef, 43555],
      ];

     @prefered = choose($variants, $request_headers);
     $the_one  = choose($variants);

DESCRIPTION
===========

This module provide a complete implementation of the HTTP content
negotiation algorithm specified in `draft-ietf-http-v11-spec-00.ps'
chapter 12.  Content negotiation allows for the selection of a preferred
content representation based upon attributes of the negotiable variants
and the value of the various Accept* header fields in the request.

The variants are ordered by preference by calling the function choose().

The first parameter is a description of the variants that we can choose
among.  The variants are described by a reference to an array.  Each
element in this array is an array with the values [$id, $qs,
$content_type, $content_encoding, $charset, $content_language,
$content_length].  The meaning of these values are described below. The
$content_encoding and $content_language can be either a single scalar
value or an array reference if there are several values.

The second optional parameter is a reference to the request headers.  This
is used to look for "Accept*" headers.  You can pass a reference to either
a HTTP::Request or a HTTP::Headers object.  If this parameter is missing,
then the accept specification is initialized from the CGI environment
variables HTTP_ACCEPT, HTTP_ACCEPT_CHARSET, HTTP_ACCEPT_ENCODING and
HTTP_ACCEPT_LANGUAGE.

In array context, choose() returns a list of variant identifier/calculated
quality pairs.  The values are sorted by quality, highest quality first.
If the calculated quality is the same for two variants, then they are
sorted by size (smallest first). *E.g.*:

     (['var1' => 1], ['var2', 0.3], ['var3' => 0]);

Note that also zero quality variants are included in the return list even
if these should never be served to the client.

In scalar context, it returns the identifier of the variant with the
highest score or undef if none have non-zero quality.

If the $HTTP::Negotiate::DEBUG variable is set to TRUE, then a lot of
noise is generated on STDOUT during evaluation of choose().

VARIANTS
========

A variant is described by a list of the following values.  If the
attribute does not make sense or is unknown for a variant, then use undef
instead.

identifier
     This is just some string that you use as a name for the variant.  The
     identifier of the preferred variant is returned by choose().

qs
     This is a number between 0.000 and 1.000 that describes the "source
     quality".  This is what `draft-ietf-http-v11-spec-00.ps' says about
     this value:

     Source quality is measured by the content provider as representing the
     amount of degradation from the original source.  For example, a
     picture in JPEG form would have a lower qs when translated to the XBM
     format, and much lower qs when translated to an ASCII-art
     representation.  Note, however, that this is a function of the source
     - an original piece of ASCII-art may degrade in quality if it is
     captured in JPEG form.  The qs values should be assigned to each
     variant by the content provider; if no qs value has been assigned, the
     default is generally "qs=1".

content-type
     This is the media type of the variant.  The media type does not
     include a charset attribute, but might contain other parameters.
     Examples are:

          text/html
          text/html;version=2.0
          text/plain
          image/gif
          image/jpg

content-encoding
     This is one or more content encodings that has been applied to the
     variant.  The content encoding is generally used as a modifier to the
     content media type.  The most common content encodings are:

          gzip
          compress

content-charset
     This is the character set used when the variant contains textual
     content.  The charset value should generally be undef or one of these:

          us-ascii
          iso-8859-1 ... iso-8859-9
          iso-2022-jp
          iso-2022-jp-2
          iso-2022-kr
          unicode-1-1
          unicode-1-1-utf-7
          unicode-1-1-utf-8

content-language
     This describes one or more languages that are used in the variant.
     Language is described like this in `draft-ietf-http-v11-spec-00.ps': A
     language is in this context a natural language spoken, written, or
     otherwise conveyed by human beings for communication of information to
     other human beings.  Computer languages are explicitly excluded.

     The language tags are the same as those defined by RFC-1766.  Examples
     are:

          no               Norwegian
          en               International English
          en-US            US English
          en-cockney

content-length
     This is the number of bytes used to represent the content.

ACCEPT HEADERS
==============

The following Accept* headers can be used for describing content
preferences in a request (This description is an edited extract from
`draft-ietf-http-v11-spec-00.ps'):

Accept
     This header can be used to indicate a list of media ranges which are
     acceptable as a reponse to the request.  The "*" character is used to
     group media types into ranges, with "*/*" indicating all media types
     and "type/*" indicating all subtypes of that type.

     The parameter q is used to indicate the quality factor, which
     represents the user's preference for that range of media types.  The
     parameter mbx gives the maximum acceptable size of the response
     content. The default values are: q=1 and mbx=infinity. If no Accept
     header is present, then the client accepts all media types with q=1.

     For example:

          Accept: audio/*;q=0.2;mbx=200000, audio/basic

     would mean: "I prefer audio/basic (of any size), but send me any audio
     type if it is the best available after an 80% mark-down in quality and
     its size is less than 200000 bytes"

Accept-Charset
     Used to indicate what character sets are acceptable for the response.
     The "us-ascii" character set is assumed to be acceptable for all user
     agents.  If no Accept-Charset field is given, the default is that any
     charset is acceptable.  Example:

          Accept-Charset: iso-8859-1, unicode-1-1

Accept-Encoding
     Restricts the Content-Encoding values which are acceptable in the
     response.  If no Accept-Encoding field is present, the server may
     assume that the client will accept any content encoding.  An empty
     Accept-Encoding means that no content encoding is acceptable.
     Example:

          Accept-Encoding: compress, gzip

Accept-Language
     This field is similar to Accept, but restrict the set of natural
     languages that are preferred as a response.  Each language may be
     given an associated quality value which represents an estimate of the
     user's comprehension of that language.  For example:

          Accept-Language: no, en-gb;q=0.8, de;q=0.55

     would mean: "I prefer Norwegian, but will accept British English (with
     80% comprehension) or German (with 55% comprehension).

COPYRIGHT
=========

Copyright 1996, Gisle Aas.

This library is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

AUTHOR
======

Gisle Aas <aas@sn.no>


File: pm.info,  Node: HTTP/Request,  Next: HTTP/Response,  Prev: HTTP/Negotiate,  Up: Module List

Class encapsulating HTTP Requests
*********************************

NAME
====

HTTP::Request - Class encapsulating HTTP Requests

SYNOPSIS
========

     require HTTP::Request;
     $request = new HTTP::Request 'GET', 'http://www.oslonett.no/';

DESCRIPTION
===========

`HTTP::Request' is a class encapsulating HTTP style requests, consisting
of a request line, a MIME header, and optional content. Note that the LWP
library also uses this HTTP style requests for non-HTTP protocols.

Instances of this class are usually passed to the `request()' method of an
`LWP::UserAgent' object:

     $ua = new LWP::UserAgent;
     $request = new HTTP::Request 'http://www.oslonett.no/';
     $response = $ua->request($request);

METHODS
=======

`HTTP::Request' is a subclass of `HTTP::Message' and therefore inherits
its methods.  The inherited methods are header(), push_header(),
remove_header(), headers_as_string() and content().  See *Note
HTTP/Message: HTTP/Message, for details.

$r = new HTTP::Request $method, $url, [$header, [$content]]
-----------------------------------------------------------

Constructs a new `HTTP::Request' object describing a request on the object
`$url' using method `$method'.  The `$url' argument can be either a
string, or a reference to a `URI::URL' object.  The $header argument
should be a reference to a HTTP::Headers object.

     $request = new HTTP::Request 'GET', 'http://www.oslonett.no/';

$r->method([$val])
------------------

$r->url([$val])
---------------

These methods provide public access to the member variables containing
respectively the method of the request and the URL object of the request.

If an argument is given the member variable is given that as its new
value. If no argument is given the value is not touched. In either case
the previous value is returned.

The url() method accept both a reference to a URI::URL object and a string
as its argument.  If a string is given, then it should be parseable as an
absolute URL.

$r->as_string()
---------------

Method returning a textual representation of the request.  Mainly useful
for debugging purposes. It takes no arguments.


File: pm.info,  Node: HTTP/Response,  Next: HTTP/Status,  Prev: HTTP/Request,  Up: Module List

Class encapsulating HTTP Responses
**********************************

NAME
====

HTTP::Response - Class encapsulating HTTP Responses

SYNOPSIS
========

     require HTTP::Response;

DESCRIPTION
===========

The `HTTP::Response' class encapsulate HTTP style responses.  A response
consist of a response line, some headers, and a (potential empty) content.
Note that the LWP library will use HTTP style responses also for non-HTTP
protocol schemes.

Instances of this class are usually created and returned by the
`request()' method of an `LWP::UserAgent' object:

     ...
     $response = $ua->request($request)
     if ($response->is_success) {
         print $response->content;
     } else {
         print $response->error_as_HTML;
     }

METHODS
=======

`HTTP::Response' is a subclass of `HTTP::Message' and therefore inherits
its methods.  The inherited methods are header(), push_header(),
remove_header(), headers_as_string(), and content().  The header
convenience methods are also available.  See *Note HTTP/Message:
HTTP/Message, for details.

$r = new HTTP::Response ($rc, [$msg, [$header, [$content]]])
------------------------------------------------------------

Constructs a new `HTTP::Response' object describing a response with
response code `$rc' and optional message `$msg'.

$r->code([$code])
-----------------

$r->message([$message])
-----------------------

$r->request([$request])
-----------------------

$r->previous([$previousResponse])
---------------------------------

These methods provide public access to the member variables.  The first
two containing respectively the response code and the message of the
response.

The request attribute is a reference the request that gave this response.
It does not have to be the same request as passed to the $ua->request()
method, because there might have been redirects and authorization retries
in between.

The previous attribute is used to link together chains of responses.  You
get chains of responses if the first response is redirect or unauthorized.

$r->base
--------

Returns the base URL for this response.  The return value will be a
reference to a URI::URL object.

The base URL is obtained from one the following sources (in priority
order):

  1. Embedded in the document content, for instance <BASE HREF="..."> in
     HTML documents.

  2. A "Content-Base:" or a "Content-Location:" header in the response.

     For backwards compatability with older HTTP implementations we will
     also look for the "Base:" header.

  3. The URL used to request this response. This might not be the original
     URL that was passed to $ua->request() method, because we might have
     received some redirect responses first.

     When the LWP protocol modules produce the HTTP::Response object, then
any base URL embedded in the document (step 1) will already have
initialized the "Content-Base:" header. This means that this method only
perform the last 2 steps (the content is not always available either).

$r->as_string()
---------------

Method returning a textual representation of the request.  Mainly useful
for debugging purposes. It takes no arguments.

$r->is_info
-----------

$r->is_success
--------------

$r->is_redirect
---------------

$r->is_error
------------

These methods indicate if the response was informational, sucessful, a
redirection, or an error.

$r->error_as_HTML()
-------------------

Return a string containing a complete HTML document indicating what error
occurred.  This method should only be called when $r->is_error is TRUE.

$r->current_age
---------------

This function will calculate the "current age" of the response as
specified by <draft-ietf-http-v11-spec-07> section 13.2.3.  The age of a
response is the time since it was sent by the origin server.  The returned
value is a number representing the age in seconds.

$r->freshness_lifetime
----------------------

This function will calculate the "freshness lifetime" of the response as
specified by <draft-ietf-http-v11-spec-07> section 13.2.4.  The "freshness
lifetime" is the length of time between the generation of a response and
its expiration time.  The returned value is a number representing the
freshness lifetime in seconds.

If the response does not contain an "Expires" or a "Cache-Control" header,
then this function will apply some simple heuristic based on
'Last-Modified' to determine a suitable lifetime.

$r->is_fresh
------------

Returns TRUE if the response is fresh, based on the values of
freshness_lifetime() and current_age().  If the response is not longer
fresh, then it has to be refetched or revalidated by the origin server.

$r->fresh_until
---------------

Returns the time when this entiy is no longer fresh.


File: pm.info,  Node: HTTP/Status,  Next: HTTPD/Authen,  Prev: HTTP/Response,  Up: Module List

HTTP Status code processing
***************************

NAME
====

HTTP::Status - HTTP Status code processing

SYNOPSIS
========

     use HTTP::Status;

     if ($rc != RC_OK) {
         print status_message($rc), "\n";
     }

     if (is_success($rc)) { ... }
     if (is_error($rc)) { ... }
     if (is_redirect($rc)) { ... }

DESCRIPTION
===========

*HTTP::Status* is a library of routines for defining and classification of
HTTP status codes for libwww-perl.  Status codes are used to encode the
overall outcome of a HTTP response message.  Codes correspond to those
defined in <draft-ietf-http-v11-spec-06>.

The following functions can be used as mnemonic status code names:

     RC_CONTINUE				(100)
     RC_SWITCHING_PROTOCOLS		(101)

     RC_OK				(200)
     RC_CREATED				(201)
     RC_ACCEPTED				(202)
     RC_NON_AUTHORITATIVE_INFORMATION	(203)
     RC_NO_CONTENT			(204)
     RC_RESET_CONTENT			(205)
     RC_PARTIAL_CONTENT			(206)

     RC_MULTIPLE_CHOICES			(300)
     RC_MOVED_PERMANENTLY			(301)
     RC_MOVED_TEMPORARILY			(302)
     RC_SEE_OTHER				(303)
     RC_NOT_MODIFIED			(304)
     RC_USE_PROXY				(305)

     RC_BAD_REQUEST			(400)
     RC_UNAUTHORIZED			(401)
     RC_PAYMENT_REQUIRED			(402)
     RC_FORBIDDEN				(403)
     RC_NOT_FOUND				(404)
     RC_METHOD_NOT_ALLOWED		(405)
     RC_NOT_ACCEPTABLE			(406)
     RC_PROXY_AUTHENTICATION_REQUIRED	(407)
     RC_REQUEST_TIMEOUT			(408)
     RC_CONFLICT				(409)
     RC_GONE				(410)
     RC_LENGTH_REQUIRED			(411)
     RC_PRECONDITION_FAILED		(412)
     RC_REQUEST_ENTITY_TOO_LARGE		(413)
     RC_REQUEST_URI_TOO_LARGE		(414)
     RC_UNSUPPORTED_MEDIA_TYPE		(415)

     RC_INTERNAL_SERVER_ERROR		(500)
     RC_NOT_IMPLEMENTED			(501)
     RC_BAD_GATEWAY			(502)
     RC_SERVICE_UNAVAILABLE		(503)
     RC_GATEWAY_TIMEOUT			(504)
     RC_HTTP_VERSION_NOT_SUPPORTED	(505)

The status_message() function will translate status codes to human
readable strings.

The is_info(), is_success(), is_redirect(), and is_error() functions will
return a TRUE value if the status code passed as argument is
informational, indicates success, and error, or a redirect respectively.

status_message($code)
---------------------

Return user friendly error message for status code `$code'

is_info($code)
--------------

Return TRUE if `$code' is an *Informational* status code.

is_success($code)
-----------------

Return TRUE if `$code' is a *Successful* status code.

is_redirect($code)
------------------

Return TRUE if `$code' is a *Redirection* status code.

is_error($code)
---------------

Return TRUE if `$code' is an Error status code.  The `$code' can be both a
client error or a server error.

is_client_error($code)
----------------------

Return TRUE if `$code' is an *Client Error* status code.

is_server_error($code)
----------------------

Return TRUE if `$code' is an *Server Error* status code.


File: pm.info,  Node: HTTPD/Authen,  Next: HTTPD/GroupAdmin,  Prev: HTTP/Status,  Up: Module List

HTTP server authentication class
********************************

NAME
====

HTTPD::Authen - HTTP server authentication class

SYNOPSIS
========

     require HTTPD::Authen;

DESCRIPTION
===========

This module provides methods for authenticating a user.  It uses
HTTPD::UserAdmin to lookup passwords in a database.  Subclasses provide
methods specific to the authentication mechanism.

Currently, under HTTP/1.0 the only supported authentication mechanism is
Basic Authentication.  NCSA Mosaic and NCSA HTTPd understand the proposed
Message Digest Authentication, which should make it into the HTTP spec
someday.  This module supports both.

METHODS
=======

new ()
------

Since HTTPD::Authen uses HTTPD::UserAdmin for database lookups it needs
many of the same attributes.  Or, if the first argument passed to the
new() object constructor is a reference to an HTTPD::UserAdmin, the
attributes are inherited.

The following attributes are recognized from HTTPD::UserAdmin:

*DBType*, *DB*, Server, Path, *DBMF*, *Encrypt*

And if you wish to query an SQL server: Host, User, *Auth*, *Driver*,
*UserTable*, *NameField*, *PasswordField*

The same defaults are assumed for these attributes, as in HTTPD::UserAdmin.
See *HTTPD::UserAdmin* for details.

     $authen = new HTTPD::Authen (DB => "www-users");
     
     =head2 basic()

Short-cut to return an HTTPD::Authen::Basic object.

     $basic = $authen->basic;

digest()
--------

Short-cut to return an HTTPD::Authen::Digest object.

     $digest = $authen->digest;

type($authorization_header_value)
---------------------------------

This method will guess the authorization scheme based on the
'Authorization' header value, and return an object bless into that
scheme's class.

By using this method, it is simple to authenticate a user without even
knowing what scheme is being used:

     $authtype = HTTPD::Authen->type($authinfo);
     @info = $authtype->parse($authinfo)
     if( $authtype->check(@info) ) {
         #response 200 OK, etc.
     }

SUBCLASSES
==========

HTTPD::Authen::Basic methods
new([$hashref])
---------------

$hashref should be an HTTPD::Authen object, it must be present when
looking up users.  Optionally, you can pass the attribute USER with the
value of an HTTPD::UserAdmin object.

Normally, this method is not called directly, but rather by
HTTPD::Authen->basic method.

parse ($authorization_header_value)
-----------------------------------

This method expects the value of the HTTP 'Authorization' header of type
Basic.  This should look something like:

     'Basic ZG91Z206anN0NG1l'

This string will be parsed and decoded, returning the username and
password.  Note that the *MIME::Base64* module is required for decoding.

     ($username,$password) = HTTPD::Authen::Basic->parse($authinfo)
     
     #or, assuming $authen is an HTTPD::Authen object
     ($username,$password) = $authen->basic->parse($authinfo)

     #or check the info at the same time
     $OK = $authen->check($authen->basic->parse($authinfo))

check($username,$password)
--------------------------

This method expects a username and *clear text* password as arguments.
Returns true if the username was found, and passwords match, otherwise
returns false.

     if($authen->check("JoeUser", "his_clear_text_password")) {
     	print "Well, the passwords match at least\n";
     }
     else {
     	print "Password mismatch! Intruder alert! Intruder alert!\n";
     }

HTTPD::Authen::Digest methods
     NOTE: The *MD5* module is required to use these methods.

new([$hashref])
---------------

$hashref should be an HTTPD::Authen object.  Normally, this method is not
called directly, but rather by HTTPD::Authen->digest method.

parse ($authorization_header_value)
-----------------------------------

This method expects the value of the HTTP 'Authorization' header of type
Basic.  This should look something like:

     Digest username="JoeUser", realm="SomePlace", nonce="826407380", uri="/test/blah.html", response="0306f29f88690fb9203451556c376ae9", opaque="5e09061a062a271c8fcc686c5be90c2a"

This method returns a hash ref containing all Name = Value pairs from the
header.

     $mda = HTTPD::Authen::Digest->parse($authinfo);

     #or, assuming $authen is an HTTPD::Authen object
     $mda = $authen->digest->parse($authinfo)

     #or check the info at the same time
     $OK = $authen->check($authen->digest->parse($authinfo))

check ($hashref[, $request [, $seconds [, $client_ip ]]])
---------------------------------------------------------

This method expects a hashref of Name Value pairs normally found in the
'Authorization' header.  With this argument alone, the method will return
true without checking nonce or the opaque string if the client 'response'
checksum matches ours.

If $request is present, it must be a hashref or an *HTTP::Request* method.
From here, we fetch the request uri and request method.  Otherwise, we
default to the value of 'uri' present in $hashref, and 'GET' for the
method.

If $seconds is present, the value of 'nonce' will be checked, returning
false if it is stale.

If $client_ip is present, the value of the 'opaque' string will be
checked, returning false if the string is not valid.

This implementation is based on the Digest Access Authentication
internet-draft http://hopf.math.nwu.edu/digestauth/draft.rfc and NCSA's
implementation http://hoohoo.ncsa.uiuc.edu/docs/howto/md5_auth.html

SEE ALSO
========

HTTPD::UserAdmin, MD5, HTTP::Request, MIME::Base64

AUTHOR
======

Doug MacEachern <dougm@osf.org>

Copyright (c) 1996, Doug MacEachern, OSF Research Institute

This library is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.


File: pm.info,  Node: HTTPD/GroupAdmin,  Next: HTTPD/UserAdmin,  Prev: HTTPD/Authen,  Up: Module List

Management of HTTP server group databases
*****************************************

NAME
====

HTTPD::GroupAdmin - Management of HTTP server group databases

SYNOPSIS
========

     require HTTPD::GroupAdmin

DESCRIPTION
===========

This software is meant to provide a generic interface that hides the
inconsistencies across HTTP server implementations of user and group
databases.

METHODS
=======

new ()
------

Here's where we find out what's different about your server.

Some examples:

     @DBM = (DBType => 'DBM',
     	    DB     => '.htgroup',
     	    Server => 'apache');

     $group = new HTTPD::GroupAdmin @DBM;

This creates an object who's database is a DBM file named '.htgroup', in a
format that the Apache server understands.

     @Text = (DBType => 'Text',
     	     DB     => '.htgroup',
     	     Server => 'ncsa');

     $group = new HTTPD::GroupAdmin @Text;

This creates an object who's database is a plain text file named
'.htgroup', in a format that the NCSA server understands.

Note: Support is not yet availible for SQL servers

Full list of constructor attributes:

Note: Attribute names are case-insensitive

Name    - Group name

*DBType*  - The type of database, one of 'DBM', 'Text', or 'SQL' (Default
is 'DBM')

*DB*      - The database name (Default is '.htpasswd' for DBM & Text
databases)

Server  - HTTP server name (Default is the generic class, that works with
NCSA, Apache and possibly others)

Note: run 'perl t/support.t matrix' to see what support is currently
availible

Path    - Relative DB files are resolved to this value  (Default is '.')

Locking - Boolean, Lock Text and DBM files (Default is true)

Debug   - Boolean, Turn on debug mode

Specific to DBM files:

*DBMF*    - The DBM file implementation to use (Default is 'NDBM')

Flags   - The read, write and create flags.  There are four modes: *rwc* -
the default, open for reading, writing and creating.  *rw* - open for
reading and writing.  *r* - open for reading only.  w - open for writing
only.

*Mode*    - The file creation mode, defaults to '0644'

From here on out, things should look the same for everyone.

add($username[,$groupname])
---------------------------

Add user $username to group $groupname, or whatever the 'Name' attribute
is set to.

Fails if $username exists in the database

     if($group->add('dougm', 'www-group')) {
     	print "Welcome!\n";
     }

delete($username[,$groupname])
------------------------------

Delete user $username from group $groupname, or whatever the 'Name'
attribute is set to.

     if($group->delete('dougm')) {
     	print "He's gone from the group\n";
     }

exists($groupname)
------------------

True if $groupname is found in the database

     if($group->exists('web-heads')) {
     	die "oh no!";
     }

list([$groupname])
------------------

Returns a list of group names, or users in a group if '$name' is present.

@groups = $group->list;

@users = $group->list('web-heads');

user()
------

Short cut for creating an HTTPD::UserAdmin object.  All applicable
attributes are inherited, but can be overridden.

     $user = $group->user();

(See HTTPD::UserAdmin)

convert(@Attributes)
--------------------

Convert a database.

     #not yet

remove($groupname)
------------------

Remove group $groupname from the database

name($groupname)
----------------

Change the value of 'Name' attribute.

     $group->name('bew-ediw-dlrow');

debug($boolean)
---------------

Turn debugging on or off

lock([$timeout]) =head2 unlock()
--------------------------------

These methods give you control of the locking mechanism.

     $group = new HTTPD::GroupAdmin (Locking => 0); #turn off auto-locking
     $group->lock; #lock the object's database
     $group->add($username,$passwd); #write while database is locked
     $group->unlock; release the lock

db($dbname);
------------

Select a different database.

     $olddb = $group->db($newdb);
     print "Now we're reading and writing '$newdb', done with '$olddb'n\";

SEE ALSO
========

HTTPD::UserAdmin

AUTHOR
======

Doug MacEachern <dougm@osf.org>

Copyright (c) 1996, Doug MacEachern, OSF Research Institute

This library is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.


File: pm.info,  Node: HTTPD/UserAdmin,  Next: I18N/Collate,  Prev: HTTPD/GroupAdmin,  Up: Module List

Management of HTTP server user databases
****************************************

NAME
====

HTTPD::UserAdmin - Management of HTTP server user databases

SYNOPSIS
========

require HTTPD::UserAdmin

DESCRIPTION
===========

This software is meant to provide a generic interface that hides the
inconsistencies across HTTP server implementations of user and group
databases.

METHODS
=======

new ()
------

Here's where we find out what's different about your server.

Some examples:

     @DBM = (DBType => 'DBM',
     	    DB     => '.htpasswd',
     	    Server => 'apache');

     $user = new HTTPD::UserAdmin @DBM;

This creates an object who's database is a DBM file named '.htpasswd', in
a format that the Apache server understands.

     @Text = (DBType => 'Text',
     	     DB     => '.htpasswd',
     	     Server => 'ncsa');

     $user = new HTTPD::UserAdmin @Text;

This creates an object who's database is a plain text file named
'.htpasswd', in a format that the NCSA server understands.

     @SQL =  (DBType =>    "SQL",
     	     Host =>      "",             #server hostname
     	     DB =>        "www",          #database name
     	     User =>      "", 	  	  #database login name
     	     Auth =>      "",             #database login password
     	     Driver =>    "mSQL",         #driver for DBI
     	     Server =>    "apache",       #HTTP server type, not required
     	     UserTable => "www-users",    #table with field names below
     	     NameField => "user",         #field for the name
     	     PasswordField => "password", #field for the password
     	     );

     $user = new HTTPD::UserAdmin @SQL;

This creates an object who's mSQL database is named 'www', with a schema
that the Apache server (extention) understands.

Full list of constructor attributes:

Note: Attribute names are case-insensitive

*DBType*  - The type of database, one of 'DBM', 'Text', or 'SQL' (Default
is 'DBM')

*DB*      - The database name (Default is '.htpasswd' for DBM & Text
databases)

Server  - HTTP server name (Default is the generic class, that works with
NCSA, Apache and possibly others)

Note: run 'perl t/support.t matrix' to see what support is currently
availible

*Encrypt* - One of 'crypt' or 'MD5', defaults to 'crypt'

Locking - Boolean, Lock Text and DBM files (Default is true)

Path    - Relative DB files are resolved to this value  (Default is '.')

Debug   - Boolean, Turn on debug mode

Specific to DBM files:

*DBMF*    - The DBM file implementation to use (Default is 'NDBM')

Flags   - The read, write and create flags.  There are four modes: *rwc* -
the default, open for reading, writing and creating.  *rw* - open for
reading and writing.  *r* - open for reading only.  w - open for writing
only.

*Mode*    - The file creation mode, defaults to '0644'

Specific to DBI: We talk to an SQL server via Tim Bunce's DBI switch, for
more info see: http://www.hermetica.com/technologia/DBI/

Host      - Server hostname

User      - Database login name

*Auth*      - Database login password

*Driver*    - Driver for DBI  (Default is 'mSQL')

*UserTable* - Table with field names below

*NameField* - Field for the name  (Default is 'user')

*PasswordField* - Field for the password  (Default is 'password')

From here on out, things should look the same for everyone.

add($username,$password[,$noenc,@fields])
-----------------------------------------

Add a user.

If $noenc is true, the password is not encrypted, useful for
copying/converting, or if you just prefer to store passwords in plain text.

Fails if $username exists in the database

     if($user->add('dougm', 'secret')) {
     	print "You have the power!\n";
     }

You may need to pass additional fields, such as the user's real name.
This depends on your server of course.

     $user->add('JoeUser', 'try2guess', '', 'Joseph A. User');

delete($username)
-----------------

Delete a user

     if($user->delete('dougm')) {
     	print "He's gone\n";
     }

exists($username)
-----------------

True if $username is found in the database

     if($user->exists('dougm')) {
     	die "oh no!";
     }

password()
----------

Returns the encrypted password for a user

     $passwd = $user->password("dougm");

Useful for copying users to another database.

list()
------

Returns a list of usernames in the current database

     @users = $user->list

update($username,$password)
---------------------------

Update $username with a new $password

     if($user->update('dougm', 'idunno')) {
     	print "Updated\n";
     }

group()
-------

Short cut for creating an HTTPD::GroupAdmin object.  All applicable
attributes are inherited, but can be overridden.

     $group = $user->group(NAME => 'www-group');

(See HTTPD::GroupAdmin)

convert(@Attributes)
--------------------

Convert a database.

     $dbmuser = $user->convert(@Apache);

lock([$timeout]) =head2 unlock()
--------------------------------

These methods give you control of the locking mechanism.

     $user = new HTTPD::UserAdmin (Locking => 0); #turn off auto-locking
     $user->lock; #lock the object's database
     $user->add($username,$passwd); #write while file is locked
     $user->unlock; release the lock

db($dbname);
------------

Select a different database.

     $olddb = $user->db($newdb);
     print "Now we're reading and writing '$newdb', done with '$olddb'n\";

Message Digest User Databases
=============================

Currently, you can store user info in a format for servers who understand
Message Digest Authentication.  Here's an example:

     $user = new HTTPD::UserAdmin (DB => '.htdigest', Encrypt => 'MD5');
     
     ($username,$realm,$password) = ('JoeUser', 'SomePlace', '14me');

     #The checksum contains more info that just a password
     $user->add($username, "$username:$realm:$password");
     $user->update($username, "$username:$realm:newone");

     $info = $user->password($username);
     ($realm, $checksum) = split(":", $info);

     $user->delete($username);

See <URL:http://hoohoo.ncsa.uiuc.edu/docs/howto/md5_auth.html> for NCSA's
implementation.

So, it's a little more work, but don't worry, a nicer interface is on the
way.

SEE ALSO
========

HTTPD::GroupAdmin, HTTPD::Authen

AUTHOR
======

Doug MacEachern <dougm@osf.org>

Copyright (c) 1996, Doug MacEachern, OSF Research Institute

This library is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.


File: pm.info,  Node: I18N/Collate,  Next: IO,  Prev: HTTPD/UserAdmin,  Up: Module List

compare 8-bit scalar data according to the current locale
*********************************************************

NAME
====

I18N::Collate - compare 8-bit scalar data according to the current locale

SYNOPSIS
========

     use I18N::Collate;
     setlocale(LC_COLLATE, 'locale-of-your-choice');
     $s1 = new I18N::Collate "scalar_data_1";
     $s2 = new I18N::Collate "scalar_data_2";

DESCRIPTION
===========

This module provides you with objects that will collate according to your
national character set, provided that the POSIX setlocale() function is
supported on your system.

You can compare $s1 and $s2 above with

     $s1 le $s2

to extract the data itself, you'll need a dereference: $$s1

This uses POSIX::setlocale(). The basic collation conversion is done by
strxfrm() which terminates at NUL characters being a decent C routine.
collate_xfrm() handles embedded NUL characters gracefully.  Due to cmp and
overload magic, `lt', `le', `eq', `ge', and `gt' work also.  The available
locales depend on your operating system; try whether `locale -a' shows
them or man pages for "locale" or "nlsinfo" or the direct approach `ls
/usr/lib/nls/loc' or `ls /usr/lib/nls'.  Not all the locales that your
vendor supports are necessarily installed: please consult your operating
system's documentation and possibly your local system administration.

The locale names are probably something like `"xx_XX.(ISO)?8859-N"' or
`"xx_XX.(ISO)?8859N"', for example `"fr_CH.ISO8859-1"' is the Swiss (CH)
variant of French (fr), ISO Latin (8859) 1 (-1) which is the Western
European character set.


File: pm.info,  Node: IO,  Next: IO/File,  Prev: I18N/Collate,  Up: Module List

load various IO modules
***********************

NAME
====

IO - load various IO modules

SYNOPSIS
========

     use IO;

DESCRIPTION
===========

`IO' provides a simple mechanism to load all of the IO modules at one go.
Currently this includes:

     IO::Handle
     IO::Seekable
     IO::File
     IO::Pipe
     IO::Socket

For more information on any of these modules, please see its respective
documentation.


File: pm.info,  Node: IO/File,  Next: IO/Handle,  Prev: IO,  Up: Module List

supply object methods for filehandles
*************************************

NAME
====

IO::File - supply object methods for filehandles

SYNOPSIS
========

     use IO::File;

     $fh = new IO::File;
     if ($fh->open "< file") {
         print <$fh>;
         $fh->close;
     }

     $fh = new IO::File "> FOO";
     if (defined $fh) {
         print $fh "bar\n";
         $fh->close;
     }

     $fh = new IO::File "file", "r";
     if (defined $fh) {
         print <$fh>;
         undef $fh;       # automatically closes the file
     }

     $fh = new IO::File "file", O_WRONLY|O_APPEND;
     if (defined $fh) {
         print $fh "corge\n";
         undef $fh;       # automatically closes the file
     }

     $pos = $fh->getpos;
     $fh->setpos $pos;

     $fh->setvbuf($buffer_var, _IOLBF, 1024);

     autoflush STDOUT 1;

DESCRIPTION
===========

`IO::File' is inherits from `IO::Handle' ans `IO::Seekable'. It extends
these classes with methods that are specific to file handles.

CONSTRUCTOR
===========

new ([ ARGS ] )
     Creates a `IO::File'.  If it receives any parameters, they are passed
     to the method open; if the open fails, the object is destroyed.
     Otherwise, it is returned to the caller.

METHODS
=======

open( FILENAME [,MODE [,PERMS]] )
     open accepts one, two or three parameters.  With one parameter, it is
     just a front end for the built-in open function.  With two
     parameters, the first parameter is a filename that may include
     whitespace or other special characters, and the second parameter is
     the open mode, optionally followed by a file permission value.

     If `IO::File::open' receives a Perl mode string (">", "+<", etc.) or
     a POSIX fopen() mode string ("w", "r+", etc.), it uses the basic Perl
     open operator.

     If `IO::File::open' is given a numeric mode, it passes that mode and
     the optional permissions value to the Perl sysopen operator.  For
     convenience, `IO::File::import' tries to import the O_XXX constants
     from the Fcntl module.  If dynamic loading is not available, this may
     fail, but the rest of IO::File will still work.

SEE ALSO
========

*Note Perlfunc: (perl.info)perlfunc,, `"I', *Note Perlop:
(perl.info)perlop,, `"I', *Note IO/Handle: IO/Handle, `"I', *Note
IO/Seekable: IO/Seekable,

HISTORY
=======

Derived from FileHandle.pm by Graham Barr <`bodg@tiuk.ti.com'>.

REVISION
========

$Revision: 1.5 $


File: pm.info,  Node: IO/Handle,  Next: IO/Pipe,  Prev: IO/File,  Up: Module List

supply object methods for I/O handles
*************************************

NAME
====

IO::Handle - supply object methods for I/O handles

SYNOPSIS
========

     use IO::Handle;

     $fh = new IO::Handle;
     if ($fh->open "< file") {
         print <$fh>;
         $fh->close;
     }

     $fh = new IO::Handle "> FOO";
     if (defined $fh) {
         print $fh "bar\n";
         $fh->close;
     }

     $fh = new IO::Handle "file", "r";
     if (defined $fh) {
         print <$fh>;
         undef $fh;       # automatically closes the file
     }

     $fh = new IO::Handle "file", O_WRONLY|O_APPEND;
     if (defined $fh) {
         print $fh "corge\n";
         undef $fh;       # automatically closes the file
     }

     $pos = $fh->getpos;
     $fh->setpos $pos;

     $fh->setvbuf($buffer_var, _IOLBF, 1024);

     autoflush STDOUT 1;

DESCRIPTION
===========

`IO::Handle' is the base class for all other IO handle classes.  A
`IO::Handle' object is a reference to a symbol (see the Symbol package)

CONSTRUCTOR
===========

new ()
     Creates a new `IO::Handle' object.

new_from_fd ( FD, MODE )
     Creates a `IO::Handle' like new does.  It requires two parameters,
     which are passed to the method fdopen; if the fdopen fails, the
     object is destroyed. Otherwise, it is returned to the caller.

METHODS
=======

If the C function setvbuf() is available, then `IO::Handle::setvbuf' sets
the buffering policy for the IO::Handle.  The calling sequence for the
Perl function is the same as its C counterpart, including the macros
`_IOFBF', `_IOLBF', and `_IONBF', except that the buffer parameter
specifies a scalar variable to use as a buffer.  WARNING: A variable used
as a buffer by `IO::Handle::setvbuf' must not be modified in any way until
the IO::Handle is closed or until `IO::Handle::setvbuf' is called again,
or memory corruption may result!

See *Note Perlfunc: (perl.info)perlfunc, for complete descriptions of each
of the following supported `IO::Handle' methods, which are just front ends
for the corresponding built-in functions:

close     fileno     getc     gets     eof     read     truncate     stat
  print     printf     sysread     syswrite

See *Note Perlvar: (perl.info)perlvar, for complete descriptions of each
of the following supported `IO::Handle' methods:

     autoflush
     output_field_separator
     output_record_separator
     input_record_separator
     input_line_number
     format_page_number
     format_lines_per_page
     format_lines_left
     format_name
     format_top_name
     format_line_break_characters
     format_formfeed
     format_write

Furthermore, for doing normal I/O you might need these:

$fh->getline
     This works like <$fh> described in `"I', *Note Perlop:
     (perl.info)perlop, except that it's more readable and can be safely
     called in an array context but still returns just one line.

$fh->getlines
     This works like <$fh> when called in an array context to read all the
     remaining lines in a file, except that it's more readable.  It will
     also croak() if accidentally called in a scalar context.

$fh->fdopen ( FD, MODE )
     fdopen is like an ordinary open except that its first parameter is
     not a filename but rather a file handle name, a IO::Handle object, or
     a file descriptor number.

$fh->write ( BUF, LEN [, OFFSET }\] )
     write is like write found in C, that is it is the opposite of read.
     The wrapper for the perl write function is called `format_write'.

$fh->opened
     Returns true if the object is currently a valid file descriptor.

Lastly, a special method for working under -T and setuid/gid scripts:

$fh->untaint
     Marks the object as taint-clean, and as such data read from it will
     also be considered taint-clean. Note that this is a very trusting
     action to take, and appropriate consideration for the data source and
     potential vulnerability should be kept in mind.

NOTE
====

A `IO::Handle' object is a GLOB reference. Some modules that inherit from
`IO::Handle' may want to keep object related variables in the hash table
part of the GLOB. In an attempt to prevent modules trampling on each other
I propose the that any such module should prefix its variables with its
own name separated by _'s. For example the IO::Socket module keeps a
timeout variable in 'io_socket_timeout'.

SEE ALSO
========

*Note Perlfunc: (perl.info)perlfunc,, `"I', *Note Perlop:
(perl.info)perlop,, `"FileHandle"', *Note POSIX: POSIX,

BUGS
====

Due to backwards compatibility, all filehandles resemble objects of class
`IO::Handle', or actually classes derived from that class.  They actually
aren't.  Which means you can't derive your own class from `IO::Handle' and
inherit those methods.

HISTORY
=======

Derived from FileHandle.pm by Graham Barr <`bodg@tiuk.ti.com'>


File: pm.info,  Node: IO/Pipe,  Next: IO/Seekable,  Prev: IO/Handle,  Up: Module List

supply object methods for pipes
*******************************

NAME
====

IO::pipe - supply object methods for pipes

SYNOPSIS
========

     use IO::Pipe;

     $pipe = new IO::Pipe;

     if($pid = fork()) { # Parent
         $pipe->reader();

     while(<$pipe> {
     		....
     }

     }
     elsif(defined $pid) { # Child
         $pipe->writer();

     print $pipe ....
     	}

     or

     $pipe = new IO::Pipe;

     $pipe->reader(qw(ls -l));

     while(<$pipe>) {
         ....
     }

DESCRIPTION
===========

`IO::Pipe' provides an interface to createing pipes between processes.

CONSTRCUTOR
===========

new ( [READER, WRITER] )
     Creates a `IO::Pipe', which is a reference to a newly created symbol
     (see the Symbol package). `IO::Pipe::new' optionally takes two
     arguments, which should be objects blessed into `IO::Handle', or a
     subclass thereof. These two objects will be used for the system call
     to pipe. If no arguments are given then then method handles is called
     on the new `IO::Pipe' object.

     These two handles are held in the array part of the GLOB until either
     reader or writer is called.

METHODS
=======

reader ([ARGS])
     The object is re-blessed into a sub-class of `IO::Handle', and
     becomes a handle at the reading end of the pipe. If `ARGS' are given
     then fork is called and `ARGS' are passed to exec.

writer ([ARGS])
     The object is re-blessed into a sub-class of `IO::Handle', and
     becomes a handle at the writing end of the pipe. If `ARGS' are given
     then fork is called and `ARGS' are passed to exec.

handles ()
     This method is called during construction by `IO::Pipe::new' on the
     newly created `IO::Pipe' object. It returns an array of two objects
     blessed into `IO::Handle', or a subclass thereof.

SEE ALSO
========

*Note IO/Handle: IO/Handle,

AUTHOR
======

Graham Barr <`bodg@tiuk.ti.com'>

REVISION
========

$Revision: 1.7 $

COPYRIGHT
=========

Copyright (c) 1995 Graham Barr. All rights reserved. This program is free
software; you can redistribute it and/or modify it under the same terms as
Perl itself.


File: pm.info,  Node: IO/Seekable,  Next: IO/Select,  Prev: IO/Pipe,  Up: Module List

supply seek based methods for I/O objects
*****************************************

NAME
====

IO::Seekable - supply seek based methods for I/O objects

SYNOPSIS
========

     use IO::Seekable;
     package IO::Something;
     @ISA = qw(IO::Seekable);

DESCRIPTION
===========

`IO::Seekable' does not have a constuctor of its own as is intended to be
inherited by other `IO::Handle' based objects. It provides methods which
allow seeking of the file descriptors.

If the C functions fgetpos() and fsetpos() are available, then
`IO::File::getpos' returns an opaque value that represents the current
position of the IO::File, and `IO::File::setpos' uses that value to return
to a previously visited position.

See *Note Perlfunc: (perl.info)perlfunc, for complete descriptions of each
of the following supported `IO::Seekable' methods, which are just front
ends for the corresponding built-in functions:

clearerr     seek     tell

SEE ALSO
========

*Note Perlfunc: (perl.info)perlfunc,, `"I', *Note Perlop:
(perl.info)perlop,, `"I', *Note IO/Handle: IO/Handle, `"I', *Note IO/File:
IO/File,

HISTORY
=======

Derived from FileHandle.pm by Graham Barr <bodg@tiuk.ti.com>

REVISION
========

$Revision: 1.5 $


File: pm.info,  Node: IO/Select,  Next: IO/Socket,  Prev: IO/Seekable,  Up: Module List

OO interface to the select system call
**************************************

NAME
====

IO::Select - OO interface to the select system call

SYNOPSIS
========

     use IO::Select;

     $s = IO::Select->new();

     $s->add(\*STDIN);
     $s->add($some_handle);

     @ready = $s->can_read($timeout);

     @ready = IO::Select->new(@handles)->read(0);

DESCRIPTION
===========

The `IO::Select' package implements an object approach to the system select
function call. It allows the user to see what IO handles, see *Note
IO/Handle: IO/Handle,, are ready for reading, writing or have an error
condition pending.

CONSTRUCTOR
===========

new ( [ HANDLES ] )
     The constructor creates a new object and optionally initialises it
     with a set of handles.

METHODS
=======

add ( HANDLES )
     Add the list of handles to the `IO::Select' object. It is these
     values that will be returned when an event occurs. `IO::Select' keeps
     these values in a cache which is indexed by the fileno of the handle,
     so if more than one handle with the same fileno is specified then
     only the last one is cached.

remove ( HANDLES )
     Remove all the given handles from the object. This method also works
     by the fileno of the handles. So the exact handles that were added
     need not be passed, just handles that have an equivalent fileno

can_read ( [ TIMEOUT ] )
     Return an array of handles that are ready for reading. `TIMEOUT' is
     the maximum amount of time to wait before returning an empty list. If
     `TIMEOUT' is not given then the call will block.

can_write ( [ TIMEOUT ] )
     Same as can_read except check for handles that can be written to.

has_error ( [ TIMEOUT ] )
     Same as can_read except check for handles that have an error
     condition, for example EOF.

count ()
     Returns the number of handles that the object will check for when one
     of the `can_' methods is called or the object is passed to the select
     static method.

select ( READ, WRITE, ERROR [, TIMEOUT ] )
     select is a static method, that is you call it with the package name
     like new. `READ', `WRITE' and `ERROR' are either undef or
     `IO::Select' objects. `TIMEOUT' is optional and has the same effect as
     before.

     The result will be an array of 3 elements, each a reference to an
     array which will hold the handles that are ready for reading, writing
     and have error conditions respectively. Upon error an empty array is
     returned.

EXAMPLE
=======

Here is a short example which shows how `IO::Select' could be used to
write a server which communicates with several sockets while also
listening for more connections on a listen socket

     use IO::Select;
     use IO::Socket;

     $lsn = new IO::Socket::INET(Listen => 1, LocalPort => 8080);
     $sel = new IO::Select( $lsn );
     
     while(@ready = $sel->can_read) {
         foreach $fh (@ready) {
             if($fh == $lsn) {
                 # Create a new socket
                 $new = $lsn->accept;
                 $sel->add($new);
             }
             else {
                 # Process socket

     # Maybe we have finished with the socket
     $sel->remove($fh);
     $fh->close;
                 }
             }
         }

AUTHOR
======

Graham Barr <`Graham.Barr@tiuk.ti.com'>

REVISION
========

$Revision: 1.9 $

COPYRIGHT
=========

Copyright (c) 1995 Graham Barr. All rights reserved. This program is free
software; you can redistribute it and/or modify it under the same terms as
Perl itself.


File: pm.info,  Node: IO/Socket,  Next: IPC/Open2,  Prev: IO/Select,  Up: Module List

Object interface to socket communications
*****************************************

NAME
====

IO::Socket - Object interface to socket communications

SYNOPSIS
========

     use IO::Socket;

DESCRIPTION
===========

`IO::Socket' provides an object interface to creating and using sockets. It
is built upon the *Note IO/Handle: IO/Handle, interface and inherits all
the methods defined by *Note IO/Handle: IO/Handle,.

`IO::Socket' only defines methods for those operations which are common to
all types of socket. Operations which are specified to a socket in a
particular domain have methods defined in sub classes of `IO::Socket'

CONSTRUCTOR
===========

new ( [ARGS] )
     Creates a `IO::Pipe', which is a reference to a newly created symbol
     (see the Symbol package). new optionally takes arguments, these
     arguments are in key-value pairs.  new only looks for one key
     `Domain' which tells new which domain the socket it will be. All
     other arguments will be passed to the configuration method of the
     package for that domain, See below.

METHODS
=======

See *Note Perlfunc: (perl.info)perlfunc, for complete descriptions of each
of the following supported `IO::Seekable' methods, which are just front
ends for the corresponding built-in functions:

     socket
     socketpair
     bind
     listen
     accept
     send
     recv
     peername (getpeername)
     sockname (getsockname)

Some methods take slightly different arguments to those defined in *Note
Perlfunc: (perl.info)perlfunc, in attempt to make the interface more
flexible. These are

accept([PKG])
     perform the system call accept on the socket and return a new object.
     The new object will be created in the same class as the listen
     socket, unless `PKG' is specified. This object can be used to
     communicate with the client that was trying to connect. In a scalar
     context the new socket is returned, or undef upon failure. In an
     array context a two-element array is returned containing the new
     socket and the peer address, the list will be empty upon failure.

     Additional methods that are provided are

timeout([VAL])
     Set or get the timeout value associated with this socket. If called
     without any arguments then the current setting is returned. If called
     with an argument the current setting is changed and the previous
     value returned.

sockopt(OPT [, VAL])
     Unified method to both set and get options in the SOL_SOCKET level.
     If called with one argument then getsockopt is called, otherwise
     setsockopt is called.

sockdomain
     Returns the numerical number for the socket domain type. For example,
     fir a AF_INET socket the value of &AF_INET will be returned.

socktype
     Returns the numerical number for the socket type. For example, fir a
     SOCK_STREAM socket the value of &SOCK_STREAM will be returned.

protocol
     Returns the numerical number for the protocol being used on the
     socket, if known. If the protocol is unknown, as with an AF_UNIX
     socket, zero is returned.

SUB-CLASSES
===========

IO::Socket::INET
----------------

IO::Socket::INET provides a constructor to create an AF_INET domain socket
and some related methods. The constructor can take the following options

     PeerAddr	Remote host address
     PeerPort	Remote port or service
     LocalPort	Local host bind	port
     LocalAddr	Local host bind	address
     Proto	Protocol name (eg tcp udp etc)
     Type	Socket type (SOCK_STREAM etc)
     Listen	Queue size for listen
     Timeout	Timeout	value for various operations

If Listen is defined then a listen socket is created, else if the socket
type,   which is derived from the protocol, is SOCK_STREAM then a connect
is called.

Only one of Type or `Proto' needs to be specified, one will be assumed
from the other.

METHODS
-------

sockaddr ()
     Return the address part of the sockaddr structure for the socket

sockport ()
     Return the port number that the socket is using on the local host

sockhost ()
     Return the address part of the sockaddr structure for the socket in a
     text form xx.xx.xx.xx

peeraddr ()
     Return the address part of the sockaddr structure for the socket on
     the peer host

peerport ()
     Return the port number for the socket on the peer host.

peerhost ()
     Return the address part of the sockaddr structure for the socket on
     the peer host in a text form xx.xx.xx.xx

IO::Socket::UNIX
----------------

IO::Socket::UNIX provides a constructor to create an AF_UNIX domain socket
and some related methods. The constructor can take the following options

     Type    	Type of socket (eg SOCK_STREAM or SOCK_DGRAM)
     Local   	Path to local fifo
     Peer    	Path to peer fifo
     Listen  	Create a listen socket

METHODS
-------

hostpath()
     Returns the pathname to the fifo at the local end.

peerpath()
     Returns the pathanme to the fifo at the peer end.

AUTHOR
======

Graham Barr <`Graham.Barr@tiuk.ti.com'>

REVISION
========

$Revision: 1.13 $

The VERSION is derived from the revision turning each number after the
first dot into a 2 digit number so

     Revision 1.8   => VERSION 1.08
     Revision 1.2.3 => VERSION 1.0203

COPYRIGHT
=========

Copyright (c) 1995 Graham Barr. All rights reserved. This program is free
software; you can redistribute it and/or modify it under the same terms as
Perl itself.


File: pm.info,  Node: IPC/Open2,  Next: IPC/Open3,  Prev: IO/Socket,  Up: Module List

open a process for both reading and writing
*******************************************

NAME
====

IPC::Open2, open2 - open a process for both reading and writing

SYNOPSIS
========

     use IPC::Open2;
     $pid = open2(\*RDR, \*WTR, 'some cmd and args');
       # or
     $pid = open2(\*RDR, \*WTR, 'some', 'cmd', 'and', 'args');

DESCRIPTION
===========

The open2() function spawns the given $cmd and connects $rdr for reading
and $wtr for writing.  It's what you think should work when you try

     open(HANDLE, "|cmd args|");

open2() returns the process ID of the child process.  It doesn't return on
failure: it just raises an exception matching `/^open2:/'.

WARNING
=======

It will not create these file handles for you.  You have to do this
yourself.  So don't pass it empty variables expecting them to get filled
in for you.

Additionally, this is very dangerous as you may block forever.  It assumes
it's going to talk to something like *bc*, both writing to it and reading
from it.  This is presumably safe because you "know" that commands like
*bc* will read a line at a time and output a line at a time.  Programs
like sort that read their entire input stream first, however, are quite
apt to cause deadlock.

The big problem with this approach is that if you don't have control over
source code being run in the the child process, you can't control what it
does with pipe buffering.  Thus you can't just open a pipe to `cat -v' and
continually read and write a line from it.

SEE ALSO
========

See `open3' in this node for an alternative that handles STDERR as well.


File: pm.info,  Node: IPC/Open3,  Next: Image/Size,  Prev: IPC/Open2,  Up: Module List

open a process for reading, writing, and error handling
*******************************************************

NAME
====

IPC::Open3, open3 - open a process for reading, writing, and error handling

SYNOPSIS
========

     $pid = open3(\*WTRFH, \*RDRFH, \*ERRFH
     		    'some cmd and args', 'optarg', ...);

DESCRIPTION
===========

Extremely similar to open2(), open3() spawns the given $cmd and connects
RDRFH for reading, WTRFH for writing, and ERRFH for errors.  If ERRFH is
'', or the same as RDRFH, then STDOUT and STDERR of the child are on the
same file handle.

If WTRFH begins with "<&", then WTRFH will be closed in the parent, and
the child will read from it directly.  If RDRFH or ERRFH begins with ">&",
then the child will send output directly to that file handle.  In both
cases, there will be a dup(2) instead of a pipe(2) made.

If you try to read from the child's stdout writer and their stderr writer,
you'll have problems with blocking, which means you'll want to use
select(), which means you'll have to use sysread() instead of normal stuff.

All caveats from open2() continue to apply.  See `open2' in this node for
details.


File: pm.info,  Node: Image/Size,  Next: IniConf,  Prev: IPC/Open3,  Up: Module List

read the dimensions of an image in several popular formats
**********************************************************

NAME
====

Image::Size - read the dimensions of an image in several popular formats

SYNOPSIS
========

     use Image::Size;
     # Get the size of globe.gif
     ($globe_x, $globe_y) = &imgsize("globe.gif");
     # Assume X=60 and Y=40 for remaining examples

     use Image::Size 'html_imgsize';
     # Get the size as "HEIGHT=X WIDTH=Y" for HTML generation
     $size = &html_imgsize("globe.gif");
     # $size == "HEIGHT=60 WIDTH=40"

     use Image::Size 'attr_imgsize';
     # Get the size as a list passable to routines in CGI.pm
     @attrs = &attr_imgsize("globe.gif");
     # @attrs == ('-HEIGHT', 60, '-WIDTH', 40)

DESCRIPTION
===========

The *Image::Size* library is based upon the `wwwis' script written by Alex
Knowles *(alex@ed.ac.uk)*, a tool to examine HTML and add HEIGHT and WIDTH
parameters to image tags. The sizes are cached internally based on file
name, so multiple calls on the same file name (such as images used in
bulleted lists, for example) does not repeat computation.

*Image::Size* provides three interfaces for possible import:

imgsize(file)
     Returns a two-item list of the X and Y dimensions (height and width,
     in that order) of *file*. Errors are noted by a -1 value for the
     first element, and an error string for the second.

html_imgsize(file)
     Returns the height and width (X and Y) of *file* pre-formatted as a
     single string `"HEIGHT=X WIDTH=Y"' suitable for addition into
     generated HTML IMG tags.

attr_imgsize(file)
     Returns the height and width of *file* as part of a 4-element list
     useful for routines that use hash tables for the manipulation of
     named parameters, such as the Tk or CGI libraries. A typical return
     value looks like `("-HEIGHT", X, "-WIDTH", Y)'.

By default, only `imgsize()' is imported. Any one or combination of the
three may be imported, or all three may be with the tag *:all*.

DIAGNOSTICS
===========

The base routine, `imgsize', returns a -1 as the first value in its list
when an error has occured. The second return element contains a descriptive
error message.

The second and third forms blindly format the returned data of `imgsize',
and as such may return corrupted data in the event of an error.

CAVEATS
=======

Current implementation can operate only on files, and uses the suffix of
the file name to determine how to examine the file. Thus, files with no
suffix or an incorrect suffix will not be sized correctly. Suffixes are
treated in a case-independant manner. Currently recognized suffixes are:
JPEG, JPG, GIF, PNG, XBM and XPM.

I have no PNG-format files on which to test the PNG sizing. I can only
trust that it works.

This will reliably work on perl 5.002 or newer. Perl versions prior to
5.003 do not have the *IO::File* module by default, which this module
requires. You will have to retrieve and install it, or upgrade to 5.003,
in which it is included as part of the core.

SEE ALSO
========

`http://www.tardis.ed.ac.uk/~ark/wwwis/' for a description of `wwwis' and
how to obtain it.

AUTHORS
=======

Perl module interface by Randy J. Ray *(rjray@uswest.com)*, original
image-sizing code by Alex Knowles *(alex@ed.ac.uk)* and Andrew Tong
*(werdna@ugcs.caltech.edu)*, used with their joint permission.


File: pm.info,  Node: IniConf,  Next: LWP,  Prev: Image/Size,  Up: Module List

A Module for reading .ini-style configuration files
***************************************************

NAME
====

IniConf - A Module for reading .ini-style configuration files

DESCRIPTION
===========

IniConf provides a way to have readable configuration files outside your
Perl script.  The configuration can be safely reloaded upon receipt of a
signal.

USAGE
=====

Get a new IniConf object with the new method:

     $cfg = IniConf->new( -file => "/path/configfile.ini" );
     $cfg = new IniConf -file => "/path/configfile.ini";

Optional named parameters may be specified after the configuration file
name.  See the new in the METHODS section, below.

INI files consist of a number of sections, each preceeded with the section
name in square brackets.  Parameters are specified in each section as
Name=Value.  Any spaces around the equals sign will be ignored, and the
value extends to the end of the line

     [section]
     Parameter=Value

Both the hash mark (#) and the semicolon (;) are comment characters.
Lines that begin with either of these characters will be ignored.  Any
amount of whitespace may preceed the comment character.

Multiline or multivalued fields may also be defined ala UNIX "here
document" syntax:

     Parameter=<<EOT
     value/line 1
     value/line 2
     EOT

You may use any string you want in place of "EOT".  Note that what follows
the "<<" and what appears at the end of the text MUST match exactly,
including any trailing whitespace.

See the METHODS section, below, for settable options.

Values from the config file are fetched with the val method:

     $value = $cfg->val('Section', 'Parameter');

If you want a multi-line/value field returned as an array, just specify an
array as the receiver:

     @values = $cfg->val('Section', 'Parameter');

METHODS
=======

new (-file=>$filename, [-option=>value ...] )
---------------------------------------------

Returns a new configuration object (or "undef" if the configuration file
has an error).  One IniConf object is required per configuration file.
The following named parameters are available:

*-default* section
     Specifies a section is used for default values.  For example, if you
     look up the "permissions" parameter in the "users" section, but there
     is none, IniConf will look to your default section for a "permissions"
     value before returning undef.

*-reloadsig* signame
     You may specify a signal (such as SIGHUP) that will cause the
     configuration file to be read.  This is useful for static daemons
     where a full restart in order to realize a configuration change would
     be undesirable.  Note that your application must be tolerant of the
     signal you choose.  If a signal handler was already in place before
     the IniConf object is created, it will be called after the
     configuration file is reread.  The signal handler will not be
     re-enabled until after the configuration file is reread any the
     previous signal handler returns.

*-reloadwarn* 0|1
     Set -reloadwarn => 1 to enable a warning message (output to STDERR)
     whenever the config file is reloaded.  The reload message is of the
     form:

          PID <PID> reloading config file <file> at YYYY.MM.DD HH:MM:SS

     See your system documentation for information on valid signals.

*-nocase* 0|1
     Set -nocase => 1 to handle the config file in a case-insensitive
     manner (case in values is preserved, however).  By default, config
     files are case-sensitive (i.e., a section named 'Test' is not the same
     as a section named 'test').  Note that there is an added overhead for
     turning off case sensitivity.

val ($section, $parameter)
--------------------------

Returns the value of the specified parameter in section $section.

setval ($section, $parameter, $value, [ $value2, ... ])
-------------------------------------------------------

Sets the value of parameter $section in section $section to $value (or to
a set of values).  See below for methods to write the new configuration
back out to a file.

You may not set a parameter that didn't exist in the original
configuration file.  *setval* will return undef if this is attempted.
Otherwise, it returns 1.

ReadConfig
----------

Forces the config file to be re-read.  Also see the *-reloadsig* option to
the new method for a way to connect this method to a signal (such as
SIGHUP).

Sections
--------

Returns an array containing section names in the configuration file.  If
the *nocase* option was turned on when the config object was created, the
section names will be returned in lowercase.

Parameters ($sectionname)
-------------------------

Returns an array containing the parameters contained in the specified
section.

GroupMembers ($group)
---------------------

Returns an array containing the members of specified $group.  Groups are
specified in the config file as new sections of the form

     [GroupName MemberName]

This is useful for building up lists.  Note that parameters within a
"member" section are referenced normally (i.e., the section name is still
"Groupname Membername", including the space).

WriteConfig ($filename)
-----------------------

Writes out a new copy of the configuration file.  A temporary file (ending
in .new) is written out and then renamed to the specified filename.  Also
see BUGS below.

RewriteConfig
-------------

Same as WriteConfig, but specifies that the original configuration file
should be rewritten.

DIAGNOSTICS
===========

@IniConf::errors
----------------

Contains a list of errors encountered while parsing the configuration
file.  If the new method returns undef, check the value of this to find
out what's wrong.  This value is reset each time a config file is read.

BUGS
====

   * IniConf won't know if you change the signal handler that it's using
     for config reloads.

   * The signal handling stuff is almost guaranteed not to work on non-UNIX
     systems.

   * The output from [Re]WriteConfig/OutputConfig might not be as pretty as
     it can be.  Comments are tied to whatever was immediately below them.

   * No locking is done by [Re]WriteConfig.  When writing servers, take
     care that only the parent ever calls this, and consider making your
     own backup.

   * The Windows INI specification (if there is one) probably isn't
     followed exactly.  First and foremost, IniConf is for making
     easy-to-maintain (and read) configuration files.

VERSION
=======

Version 0.9 (beta)

AUTHOR
======

Scott Hutton (shutton@indiana.edu)

COPYRIGHT
=========

Copyright (c) 1996 Scott Hutton. All rights reserved. This program is free
software; you can redistribute it and/or modify it under the same terms as
Perl itself.


File: pm.info,  Node: LWP,  Next: LWP/Debug,  Prev: IniConf,  Up: Module List

Library for WWW access in Perl
******************************

NAME
====

LWP - Library for WWW access in Perl

DESCRIPTION
===========

Libwww-perl is a collection of Perl modules which provides a simple and
consistent programming interface (API) to the World-Wide Web.  The main
focus of the library is to provide classes and functions that allow you to
write WWW clients, thus libwww-perl said to be a WWW client library. The
library also contain modules that are of more general use.

The main architecture of the library is object oriented.  The user agent,
requests sent and responses received from the WWW server are all
represented by objects.  This makes a simple and powerful interface to
these services.  The interface should be easy to extend and customize for
your needs.

The main features of the library are:

   * Contains various reusable components (modules) that can be used
     separately or together.

   * Provides an object oriented model of HTTP-style communication.  Within
     this framework we currently support access to http, gopher, ftp, news,
     file, and mailto resources.

   * The library be used through the full object oriented interface or
     through a very simple procedural interface.

   * Support the basic and digest authorization schemes.

   * Transparent redirect handling.

   * Supports access through proxy servers.

   * URL handling (both absolute and relative URLs are supported).

   * A parser for `robots.txt' files and a framework for constructing
     robots.

   * An experimental HTML parser and formatters (for PostScript and plain
     text).

   * The library can cooperate with Tk.  A simple Tk-based GUI browser
     called 'tkweb' is distributed with the Tk extension for perl.

   * An implementation of the HTTP content negotiation algorithm that can
     be used both in protocol modules and in server scripts (like CGI
     scripts).

   * A simple command line client application called `lwp-request'.

HTTP STYLE COMMUNICATION
========================

The libwww-perl library is based on HTTP style communication. This section
try to describe what that means.

Let us start with this quote from the HTTP specification document
<URL:http://www.w3.org/pub/WWW/Protocols/>:


     The HTTP protocol is based on a request/response paradigm. A client
     establishes a connection with a server and sends a request to the
     server in the form of a request method, URI, and protocol version,
     followed by a MIME-like message containing request modifiers, client
     information, and possible body content. The server responds with a
     status line, including the message's protocol version and a success or
     error code, followed by a MIME-like message containing server
     information, entity meta-information, and possible body content.

What this means to libwww-perl is that communication always take place
through these steps: First a *request* object is created and configured.
This object is then passed to a server and we get a *response* object in
return that we can examine. A request is always independent of any
previous requests, i.e. the service is stateless.  The same simple model
is used for any kind of service we want to access.

For example, if we want to fetch a document from a remote file server,
then we send it a request that contains a name for that document and the
response will contain the document itself.  If we access a search engine,
then the content of the request will contain the query parameters and the
response will contain the query result.  If we want to send a mail message
to somebody then we send a request object which contains our message to
the mail server and the response object will contain an acknowledgment
that tells us that the message has been accepted and will be forwarded to
the recipient(s).

It is as simple as that!

The Request Object
------------------

The request object has the class name `HTTP::Request' in libwww-perl. The
fact that the class name use `HTTP::' as a name prefix only implies that
we use the HTTP model of communication. It does not limit the kind of
services we can try to pass this *request* to.  For instance, we will send
`HTTP::Request's both to ftp and gopher servers, as well as to the local
file system.

The main attributes of the request objects are:

   * The *method* is a short string that tells what kind of request this
     is.  The most used methods are GET, *PUT*, POST and HEAD.

   * The url is a string denoting the protocol, server and the name of the
     "document" we want to access.  The url might also encode various
     other parameters.

   * The *headers* contain additional information about the request and
     can also used to describe the content.  The headers is a set of
     keyword/value pairs.

   * The *content* is an arbitrary amount of data.

The Response Object
-------------------

The request object has the class name `HTTP::Response' in libwww-perl.
The main attributes of objects of this class are:

   * The code is a numerical value that encode the overall outcome of the
     request.

   * The message is a short (human readable) string that corresponds to
     the code.

   * The *headers* contain additional information about the response and
     they also describe the content.

   * The *content* is an arbitrary amount of data.

Since we don't want to handle all possible code values directly in our
programs, the libwww-perl response object have methods that can be used to
query what kind of response this is.  The most commonly used response
classification methods are:

is_success()
     The request was was successfully received, understood or accepted.

is_error()
     The request failed.  The server or the resource might not be
     available, access to the resource might be denied or other things
     might have failed for some reason.

The User Agent
--------------

Let us assume that we have created a *request* object. What do we actually
do with it in order to receive a *response*?

The answer is that you pass it on to a *user agent* object and this object
will take care of all the things that need to be done (low-level
communication and error handling). The user agent will give you back a
*response* object. The user agent represents your application on the
network and it provides you with an interface that can accept *requests*
and will return *responses*.

You should think about the user agent as an interface layer between your
application code and the network.  Through this interface you are able to
access the various servers on the network.

The libwww-perl class name for the user agent is `LWP::UserAgent'. Every
libwww-perl application that wants to communicate should create at least
one object of this kind. The main method provided by this object is
request(). This method takes an `HTTP::Request' object as argument and
will (eventually) return a `HTTP::Response' object.

The user agent has many other attributes that lets you configure how it
will interact with the network and with your application code.

   * The timeout specify how much time we give remote servers in creating
     responses before the library disconnect and creates an internal
     timeout response.

   * The *agent* specify the name that your application should use when it
     presents itself on the network.

   * The *from* attribute can be set to the e-mail address of the person
     responsible for running the application.  If this is set, then the
     address will be sent to the servers with every request.

   * The *use_alarm* specify if it is OK for the user agent to use the
     alarm(2) system to implement timeouts.

   * The *use_eval* specify if the agent should raise an exception (die in
     perl) if an error condition occur.

   * The *parse_head* specify whether we should initialize response
     headers from the <head> section of HTML documents.

   * The *proxy* and *no_proxy* specify if and when communication should
     go through a proxy server. <URL:http://www.w3.org/pub/WWW/Proxies/>

   * The *credentials* provide a way to set up user names and passwords
     that is needed to access certain services.

Many applications would want even more control over how they interact with
the network and they get this by specializing the `LWP::UserAgent' by
sub-classing.  The library provide a specialization called `LWP::RobotUA'
that is used by robot applications.

An Example
----------

This example shows how the user agent, a request and a response are
represented in actual perl code:

     # Create a user agent object
     use LWP::UserAgent;
     $ua = new LWP::UserAgent;
     $ua->agent("AgentName/0.1 " . $ua->agent);

     # Create a request
     my $req = new HTTP::Request POST => 'http://www.perl.com/cgi-bin/BugGlimpse';
     $req->content_type('application/x-www-form-urlencoded');
     $req->content('match=www&errors=0');

     # Pass request to the user agent and get a response back
     my $res = $ua->request($req);

     # Check the outcome of the response
     if ($res->is_success) {
         print $res->content;
     } else {
         print "Bad luck this time\n";
     }

The $ua is created once when the application starts up.  New request
objects are normally created for each request sent.

NETWORK SUPPORT
===============

This section goes through the various protocol schemes and describe the
HTTP style methods that are supported and the headers that might have any
effect.

For all requests, a "User-Agent" header is added and initialized from the
$ua->agent value before the request is handed to the network layer.  In
the same way, a "From" header is initialized from the $ua->from value.

For all responses, the library will add a header called "Client-Date".
This header will recode the time when the response was received by your
application.  This format and semantics of the header is just like the
server created "Date" header.

HTTP Requests
-------------

HTTP request are really just handed off to an HTTP server and it will
decide what happens.  Few servers implement methods beside the usual
"GET", "HEAD", "POST" and "PUT" but CGI-scripts can really implement any
method they like.

If the server is not available then the library will generate an internal
error response.

The library automatically adds a "Host" and a "Content-Length" header to
the HTTP request before it is sent over the network.

For GET request you might want to add the "If-Modified-Since" header to
make the request conditional.

For POST request you should add the "Content-Type" header.  When you try
to emulate HTML <FORM> handling you should usually let the value of the
"Content-Type" header be "application/x-www-form-urlencoded".  See *Note
Lwpcook: lwpcook, for examples of this.

The libwww-perl HTTP implementation currently support the HTTP/1.0
protocol.  HTTP/0.9 servers are also handled correctly.

The library allows you to access proxy server through HTTP.  This means
that you can set up the library to forward all types of request through
the HTTP protocol module.  See *Note LWP/UserAgent: LWP/UserAgent, for
documentation of this.

FTP Requests
------------

The library currently support GET, HEAD and PUT requests.  GET will
retrieve a file or a directory listing from an FTP server.  PUT will store
a file on a ftp server.

You can specify a ftp account for servers that want this in addition user
name and password.  This is specified by passing an "Account" header in
the request.

User name/password can be specified using basic authorization or be
encoded in the URL.  Bad logins return an UNAUTHORIZED response with
"WWW-Authenticate: Basic" and can be treated as basic authorization for
HTTP.

The library support ftp ASCII transfer mode by specifying the "type=a"
parameter in the URL.

Directory listings are by default returned unprocessed (as returned from
the ftp server) with the content media type reported to be
"text/ftp-dir-listing". The `File::Listing' module provide functionality
for parsing of these directory listing.

The ftp module is also able to convert directory listings to HTML and this
can be requested via the standard HTTP content negotiation mechanisms (add
an "Accept: text/html" header in the request if you want this).

The normal file retrievals, the "Content-Type" is guessed based on the
file name suffix. See *Note LWP/MediaTypes: LWP/MediaTypes,.

The "If-Modified-Since" header is not honored yet.

Example:

     $req = HTTP::Request->new(GET => 'ftp://me:passwd@ftp.some.where.com/');
     $req->header(Accept => "text/html, */*;q=0.1");

News Requests
-------------

Access to the USENET News system is implemented through the NNTP protocol.
The name of the news server is obtained from the NNTP_SERVER environment
variable and defaults to "news".  It is not possible to specify the
hostname of the NNTP server in the news:-URLs.

The library support GET and HEAD to retrieve news articles through the
NNTP protocol.  You can also post articles to newsgroups by using
(surprise!) the POST method.

GET on newsgroups is not implemented yet.

Examples:

     $req = HTTP::Request->new(GET => 'news:abc1234@a.sn.no');

     $req = HTTP::Request->new(POST => 'news:comp.lang.perl.test');
     $req->header(Subject => 'This is a test',
                  From    => 'me@some.where.org');
     $req->content(<<EOT);
     This is the content of the message that we are sending to
     the world.
     EOT

Gopher Request
--------------

The library supports the GET and HEAD method for gopher request.  All
request header values are ignored.  HEAD cheats and will return a response
without even talking to server.

Gopher menus are always converted to HTML.

The response "Content-Type" is generated from the document type encoded
(as the first letter) in the request URL path itself.

Example:

     $req = HTTP::Request->new('GET', 'gopher://gopher.sn.no/');

File Request
------------

The library supports GET and HEAD methods for file requests.  The
"If-Modified-Since" header is supported.  All other headers are ignored.
The host component of the file URL must be empty or set to "localhost".
Any other host value will be treated as an error.

Directories are always converted to an HTML document.  For normal files,
the "Content-Type" and "Content-Encoding" in the response are guessed
based on the file suffix.

Example:

     $req = HTTP::Request->new(GET => 'file:/etc/passwd');

Mailto Request
--------------

You can send (aka "POST") mail messages using the library.  All headers
specified for the request are passed on to the mail system.  The "To"
header is initialized from the mail address in the URL.

Example:

     $req = HTTP::Request->new(POST => 'mailto:libwww-perl-request@ics.uci.edu');
     $req->header("Subject", "subscribe");
     $req->content("Please subscribe me to the libwww-perl mailing list!\n");

OVERVIEW OF CLASSES AND PACKAGES
================================

This table should give you a quick overview of the classes provided by the
library. Indentation shows class inheritance.

     LWP::MemberMixin   -- Access to member variables of Perl5 classes
       LWP::UserAgent   -- WWW user agent class
         LWP::RobotUA   -- When developing a robot applications
       LWP::Protocol          -- Interface to various protocol schemes
         LWP::Protocol::http  -- http:// access
         LWP::Protocol::file  -- file:// access
         LWP::Protocol::ftp   -- ftp:// access
         ...

     LWP::Socket        -- Socket creation and IO

     HTTP::Headers      -- MIME/RFC822 style header (used by HTTP::Message)
     HTTP::Message      -- HTTP style message
       HTTP::Request    -- HTTP request
       HTTP::Response   -- HTTP response
     HTTP::Daemon       -- A HTTP server class

     URI::URL           -- Uniform Resource Locators

     WWW::RobotRules    -- Parse robots.txt files
       WWW::RobotRules::AnyDBM_File -- Persistent RobotRules

     HTML::Parser       -- Parse HTML documents
       HTML::TreeBuilder-- Build a HTML syntax tree
       HTML::HeadParser -- Parse the <HEAD> section of a HTML document
       HTML::LinkExtor  -- Extract links from a HTML document
     HTML::Element      -- Building block for the HTML::TreeBuilder
     HTML::Formatter    -- Convert HTML syntax trees to readable formats
       HTML::FormatText -- Output is plain text
       HTML::FormatPS   -- Output is PostScript

The following modules provide various functions and definitions.

     LWP                -- This file.  Library version number and documentation.
     LWP::MediaTypes    -- MIME types configuration (text/html etc.)
     LWP::Debug         -- Debug logging module
     LWP::Simple        -- Simplified procedural interface for common functions
     HTTP::Status       -- HTTP status code (200 OK etc)
     HTTP::Date         -- Date parsing module for HTTP date formats
     HTTP::Negotiate    -- HTTP content negotiation calculation
     HTML::Entities     -- Expand or unexpand entities in HTML text
     File::Listing      -- Parse directory listings

HTTP use the Base64 encoding at some places.  The QuotedPrint module is
just included to make the MIME:: collection more complete.

     MIME::Base64       -- Base64 encoding/decoding routines
     MIME::QuotedPrint  -- Quoted Printable encoding/decoding routines

The following modules does not have much to do with the World Wide Web,
but are included just because I am lazy and did not bother to make
separate distributions for them.  Regard them as bonus, provided free for
your pleasure.

     Font::AFM          -- Parse Adobe Font Metric files
     File::CounterFile  -- Persistent counter class

MORE DOCUMENTATION
==================

All modules contain detailed information on the interfaces they provide.
The *Note Lwpcook: lwpcook, is the libwww-perl cookbook that contain
examples of typical usage of the library.  You might want to take a look
at how the scripts `lwp-request', `lwp-rget' and `lwp-mirror' are
implemented.

BUGS
====

The library can not handle multiple simultaneous requests yet.  The HTML::
modules are still experimental.  Also, check out what's left in the TODO
file.

ACKNOWLEDGEMENTS
================

This package owes a lot in motivation, design, and code, to the
libwww-perl library for Perl 4, maintained by Roy Fielding
<fielding@ics.uci.edu>.

That package used work from Alberto Accomazzi, James Casey, Brooks Cutter,
Martijn Koster, Oscar Nierstrasz, Mel Melchner, Gertjan van Oosten, Jared
Rhine, Jack Shirazi, Gene Spafford, Marc VanHeyningen, Steven E. Brenner,
Marion Hakanson, Waldemar Kebsch, Tony Sanders, and Larry Wall; see the
libwww-perl-0.40 library for details.

The primary architect for this Perl 5 library is Martijn Koster and Gisle
Aas, with lots of help from Graham Barr, Tim Bunce, Andreas Koenig, Jared
Rhine, and Jack Shirazi.

COPYRIGHT
=========

     Copyright 1995-1996, Gisle Aas
     Copyright 1995, Martijn Koster

This library is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

AVAILABILITY
============

The latest version of this library is likely to be available from:

     http://www.sn.no/libwww-perl/

The best place to discuss this code is on the <libwww-perl@ics.uci.edu>
mailing list.


File: pm.info,  Node: LWP/Debug,  Next: LWP/IO,  Prev: LWP,  Up: Module List

debug routines for the libwww-perl library
******************************************

NAME
====

LWP::Debug - debug routines for the libwww-perl library

SYNOPSIS
========

     use LWP::Debug qw(+ -conns);

     # Used internally in the library
     LWP::Debug::trace('send()');
     LWP::Debug::debug('url ok');
     LWP::Debug::conns("read $n bytes: $data");

DESCRIPTION
===========

LWP::Debug provides tracing facilities. The trace(), debug() and conns()
function are called within the library and they log information at
increasing levels of detail. Which level of detail is actually printed is
controlled with the `level()' function.

FUNCTIONS
=========

level(...)
----------

The `level()' function controls the level of detail being logged. Passing
'+' or '-' indicates full and no logging respectively. Inidividual levels
can switched on and of by passing the name of the level with a '+' or '-'
prepended.  The levels are:

     trace   : trace function calls
     debug   : print debug messages
     conns   : show all data transfered over the connections

The LWP::Debug module provide a special import() method that allows you to
pass the level() arguments with initial use statement.  If a use argument
start with '+' or '-' then it is passed to the level function, else the
name is exported as usual.  The following two statements are thus
equivalent (if you ignore that the second pollutes your namespace):

     use LWP::Debug qw(+);
     use LWP::Debug qw(level); level('+');

trace($msg)
-----------

The `trace()' function is used for tracing function calls. The package and
calling subroutine name is printed along with the passed argument. This
should be called at the start of every major function.

debug($msg)
-----------

The `debug()' function is used for high-granularity reporting of state in
functions.

conns($msg)
-----------

The `conns()' function is used to show data being transferred over the
connections. This may generate considerable output.


File: pm.info,  Node: LWP/IO,  Next: LWP/MediaTypes,  Prev: LWP/Debug,  Up: Module List

Low level I/O capability
************************

NAME
====

LWP::IO - Low level I/O capability

DESCRIPTION
===========

LWP::IO::read($fd, $data, $size, $offset, $timeout)
---------------------------------------------------

LWP::IO::write($fd, $data, $timeout)
------------------------------------

These routines provide low level I/O with timeout capability for the LWP
library.  These routines will only be installed if they are not already
defined.  This fact can be used by programs that need to override these
functions.  Just provide replacement functions before you require LWP. See
also *Note LWP/TkIO: LWP/TkIO,.


File: pm.info,  Node: LWP/MediaTypes,  Next: LWP/MemberMixin,  Prev: LWP/IO,  Up: Module List

guess media type for a file or a URL.
*************************************

NAME
====

guess_media_type - guess media type for a file or a URL.

media_suffix - returns file extentions for a media type

DESCRIPTION
===========

This module provides functions for handling of media (also known as MIME)
types and encodings.  The mapping from file extentions to media types is
defined by the `media.types' file.  If the `~/.media.types' file exist it
is used as a replacement.

For backwards compatability we will also look for `~/.mime.types'.

FUNCTIONS
=========

guess_media_type($filename)
---------------------------

This function tries to guess media type and encoding for given file.  In
scalar context it returns only the content-type.  In array context it
returns an array consisting of content-type followed by any
content-encodings applied.

The guess_media_type function also accepts a URI::URL object as argument.

If the type can not be deduced from looking at the file name only, then
guess_media_type() will take a look at the actual file using the -T perl
operator in order to determine if this is a text file (text/plain).  If
this does not work it will return *application/octet-stream* as the type.

media_suffix($type)
-------------------

     media_suffix('image/*')

This function will return all suffixes that can be used to denote the
specified media type.  Wildcard types can be used.


File: pm.info,  Node: LWP/MemberMixin,  Next: LWP/Protocol,  Prev: LWP/MediaTypes,  Up: Module List

Member access mixin class
*************************

NAME
====

LWP::MemberMixin - Member access mixin class

DESCRIPTION
===========

A mixin class to get methods that provide easy access to member variables
in the %$self.

BUGS
====

Ideally there should be better Perl langauge support for this.

METHODS
=======

_elem($elem [, $val])
---------------------

Internal method to get/set the value of member variable `$elem'. If `$val'
is defined it is used as the new value for the member variable.  If it is
undefined the current value is not touched. In both cases the previous
value of the member variable is returned.


File: pm.info,  Node: LWP/Protocol,  Next: LWP/RobotUA,  Prev: LWP/MemberMixin,  Up: Module List

Base class for LWP protocols
****************************

NAME
====

LWP::Protocol - Base class for LWP protocols

DESCRIPTION
===========

This class is used a the base class for all protocol implementations
supported by the LWP library.

When creating an instance of this class using
`LWP::Protocol::create($url)', and you get an initialised subclass
appropriate for that access method. In other words, the
LWP::Protocol::create() function calls the constructor for one of its
subclasses.

All derived LWP::Protocol classes need to override the request() method
which is used to service a request. The overridden method can make use of
the collect() function to collect together chunks of data as it is
received.

SEE ALSO
========

Inspect the `LWP/Protocol/file.pm' and `LWP/Protocol/http.pm' files for
examples of usage.

METHODS AND FUNCTIONS
=====================

$prot = new HTTP::Protocol;
---------------------------

The LWP::Protocol constructor is inherited by subclasses. As this is a
virtual base class this method should *not* be called directly.

$prot = LWP::Protocol::create($url)
-----------------------------------

Create an object of the class implementing the protocol to handle the
given scheme. This is a function, not a method. It is more an object
factory than a constructor. This is the function user agents should use to
access protocols.

$class = LWP::Protocol::implementor($scheme, [$class])
------------------------------------------------------

Get and/or set implementor class for a scheme.  Returns '' if the
specified scheme is not supported.

$prot->request(...)
-------------------

     $response = $protocol->request($request, $proxy, undef);
     $response = $protocol->request($request, $proxy, '/tmp/sss');
     $response = $protocol->request($request, $proxy, \&callback, 1024);

Dispactches a request over the protocol, and returns a response object.
This method needs to be overridden in subclasses.  Referer to *Note
LWP/UserAgent: LWP/UserAgent, for description of the arguments.

$prot->timeout($seconds)
------------------------

Get and set the timeout value in seconds

$prot->use_alarm($yesno)
------------------------

Indicates if the library is allowed to use the core alarm() function to
implement timeouts.

$prot->parse_head($yesno)
-------------------------

Should we initialize response headers from the <head> section of HTML
documents.

$prot->collect($arg, $response, $collector)
-------------------------------------------

Called to collect the content of a request, and process it appropriately
into a scalar, file, or by calling a callback.  If $arg is undefined, then
the content is stored within the $response.  If $arg is a simple scalar,
then $arg is interpreted as a file name and the content is written to this
file.  If $arg is a reference to a routine, then content is passed to this
routine.

The $collector is a routine that will be called and which is reponsible
for returning pieces (as ref to scalar) of the content to process.  The
$collector signals EOF by returning a reference to an empty sting.

The return value from collect() is the $response object reference.

*Note:* We will only use the callback or file argument if
$response->is_success().  This avoids sendig content data for redirects
and authentization responses to the callback which would be confusing.

$prot->collect_once($arg, $response, $content)
----------------------------------------------

Can be called when the whole response content is available as $content.
This will invoke collect() with a collector callback that returns a
reference to $content the first time and an empty string the next.


File: pm.info,  Node: LWP/RobotUA,  Next: LWP/Simple,  Prev: LWP/Protocol,  Up: Module List

A class for Web Robots
**********************

NAME
====

LWP::RobotUA - A class for Web Robots

SYNOPSIS
========

     require LWP::RobotUA;
     $ua = new LWP::RobotUA 'my-robot/0.1', 'me@foo.com';
     $ua->delay(10);  # be very nice, go slowly
     ...
     # just use it just like a normal LWP::UserAgent
     $res = $ua->request($req);

DESCRIPTION
===========

This class implements a user agent that is suitable for robot
applications.  Robots should be nice to the servers they visit.  They
should consult the `robots.txt' file to ensure that they are welcomed and
they should not send too frequent requests.

But, before you consider writing a robot take a look at
<URL:http://info.webcrawler.com/mak/projects/robots/robots.html>.

When you use a *LWP::RobotUA* as your user agent, then you do not really
have to think about these things yourself.  Just send requests as you do
when you are using a normal *LWP::UserAgent* and this special agent will
make sure you are nice.

METHODS
=======

The LWP::RobotUA is a sub-class of LWP::UserAgent and implements the same
methods.  The use_alarm() method also desides whether we will wait if a
request is tried too early (if true), or will return an error response (if
false).

In addition these methods are provided:

$ua = LWP::RobotUA->new($agent_name, $from, [$rules])
-----------------------------------------------------

Your robot's name and the mail address of the human responsible for the
robot (i.e. you) is required by the constructor.

Optionally it allows you to specify the *WWW::RobotRules* object to use.

$ua->delay([$minutes])
----------------------

Set the minimum delay between requests to the same server.  The default is
1 minute.

$ua->rules([$rules])
--------------------

Set/get which *WWW::RobotRules* object to use.

$ua->no_visits($netloc)
-----------------------

Returns the number of documents fetched from this server host.

$ua->host_wait($netloc)
-----------------------

Returns the number of seconds you must wait before you can make a new
request to this host.

$ua->as_string
--------------

Returns a text that describe the state of the UA.  Mainly useful for
debugging.

SEE ALSO
========

*Note LWP/UserAgent: LWP/UserAgent,, *Note WWW/RobotRules: WWW/RobotRules,

AUTHOR
======

Gisle Aas <aas@sn.no>


File: pm.info,  Node: LWP/Simple,  Next: LWP/Socket,  Prev: LWP/RobotUA,  Up: Module List

Procedural LWP interface
************************

NAME
====

get, head, getprint, getstore, mirror - Procedural LWP interface

SYNOPSIS
========

     perl -MLWP::Simple -e 'getprint "http://www.sn.no"'

     use LWP::Simple;
     $content = get("http://www.sn.no/")
     if (mirror("http://www.sn.no/", "foo") == RC_NOT_MODIFIED) {
         ...
     }
     if (is_success(getprint("http://www.sn.no/"))) {
         ...
     }

DESCRIPTION
===========

This interface is intended for those who want a simplified view of the
libwww-perl library.  This interface should also be suitable for
one-liners.  If you need more control or access to the header fields in
the requests sent and responses received you should use the full OO
interface provided by the LWP::UserAgent module.

This following functions are provided (and exported) by this module:

get($url)
     This function will get the document identified by the given URL.  The
     get() function will return the document if successful or 'undef' if it
     fails.  The $url argument can be either a simple string or a reference
     to a URI::URL object.

     You will not be able to examine the response code or response headers
     (like *Content-Type*) when you are accessing the web using this
     function.  If you need this you should use the full OO interface.

head($url)
     Get document headers. Returns the following values if successful:
     ($content_type, $document_length, $modified_time, $expires, $server)

     Returns an empty list if it fails.

getprint($url)
     Get and print a document identified by a URL. The document is printet
     on STDOUT. The error message (formatted as HTML) is printed on STDERR
     if the request fails.  The return value is the HTTP response code.

getstore($url, $file)
     Gets a document identified by a URL and stores it in the file. The
     return value is the HTTP response code.

mirror($url, $file)
     Get and store a document identified by a URL, using
     *If-modified-since*, and checking of the *Content-Length*.  Returns
     the HTTP response code.

This module also exports the HTTP::Status constants and procedures.  These
can be used when you check the response code from getprint(), getstore()
and mirror().  The constants are:

     RC_CONTINUE
     RC_SWITCHING_PROTOCOLS
     RC_OK
     RC_CREATED
     RC_ACCEPTED
     RC_NON_AUTHORITATIVE_INFORMATION
     RC_NO_CONTENT
     RC_RESET_CONTENT
     RC_PARTIAL_CONTENT
     RC_MULTIPLE_CHOICES
     RC_MOVED_PERMANENTLY
     RC_MOVED_TEMPORARILY
     RC_SEE_OTHER
     RC_NOT_MODIFIED
     RC_USE_PROXY
     RC_BAD_REQUEST
     RC_UNAUTHORIZED
     RC_PAYMENT_REQUIRED
     RC_FORBIDDEN
     RC_NOT_FOUND
     RC_METHOD_NOT_ALLOWED
     RC_NOT_ACCEPTABLE
     RC_PROXY_AUTHENTICATION_REQUIRED
     RC_REQUEST_TIMEOUT
     RC_CONFLICT
     RC_GONE
     RC_LENGTH_REQUIRED
     RC_PRECONDITION_FAILED
     RC_REQUEST_ENTITY_TOO_LARGE
     RC_REQUEST_URI_TOO_LARGE
     RC_UNSUPPORTED_MEDIA_TYPE
     RC_INTERNAL_SERVER_ERROR
     RC_NOT_IMPLEMENTED
     RC_BAD_GATEWAY
     RC_SERVICE_UNAVAILABLE
     RC_GATEWAY_TIMEOUT
     RC_HTTP_VERSION_NOT_SUPPORTED

The HTTP::Status classification functions are:

is_success($rc)
     Check if response code indicated successfull request.

is_error($rc)
     Check if response code indicated that an error occured.

The module will also export the LWP::UserAgent object as `$ua' if you ask
for it explicitly.

The user agent created by this module will identify itself as
"LWP::Simple/0.00" and will initialize its proxy defaults from the
environment (by calling $ua->env_proxy).

SEE ALSO
========

*Note LWP: LWP,, *Note LWP/UserAgent: LWP/UserAgent,, *Note HTTP/Status:
HTTP/Status,, `request' in this node, `mirror' in this node


File: pm.info,  Node: LWP/Socket,  Next: LWP/TkIO,  Prev: LWP/Simple,  Up: Module List

TCP/IP socket interface
***********************

NAME
====

LWP::Socket - TCP/IP socket interface

SYNOPSIS
========

     $socket = new LWP::Socket;
     $socket->connect('localhost', 7); # echo
     $quote = 'I dunno, I dream in Perl sometimes...';
     $socket->write("$quote\n");
     $socket->read_until("\n", \$buffer);
     $socket->read(\$buffer);
     $socket = undef;  # close

DESCRIPTION
===========

This class implements TCP/IP sockets.  It groups socket generation, TCP
address manipulation and buffered reading. Errors are handled by dying
(throws exceptions).

This class should really not be required, something like this should be
part of the standard Perl5 library.

Running this module standalone executes a self test which requires
localhost to serve chargen and echo protocols.

METHODS
=======

$sock = new LWP::Socket()
-------------------------

Constructs a new socket object.

$sock->connect($host, $port)
----------------------------

Connect the socket to given host and port.

$sock->shutdown()
-----------------

Shuts down the connection.

$sock->bind($host, $port)
-------------------------

Binds a name to the socket.

$sock->listen($queuesize)
-------------------------

Set up listen queue for socket.

$sock->accept($timeout)
-----------------------

Accepts a new connection.  Returns a new LWP::Socket object if successful.
Timeout not implemented yet.

$sock->getsockname()
--------------------

Returns a 2 element array ($host, $port)

$sock->read_until($delim, $data_ref, $size, $timeout)
-----------------------------------------------------

Reads data from the socket, up to a delimiter specified by a regular
expression.  If $delim is undefined all data is read.  If $size is
defined, data will be read internally in chunks of $size bytes.  This does
not mean that we will return the data when size bytes are read.

Note that $delim is discarded from the data returned.

$sock->read($bufref, [$size, $timeout])
---------------------------------------

Reads data of the socket.  Not more than $size bytes.  Might return less
if the data is available.  Dies on timeout.

$sock->pushback($data)
----------------------

Put data back into the socket.  Data will returned next time you read().
Can be used if you find out that you have read too much.

$sock->write($data, [$timeout])
-------------------------------

Write data to socket.  The $data argument might be a scalar or code.

If data is a reference to a subroutine, then we will call this routine to
obtain the data to be written.  The routine will be called until it
returns undef or empty data.  Data might be returned from the callback as
a scalar or as a reference to a scalar.

Write returns the number of bytes written to the socket.

_getaddress($h, $p)
-------------------

Given a host and a port, it will return the address (sockaddr_in) suitable
as the `name' argument for connect() or bind(). Might return several
addresses in array context if the hostname is bound to several IP
addresses.

SELF TEST
=========

This self test is only executed when this file is run standalone. It tests
its functions against some standard TCP services implemented by inetd. If
you do not have them around the tests will fail.


File: pm.info,  Node: LWP/TkIO,  Next: LWP/UserAgent,  Prev: LWP/Socket,  Up: Module List

Tk I/O routines for the LWP library
***********************************

NAME
====

LWP::TkIO - Tk I/O routines for the LWP library

SYNOPSIS
========

     use Tk;
     require LWP::TkIO;
     require LWP::UserAgent;

DESCRIPTION
===========

This module provide replacement functions for the LWP::IO functions.
Require this module if you use Tk and want non exclusive IO behaviour from
LWP.  This does not allow LWP to run simultaneous requests though.

See also *Note LWP/IO: LWP/IO,.


File: pm.info,  Node: LWP/UserAgent,  Next: Log/Topics,  Prev: LWP/TkIO,  Up: Module List

A WWW UserAgent class
*********************

NAME
====

LWP::UserAgent - A WWW UserAgent class

SYNOPSIS
========

     require LWP::UserAgent;
     $ua = new LWP::UserAgent;

     $request = new HTTP::Request('GET', 'file://localhost/etc/motd');

     $response = $ua->request($request); # or
     $response = $ua->request($request, '/tmp/sss'); # or
     $response = $ua->request($request, \&callback, 4096);

     sub callback { my($data, $response, $protocol) = @_; .... }

DESCRIPTION
===========

The `LWP::UserAgent' is a class implementing a simple World-Wide Web user
agent in Perl. It brings together the HTTP::Request, HTTP::Response and
the LWP::Protocol classes that form the rest of the core of libwww-perl
library. For simple uses this class can be used directly to dispatch WWW
requests, alternatively it can be subclassed for application-specific
behaviour.

In normal usage the application creates a UserAgent object, and then
configures it with values for timeouts proxies, name, etc. The next step
is to create an instance of `HTTP::Request' for the request that needs to
be performed. This request is then passed to the UserAgent request()
method, which dispatches it using the relevant protocol, and returns a
`HTTP::Response' object.

The basic approach of the library is to use HTTP style communication for
all protocol schemes, i.e. you will receive an `HTTP::Response' object
also for gopher or ftp requests.  In order to achieve even more
similarities with HTTP style communications, gopher menus and file
directories will be converted to HTML documents.

The request() method can process the content of the response in one of
three ways: in core, into a file, or into repeated calls of a subroutine.
You choose which one by the kind of value passed as the second argument to
request().

The in core variant simply returns the content in a scalar attribute
called content() of the response object, and is suitable for small HTML
replies that might need further parsing.  This variant is used if the
second argument is missing (or is undef).

The filename variant requires a scalar containing a filename as the second
argument to request(), and is suitable for large WWW objects which need to
be written directly to the file, without requiring large amounts of
memory. In this case the response object returned from request() will have
empty content().  If the request fails, then the content() might not be
empty, and the file will be untouched.

The subroutine variant requires a reference to callback routine as the
second argument to request() and it can also take an optional chuck size
as third argument.  This variant can be used to construct "pipe-lined"
processing, where processing of received chuncks can begin before the
complete data has arrived.  The callback function is called with 3
arguments: the data received this time, a reference to the response object
and a reference to the protocol object.  The response object returned from
request() will have empty content().  If the request fails, then the the
callback routine will not have been called, and the response->content()
might not be empty.

The request can be aborted by calling die() within the callback routine.
The die message will be available as the "X-Died" special response header
field.

The library also accepts that you put a subroutine reference as content in
the request object.  This subroutine should return the content (possibly
in pieces) when called.  It should return an empty string when there is no
more content.

The user of this module can finetune timeouts and error handling by
calling the use_alarm() and use_eval() methods.

By default the library uses alarm() to implement timeouts, dying if the
timeout occurs. If this is not the prefered behaviour or it interferes
with other parts of the application one can disable the use alarms. When
alarms are disabled timeouts can still occur for example when reading
data, but other cases like name lookups etc will not be timed out by the
library itself.

The library catches errors (such as internal errors and timeouts) and
present them as HTTP error responses. Alternatively one can switch off
this behaviour, and let the application handle dies.

SEE ALSO
========

See *Note LWP: LWP, for a complete overview of libwww-perl5.  See
`request' in this node and `mirror' in this node for examples of usage.

METHODS
=======

$ua = new LWP::UserAgent;
-------------------------

Constructor for the UserAgent.  Returns a reference to a LWP::UserAgent
object.

$ua->simple_request($request, [$arg [, $size]])
-----------------------------------------------

This method dispatches a single WWW request on behalf of a user, and
returns the response received.  The `$request' should be a reference to a
`HTTP::Request' object with values defined for at least the method() and
url() attributes.

If `$arg' is a scalar it is taken as a filename where the content of the
response is stored.

If `$arg' is a reference to a subroutine, then this routine is called as
chunks of the content is received.  An optional `$size' argument is taken
as a hint for an appropriate chunk size.

If `$arg' is omitted, then the content is stored in the response object
itself.

$ua->request($request, $arg [, $size])
--------------------------------------

Process a request, including redirects and security.  This method may
actually send several different simple reqeusts.

The arguments are the same as for `simple_request()'.

$ua->redirect_ok
----------------

This method is called by request() before it tries to do any redirects.
It should return a true value if the redirect is allowed to be performed.
Subclasses might want to override this.

The default implementation will return FALSE for POST request and TRUE for
all others.

$ua->credentials($netloc, $realm, $uname, $pass)
------------------------------------------------

Set the user name and password to be used for a realm.  It is often more
useful to specialize the get_basic_credentials() method instead.

$ua->get_basic_credentials($realm, $uri)
----------------------------------------

This is called by request() to retrieve credentials for a Realm protected
by Basic Authentication or Digest Authentication.

Should return username and password in a list.  Return undef to abort the
authentication resolution atempts.

This implementation simply checks a set of pre-stored member variables.
Subclasses can override this method to e.g. ask the user for a
username/password.  An example of this can be found in `lwp-request'
program distributed with this library.

$ua->agent([$product_id])
-------------------------

Get/set the product token that is used to identify the user agent on the
network.  The agent value is sent as the "User-Agent" header in the
requests. The default agent name is "libwww-perl/#.##", where "#.##" is
substitued with the version numer of this library.

The user agent string should be one or more simple product identifiers
with an optional version number separated by the "/" character.  Examples
are:

     $ua->agent('Checkbot/0.4 ' . $ua->agent);
     $ua->agent('Mozilla/5.0');

$ua->from([$email_address])
---------------------------

Get/set the Internet e-mail address for the human user who controls the
requesting user agent.  The address should be machine-usable, as defined
in RFC 822.  The from value is send as the "From" header in the requests.
There is no default.  Example:

     $ua->from('aas@sn.no');

$ua->timeout([$secs])
---------------------

Get/set the timeout value in seconds. The default timeout() value is 180
seconds, i.e. 3 minutes.

$ua->use_alarm([$boolean])
--------------------------

Get/set a value indicating wether to use alarm() when implementing
timeouts.  The default is TRUE, i.e. to use alarm.  Disable this on
systems that does not implement alarm, or if this interfers with other
uses of alarm in your application.

$ua->use_eval([$boolean])
-------------------------

Get/set a value indicating wether to handle internal errors internally by
trapping with eval.  The default is TRUE, i.e. the $ua->request() will
never die.

$ua->parse_head([$boolean])
---------------------------

Get/set a value indicating wether we should initialize response headers
from the <head> section of HTML documents. The default is TRUE.  Do not
turn this off, unless you know what you are doing.

$ua->clone;
-----------

Returns a copy of the LWP::UserAgent object

$ua->is_protocol_supported($scheme)
-----------------------------------

You can use this method to query if the library currently support the
specified `scheme'.  The `scheme' might be a string (like 'http' or 'ftp')
or it might be an URI::URL object reference.

$ua->mirror($url, $file)
------------------------

Get and store a document identified by a URL, using If-Modified-Since, and
checking of the Content-Length.  Returns a reference to the response
object.

$ua->proxy(...)
---------------

Set/retrieve proxy URL for a scheme:

     $ua->proxy(['http', 'ftp'], 'http://proxy.sn.no:8001/');
     $ua->proxy('gopher', 'http://proxy.sn.no:8001/');

The first form specifies that the URL is to be used for proxying of access
methods listed in the list in the first method argument, i.e. 'http' and
'ftp'.

The second form shows a shorthand form for specifying proxy URL for a
single access scheme.

$ua->env_proxy()
----------------

Load proxy settings from *_proxy environment variables.  You might specify
proxies like this (sh-syntax):

     gopher_proxy=http://proxy.my.place/
     wais_proxy=http://proxy.my.place/
     no_proxy="my.place"
     export gopher_proxy wais_proxy no_proxy

Csh or tcsh users should use the `setenv' command to define these
envirionment variables.

$ua->no_proxy($domain,...)
--------------------------

Do not proxy requests to the given domains.  Calling no_proxy without any
domains clears the list of domains. Eg:

     $ua->no_proxy('localhost', 'no', ...);


File: pm.info,  Node: Log/Topics,  Next: Logfile,  Prev: LWP/UserAgent,  Up: Module List

control flow of logging messages
********************************

NAME
====

Log::Topics - control flow of logging messages

SYNOPSIS
========

     use Log::Topics qw(add_topic log_topic topics);
     add_topic $topic_name,$filehandle,$overload
     add_topic $topic_name,$filename,$overload
     log_topic $topic_name,@messages
     @topicslist=topics();

DESCRIPTION
===========

This package provides services for controlling the output of logging
messages from an application. Log messages are identified by named topics,
and the messages for each topic can be directed or redirected to file
handles or files.

The add_topic() function can be used to associate a named topic with a
particular file handle. If a value of 0 then logging of that particular
topic is switched off. If the file handle is not connected to a file then
it will be created and connected to a file of the same name. add_topic()
returns the name of the file handle. The third $overload parameter, if
specified and false will only set the file handle if the specified topic
is not already associated with a file handle.

Log messages are written using the log_topic() function which takes the
topic name, and if that particular topic is enabled will print its
remaining arguments to the associated file handle. It is an error to use a
topic name that has not been declared using add_topic() first.

The topics() function returns a list of all the current registered topics.

This package can usefully be used for controlling all the output of a
program, not just debugging and logging messages.

If you have Getopt::Regex package then the following lines of code allow
the user to control the log messages from the command line using either
'-Lname=FILE' or '-Lname FILE' syntaxes.

     use Log::Topics qw(add_topic log_topic);
     use Getopt::Regex qw(GetOptions);
     GetOptions(\@ARGV,
      ['-L(.+)=(.+)',sub { add_topic $1,$2; }    ,0],
      ['-L(.+)',     sub { add_topic $1; $_[0]; },1]);

HISTORY
=======

     $Log: Topics.pm,v $
     Revision 1.5  1996/01/04 20:45:38  willijar
     Renamed module to Log::Topics, and renamed functions to more
     accurately reflect modules operation.
     Added topics() function to obtain list of available topics and removed
     internal hash variable from export list.
     Reduced to one the hash dereference in log_topic for slight efficiency
     gain.

     Revision 1.4  1995/12/17 17:16:31  willijar
     Fixed bug that crept in in non-overloading case of diagnose

     Revision 1.3  1995/12/16 11:59:19  willijar
     Removed function for reading arguments from commandline -
     use Getopt::Regex instead.
     Added ability to open files for undefined filehandles.
     Improvements to documentation
     Changed name to be closer to module guidlines.

     Revision 1.2  1995/09/20  19:11:44  willijar
     Added pod documentation and RCS control

TO DO
=====

Could perhaps have the idea of groups of related topics which could be set
and changed together. Would this be useful?

BUGS
====

Please let me know of any bugs.  Suggestions for improvements gladly
received.

AUTHOR
======

John A.R. Williams, <J.A.R.Williams@aston.ac.uk>

Thanks to Tim Bunce <Tim.Bunce@ig.co.uk> for helpful suggestions and
comments.


File: pm.info,  Node: Logfile,  Next: MD5,  Prev: Log/Topics,  Up: Module List

Perl extension for generating reports from logfiles
***************************************************

NAME
====

Logfile - Perl extension for generating reports from logfiles

SYNOPSIS
========

     use Logfile::Cern;

     $l = new Logfile::Cern  File  => 'cache.log.gz',
                             Group => [Domain,File,Hour];
     $l->report(Group => File,   Sort => Records);
     $l->report(Group => Domain, Sort => Bytes);
     $l->report(Group => Hour, List => [Bytes, Records]);

     use Logfile::Wftp;

     [...]

DESCRIPTION
===========

The Logfile extension will help you generate various reports from
different server logfiles. In general there is no restriction as to what
information you extract from the logfiles.

Reading the files
-----------------

The package can be customized by subclassing `Logfile'.

A subclass should provide a funtion next which reads the next record from
the file handle `$self->{Fh}' and returns an object of type
`Logfile::Record'. In addition a function `norm' may be specified to
normalize the various record fields.

Here is a shortened version of the `Logfile::Cern' class:

     package Logfile::Cern;
     @ISA = qw ( Logfile::Base ) ;

     sub next {
         my $self = shift;
         my $fh = $self->{Fh};

     *S = $fh;
     my ($line,$host,$user,$pass,$rest,$date,$req,$code,$bytes);

     ($host,$user,$pass,$rest) = split ' ', $line, 4;
     ($rest =~ s!\[([^\]]+)\]\s*!!) && ($date = $1);
     ($rest =~ s!\"([^\"]+)\"\s*!!) && ($req = (split ' ', $1)[1]);
     ($code, $bytes) = split ' ', $rest;
     Logfile::Record->new(Host  => $host,
                          Date  => $date,
                          File  => $req,
                          Bytes => $bytes);
       }

As stated above, in general you are free to choose the fields you enter in
the record. But:

Date
     should be a valid date string. For conversion to the seconds elapsed
     since the start of epoch the modules `GetDate' and `Date::DateParse'
     are tried. If both cannot be useed, a crude build-in module is used.

     The record constructor replaces Date by the date in `yymmdd' form to
     make it sortable. Also the field *Hour* is padded in.

Host
     Setting Host will also set field *Domain* by the verbose name of the
     country given by the the domain suffix of the fully qualified domain
     name (hostname.domain). `foo.bar.PG' will be mapped to `Papua New'.
     Hostnames containing no dot will be assigned to the domain *Local*.
     IP numbers will be assiged to the domain *Unresolved*. Mapping of
     short to long domain names is done in the *Net::Country* extension
     which might be usefull in other contexts:

          use Net::Country;
          $germany = Net::Country::Name('de');

Records
     is always set to 1 in the `Record' constructor. So this field gives
     the number of successful returns from the next function.

Here is the shortened optional `norm' method:

     sub norm {
         my ($self, $key, $val) = @_;

     if ($key eq File) {
         $val =~ s/\?.*//;                             # remove query
         $val =~ s!%([\da-f][\da-f])!chr(hex($1))!eig; # decode escapes
     }
     $val;
       }

The constructor reads in a logfile and builds one or more indices.

     $l = new Logfile::Cern  File => 'cache.log.gz',
                             Group => [Host,Domain,File,Hour,Date];

There is little space but some time overhead in generating additional
indexes. If the *File* parameter is not given, *STDIN* is used. The Group
parameter may be a field name or a reference to a list of field names.
Only the field names given as constructor argument can be used for report
generation.

Report Generation
-----------------

The Index to use for a report must be given as the Group parameter. Output
is sorted by the index field unless a Sort parameter is given. Also the
output can be truncated by a Top argument or Limit.

The report generator lists the fields *Bytes* and Records for a given
index. The option List may be a single field name or a reference to an
array fo field names. It specifies which field should be listed in
addition to the Group field. List defaults to Records.

     $l->report(Group => Domain, List => [Bytes, Records])

Output is sorted by the Group field unless overwritten by a Sort option.
Default sorting order is increasing for Date and *Hour* fields and
decreasing for all other Fields. The order can be reversed using the
Reverse option.

This code

     $l->report(Group => File, Sort => Records, Top => 10);

prints:

     File                          Records
     =====================================
     /htbin/SFgate               30 31.58%
     /freeWAIS-sf/*              22 23.16%
     /SFgate/SFgate               8  8.42%
     /SFgate/SFgate-small         7  7.37%
     /icons/*                     4  4.21%
     /~goevert                    3  3.16%
     /journals/SIGMOD             3  3.16%
     /SFgate/ciw                  2  2.11%
     /search                      1  1.05%
     /reports/96/                 1  1.05%

Here are other examples. Also take a look at the `t/*' files.

     $l->report(Group => Domain, Sort => Bytes);

     Domain                  Records
     ===============================
     Germany               12 12.63%
     Unresolved             8  8.42%
     Israel                34 35.79%
     Denmark                4  4.21%
     Canada                 3  3.16%
     Network                6  6.32%
     US Commercial         14 14.74%
     US Educational         8  8.42%
     Hong Kong              2  2.11%
     Sweden                 2  2.11%
     Non-Profit             1  1.05%
     Local                  1  1.05%
     
     $l->report(Group => Hour, List => [Bytes, Records]);

     Hour            Bytes          Records
     ======================================
     07      245093 17.66%        34 35.79%
     08      438280 31.59%        19 20.00%
     09      156730 11.30%        11 11.58%
     10      255451 18.41%        16 16.84%
     11      274521 19.79%        10 10.53%
     12       17396  1.25%         5  5.26%

Report options
--------------

Group `=>' *field*
     Mandatory. *field* must be one of the fields passed to the
     constructor.

List `=>' *field*
List `=>' [*field*, *field*]
     List the subtotals for *field*s. Defaults to Records.

Sort `=>' *field*.
     Sort output by *field*. By default, Date and *Hour* are sorted in
     increasing order, whereas all   other fields are sorted in decreasing
     order.

Reverse `=> 1'
     Reverse sorting order.

Top `=>' number
     Print only the first number subtotals.

Limit `=>' number
     Print only the subtotals with Sort field greater than number (less
     than number if sorted in increasing order).

Currently reports are simply printed to STDOUT.

AUTHOR
======

Ulrich Pfeifer <`pfeifer@ls6.informatik.uni-dortmund.de'>

SEE ALSO
========

perl(1).


File: pm.info,  Node: MD5,  Next: MIME/Base64,  Prev: Logfile,  Up: Module List

Perl interface to the RSA Data Security Inc. MD5 Message-Digest Algorithm
*************************************************************************

NAME
====

MD5 - Perl interface to the RSA Data Security Inc. MD5 Message-Digest
Algorithm

SYNOPSIS
========

     use MD5;
     
     $context = new MD5;
     $context->reset();
     
     $context->add(LIST);
     $context->addfile(HANDLE);
     
     $digest = $context->digest();
     $string = $context->hexdigest();

     $digest = MD5->hash(SCALAR);
     $string = MD5->hexhash(SCALAR);

DESCRIPTION
===========

The *MD5* module allows you to use the RSA Data Security Inc. MD5 Message
Digest algorithm from within Perl programs.

A new MD5 context object is created with the new operation.  Multiple
simultaneous digest contexts can be maintained, if desired.  The context
is updated with the add operation which adds the strings contained in the
LIST parameter. Note, however, that `add('foo', 'bar')', `add('foo')'
followed by `add('bar')' and `add('foobar')' should all give the same
result.

The final message digest value is returned by the *digest* operation as a
16-byte binary string. This operation delivers the result of add
operations since the last new or reset operation. Note that the *digest*
operation is effectively a destructive, read-once operation. Once it has
been performed, the context must be reset before being used to calculate
another digest value.

Several convenience functions are also provided. The *addfile* operation
takes an open file-handle and reads it until end-of file in 1024 byte
blocks adding the contents to the context. The file-handle can either be
specified by name or passed as a type-glob reference, as shown in the
examples below. The *hexdigest* operation calls *digest* and returns the
result as a printable string of hexdecimal digits. This is exactly the
same operation as performed by the unpack operation in the examples below.

The *hash* operation can act as either a static member function (ie you
invoke it on the MD5 class as in the synopsis above) or as a normal
virtual function. In both cases it performs the complete MD5 cycle (reset,
add, digest) on the supplied scalar value. This is convenient for handling
small quantities of data. When invoked on the class a temporary context is
created. When invoked through an already created context object, this
context is used. The latter form is slightly more efficient. The *hexhash*
operation is analogous to *hexdigest*.

EXAMPLES
========

     use MD5;
     
     $md5 = new MD5;
     $md5->add('foo', 'bar');
     $md5->add('baz');
     $digest = $md5->digest();
     
     print("Digest is " . unpack("H*", $digest) . "\n");

The above example would print out the message

     Digest is 6df23dc03f9b54cc38a0fc1483df6e21

provided that the implementation is working correctly.

Remembering the Perl motto ("There's more than one way to do it"), the
following should all give the same result:

     use MD5;
     $md5 = new MD5;

     die "Can't open /etc/passwd ($!)\n" unless open(P, "/etc/passwd");

     seek(P, 0, 0);
     $md5->reset;
     $md5->addfile(P);
     $d = $md5->hexdigest;
     print "addfile (handle name) = $d\n";

     seek(P, 0, 0);
     $md5->reset;
     $md5->addfile(\*P);
     $d = $md5->hexdigest;
     print "addfile (type-glob reference) = $d\n";

     seek(P, 0, 0);
     $md5->reset;
     while (<P>)
     {
         $md5->add($_);
     }
     $d = $md5->hexdigest;
     print "Line at a time = $d\n";

     seek(P, 0, 0);
     $md5->reset;
     $md5->add(<P>);
     $d = $md5->hexdigest;
     print "All lines at once = $d\n";

     seek(P, 0, 0);
     $md5->reset;
     while (read(P, $data, (rand % 128) + 1))
     {
         $md5->add($data);
     }
     $d = $md5->hexdigest;
     print "Random chunks = $d\n";

     seek(P, 0, 0);
     $md5->reset;
     undef $/;
     $data = <P>;
     $d = $md5->hexhash($data);
     print "Single string = $d\n";

     close(P);

NOTE
====

The MD5 extension may be redistributed under the same terms as Perl.  The
MD5 algorithm is defined in RFC1321. The basic C code implementing the
algorithm is derived from that in the RFC and is covered by the following
copyright:

Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All rights
reserved.

License to copy and use this software is granted provided that it is
identified as the "RSA Data Security, Inc. MD5 Message-Digest Algorithm"
in all material mentioning or referencing this software or this function.

License is also granted to make and use derivative works provided that
such works are identified as "derived from the RSA Data Security, Inc. MD5
Message-Digest Algorithm" in all material mentioning or referencing the
derived work.

RSA Data Security, Inc. makes no representations concerning either the
merchantability of this software or the suitability of this software for
any particular purpose. It is provided "as is" without express or implied
warranty of any kind.

These notices must be retained in any copies of any part of this
documentation and/or software.

This copyright does not prohibit distribution of any version of Perl
containing this extension under the terms of the GNU or Artistic licences.

AUTHOR
======

The MD5 interface was written by Neil Winton (`N.Winton@axion.bt.co.uk').

SEE ALSO
========

perl(1).


File: pm.info,  Node: MIME/Base64,  Next: MIME/Body,  Prev: MD5,  Up: Module List

Encode string using base64 encoding
***********************************

NAME
====

encode_base64 - Encode string using base64 encoding

decode_base64 - Decode base64 string

SYNOPSIS
========

     use MIME::Base64;

     $encoded = encode_base64('Aladdin:open sesame');
     $decoded = decode_base64($encoded);

DESCRIPTION
===========

This module provides functions to encode and decode strings into the
Base64 encoding specified in RFC 1521 - *MIME (Multipurpose Internet Mail
Extensions)*. The Base64 encoding is designed to represent arbitrary
sequences of octets in a form that need not be humanly readable. A
65-character subset ([A-Za-z0-9+/=]) of US-ASCII is used, enabling 6 bits
to be represented per printable character.

RFC 1521 says that the encoded bytes must be represented in lines of no
more than 76 characters each.  The second argument to encode_base64() is
the line ending sequence to use. It defaults to `"\n"'.  Use an empty
string as second argument if you do not want the encoded string broken
into lines.

If you prefer not to import these routines into your namespace you can
call them as:

     use MIME::Base64 ();
     $encoded = MIME::Base64::encode('Aladdin:open sesame');
     $decoded = MIME::Base64::decode($encoded);

COPYRIGHT
=========

Copyright 1995, 1996 Gisle Aas.

This library is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

AUTHOR
======

Gisle Aas <aas@sn.no>

Based on LWP::Base64 written by Martijn Koster <m.koster@nexor.co.uk> and
Joerg Reichelt <j.reichelt@nexor.co.uk> and code posted to comp.lang.perl
<3pd2lp$6gf@wsinti07.win.tue.nl> by Hans Mulder <hansm@wsinti07.win.tue.nl>


File: pm.info,  Node: MIME/Body,  Next: MIME/Decoder,  Prev: MIME/Base64,  Up: Module List

the body of a MIME message
**************************

NAME
====

MIME::Body - the body of a MIME message

SYNOPSIS
========

Here's how a typical body object is created and used:

     # Create new body:
     $body = new MIME::Body::File "/path/to/file";
     
     # Write data to the body:
     $IO = $body->open("w")      || die "open body: $!";
     $IO->print($message);
     $IO->close                  || die "close I/O handle: $!";
     
     # Read data from the body:
     $IO = $body->open("r")      || die "open body: $!";
     while (defined($_ = $IO->getline)) {
         # do stuff
     }
     $IO->close                  || die "close I/O handle: $!";

For example, this subclass stores the data in a disk file, which is only
opened when needed:

     $body = new MIME::Body::File "/path/to/file";

While *this* subclass stores the data in an in-core scalar:

     $body = new MIME::Body::Scalar \$scalar;

In any case, once a MIME::Body has been created, you use the same
mechanisms for reading from or writing to it, no matter what the subclass
is.

DESCRIPTION
===========

MIME messages can be very long (e.g., tar files, MPEGs, etc.) or very
short (short textual notes, as in ordinary mail).  Long messages are best
stored in files, while short ones are perhaps best stored in core.

This class is an attempt to define a common interface for objects which
contain that message data, regardless of how the data is physically
stored.  It works this way:

   * *A "body" knows where the data is.*  You can ask to "open" this data
     source for *reading* or *writing*, and you will get back an "I/O
     handle".

   * *An "I/O handle" knows how to read/write the data.* It is an object
     that is basically like an IO::Handle or a FileHandle: it can be any
     class, so long as it supports a small, standard set of methods for
     reading from or writing to the underlying data source.

The lifespan of a "body" usually looks like this:

  1. Body object is created by a MIME::Parser during parsing.  It's at
     this point that the actual MIME::Body subclass is chosen, and new()
     is invoked.  (For example: if the body data is going to a file, then
     it is at this point that the class MIME::Body::File, and the
     filename, is chosen).

  2. Data is written (usually by the MIME parser) like this:

     a. Body is opened for writing, via `open("w")'.     This will trash
     any previous contents, and return an    "I/O handle" opened for
     writing.

     b. Data is written to the I/O handle, via print().

     c. I/O handle is closed, via close().

  3. Data is read (usually by the user application) like this:

     a. Body is opened for reading by a user application, via `open("r")'.
       This will return an "I/O handle" opened for reading.

     b. Data is read from the I/O handle, via read(), getline(), or
     getlines().

     c. I/O handle is closed, via close().

  4. Body object is destructed.

     You can write your own subclasses, as long as they follow the
interface described below.  Implementers of subclasses should assume that
steps 2 and 3 may be repeated any number of times, and in different orders
(e.g., 1-2-2-3-2-3-3-3-3-3-2-4).

Users should be aware that unless they know for certain what they have,
they should not assume that the body has an underlying filehandle.

DEFINING YOUR OWN SUBCLASSES
============================

So you're not happy with files, scalars, and arrays?  No problem: just
define your own MIME::Body subclass, and make a subclass of MIME::Parser
or MIME::ParserBase which returns an instance of your body class whenever
appropriate in the `new_body_for(head)' method.

*Things to make you go hmm:* there's nothing stopping you from writing a
single class that is both a "body" class and an "I/O handle" class for
that body.  Look at *MIME::Body::Scalar* for an example.

Writing a "body" class
----------------------

Your "body" class must inherit from MIME::Body (or some subclass of it),
and it must either provide or inherit the following methods:

init ARGS...
     *Instance method.* This is called automatically by new(), with the
     arguments given to new().  The arguments are optional, and entirely
     up to your class.

open MODE
     *Instance method.* This should do whatever is necessary to open the
     body for either writing (if MODE is "w") or reading (if mode is "r").
     Return an "I/O handle" on success, false on error.

binmode [ONOFF]
     *Instance method.* With argument, flags whether or not open() should
     return an I/O handle which has binmode() activated.  With no
     argument, just returns the current value.  The inherited action
     should be fine.

path
     *Instance method.* Oh, the joys of encapsulation.  If you're storing
     the body data in a new disk file, you'll want to give applications
     the ability to get at that file, if only for cleanup.  This method
     should return the path to the file, or undef if there is none (e.g.,
     if the data is in core).  The default inherited method just returns
     undef.

Writing/using an "I/O handle" class
-----------------------------------

Your "body" class' `open()' method must return an "I/O handle" object,
which can be any object that supports a small set of standard methods for
reading/writing data.

See the documentation on the *MIME::IO* class for details on what is
expected of an I/O handle.  Note that the *IO::Handle* class already
conforms to this interface, as does *MIME::IO*.

NOTES
=====

Design issues
-------------

One reason I didn't just use FileHandle or IO::Handle objects for message
bodies was that I wanted a "body" object to be a form of completely
encapsulated program-persistent storage; that is, I wanted users to be
able to write code like this...

     # Get body handle from this MIME message, and read its data:
     $body = $entity->bodyhandle;
     $IO = $body->open("r");
     while (defined($_ = $IO->getline)) {
         print STDOUT $_;
     }
     $IO->close;

...without requiring that they know anything more about how the $body
object is actually storing its data (disk file, scalar variable, array
variable, or whatever).

Storing the body of each MIME message in a persistently-open IO::Handle
was a possibility, but it seemed like a bad idea, considering that a
single multipart MIME message could easily suck up all the available file
descriptors.  This risk increases if the user application is processing
more than one MIME entity at a time.

SUBCLASSES
==========

MIME::Body::File;
-----------------

A body class that stores the data in a disk file.  The I/O handle is a
wrapped filehandle.  Invoke the constructor as:

     $body = new MIME::Body::File "/path/to/file";

In this case, the path() method would return the given path.

You can even use this class to pipe the data through shell commands on
input and/or output.  For example, here's an easy way to store the data in
compressed format without having to explicitly do the compression yourself:

     $body = new MIME::Body::File "/tmp/somefile.gz";
     $body->writer("| gzip > /tmp/somefile.gz");
     $body->reader("zcat /tmp/somefile.gz |");
     ...
     $IO = $body->open("w")  || die "open failed: $!";
     $IO->print("I'll automatically be stored compressed!\n");
     $IO->close              || die "close failed: $!";

Notice the semantics of the "path" in this case: it names the file that is
created to hold the data, even though that file can't be used directly.

*Note:* All of the usual caveats related to shell commands apply!  To make
sure you won't accidentally do something you'll regret, use taint-checking
(*perl -T*) in your application.

MIME::Body::Scalar;
-------------------

A body class that stores the data in-core, in a simple scalar.  Invoke the
constructor as:

     $body = new MIME::Body::Scalar \$scalar;

A single scalar argument sets the body to that value, exactly as though
you'd opened for the body for writing, written the value, and closed the
body again:

$body = new MIME::Body::Scalar "Line 1\nLine 2\nLine 3";

A single array reference sets the body to the result of joining all the
elements of that array together:

     $body = new MIME::Body::Scalar ["Line 1\n",
                                     "Line 2\n",
                                     "Line 3"];

Uses MIME::IO::Scalar as the I/O handle.

AUTHOR
======

Copyright (c) 1996 by Eryq / eryq@rhine.gsfc.nasa.gov

All rights reserved.  This program is free software; you can redistribute
it and/or modify it under the same terms as Perl itself.

Thanks to Achim Bohnet for suggesting that MIME::Parser not be restricted
to the use of FileHandles.

VERSION
=======

$Revision: 1.9 $ $Date: 1996/10/28 06:51:47 $


File: pm.info,  Node: MIME/Decoder,  Next: MIME/Entity,  Prev: MIME/Body,  Up: Module List

an object for decoding the body part of a MIME stream
*****************************************************

NAME
====

MIME::Decoder - an object for decoding the body part of a MIME stream

SYNOPSIS
========

*Decoding a data stream.* Here's a simple filter program to read
quoted-printable data from STDIN (until EOF) and write the decoded data to
STDOUT:

     use MIME::Decoder;
     
     $decoder = new MIME::Decoder 'quoted-printable' or die "unsupported";
     $decoder->decode(\*STDIN, \*STDOUT);

*Encoding a data stream.* Here's a simple filter program to read binary
data from STDIN (until EOF) and write base64-encoded data to STDOUT:

     use MIME::Decoder;
     
     $decoder = new MIME::Decoder 'base64' or die "unsupported";
     $decoder->encode(\*STDIN, \*STDOUT);

You can *write and install your own decoders* so that MIME::Decoder will
know about them:

     use MyBase64Decoder;
     
     install MyBase64Decoder 'base64';

You can also *test if an encoding is supported:*

     if (MIME::Decoder->supported('x-uuencode')) {
         # we can uuencode!
     }

DESCRIPTION
===========

This abstract class, and its private concrete subclasses (see below)
provide an OO front end to the actions of...

   * Decoding a MIME-encoded stream

   * Encoding a raw data stream into a MIME-encoded stream.

The constructor for MIME::Decoder takes the name of an encoding (`base64',
`7bit', etc.), and returns an instance of a *subclass* of MIME::Decoder
whose `decode()' method will perform the appropriate decoding action, and
whose `encode()' method will perform the appropriate encoding action.

PUBLIC INTERFACE
================

Standard interface
------------------

If all you are doing is *using* this class, here's all you'll need...

new ENCODING
     *Class method*.  Create and return a new decoder object which can
     handle the given ENCODING.

          my $decoder = new MIME::Decoder "7bit";

     Returns the undefined value if no known decoders are appropriate.

decode INSTREAM,OUTSTREAM
     Decode the document waiting in the input handle INSTREAM, writing the
     decoded information to the output handle OUTSTREAM.

     Read the section in this document on I/O handles for more information
     about the arguments.  Note that you can still supply old-style
     unblessed filehandles for INSTREAM and OUTSTREAM.

encode INSTREAM,OUTSTREAM
     Encode the document waiting in the input filehandle INSTREAM, writing
     the encoded information to the output stream OUTSTREAM.

     Read the section in this document on I/O handles for more information
     about the arguments.  Note that you can still supply old-style
     unblessed filehandles for INSTREAM and OUTSTREAM.

encoding
     Return the encoding that this object was created to handle, coerced
     to all lowercase (e.g., `"base64"').

supported [ENCODING]
     *Class method*.  With one arg (an ENCODING name), returns truth if
     that encoding is currently handled, and falsity otherwise.  The
     ENCODING will be automatically coerced to lowercase:

          if (MIME::Decoder->supported('7BIT')) {
              # yes, we can handle it...
          }
          else {
              # drop back six and punt...
          }

     With no args, returns all the available decoders as a hash
     reference...  where the key is the encoding name (all lowercase, like
     '7bit'), and the associated value is true (it happens to be the name
     of the class that handles the decoding, but you probably shouldn't
     rely on that).  Hence:

          my $supported = MIME::Decoder->supported;
          if ($supported->{7bit}) {
              # yes, we can handle it...
          }
          elsif ($supported->{8bit}) {
              # yes, we can handle it...
          }

     You may safely modify this hash; it will *not* change the way the
     module performs its lookups.  Only install can do that.

     *Thanks to Achim Bohnet for suggesting this method.*

Subclass interface
------------------

If you are writing (or installing) a new decoder subclass, there are some
other methods you'll need to know about:

decode_it INSTREAM,OUTSTREAM
     *Abstract instance method*.  The back-end of the decode method.  It
     takes an input handle opened for reading (INSTREAM), and an output
     handle opened for writing (OUTSTREAM).

     If you are writing your own decoder subclass, you must override this
     method in your class.  Your method should read from the input handle
     via `getline()' or `read()', decode this input, and print the decoded
     data to the output handle via `print()'.  You may do this however you
     see fit, so long as the end result is the same.

     Note that unblessed references and globrefs are automatically turned
     into I/O handles for you by `decode()', so you don't need to worry
     about it.

     Your method must return either undef (to indicate failure), or 1 (to
     indicate success).

encode_it INSTREAM,OUTSTREAM
     *Abstract instance method*.  The back-end of the encode method.  It
     takes an input handle opened for reading (INSTREAM), and an output
     handle opened for writing (OUTSTREAM).

     If you are writing your own decoder subclass, you must override this
     method in your class.  Your method should read from the input handle
     via `getline()' or `read()', encode this input, and print the encoded
     data to the output handle via `print()'.  You may do this however you
     see fit, so long as the end result is the same.

     Note that unblessed references and globrefs are automatically turned
     into I/O handles for you by `encode()', so you don't need to worry
     about it.

     Your method must return either undef (to indicate failure), or 1 (to
     indicate success).

init ARGS...
     *Instance method*.  Do any necessary initialization of the new
     instance, taking whatever arguments were given to new().  Should
     return the self object on success, undef on failure.

install ENCODING
     *Class method*.  Install this class so that ENCODING is handled by it.
     You should not override this method.

BUILT-IN DECODER SUBCLASSES
===========================

You don't need to "use" any other Perl modules; the following are included
as part of MIME::Decoder.

MIME::Decoder::Base64
---------------------

The built-in decoder for the `"base64"' encoding.

The name was chosen to jibe with the pre-existing MIME::Base64 utility
package, which this class actually uses to translate each line.

When *decoding*, the input is read one line at a time.  The input
accumulates in an internal buffer, which is decoded in multiple-of-4-sized
chunks (plus a possible "leftover" input chunk, of course).

When encoding, the input is read 45 bytes at a time: this ensures that the
output lines are not too long.   We chose 45 since it is a multiple of 3
and produces lines under 76 characters, as RFC-1521 specifies.

*Thanks to Phil Abercrombie for locating one idiotic bug in this module,
which led me to discover another.*

MIME::Decoder::Binary
---------------------

The built-in decoder for a `"binary"' encoding (in other words, no
encoding).

The `"binary"' decoder is a special case, since it's ill-advised to read
the input line-by-line: after all, an uncompressed image file might
conceivably have loooooooooong stretches of bytes without a `"\n"' among
them, and we don't want to risk blowing out our core.  So, we
read-and-write fixed-size chunks.

Both the *encoder* and *decoder* do a simple pass-through of the data from
input to output.

MIME::Decoder::QuotedPrint
--------------------------

The built-in decoder the for `"quoted-printable"' encoding.

The name was chosen to jibe with the pre-existing MIME::QuotedPrint
utility package, which this class actually uses to translate each line.

The *decoder* does a line-by-line translation from input to output.

The *encoder* does a line-by-line translation, breaking lines so that they
fall under the standard 76-character limit for this encoding.

*Note:* just like MIME::QuotedPrint, we currently use the native `"\n"'
for line breaks, and not `CRLF'.  This may need to change in future
versions.

MIME::Decoder::Xbit
-------------------

The built-in decoder for both `"7bit"' and `"8bit"' encodings, which
guarantee short lines (a maximum of 1000 characters per line) of US-ASCII
data compatible with RFC-821.

The *decoder* does a line-by-line pass-through from input to output,
leaving the data unchanged *except* that an end-of-line sequence of CRLF
is converted to a newline "\n".

The *encoder* does a line-by-line pass-through from input to output,
splitting long lines if necessary.  If created as a 7-bit encoder, any
8-bit characters are mapped to zero or more 7-bit characters: note that
this is a potentially *lossy* encoding if you hand it anything but 7-bit
input: therefore, don't use it on binary files (GIFs) and the like; use it
only when it "doesn't matter" if extra newlines are inserted and 8-bit
characters are squished.

There are several possible ways to use this class to encode arbitrary
8-bit text as 7-bit text:

Don't use this class.
     Really.  Use a more-appropriate encoding, like quoted-printable.

APPROX
     Approximate the appearance of the Latin-1 character via Internet
     conventions; e.g., `"\c,"', `"\n~"', etc.  This is the default
     behavior of this class.

CLEARBIT8
     Just clear the 8th bit.  Yuck.  Sort of a sledgehammer approach.  Not
     recommended at all.

ENTITY
     Output as an HTML-style entity; e.g., `"&'`#189;"'.  This sounds like
     a good idea, until you see some French text which is actually encoded
     this way... yuck.  You're better off with quoted-printable.

STRIP
     Strip out any 8-bit characters.  Nice if you're *really* sure that any
     such characters in your input are mistakes to be deleted, but it'll
     transform non-English documents into an abbreviated mess.

NOTES
=====

Input/Output handles
--------------------

As of MIME-tools 2.0, this class has to play nice with the new MIME::Body
class... which means that input and output routines cannot just assume that
they are dealing with filehandles.

Therefore, all that MIME::Decoder and its subclasses require (and, thus,
all that they can assume) is that INSTREAMs and OUTSTREAMs are objects
which respond to the messages defined in *MIME::IO* (basically, a subset
of those defined by IO::Handle).

For backwards compatibilty, if you supply a scalar filehandle name (like
`"STDOUT"') or an unblessed glob reference (like `\*STDOUT') where an
INSTREAM or OUTSTREAM is expected, this package will automatically wrap it
in an object that fits the I/O handle criteria.

*Thanks to Achim Bohnet for suggesting this more-generic I/O model.*

Writing a decoder
-----------------

If you're experimenting with your own encodings, you'll probably want to
write a decoder.  Here are the basics:

  1. Create a module, like "MyDecoder::", for your decoder.  Declare it to
     be a subclass of MIME::Decoder.

  2. Create the following instance methods in your class, as described
     above:

          decode_it
          encode_it
          init

  3. In your application program, activate your decoder for one or more
     encodings like this:

          require MyDecoder;

          install MyDecoder "7bit";        # use MyDecoder to decode "7bit"
          install MyDecoder "x-foo";       # also, use MyDecoder to decode "x-foo"

     To illustrate, here's a custom decoder class for the
`quoted-printable' encoding:

     package MyQPDecoder;

     @ISA = qw(MIME::Decoder);
     use MIME::Decoder;
     use MIME::QuotedPrint;
     
     # decode_it - the private decoding method
     sub decode_it {
         my ($self, $in, $out) = @_;
     
         while (defined($_ = $in->getline())) {
             my $decoded = decode_qp($_);
     	    $out->print($decoded);
         }
         1;
     }
     
     # encode_it - the private encoding method
     sub encode_it {
         my ($self, $in, $out) = @_;
     
         my ($buf, $nread) = ('', 0);
         while ($in->read($buf, 60)) {
             my $encoded = encode_qp($buf);
     	    $out->print($encoded);
         }
         1;
     }

That's it.

The task was pretty simple because the `"quoted-printable"' encoding can
easily be converted line-by-line... as can even `"7bit"' and `"8bit"'
(since all these encodings guarantee short lines, with a max of 1000
characters).  The good news is: it is very likely that it will be
similarly-easy to write a MIME::Decoder for any future standard encodings.

The `"binary"' decoder, however, really required block reads and writes:
see `"MIME::Decoder::Binary"' in this node for details.

SEE ALSO
========

MIME::Decoder, MIME::Entity, MIME::Head, MIME::Parser.

AUTHOR
======

Copyright (c) 1996 by Eryq / eryq@rhine.gsfc.nasa.gov

All rights reserved.  This program is free software; you can redistribute
it and/or modify it under the same terms as Perl itself.

VERSION
=======

$Revision: 2.7 $ $Date: 1996/10/23 17:03:49 $


File: pm.info,  Node: MIME/Entity,  Next: MIME/Field/ConTraEnc,  Prev: MIME/Decoder,  Up: Module List

class for parsed-and-decoded MIME message
*****************************************

NAME
====

MIME::Entity - class for parsed-and-decoded MIME message

SYNOPSIS
========

Create a MIME entity from an array, and output it as a MIME stream to
STDOUT:

     $ent = new MIME::Entity [
     			  "Subject: Greetings\n",
     			  "Content-type: text/plain\n",
     			  "Content-transfer-encoding: 7bit\n",
     			  "\n",
     			  "Hi there!\n",
     			  "Bye there!\n"
         		  ];
     $ent->print(\*STDOUT);

Create a document for an ordinary 7-bit ASCII text file (lots of stuff is
defaulted for us):

     $ent = build MIME::Entity Path=>"english-msg.txt";

Create a document for a text file with 8-bit (Latin-1) characters:

     $ent = build MIME::Entity Path     =>"french-msg.txt",
                               Encoding =>"quoted-printable";

Create a document for a GIF file (the description is completely optional,
and note that we have to specify content-type and encoding since they're
not the default values):

     $ent = build MIME::Entity Description => "A pretty picture",
                               Path        => "./docs/mime-sm.gif",
                               Type        => "image/gif",
                               Encoding    => "base64";

Create a document that you already have the text for:

     $ent = build MIME::Entity  Type        => "text/plain",
                                Encoding    => "quoted-printable",
                                Data        => [
                                      "First line.\n",
                                      "Second line.\n",
                                      "Last line.\n",
                                ];

Create a multipart message (could it *be* much easier?)

     # Create the top-level, and set up the mail headers:
     $top = build MIME::Entity Type=>"multipart/mixed";
     $top->head->add('from',    "me\@myhost.com");
     $top->head->add('to',      "you\@yourhost.com");
     $top->head->add('subject', "Hello, nurse!");
     
     # Attachment #1: a simple text document:
     attach $top  Path=>"./testin/short.txt";
     
     # Attachment #2: a GIF file:
     attach $top  Path        => "./docs/mime-sm.gif",
                  Type        => "image/gif",
                  Encoding    => "base64";
     
     # Attachment #3: text we'll create with text we have on-hand:
     attach $top Data=>$contents;
     
     # Output!
     $top->print(\*STDOUT);

Extract information from MIME entities:

     # Get the head, a MIME::Head:
     $head = $ent->head;
     
     # Get the body, as a MIME::Body;
     $bodyh = $ent->bodyhandle;

See MIME::Parser for additional examples of usage.

DESCRIPTION
===========

A subclass of *Mail::Internet*.

This package provides a class for representing MIME message entities, as
specified in RFC 1521, *Multipurpose Internet Mail Extensions*.

Here are some excerpts from RFC-1521 explaining the terminology: each is
accompanied by the equivalent in MIME:: terms:

Message
     From RFC-1521:

          The term "message", when not further qualified, means either the
          (complete or "top-level") message being transferred on a network, or
          a message encapsulated in a body of type "message".

     There currently is no explicit package for messages; under MIME::,
     messages may be read in from readable files or filehandles.  A future
     extension will allow them to be read from any object reference that
     responds to a special "next line" method.

Body part
     From RFC-1521:

          The term "body part", in this document, means one of the parts of the
          body of a multipart entity. A body part has a header and a body, so
          it makes sense to speak about the body of a body part.

     Since a body part is just a kind of entity (see below), a body part
     is represented by an instance of MIME::Entity.

Entity
     From RFC-1521:

          The term "entity", in this document, means either a message or a body
          part.  All kinds of entities share the property that they have a
          header and a body.

     An entity is represented by an instance of MIME::Entity.  There are
     instance methods for recovering the header (a MIME::Head) and the
     body (see below).

Body
     From RFC-1521:

          The term "body", when not further qualified, means the body of an
          entity, that is the body of either a message or of a body part.

     Well, this is a toughie.  Both Mail::Internet (1.17) and Mail::MIME
     (1.03) represent message bodies in-core; unfortunately, this is not
     always the best way to handle things, especially for MIME streams
     that contain multi-megabyte tar files.

PUBLIC INTERFACE
================

Constructors and converters
---------------------------

new [SOURCE]
     *Class method.* Create a new, empty MIME entity.  Basically, this
     uses the Mail::Internet constructor...

     If SOURCE is an ARRAYREF, it is assumed to be an array of lines that
     will be used to create both the header and an in-core body.

     Else, if SOURCE is defined, it is assumed to be a filehandle from
     which the header and in-core body is to be read.

     *Note:* in either case, the body will not be *parsed:* merely read!

build PARAMHASH
     *Class/instance method.* A quick-and-easy catch-all way to create an
     entity.  Use it like this to build a "normal" single-part entity:

          $ent = build MIME::Entity Type     => "image/gif",
          		             Encoding => "base64",
                                    Path     => "/path/to/xyz12345.gif",
                                    Filename => "saveme.gif";

     And like this to build a "multipart" entity:

          $ent = build MIME::Entity Type     => "multipart/mixed",
                                    Boundary => "---1234567";

     A minimal MIME header will be created.  The params are:

    Boundary
          *Multipart entities only. Optional.* The boundary string.  If
          you omit this, a random string will be chosen... which is
          probably safer.

    Data
          *Single-part entities only. Optional.* An alternative to Path
          (q.v.): the actual data, either as a scalar or an array
          reference (whose elements are joined together to make the actual
          scalar).  The body is opened on the data using
          MIME::Body::Scalar.

    Description
          *Optional.* The text of the content-description.  If you don't
          specify it, the field is not put in the header.

    Encoding
          *Optional.* The content-transfer-encoding.  If you don't specify
          it, the field is not put in the header...  which means that the
          encoding implicitly defaults to `"7bit"' as per RFC-1521.  *Do
          yourself a favor: put it in.*

    Filename
          *Single-part entities only. Optional.* The recommended filename.
          Overrides any name extracted from Path.  The information is
          stored both the deprecated (content-type) and preferred
          (content-disposition) locations.

    Path
          *Single-part entities only. Optional.* The path to the file to
          attach.  The body is opened on that file using MIME::Body::File.

    Top
          *Optional.* Is this a top-level entity?  If so, it must sport a
          MIME-Version.  The default is true.

    Type
          *Optional.* The content-type.  If you don't specify it, it
          defaults to `"text/plain"' as per RFC-1521.  *Do yourself a
          favor: put it in.*

Instance methods
----------------

add_part ENTITY
     Assuming we are a multipart message, add a body part (a MIME::Entity)
     to the array of body parts.  Do *not* call this for single-part
     messages; i.e., don't call it unless the header has a `"multipart"'
     content-type.

     Returns the part that was just added.

attach PARAMHASH
     The real quick-and-easy way to create multipart messages.  Basically
     equivalent to:

          $entity->add_part(ref($entity)->build(PARAMHASH));

     Except that it's a lot nicer to look at.

body [VALUE]
    *If emulating version 1.x:*
          Get or set the path to the file containing the body.

          If `VALUE' *is not* given, the current body file is returned.
          If `VALUE' *is* given, the body file is set to the new value,
          and the previous value is returned.

    Otherwise:
          Get or set the body, as an array of lines.  This should be
          regarded as a read-only data structure: changing its contents
          will have unpredictable results (you can, of course, make your
          own copy, and work with that).

          Provided for compatibility with Mail::Internet, and it might not
          be as efficient as you'd like.  Also, it's somewhat
          silly/wrongheaded for binary bodies, like GIFs and tar files.

     Both forms are deprecated for MIME entities: instead, use the
     bodyhandle() method to get and use a MIME::Body.  The content-type of
     the entity will tell you whether that body is best read as text (via
     getline()) or raw data (via read()).

bodyhandle [VALUE]
     Get or set an abstract object representing the body.

     If `VALUE' *is not* given, the current bodyhandle is returned.  If
     `VALUE' *is* given, the bodyhandle is set to the new value, and the
     previous value is returned.

dump_skeleton [FILEHANDLE]
     Dump the skeleton of the entity to the given FILEHANDLE, or to the
     currently-selected one if none given.  This is really just useful for
     debugging purposes.

head [VALUE]
     Get/set the head.

     If there is no VALUE given, returns the current head.  If none
     exists, an empty instance of MIME::Head is created, set, and returned.

     *Note:* This is a patch over a bug in Mail::Internet, which doesn't
     provide a method for setting the head to some given object.

is_multipart
     Does this entity's MIME type indicate that it's a multipart entity?
     Returns undef (false) if the answer couldn't be determined, 0 (false)
     if it was determined to be false, and true otherwise.

     Note that this says nothing about whether or not parts were extracted.

mime_type
     A purely-for-convenience method.  This simply relays the request to
     the associated MIME::Head object.  The following are identical:

          $x = $entity->mime_type;
          
          $x = $entity->head->mime_type;

     If there is no head, returns undef in a scalar context and the empty
     array in a list context.

     Note that, while parsed entities still have MIME types, they do not
     have MIME encodings, or MIME versions, or fields, etc., etc...  for
     those attributes, you still have to go to the head explicitly.

parts
     Return an array of all sub parts (each of which is a MIME::Entity),
     or the empty array if there are none.

     For single-part messages, the empty array will be returned.  For
     multipart messages, the preamble and epilogue parts are *not* in the
     list!

     Note that in a scalar context, this returns you the number of parts.

print [FILEHANDLE]
     *Instance method, override.* Print the entity to the given
     FILEHANDLE, or to the currently-selected one if none given.

     *If a single-part entity,* the header and the body are both output,
     with the body being output according to the encoding specified by the
     header.

     *If a multipart entity,* this is invoked recursively on all its
     parts, with appropriate boundaries and a preamble generated for you.

     See `print_body()' for an important note on how the body is output.

print_body [FILEHANDLE]
     *Instance method, override.* Print the body of the entity to the
     given FILEHANDLE, or to the currently-selected one if none given.

     *Important note:* the body is output according to the encoding
     specified by  the header (`'binary'' if no encoding given).  This
     means that the following code:

          $ent = new MIME::Entity ["Subject: Greetings\n",
          			     "Content-transfer-encoding: base64\n",
          			     "\n",
          			     "Hi there!\n",
          			     "Bye there!\n"
          			     ];
          $ent->print;   # uses print_body() internally

     Prints this:

          Subject: Greetings
          Content-transfer-encoding: base64

          SGkgdGhlcmUhCkJ5ZSB0aGVyZSEK

     The body is *stored* in an unencoded form; however, the idea is that
     the transfer encoding is used to determine how it should be *output.*
     This means that the `print()' method is always guaranteed to get you
     a sendmail-ready stream whose body is consistent with its head.

     If you want the raw body data to be output, you can either read it
     from the bodyhandle yourself, or use:

          $ent->bodyhandle->print;

     which uses read() calls to extract the information, and thus will
     work with both text and binary bodies.

NOTES
=====

Under the hood
--------------

A *MIME::Entity* is composed of the following elements:

   * A head, which is a reference to a MIME::Head object containing the
     header information.

   * A bodyhandle, which is a reference a MIME::Body object containing the
     decoded body data.  (In pre-2.0 releases, this was accessed via body,
     which was a path to a file containing the decoded body.  Integration
     with Mail::Internet has forced this to change.)

   * A list of zero or more parts, each of which is a MIME::Entity object.
     The number of parts will only be nonzero if the content-type is some
     subtype of `"multipart"'.

     Note that, in 2.0+, a multipart entity does *not* have a body.  Of
     course, any/all of its component parts can have bodies.

Design issues
-------------

Some things just can't be ignored
     In multipart messages, the *"preamble"* is the portion that precedes
     the first encapsulation boundary, and the *"epilogue"* is the portion
     that follows the last encapsulation boundary.

     According to RFC-1521:

          There appears to be room for additional information prior to the
          first encapsulation boundary and following the final boundary.  These
          areas should generally be left blank, and implementations must ignore
          anything that appears before the first boundary or after the last one.

          NOTE: These "preamble" and "epilogue" areas are generally not used
          because of the lack of proper typing of these parts and the lack
          of clear semantics for handling these areas at gateways,
          particularly X.400 gateways.  However, rather than leaving the
          preamble area blank, many MIME implementations have found this to
          be a convenient place to insert an explanatory note for recipients
          who read the message with pre-MIME software, since such notes will
          be ignored by MIME-compliant software.

     In the world of standards-and-practices, that's the standard.  Now
     for the practice:

     *Some "MIME" mailers may incorrectly put a "part" in the preamble*.
     Since we have to parse over the stuff *anyway*, in the future I *may*
     allow the parser option of creating special MIME::Entity objects for
     the preamble and epilogue, with bogus MIME::Head objects.

     For now, though, we're MIME-compliant, so I probably won't change how
     we work.

SEE ALSO
========

MIME::Decoder, MIME::Entity, MIME::Head, MIME::Parser.

AUTHOR
======

Copyright (c) 1996 by Eryq / eryq@rhine.gsfc.nasa.gov

All rights reserved.  This program is free software; you can redistribute
it and/or modify it under the same terms as Perl itself.

VERSION
=======

$Revision: 2.8 $ $Date: 1996/11/03 00:19:30 $


File: pm.info,  Node: MIME/Field/ConTraEnc,  Next: MIME/Field/ContDisp,  Prev: MIME/Entity,  Up: Module List

a "Content-transfer-encoding" field
***********************************

NAME
====

MIME::Field::ConTraEnc - a "Content-transfer-encoding" field

DESCRIPTION
===========

A subclass of Mail::Field.

*Don't use this class directly... its name may change in the future!*
Instead, ask Mail::Field for new instances based on the field name!

SYNOPSIS
========

     use Mail::Field;
     use MIME::Head;
     
     # Create an instance from some text:
     $field = Mail::Field->new('Content-transfer-encoding', '7bit');
     
     # Get the encoding.
     #    Possible values: 'binary', '7bit', '8bit', 'quoted-printable',
     #    'base64' and '' (unspecified).  Note that there can't be a
     #    single default for this, since it depends on the content type!
     $encoding = $field->encoding;


File: pm.info,  Node: MIME/Field/ContDisp,  Next: MIME/Field/ContType,  Prev: MIME/Field/ConTraEnc,  Up: Module List

a "Content-disposition" field
*****************************

NAME
====

MIME::Field::ContDisp - a "Content-disposition" field

DESCRIPTION
===========

A subclass of Mail::Field.

*Don't use this class directly... its name may change in the future!*
Instead, ask Mail::Field for new instances based on the field name!

SYNOPSIS
========

     use Mail::Field;
     use MIME::Head;
     
     # Create an instance from some text:
     $field = Mail::Field->new('Content-disposition', $text);
     
     # Inline or attachment?
     $type = $field->type;
     
     # Recommended filename?
     $filename = $field->filename;


File: pm.info,  Node: MIME/Field/ContType,  Next: MIME/Field/ParamVal,  Prev: MIME/Field/ContDisp,  Up: Module List

a "Content-type" field
**********************

NAME
====

MIME::Field::ContType - a "Content-type" field

DESCRIPTION
===========

A subclass of Mail::Field.

*Don't use this class directly... its name may change in the future!*
Instead, ask Mail::Field for new instances based on the field name!

SYNOPSIS
========

     use Mail::Field;
     use MIME::Head;
     
     # Create an instance from some text:
     $field = Mail::Field->new('Content-type',
                               'text/HTML; charset="US-ASCII"');
     
     # Get the MIME type, like 'text/plain' or 'x-foobar'.
     # Returns 'text/plain' as default, as per RFC-1521:
     my ($type, $subtype) = split('/', $field->type);

     # Get generic information:
     print $field->name;
     
     # Get information related to "message" type:
     if ($type eq 'message') {
     	print $field->id;
     	print $field->number;
     	print $field->total;
     }
     
     # Get information related to "multipart" type:
     if ($type eq 'multipart') {
     	print $field->boundary;            # the basic value, fixed up
     	print $field->multipart_boundary;  # empty if not a multipart message!
     }
     
     # Get information related to "text" type:
     if ($type eq 'text') {
     	print $field->charset;      # returns 'us-ascii' as default
     }

NOTES
=====

Since nearly all (if not all) parameters must have non-empty values to be
considered valid, we just return the empty string to signify missing
fields.  If you need to get the *real* underlying value, use the inherited
`param()' method (which returns undef if the parameter is missing).

PUBLIC INTERFACE
================

boundary
     Return the boundary field.  The boundary is returned exactly as given
     in the `Content-type:' field; that is, the leading double-hyphen
     (`--') is *not* prepended.

     (Well, *almost* exactly... from RFC-1521:

          (If a boundary appears to end with white space, the white space
          must be presumed to have been added by a gateway, and must be deleted.)

     so we oblige and remove any trailing spaces.)

     Returns the empty string if there is no boundary, or if the boundary
     is illegal (e.g., if it is empty after all trailing whitespace has
     been removed).

multipart_boundary
     Like `boundary()', except that this will also return the empty string
     if the message is not a multipart message.  In other words, there's
     an automatic sanity check.

type
     Try real hard to determine the content type (e.g., `"text/plain"',
     `"image/gif"', `"x-weird-type"', which is returned in all-lowercase.

     A happy thing: the following code will work just as you would want,
     even if there's no subtype (as in `"x-weird-type"')... in such a case,
     the $subtype would simply be the empty string:

          ($type, $subtype) = split('/', $head->mime_type);

     If the content-type information is missing, it defaults to
     `"text/plain"', as per RFC-1521:

          Default RFC-822 messages are typed by this protocol as plain text in
          the US-ASCII character set, which can be explicitly specified as
          "Content-type: text/plain; charset=us-ascii".  If no Content-Type is
          specified, this default is assumed.

     If *just* the subtype is missing (a syntax error unless the type
     begins with `"x-"', but we'll tolerate it, since some brain-dead
     mailers actually do this), then it simply is not reported; e.g.,
     `"Content-type: TEXT"' is returned simply as `"text"'.

     If the content type is present but can't be parsed at all (yow!), the
     empty string is returned.


File: pm.info,  Node: MIME/Field/ParamVal,  Next: MIME/Head,  Prev: MIME/Field/ContType,  Up: Module List

subclass of Mail::Field, for structured MIME fields
***************************************************

NAME
====

MIME::Field::ParamVal - subclass of Mail::Field, for structured MIME fields

DESCRIPTION
===========

This is an abstract superclass of most MIME fields.  It handles fields
with a general syntax like this:

     Content-Type: Message/Partial;
         number=2; total=3;
         id="oc=jpbe0M2Yt4s@thumper.bellcore.com"

Comments are supported *between* items, like this:

     Content-Type: Message/Partial; (a comment)
         number=2  (another comment) ; (yet another comment) total=3;
         id="oc=jpbe0M2Yt4s@thumper.bellcore.com"

PUBLIC INTERFACE
================

set [\%PARAMHASH | KEY=>VAL,...,KEY=>VAL]
     Set this field.  The paramhash should contain parameter names in *all
     lowercase*, with the special `"_"' parameter name signifying the
     "default" (unnamed) parameter for the field:

          # Set up to be...
          #
          #     Content-type: Message/Partial; number=2; total=3; id="ocj=pbe0M2"
          #
          $conttype->set('_'       => 'Message/Partial',
          		  'number'  => 2,
          		  'total'   => 3,
          		  'id'      => "ocj=pbe0M2");

     Note that a single argument is taken to be a *reference* to a
     paramhash, while multiple args are taken to be the elements of the
     paramhash themselves.

     Supplying undef for a hashref, or an empty set of values, effectively
     clears the object.

     The self object is returned.

parse_params STRING
     *Class/instance utility method.* Extract parameter info from a
     structured field, and return it as a hash reference.  For example,
     here is a field with parameters:

          Content-Type: Message/Partial;
              number=2; total=3;
              id="oc=jpbe0M2Yt4s@thumper.bellcore.com"

     Here is how you'd extract them:

          $params = $class->parse_params('content-type');
          if ($$params{'_'} eq 'message/partial') {
              $number = $$params{'number'};
              $total  = $$params{'total'};
              $id     = $$params{'id'};
          }

     Like field names, parameter names are coerced to lowercase.  The
     special '_' parameter means the default parameter for the field.

     *NOTE:* This has been provided as a public method to support backwards
     compatibility, but you probably shouldn't use it.

parse STRING
     Parse the string into the instance.  Any previous information is
     wiped.

     The self object is returned.

param PARAMNAME,[VALUE]
     Return the given parameter, or undef if it isn't there.  With
     argument, set the parameter to that VALUE.  The PARAMNAME is
     case-insensitive.  A "_" refers to the "default" parameter.

stringify
     Convert the field to a string, and return it.

tag
     Return the tag for this field.  Abstract!


File: pm.info,  Node: MIME/Head,  Next: MIME/IO,  Prev: MIME/Field/ParamVal,  Up: Module List

MIME message header (a subclass of Mail::Header)
************************************************

NAME
====

MIME::Head - MIME message header (a subclass of Mail::Header)

SYNOPSIS
========

Start off by requiring or using this package:

     require MIME::Head;

You can create a MIME::Head object in a number of ways:

     # Create a new, empty header, and populate it manually:
     $head = MIME::Head->new;
     $head->set('content-type', 'text/plain; charset=US-ASCII');
     $head->set('content-length', $len);
     
     # Create a new header by parsing in the STDIN stream:
     $head = MIME::Head->read(\*STDIN);
     
     # Create a new header by parsing in a file:
     $head = MIME::Head->from_file("/tmp/test.hdr");
     
     # Create a new header by running a program:
     $head = MIME::Head->from_file("cat a.hdr b.hdr |");

To get rid of all internal newlines in all fields (called *unfolding*):

     # Get rid of all internal newlines:
     $head->unfold();

To test whether a given field exists:

     # Was a "Subject:" given?
     if ($head->exists('subject')) {
         # yes, it does!
     }

To *get the contents of a field,* either a *specific* occurence (defaults
to the first occurence in a scalar context) or all occurences (in an array
context):

     # Is this a reply?
     $reply = 1 if ($head->get('Subject') =~ /^Re: /);
     
     # Get receipt information:
     print "Last received from: ", $head->get('Received', 0), "\n";
     @all_received = $head->get('Received');

To *get the first occurence* of a field as a string, regardless of context:

     # Print the subject, or the empty string if none:
     print "Subject: ", $head->get('Subject',0), "\n";

To *get all occurences* of a field as an array, regardless of context:

     # Too many hops?  Count 'em and see!
     if (int($head->get_all('Received')) > 5) { ...

To *set a field* to a given string:

     # Declare this to be an HTML header:
     $head->replace('Content-type', 'text/html');

To get certain commonly-used *MIME information*:

     # The content type (e.g., "text/html"):
     $mime_type     = $head->mime_type;
     
     # The content transfer encoding (e.g., "quoted-printable"):
     $mime_encoding = $head->mime_encoding;
     
     # The recommended filename (e.g., "choosy-moms-choose.gif"):
     $file_name     = $head->recommended_filename;
     
     # The boundary text, for multipart messages:
     $boundary      = $head->multipart_boundary;

DESCRIPTION
===========

A class for parsing in and manipulating RFC-822 message headers, with some
methods geared towards standard (and not so standard) MIME fields as
specified in RFC-1521, *Multipurpose Internet Mail Extensions*.

PUBLIC INTERFACE
================

Creation, input, and output
---------------------------

new [ARG],[OPTIONS]
     *Class method.* *Inherited.* Creates a new header object.  Arguments
     are the same as those in the superclass.

from_file EXPR,OPTIONS
     *Class or instance method*.  For convenience, you can use this to
     parse a header object in from EXPR, which may actually be any
     expression that can be sent to open() so as to return a readable
     filehandle.  The "file" will be opened, read, and then closed:

          # Create a new header by parsing in a file:
          my $head = MIME::Head->from_file("/tmp/test.hdr");

     Since this method can function as either a class constructor *or* an
     instance initializer, the above is exactly equivalent to:

          # Create a new header by parsing in a file:
          my $head = MIME::Head->new->from_file("/tmp/test.hdr");

     On success, the object will be returned; on failure, the undefined
     value.

     The OPTIONS are the same as in new(), and are passed into new() if
     this is invoked as a class method.

     *NOTE:* This is really just a convenience front-end onto `read()',
     provided mostly for backwards-compatibility with MIME-parser 1.0.

read FILEHANDLE
     *Instance (or class) method.* This initiallizes a header object by
     reading it in from a FILEHANDLE, until the terminating blank line is
     encountered.  A syntax error or end-of-stream will also halt
     processing.

     Supply this routine with a reference to a filehandle glob; e.g.,
     `\*STDIN':

          # Create a new header by parsing in STDIN:
          $head->read(\*STDIN);

     On success, the self object will be returned; on failure, a false
     value.

     *Note:* in the MIME world, it is perfectly legal for a header to be
     empty, consisting of nothing but the terminating blank line.  Thus,
     we can't just use the formula that "no tags equals error".

     Warning: as of the time of this writing, Mail::Header::read did not
     flag either syntax errors or unexpected end-of-file conditions (an EOF
     before the terminating blank line).  MIME::ParserBase takes this into
     account.

Getting/setting fields
----------------------

*NOTE:* this interface is not as extensive as that of Mail::Internet;
however, I have provided a set of methods that I can guarantee are
supportable across any changes to the internal implementation of this
class.

add TAG,TEXT,[INDEX]
     *Inherited.* Add a new occurence of the field named TAG, given by
     TEXT:

          # Add the trace information:
          $head->add('Received', 'from eryq.pr.mcs.net by gonzo.net with smtp');

     Normally, the new occurence will be *appended* to the existing
     occurences.  However, if the optional INDEX argument is 0, then the
     new occurence will be *prepended*.  If you want to be *explicit*
     about appending, specify an INDEX of -1.

     *NOTE:* use of "BEFORE" (for index 0) or "AFTER" (for index -1) is
     still allowed, but deprecated.

     WARNING: this method always adds new occurences; it doesn't overwrite
     any existing occurences... so if you just want to *change* the value
     of a field (creating it if necessary), then you probably *don't* want
     to use this method: consider using `set()' instead.

delete TAG,[INDEX]
     *Inherited.* Delete all occurences of the field named TAG.

          # Remove all the MIME information:
          $head->delete('MIME-Version');
          $head->delete('Content-type');
          $head->delete('Content-transfer-encoding');
          $head->delete('Content-disposition');

exists TAG
     Returns whether a given field exists:

          # Was a "Subject:" given?
          if ($head->exists('subject')) {
              # yes, it does!
          }

     The TAG is treated in a case-insensitive manner.  This method returns
     some false value if the field doesn't exist, and some true value if
     it does.

get TAG,[INDEX]
     *Inherited.* Get the contents of field TAG.

     If a *numeric INDEX* is given, returns the occurence at that index,
     or undef if not present:

          # Print the first 'Received:' entry (explicitly):
          print "Most recent: ", $head->get('received',0), "\n";
          
          # Print the last 'Received:' entry:
          print "Least recent: ", $head->get('received', -1), "\n";

     If *no INDEX* is given, but invoked in a scalar context, then INDEX
     simply defaults to 0:

          # Get the first 'Received:' entry (implicitly):
          my $most_recent = $head->get('received');

     If *no INDEX* is given, and invoked in an *array* context, then all
     occurences of the field are returned:

          # Get all 'Received:' entries:
          my @all_received = $head->get('received');

     *WARNING:* *This has changed since MIME-parser 1.x.  You should now
     use the two-argument form if you want the old behavior, or else tweak
     the module to emulate version 1.0.*

get_all FIELD
     Returns the list of all occurences of the field, or the empty list if
     the field is not present:

          # How did it get here?
          @history = $head->get_all('Received');

     *NOTE:* I had originally experimented with having `get()' return all
     occurences when invoked in an array context... but that causes a lot
     of accidents when you get careless and do stuff like this:

          print "\u$field: ", $head->get($field), "\n";

     It also made the intuitive behaviour unclear if the INDEX argument
     was given in an array context.  So I opted for an explicit approach
     to asking for all occurences.

original_text
     Recover the original text that was read() in to create this object:

          print "PARSED FROM:\n", $head->original_text;

     *WARNING:* does no such thing now.  Just returns a reasonable
     approximation of that text.

set TAG,TEXT
     Set the field named TAG to [the single occurence given by the TEXT:

          # Set the MIME type:
          $head->set('content-type', 'text/html');
          
          The TAG is treated in a case-insensitive manner.

     *DEPRECATED.*  Use replace() instead.

unfold [FIELD]
     Unfold the text of all occurences of the given FIELD.  If the FIELD
     is omitted, all fields are unfolded.

     "Unfolding" is the act of removing all newlines.

          $head->unfold;

     Returns the "self" object.

MIME-specific methods
---------------------

All of the following methods extract information from the following fields:

     Content-type
     Content-transfer-encoding
     Content-disposition

Be aware that they do not just return the raw contents of those fields,
and in some cases they will fill in sensible (I hope) default values.  Use
`get()' if you need to grab and process the raw field text.

*NOTE:* some of these methods are provided both as a convenience and for
backwards-compatibility only, while others (like recommended_filename())
*really do have to be in MIME::Head to work properly,* since they look for
their value in more than one field.  However, if you know that a value is
restricted to a single field, you should really use the Mail::Field
interface to get it.

mime_encoding
     Try *real hard* to determine the content transfer encoding (e.g.,
     `"base64"', `"binary"'), which is returned in all-lowercase.

     If no encoding could be found, the default of `"7bit"' is returned.
     I quote from RFC-1521 section 5:

          This is the default value -- that is, "Content-Transfer-Encoding: 7BIT"
          is assumed if the Content-Transfer-Encoding header field is not present.

mime_type
     Try `real hard' to determine the content type (e.g., `"text/plain"',
     `"image/gif"', `"x-weird-type"', which is returned in all-lowercase.

     If no content type could be found, the default of `"text/plain"' is
     returned.  I quote from RFC-1521 section 7.1:

          The default Content-Type for Internet mail is
          "text/plain; charset=us-ascii".

multipart_boundary
     If this is a header for a multipart message, return the
     "encapsulation boundary" used to separate the parts.  The boundary is
     returned exactly as given in the `Content-type:' field; that is, the
     leading double-hyphen (`--') is *not* prepended.

     (Well, *almost* exactly... from RFC-1521:

          (If a boundary appears to end with white space, the white space
          must be presumed to have been added by a gateway, and must be deleted.)

     so we oblige and remove any trailing spaces.)

     Returns undef (*not* the empty string) if either the message is not
     multipart, if there is no specified boundary, or if the boundary is
     illegal (e.g., if it is empty after all trailing whitespace has been
     removed).

recommended_filename
     Return the recommended external filename.  This is used when
     extracting the data from the MIME stream.

     Returns undef if no filename could be suggested.

Compatibility tweaks
--------------------

NOTES
=====

Design issues
-------------

Why have separate objects for the entity, head, and body?
     See the documentation for the MIME-parser distribution for the
     rationale behind this decision.

Why assume that MIME headers are email headers?
     I quote from Achim Bohnet, who gave feedback on v.1.9 (I think he's
     using the word header where I would use *field*; e.g., to refer to
     "Subject:", "Content-type:", etc.):

          There is also IMHO no requirement [for] MIME::Heads to look
          like [email] headers; so to speak, the MIME::Head [simply stores]
          the attributes of a complex object, e.g.:

          new MIME::Head type => "text/plain",
                         charset => ...,
                         disposition => ..., ... ;

     I agree in principle, but (alas and dammit) RFC-1521 says otherwise.
     RFC-1521 [MIME] headers are a syntactic subset of RFC-822 [email]
     headers.  Perhaps a better name for these modules would be RFC1521::
     instead of MIME::, but we're a little beyond that stage now.

     In my mind's eye, I see an abstract class, call it MIME::Attrs, which
     does what Achim suggests... so you could say:

          my $attrs = new MIME::Attrs type => "text/plain",
          				 charset => ...,
                                      disposition => ..., ... ;

     We could even make it a superclass of MIME::Head: that way, MIME::Head
     would have to implement its interface, *and* allow itself to be
     initiallized from a MIME::Attrs object.

     However, when you read RFC-1521, you begin to see how much MIME
     information is organized by its presence in particular fields.  I
     imagine that we'd begin to mirror the structure of RFC-1521 fields
     and subfields to such a degree that this might not give us a
     tremendous gain over just having MIME::Head.

Why all this "occurence" and "index" jazz?  Isn't every field unique?
     Aaaaaaaaaahh....no.

     (This question is generic to all Mail::Header subclasses, but I'll
     field it here...)

     Looking at a typical mail message header, it is sooooooo tempting to
     just store the fields as a hash of strings, one string per hash entry.
     Unfortunately, there's the little matter of the `Received:' field,
     which (unlike `From:', `To:', etc.) will often have multiple
     occurences; e.g.:

          Received: from gsfc.nasa.gov by eryq.pr.mcs.net  with smtp
              (Linux Smail3.1.28.1 #5) id m0tStZ7-0007X4C; Thu, 21 Dec 95 16:34 CST
          Received: from rhine.gsfc.nasa.gov by gsfc.nasa.gov (5.65/Ultrix3.0-C)
              id AA13596; Thu, 21 Dec 95 17:20:38 -0500
          Received: (from eryq@localhost) by rhine.gsfc.nasa.gov (8.6.12/8.6.12)
              id RAA28069; Thu, 21 Dec 1995 17:27:54 -0500
          Date: Thu, 21 Dec 1995 17:27:54 -0500
          From: Eryq <eryq@rhine.gsfc.nasa.gov>
          Message-Id: <199512212227.RAA28069@rhine.gsfc.nasa.gov>
          To: eryq@eryq.pr.mcs.net
          Subject: Stuff and things

     The `Received:' field is used for tracing message routes, and although
     it's not generally used for anything other than human debugging, I
     didn't want to inconvenience anyone who actually wanted to get at that
     information.

     I *also* didn't want to make this a special case; after all, who
     knows what other fields could have multiple occurences in the future?
     So, clearly, multiple entries had to somehow be stored multiple
     times... and the different occurences had to be retrievable.

WARNINGS
========

NEWS FLASH!
-----------

Rejoice!  As of MIME-parser 2.0, this is a subclass of Mail::Header, as
the Maker of All Things intended.  It will continue to exist, both for
backwards-compatibility with MIME-parser 1.0, and to allow me to tinker
with MIME-specific methods.

If you are upgrading from the MIME-parser 1.0 package, and you used this
module directly, you may notice some warnings about deprecated constructs
in your code... all your stuff should (hopefully) still work... you'll
just see a lot of warnings.  *However, you should read the *COMPATIBILITY
TWEAKS* and WARNINGS sections before installing it!*

I have also changed terminology to match with the new MailTools
distribution.  Thus, the *name* of a field ("Subject", "From", "To", etc.)
is now called a *"tag"* instead of a "field".

However, I have retained all the documentation where appropriate, even
when inheriting from the Mail::Header module.  Hopefully, you won't need
to flip back and forth between man pages to use this module.

UPGRADING FROM 1.x to 2.x
-------------------------

Altered methods/usage
     There are things you must beware of if you are either a MIME-parser
     1.x user or a Mail::Header user:

    Modified get() behavior
          In the old system, always `get()' returned a single value, and
          `get_all()' returned multiple values: array vs. scalar context
          was not used.

          Since Mail::Header does stuff differently, we have to obey our
          superclass or we might break some of its complex methods that
          use `get()' (like `Mail::Header::combine()', which expects
          `get()' to return all fields in an array context).
          Unfortunately, this will break some of *your* old code.

          *For now,* you can tell the system to emulate the MIME-parser
          version 1 behavior.

          *For future compatibility,* you should, as soon as possible,
          modify your code to use the two-arg form of get if you want a
          single value, with the second arg being 0.  This does what the
          old `get()' method did:

               print "Subject: ",  $head->get('subject',0), "\n";

Deprecated methods/usage
     The following are deprecated as of MIME-parser v.2.0.  In many cases,
     they are redundant with Mail::Header subroutines of different names:

    add
          Use numeric index 0 for 'BEFORE' and -1 for 'AFTER'.

    add_text
          If you really need this, use the inherited `replace()' method
          instead.  The current implementation is now somewhat inefficient.

    copy
          Use the inherited `dup()' method instead.

    fields
          Use the inherited `tags()' method instead.  *Beware:* that
          method does not automatically downcase its output for you: you
          will have to do that yourself.

    params
          Use the new MIME::Field interface classes (subclasses of
          Mail::Field) to access portions of a structured MIME field.

    set
          Use the inherited `replace()' method instead.

    tweak_FROM_parsing
          Use the inherited `mail_from()' method instead.

AUTHOR
======

Copyright (c) 1996 by Eryq / eryq@rhine.gsfc.nasa.gov

All rights reserved.  This program is free software; you can redistribute
it and/or modify it under the same terms as Perl itself.

The more-comprehensive filename extraction is courtesy of Lee E. Brotzman,
Advanced Data Solutions.

VERSION
=======

$Revision: 2.9 $ $Date: 1996/10/28 18:29:55 $


File: pm.info,  Node: MIME/IO,  Next: MIME/Latin1,  Prev: MIME/Head,  Up: Module List

a small package for turning things into IO handles
**************************************************

NAME
====

MIME::IO - a small package for turning things into IO handles

DESCRIPTION
===========

As of MIME-tools 2.0, input and output routines cannot just assume that
they are dealing with filehandles.  In an effort to come up with a nice,
OO way of encapsulating input/output streams, I decided to use a minimal
subset of Graham Barr's *IO::Handle* interface (which is itself derived
from the FileHandle interface).

Therefore, all that MIME::Body, MIME::Decoder, and the other classes
require (and, thus, all that they can assume) is that they are manipulating
an object which responds to the following small, well-defined set of
messages:

close
     *Instance method.* This should close the input/output stream.

getline
     *Instance method.* This should get a single line from the input
     stream, and return it (or undef on end of file).  The returned line
     should end with the newline (unless, of course, this is the last line
     of a file which is not terminated by a newline).

getlines
     *Instance method.* This should get the entire input stream as an
     array of lines, which each line is terminated by the `"\n"' (except,
     maybe, the last one).

print ARGS...
     *Instance method.* This should output the ARGS to the stream.

read BUFFER,NBYTES
     *Instance method.* This should get NBYTES from the input stream,
     placing them in BUFFER.  It should return the number of bytes
     actually read, undef on error, and 0 on end of file.

*Thanks to Achim Bohnet for suggesting this more-generic I/O model.*

BUILT-IN SUBCLASSES
===================

MIME::IO::Handle
----------------

DESCRIPTION
     An I/O interface object wrapped around a raw filehandle.  If you hand
     this class' `wrap()' constructor an argument, it is expected to be
     one of the following:

        * *A raw scalar filehandle name,* like `"STDOUT"' or
          `"Class::HANDLE"'.  In this case, the filehandle name is wrapped
          in a MIME::IO object, which is returned.

        * *A raw filehandle glob,* like `\*STDOUT'.  In this case, the
          filehandle glob is wrapped in a MIME::IO object, which is
          returned.

        * *A blessed FileHandle object.* In this case, the FileHandle is
          wrapped in a MIME::IO object if and only if your FileHandle
          class does not support the `read()' method.

        * *Any other kind of blessed object,* which is assumed to be
          already conformant to the I/O object interface.  In this case,
          you just get back that object.

     Like this:

          my $IO = wrap MIME::IO::Handle \*STDOUT;

     *All this class does* is to provide a simple means for the MIME::
     classes to wrap raw filehandles inside a class which responds to the
     above messages (by passing the messages on to the actual filehandle
     in the form of the standard function calls).

     The bottom line: what you get back is an object which is guaranteed
     to support the methods defined above.

     This interface is used by many of the MIME-tool classes, for backwards
     compatibility with earlier versions of MIME-parser: if you supply a
     raw filehandle where an INSTREAM or OUTSTREAM is expected, most MIME
     packages will automatically wrap that raw filehandle in a MIME::IO
     object, which fits the I/O handle criteria.

NOTES
     Clearly, when wrapping a raw external filehandle (like \*STDOUT), I
     didn't want to close the file descriptor when this object is
     destructed... since the user might not appreciate that.  Hence,
     there's no DESTROY method in this class.

     When wrapping a FileHandle object, however, I believe that Perl will
     invoke the FileHandle::DESTROY when the last reference goes away, so
     in that case, the filehandle is closed if the wrapped FileHandle
     really was the last reference to it.

MIME::IO::Scalar
----------------

DESCRIPTION
     An I/O interface object wrapped around a scalar.  This is to
     implement things that look like filehandles, but which keep all of
     their data in-core.

     Use it like this:

          $IO = new MIME::IO::Scalar \$scalar;
          $IO->print("Some data\n");
          $IO->print("Some more data\n");
          $IO->close;    # ...$scalar now holds "Some data\nSome more data\n"

NOTES
=====

I know, I know: three-level-nesting of packages is evil when those
packages are not "private".  Sure, I could have made this two modules,
`MIME::IOHandle' and `MIME::IOScalar'...  but it just seemed more sensible
to mimic the IO:: hierarchy, one level down (under MIME::).

AUTHOR
======

Copyright (c) 1996 by Eryq / eryq@rhine.gsfc.nasa.gov

All rights reserved.  This program is free software; you can redistribute
it and/or modify it under the same terms as Perl itself.

VERSION
=======

$Revision: 1.5 $ $Date: 1996/10/28 18:47:29 $


File: pm.info,  Node: MIME/Latin1,  Next: MIME/OLD/ParserUtil,  Prev: MIME/IO,  Up: Module List

translate ISO-8859-1 into 7-bit approximations
**********************************************

NAME
====

MIME::Latin1 - translate ISO-8859-1 into 7-bit approximations

SYNOPSIS
========

     use MIME::Latin1 qw(latin1_to_ascii);
     
     $dirty = "Fran\347ois";
     print latin1_to_ascii($dirty);      # prints out "Fran\c,ois"

DESCRIPTION
===========

This is a small package used by the `"7bit"' encoder/decoder for handling
the case where a user wants to 7bit-encode a document that contains 8-bit
(presumably Latin-1) characters.

PUBLIC INTERFACE
================

latin1_to_ascii STRING,[OPTS]
     Map the Latin-1 characters in the string to sequences of the form:

          \xy

     Where `xy' is a two-character sequence that visually approximates the
     Latin-1 character.  For example:

          c cedilla      => \c,
          n tilde        => \n~
          AE ligature    => \AE
          small o slash  => \o/

     The sequences are taken almost exactly from the Sun character
     composition sequences for generating these characters.  The
     translation may be further tweaked by the OPTS string:

     *If no OPTS string is given,* only 8-bit characters are affected, and
     their output is of the form `\xy':

          \<<Fran\c,ois M\u"ller\>>   c:\usr\games

     *If the OPTS string contains 'NOSLASH',* then the leading `"\"' is
     not output, and the output is more compact:

          <<Franc,ois Mu"ller>>       c:\usr\games

     *If the OPTS string contains 'ENCODE',* then not only is the leading
     `"\"' output, but any other occurences of `"\"' are escaped as well
     by turning them into `"\\"'.  This produces output which may easily
     be parsed and turned back into the original 8-bit characters, so in a
     way it is its own full-fledged encoding... and given that `"\"' is a
     rare-enough character, not much uglier that the normal output:

          \<<Fran\c,ois M\u"ller\>>   c:\\usr\\games

AUTHOR
======

Copyright (c) 1996 by Eryq / eryq@rhine.gsfc.nasa.gov

All rights reserved.  This program is free software; you can redistribute
it and/or modify it under the same terms as Perl itself.

VERSION
=======

$Revision: 1.2 $ $Date: 1996/10/18 21:32:56 $


File: pm.info,  Node: MIME/OLD/ParserUtil,  Next: MIME/Parser,  Prev: MIME/Latin1,  Up: Module List

MIME-parser configuration
*************************

NAME
====

MIME::ParserConf - MIME-parser configuration

DESCRIPTION
===========

A catch-all place for miscellaneous global information related to the
configuration of the MIME-parser kit.

PUBLIC INTERFACE
================

emulate_version [VERSION]
     *Class method.* Emulate MIME::Parser's behavior of a previoous
     version.  This will *not* turn off warnings about deprecated usage
     (that would be too dangerous), but it *will* patch the `get()' method:

          MIME::ParserConf->emulate_version(1.0)

     The VERSION should be '1' or '1.0'.

AUTHOR
======

Copyright (c) 1996 by Eryq / eryq@rhine.gsfc.nasa.gov

All rights reserved.  This program is free software; you can redistribute
it and/or modify it under the same terms as Perl itself.

VERSION
=======

$Revision: 1.1 $ $Date: 1996/10/05 04:50:29 $


File: pm.info,  Node: MIME/Parser,  Next: MIME/ParserBase,  Prev: MIME/OLD/ParserUtil,  Up: Module List

split MIME mail into decoded components
***************************************

NAME
====

MIME::Parser - split MIME mail into decoded components

SYNOPSIS
========

     use MIME::Parser;
     
     # Create a new parser object:
     my $parser = new MIME::Parser;
     
     # Set up output directory for files:
     $parser->output_dir("$ENV{HOME}/mimemail");
     
     # Set up the prefix for files with auto-generated names:
     $parser->output_prefix("part");
     
     # If content length is this or below, write to in-core scalar;
     # Else, write to a disk file (the default action):
     $parser->output_to_core(20000);
     
     # Parse an input stream:
     $entity = $parser->read(\*STDIN) or die "couldn't parse MIME stream";
     
     # Congratulations: you now have a (possibly multipart) MIME entity!
     $entity->dump_skeleton;          # for debugging

DESCRIPTION
===========

A subclass of MIME::ParserHead, providing one useful way to parse MIME
streams and obtain MIME::Entity objects.  This particular parser class
outputs the different parts as files on disk, in the directory of your
choice.

If you don't like the way files are named... it's object-oriented and
subclassable.  If you want to do something *really* different, perhaps you
want to subclass MIME::ParserBase instead.

WARNINGS
========

The organization of the `output_path()' code changed in version 1.11 of
this module.  If you are upgrading from a previous version, and you use
inheritance to override the `output_path()' method, please take a moment
to familiarize yourself with the new code.  Everything *should* still
work, but you never know...

PUBLIC INTERFACE
================

new_body_for HEAD
     Based on the HEAD of a part we are parsing, return a new body object
     (any desirable subclass of MIME::Body) for receiving that part's data.

     The default behavior is to examine the HEAD for a recommended
     filename (generating a random one if none is available), and create a
     new MIME::Body::File on that filename in the parser's current
     `output_dir()'.

     If you use the output_to_core method (q.v.) before parsing, you can
     force this method to output some or all or a message's parts to
     in-core data structures, based on their size.

     If you want the parser to do something else entirely, you should
     override this method in a subclass.

output_to_core [CUTOFF]
     Normally, instances of this class output all their decoded body data
     to disk files (via MIME::Body::File).  However, you can change this
     behaviour by invoking this method before parsing:

     *If CUTOFF is an integer,* then we examine the `Content-length' of
     each entity being parsed.  If the content-length is known to be
     CUTOFF or below, the body data will go to an in-core data structure;
     If the content-length is unknown or if it exceeds CUTOFF, then the
     body data will go to a disk file.

     *If the CUTOFF is the string "NONE",* then all body data goes to disk
     files regardless of the content-length.  This is the default
     behaviour.

     *If the CUTOFF is the string "ALL",* then all body data goes to
     in-core data structures regardless of the content-length.  *This is
     very risky* (what if someone emails you an MPEG or a tar file, hmmm?)
     but people seem to want this bit of noose-shaped rope, so I'm
     providing it.

     Without argument, returns the current cutoff: "ALL", "NONE" (the
     default), or a number.

     See the `new_body_for()' method for more details.

output_dir [DIRECTORY]
     Get/set the output directory for the parsing operation.  This is the
     directory where the extracted and decoded body parts will go.  The
     default is `"."'.

     If `DIRECTORY' *is not* given, the current output directory is
     returned.  If `DIRECTORY' *is* given, the output directory is set to
     the new value, and the previous value is returned.

     *Note:* this is used by the `output_path()' method in this class.  It
     should also be used by subclasses, but if a subclass decides to
     output parts in some completely different manner, this method may of
     course be completely ignored.

evil_filename FILENAME
     *Instance method.* Is this an evil filename?  It is if it contains
     path info or non-ASCII characters.  Returns true or false.

     *Note:* Override this method in a subclass if you just want to change
     which externally-provided filenames are allowed, and which are not.

     *Thanks to Andrew Pimlott for finding a real dumb bug. :-)*

output_path HEAD
     *Instance method.* Given a MIME head for a file to be extracted, come
     up with a good output pathname for the extracted file.

     The "directory" portion of the returned path will be the
     `output_dir()', and the "filename" portion will be determined as
     follows:

        * If the MIME header contains a recommended filename, and it is
          *not* judged to be "evil" (evil filenames are ones which contain
          things like "/" or ".." or non-ASCII characters), then that
          filename will be used.

        * If the MIME header contains a recommended filename, but it *is*
          judged to be "evil", then a warning is issued and we pretend that
          there was no recommended filename.  In which case...

        * If the MIME header does not specify a recommended filename, then
          a simple temporary file name, starting with the
          `output_prefix()', will be used.

     *Note:* If you don't like the behavior of this function, you can
     define your own subclass of MIME::Parser and override it there:

          package MIME::MyParser;
          
          require 5.002;                # for SUPER
          use package MIME::Parser;
          
          @MIME::MyParser::ISA = ('MIME::Parser');
          
          sub output_path {
              my ($self, $head) = @_;
          
              # Your code here; FOR EXAMPLE...
              if (i_have_a_preference) {
          	     return my_custom_path;
              }
          	 else {                      # return the default path:
                  return $self->SUPER::output_path($head);
              }
          }
          1;

     *Thanks to Laurent Amon for pointing out problems with the original
     implementation, and for making some good suggestions.  Thanks also to
     Achim Bohnet for pointing out that there should be a hookless, OO way
     of overriding the output_path.*

output_path_hook SUBREF
     *Instance method: DEPRECATED.* Install a different function to
     generate the output filename for extracted message data.  Declare it
     like this:

          sub my_output_path_hook {
              my $parser = shift;   # this MIME::Parser
          	my $head = shift;     # the MIME::Head for the current message

          # Your code here: it must return a path that can be
          # open()ed for writing.  Remember that you can ask the
          # $parser about the output_dir, and you can ask the
          # $head about the recommended_filename!
              }

     And install it immediately before parsing the input stream, like this:

          # Create a new parser object, and install my own output_path hook:
          my $parser = new MIME::Parser;
          $parser->output_path_hook(\&my_output_path_hook);
          
          # NOW we can parse an input stream:
          $entity = $parser->read(\*STDIN);

     This method is intended for people who are squeamish about creating
     subclasses.  See the `output_path()' documentation for a cleaner,
     OOish way to do this.

output_prefix [PREFIX]
     Get/set the output prefix for the parsing operation.  This is a short
     string that all filenames for extracted and decoded body parts will
     begin with.  The default is `"msg"'.

     If PREFIX *is not* given, the current output prefix is returned.  If
     PREFIX *is* given, the output directory is set to the new value, and
     the previous value is returned.

WRITING SUBCLASSES
==================

Authors of subclasses can consider overriding the following methods.  They
are listed in approximate order of most-to-least impact.

new_body_for
     Override this if you want to change the *entire* mechanism for
     choosing the output destination.  You may want to use information in
     the MIME header to determine how files are named, and whether or not
     their data goes to a disk file or to an in-core scalar.  (You have
     the MIME header object at your disposal.)

output_path
     Override this if you want to completely change how the output path
     (containing both the directory and filename) is determined for those
     parts being output to disk files.  (You have the MIME header object
     at your disposal.)

evil_filename
     Override this if you want to change the test that determines whether
     or not a filename obtained from the header is permissible.

output_prefix
     Override this if you want to change the mechanism for getting/setting
     the desired output prefix (used in naming files when no other names
     are suggested).

output_dir
     Override this if you want to change the mechanism for getting/setting
     the desired output directory (where extracted and decoded files are
     placed).

SEE ALSO
========

MIME::Decoder, MIME::Entity, MIME::Head, MIME::Parser.

AUTHOR
======

Copyright (c) 1996 by Eryq / eryq@rhine.gsfc.nasa.gov

All rights reserved.  This program is free software; you can redistribute
it and/or modify it under the same terms as Perl itself.

VERSION
=======

$Revision: 2.4 $ $Date: 1996/10/28 18:38:42 $


File: pm.info,  Node: MIME/ParserBase,  Next: MIME/QuotedPrint,  Prev: MIME/Parser,  Up: Module List

abstract class for parsing MIME mail
************************************

NAME
====

MIME::ParserBase - abstract class for parsing MIME mail

SYNOPSIS
========

This is an *abstract* class; however, here's how one of its *concrete
subclasses* is used:

     use MIME::Parser;
     
     # Create a new parser object:
     my $parser = new MIME::Parser;
     
     # Parse an input stream:
     $entity = $parser->read(\*STDIN) or die "couldn't parse MIME stream";
     
     # Congratulations: you now have a (possibly multipart) MIME entity!
     $entity->dump_skeleton;          # for debugging

There are also some convenience methods:

     # Parse already-split input (as "deliver" would give it to you):
     $entity = $parser->parse_two("msg.head", "msg.body")
           || die "couldn't parse MIME files";

In case a parse fails, it's nice to know who sent it to us.  So...

     # Parse an input stream:
     $entity = $parser->read(\*STDIN);
     if (!$entity) {           # oops!
     	my $decapitated = $parser->last_head;    # last top-level head
     }

You can also alter the behavior of the parser:

     # Parse contained "message/rfc822" objects as nested MIME streams:
     $parser->parse_nested_messages(1);

DESCRIPTION
===========

Where it all begins.

This is the class that contains all the knowledge for *parsing* MIME
streams.  It's an abstract class, containing no methods governing the
*output* of the parsed entities: such methods belong in the concrete
subclasses.

You can inherit from this class to create your own subclasses that parse
MIME streams into MIME::Entity objects.  One such subclass,
*MIME::Parser*, is already provided in this kit.

PUBLIC INTERFACE
================

new ARGS...
     *Class method.* Create a new parser object.  Passes any subsequent
     arguments onto the `init()' method.

     Once you create a parser object, you can then set up various
     parameters before doing the actual parsing.  Here's an example using
     one of our concrete subclasses:

          my $parser = new MIME::Parser;
          $parser->output_dir("/tmp");
          $parser->output_prefix("msg1");
          my $entity = $parser->read(\*STDIN);

init ARGS...
     *Instance method.* Initiallize the new parser object, with any args
     passed to new().

     If you override this in a subclass, make sure you call the inherited
     method to init your parents!

          package MyParser;
          @ISA = qw(MIME::Parser);
          ...
          sub init {
          	my $self = shift;
          	$self->SUPER::init(@_);        # do my parent's init
          
          	# ...my init stuff goes here...
          
          	$self;                         # return
          }

     Should return the self object on success, and undef on failure.

interface ROLE,[VALUE]
     *Instance method.* During parsing, the parser normally creates
     instances of certain classes, like MIME::Entity.  However, you may
     want to create a parser subclass that uses your own experimental
     head, entity, etc. classes (for example, your "head" class may
     provide some additional MIME-field-oriented methods).

     If so, then this is the method that your subclass should invoke during
     init.  Use it like this:

          package MyParser;
          @ISA = qw(MIME::Parser);
          ...
          sub init {
          	my $self = shift;
          	$self->SUPER::init(@_);        # do my parent's init
              $self->interface(ENTITY_CLASS => 'MIME::MyEntity');
          	$self->interface(HEAD_CLASS   => 'MIME::MyHead');
          	$self;                         # return
          }

     With no VALUE, returns the VALUE currently associated with that ROLE.

last_head
     Return the top-level MIME header of the last stream we attempted to
     parse.  This is useful for replying to people who sent us bad MIME
     messages.

          # Parse an input stream:
          $entity = $parser->read(\*STDIN);
          if (!$entity) {           # oops!
          	my $decapitated = $parser->last_head;    # last top-level head
          }

parse_nested_messages OPTION
     Some MIME messages will contain a part of type `message/rfc822':
     literally, the text of an embedded mail message.  The normal behavior
     is to save such a message just as if it were a `text/plain' document.
     However, you can change this: before parsing, invoke this method
     with the OPTION you want:

     *If OPTION is false,* the normal behavior will be used.

     *If OPTION is true,* the body of the `message/rfc822' part is decoded
     (after all, it might be encoded!) into a temporary file, which is
     then rewound and parsed by this parser, creating an entity object.
     What happens then is determined by the OPTION:

    NEST or 1
          The contained message becomes a "part" of the `message/rfc822'
          entity, as though the `message/rfc822' were a special kind of
          `multipart' entity.  This is the default behavior if the generic
          true value of "1" is given.

    REPLACE
          The contained message replaces the `message/rfc822' entity, as
          though the `message/rfc822' "envelope" never existed.  Notice
          that, with this option, all the header information in the
          `message/rfc822' header is lost, so this option is *not*
          recommended.

     *Thanks to Andreas Koenig for suggesting this method.*

parse_two HEADFILE BODYFILE
     Convenience front-end onto `read()', intended for programs running
     under mail-handlers like *deliver*, which splits the incoming mail
     message into a header file and a body file.

     Simply give this method the paths to the respective files.  *These
     must be pathnames:* Perl "open-able" expressions won't work, since
     the pathnames are shell-quoted for safety.

     *WARNING:* it is assumed that, once the files are cat'ed together,
     there will be a blank line separating the head part and the body part.

read FILEHANDLE
     Takes a MIME-stream and splits it into its component entities, each
     of which is decoded and placed in a separate file in the splitter's
     output_dir().

     The stream should be given as a FileHandle, or at least a glob ref to
     a readable FILEHANDLE; e.g., `\*STDIN'.

     Returns a MIME::Entity, which may be a single entity, or an
     arbitrarily-nested multipart entity.  Returns undef on failure.

WRITING SUBCLASSES
==================

All you have to do to write a subclass is to provide the following methods:

new_body_for HEAD
     *Abstract method.* Based on the HEAD of a part we are parsing, return
     a new body object (any desirable subclass of MIME::Body) for
     receiving that part's data (both will be put into the "entity" object
     for that part).

     If you want the parser to do something other than write its parts out
     to files, you should override this method in a subclass.  For an
     example, see *MIME::Parser*.

     *Note:* the reason that we don't use the "interface" mechanism for
     this is that your choice of (1) which body class to use, and (2) how
     its new() method is invoked, may be very much based on the
     information in the header.

You are of course free to override any other methods as you see fit, like
new.

NOTES
=====

*This is an abstract class.* If you actually want to parse a MIME stream,
use one of the children of this class, like the backwards-compatible
MIME::Parser.

Under the hood
--------------

RFC-1521 gives us the following BNF grammar for the body of a multipart
MIME message:

     multipart-body  := preamble 1*encapsulation close-delimiter epilogue

     encapsulation   := delimiter body-part CRLF

     delimiter       := "--" boundary CRLF
                                  ; taken from Content-Type field.
                                  ; There must be no space between "--"
                                  ; and boundary.

     close-delimiter := "--" boundary "--" CRLF
                                  ; Again, no space by "--"

     preamble        := discard-text
                                  ; to be ignored upon receipt.

     epilogue        := discard-text
                                  ; to be ignored upon receipt.

     discard-text    := *(*text CRLF)

     body-part       := <"message" as defined in RFC 822, with all
                         header fields optional, and with the specified
                         delimiter not occurring anywhere in the message
                         body, either on a line by itself or as a substring
                         anywhere.  Note that the semantics of a part
                         differ from the semantics of a message, as
                         described in the text.>

From this we glean the following algorithm for parsing a MIME stream:

     PROCEDURE parse
     INPUT
         A FILEHANDLE for the stream.
         An optional end-of-stream OUTER_BOUND (for a nested multipart message).
     
     RETURNS
         The (possibly-multipart) ENTITY that was parsed.
         A STATE indicating how we left things: "END" or "ERROR".
     
     BEGIN
         LET OUTER_DELIM = "--OUTER_BOUND".
         LET OUTER_CLOSE = "--OUTER_BOUND--".
     
         LET ENTITY = a new MIME entity object.
         LET STATE  = "OK".
     
         Parse the (possibly empty) header, up to and including the
         blank line that terminates it.   Store it in the ENTITY.
     
         IF the MIME type is "multipart":
             LET INNER_BOUND = get multipart "boundary" from header.
             LET INNER_DELIM = "--INNER_BOUND".
             LET INNER_CLOSE = "--INNER_BOUND--".
     
             Parse preamble:
                 REPEAT:
                     Read (and discard) next line
                 UNTIL (line is INNER_DELIM) OR we hit EOF (error).
     
             Parse parts:
                 REPEAT:
                     LET (PART, STATE) = parse(FILEHANDLE, INNER_BOUND).
                     Add PART to ENTITY.
                 UNTIL (STATE != "DELIM").
     
             Parse epilogue:
                 REPEAT (to parse epilogue):
                     Read (and discard) next line
                 UNTIL (line is OUTER_DELIM or OUTER_CLOSE) OR we hit EOF
                 LET STATE = "EOF", "DELIM", or "CLOSE" accordingly.
     
         ELSE (if the MIME type is not "multipart"):
             Open output destination (e.g., a file)
     
             DO:
                 Read, decode, and output data from FILEHANDLE
             UNTIL (line is OUTER_DELIM or OUTER_CLOSE) OR we hit EOF.
             LET STATE = "EOF", "DELIM", or "CLOSE" accordingly.
     
         ENDIF
     
         RETURN (ENTITY, STATE).
     END

For reasons discussed in MIME::Entity, we can't just discard the "discard
text": some mailers actually put data in the preamble.

Questionable practices
----------------------

Multipart messages are always read line-by-line
     Multipart document parts are read line-by-line, so that the
     encapsulation boundaries may easily be detected.  However, bad MIME
     composition agents (for example, naive CGI scripts) might return
     multipart documents where the parts are, say, unencoded bitmap
     files... and, consequently, where such "lines" might be veeeeeeeeery
     long indeed.

     A better solution for this case would be to set up some form of state
     machine for input processing.  This will be left for future versions.

Multipart parts read into temp files before decoding
     In my original implementation, the MIME::Decoder classes had to be
     aware of encapsulation boundaries in multipart MIME documents.  While
     this decode-while-parsing approach obviated the need for temporary
     files, it resulted in inflexible and complex decoder implementations.

     The revised implementation uses a temporary file (a la `tmpfile()')
     during parsing to hold the *encoded* portion of the current MIME
     document or part.  This file is deleted automatically after the
     current part is decoded and the data is written to the "body stream"
     object; you'll never see it, and should never need to worry about it.

     Some folks have asked for the ability to bypass this temp-file
     mechanism, I suppose because they assume it would slow down their
     application.  I considered accomodating this wish, but the temp-file
     approach solves a lot of thorny problems in parsing, and it also
     protects against hidden bugs in user applications (what if you've
     directed the encoded part into a scalar, and someone unexpectedly
     sends you a 6 MB tar file?).  Finally, I'm just not conviced that the
     temp-file use adds significant overhead.

Fuzzing of CRLF and newline on input
     RFC-1521 dictates that MIME streams have lines terminated by CRLF
     (`"\r\n"').  However, it is extremely likely that folks will want to
     parse MIME streams where each line ends in the local newline
     character `"\n"' instead.

     An attempt has been made to allow the parser to handle both CRLF and
     newline-terminated input.

Fuzzing of CRLF and newline on output
     The `"7bit"' and `"8bit"' decoders will decode both a `"\n"' and a
     `"\r\n"' end-of-line sequence into a `"\n"'.

     The `"binary"' decoder (default if no encoding specified) still
     outputs stuff verbatim... so a MIME message with CRLFs and no
     explicit encoding will be output as a text file that, on many
     systems, will have an annoying ^M at the end of each line... *but
     this is as it should be*.

WARNINGS
========

binmode
     New, untested binmode() calls were added in module version 1.11...
     if binmode() is *not* a NOOP on your system, please pay careful
     attention to your output, and report any anomalies.  *It is possible
     that "make test" will fail on such systems,* since some of the tests
     involve checking the sizes of the output files.  That doesn't
     necessarily indicate a problem.

     *If anyone* wants to test out this package's handling of both binary
     and textual email on a system where binmode() is not a NOOP, I would
     be most grateful.  If stuff breaks, send me the pieces (including the
     original email that broke it, and at the very least a description of
     how the output was screwed up).

SEE ALSO
========

MIME::Decoder, MIME::Entity, MIME::Head, MIME::Parser.

AUTHOR
======

Copyright (c) 1996 by Eryq / eryq@rhine.gsfc.nasa.gov

All rights reserved.  This program is free software; you can redistribute
it and/or modify it under the same terms as Perl itself.

VERSION
=======

$Revision: 1.1 $ $Date: 1996/10/18 06:52:28 $


File: pm.info,  Node: MIME/QuotedPrint,  Next: MIME/ToolUtils,  Prev: MIME/ParserBase,  Up: Module List

Encode string using quoted-printable encoding
*********************************************

NAME
====

encode_qp - Encode string using quoted-printable encoding

decode_qp - Decode quoted-printable string

SYNOPSIS
========

     use MIME::QuotedPrint;

     $encoded = encode_qp($decoded);
     $decoded = decode_qp($encoded);

DESCRIPTION
===========

This module provides functions to encode and decode strings into the
Quoted-Printable encoding specified in RFC 1521 - *MIME (Multipurpose
Internet Mail Extensions)*.  The Quoted-Printable encoding is intended to
represent data that largely consists of bytes that correspond to printable
characters in the ASCII character set.  Non-printable characters (as
defined by enghlish americans) are represented by a triplet consisting of
the character "=" followed by two hexadecimal digits.

Note that the encode_qp() routine does not change newlines `"\n"' to the
CRLF sequence even though this might be considered the right thing to do
(RFC 1521 (Q-P Rule #4)).

If you prefer not to import these routines into your namespace you can
call them as:

     use MIME::QuotedPrint ();
     $encoded = MIME::QuotedPrint::encode($decoded);
     $decoded = MIME::QuotedPrint::decode($encoded);

COPYRIGHT
=========

Copyright 1995, 1996 Gisle Aas.

This library is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

AUTHOR
======

Gisle Aas <aas@sn.no>


File: pm.info,  Node: MIME/ToolUtils,  Next: MLDBM,  Prev: MIME/QuotedPrint,  Up: Module List

MIME-tools kit configuration and utilities
******************************************

NAME
====

MIME::ToolUtils - MIME-tools kit configuration and utilities

DESCRIPTION
===========

A catch-all place for miscellaneous global information related to the
configuration of the MIME-tools kit.

PUBLIC INTERFACE
================

debugging ONOFF
     *Class method.* Turn debugging on (true) or off (false) for the
     entire MIME-tools library.  Debug messages go to STDERR.

emulate_version [VERSION]
     *Class method.* Emulate the behavior of a previous version of the
     MIME-tools kit (a.k.a the MIME-parser kit in its version 1.x
     incarnations).  This will *not* turn off warnings about deprecated
     usage (that would impede progress), but it *will* patch things like
     the `get()' method of MIME::Head:

          MIME::ToolUtils->emulate_version(1.0)

     The VERSION should be '1' or '1.0'.

AUTHOR
======

Copyright (c) 1996 by Eryq / eryq@rhine.gsfc.nasa.gov

All rights reserved.  This program is free software; you can redistribute
it and/or modify it under the same terms as Perl itself.

VERSION
=======

$Revision: 1.2 $ $Date: 1996/10/18 06:52:28 $


File: pm.info,  Node: MLDBM,  Next: Mail/Address,  Prev: MIME/ToolUtils,  Up: Module List

store multi-level hash structure in single level tied hash
**********************************************************

NAME
====

MLDBM - store multi-level hash structure in single level tied hash

SYNOPSIS
========

     use MLDBM;                   # this gets the default, SDBM
     #use MLDBM qw(DB_File);
     
     $dbm = tie %o, MLDBM [..other DBM args..] or die $!;

DESCRIPTION
===========

This module, intended primarily for use with DBM packages, can serve as a
transparent interface to any TIEHASH package that must be used to store
arbitrary perl data, including nested references.

It works by converting the values in the hash that are references, to their
string representation in perl syntax.  When using a DBM database, it is
this string that gets stored.

It requires the Data::Dumper package, available at any CPAN site.

See the BUGS section for important limitations.

Configuration Variables/Methods
-------------------------------

$MLDBM::UseDB
     You may want to set $MLDBM::UseDB to default to something other than
     "SDBM_File", in case you have a more efficient DBM, or if you want to
     use this with some other TIEHASH implementation.  Alternatively, you
     can specify the name of the package at use time.  Nested module names
     can be specified as "Foo::Bar".

$MLDBM::Key
     Defaults to the magic string used to recognize MLDBM data. It is a six
     character wide, unique string. This is best left alone, unless you
     know what you're doing.

$MLDBM::DumpMeth  *or*  $*OBJ*->DumpMeth(*[METHNAME]*)
     This controls which of the two dumping methods available from
     `Data::Dumper' are used.  By default, this is set to "Dumpxs", the
     faster of the two methods, but only if MLDBM detects that "Dumpxs" is
     supported on your platform.  Otherwise, defaults to the slower "Dump"
     method.

EXAMPLE
=======

     use MLDBM;                            # this gets SDBM
     #use MLDBM qw(DB_File);
     use Fcntl;                            # to get 'em constants
     
     $dbm = tie %o, MLDBM, 'testmldbm', O_CREAT|O_RDWR, 0640 or die $!;
     
     $c = [\ 'c'];
     $b = {};
     $a = [1, $b, $c];
     $b->{a} = $a;
     $b->{b} = $a->[1];
     $b->{c} = $a->[2];
     @o{qw(a b c)} = ($a, $b, $c);
     
     #
     # to see what wuz stored
     #
     use Data::Dumper;
     print Data::Dumper->Dump([@o{qw(a b c)}], [qw(a b c)]);

     #
     # to modify data in a substructure
     #
     $tmp = $o{a};
     $tmp[0] = 'foo';
     $o{a} = $tmp;
     
     #
     # can access the underlying DBM methods transparently
     #
     #print $dbm->fd, "\n";                # DB_File method

BUGS
====

  1. Adding or altering substructures to a hash value is not entirely
     transparent in current perl.  If you want to store a reference or
     modify an existing reference value in the DBM, it must first be
     retrieved and stored in a temporary variable for further
     modifications.  In particular, something like this will NOT work
     properly:

          $mldb{key}{subkey}[3] = 'stuff';  # won't work

     Instead, that must be written as:

          $tmp = $mldb{key};                # retrieve value
          $tmp->{subkey}[3] = 'stuff';
          $mldb{key} = $tmp;                # store value

     This limitation exists because the perl TIEHASH interface currently
     has no support for multidimensional ties.

  2. MLDBM was first released along with the Data::Dumper package as an
     example.  If you got serious with that and have a DBM file from that
     version, you can do something like this to convert the old records to
     the new format:

          use MLDBM (DB_File);              # be sure it's the new MLDBM
          use Fcntl;
          tie %o, MLDBM, 'oldmldbm.file', O_RDWR, 0640 or die $!;
          for $k (keys %o) {
            my $v = $o{$k};
            if ($v =~ /^\$CrYpTiCkEy/o) {
          	$v = eval $v;
          	if ($@) { warn "Error: $@\twhile evaluating $v\n"; }
          	else    { $o{$k} = $v; }
            }
          }


AUTHOR
======

Gurusamy Sarathy        gsar@umich.edu

Copyright (c) 1995 Gurusamy Sarathy. All rights reserved.  This program is
free software; you can redistribute it and/or modify it under the same
terms as Perl itself.

VERSION
=======

Version 1.21    9 April 1996

SEE ALSO
========

perl(1)


File: pm.info,  Node: Mail/Address,  Next: Mail/Cap,  Prev: MLDBM,  Up: Module List

Parse mail addresses
********************

NAME
====

Mail::Address - Parse mail addresses

DESCRIPTION
===========

Parse mailcap files as specified in RFC 822 - *Standard for ARPA Internet
Text Messages*.

CONSTRUCTORS
============

new($phrase, $address, [ $comment])
-----------------------------------

     Mail::Address->new("Perl5 Porters", "perl5-porters@africa.nicoh.com");

Create a new object which represent an address with the elements given. In
a message these 3 elements would be seen like:

     $phrase <$address> ($comment)
     $address ($comment)

parse($line)
------------

     Mail::Address->parse($line);

     Parse the given line a return a list of extracted objects. The line would
     normally be one taken from a To,Cc or Bcc line in a message

METHODS
=======

phrase()
--------

address()
---------

comment()
---------

These methods each return one part of the object

format()
--------

Return a string representing the address in a suitable form to be placed
on a To,Cc or Bcc line of a message

name()
------

Using the information contained within the object attempt to identify what
the perons or groups name is

host()
------

Return the address excluding the user id and '@'

host()
------

Return the address excluding the '@' and the mail domain

path()
------

Unimplemented yet but shoud return the UUCP path for the message

canon()
-------

Unimplemented yet but shoud return the UUCP canon for the message


File: pm.info,  Node: Mail/Cap,  Next: Mail/Field,  Prev: Mail/Address,  Up: Module List

Parse mailcap files
*******************

NAME
====

Mail::Cap - Parse mailcap files

DESCRIPTION
===========

Parse mailcap files as specified in RFC 1524 - *A User Agent Configuration
Mechanism For Multimedia Mail Format Information*.  In the description
below `$type' refers to the MIME type as specified in the *Content-Type*
header of mail or HTTP messages.  Examples of types are:

     image/gif
     text/html
     text/plain; charset=iso-8859-1

METHODS
=======

new()
-----

     $mcap = new Mail::Cap;
     $mcap = new Mail::Cap "/mydir/mailcap";

Create and initialize a new Mail::Cap object.  If you give it an argument
it will try to parse the specified file.  Without any arguments it will
search for the mailcap file using the standard mailcap path, or the
MAILCAPS environment variable if it is defined.

view($type, $file)
------------------

compose($type, $file)
---------------------

edit($type, $file)
------------------

print($type, $file)
-------------------

These methods invoke a suitable progam presenting or manipulating the
media object in the specified file.  They all return 1 if a command was
found, and `0' otherwise.  You might test C<$?" for the outcome of the
command.

viewCmd($type, $file)
---------------------

composeCmd($type, $file)
------------------------

editCmd($type, $file)
---------------------

printCmd($type, $file)
----------------------

These methods return a string that is suitable for feeding to system() in
order to invoke a suitable progam presenting or manipulating the media
object in the specified file.  It will return undef if no suitable
specification exists.

field($type, $field)
--------------------

Returns the specified field for the type.  Returns undef if no
specification exsists.

description($type)
------------------

textualnewlines($type)
----------------------

x11_bitmap($type)
-----------------

nametemplate($type)
-------------------

These methods return the corresponding mailcap field for the type.  These
methods should be more convenient to use than the field() method for the
same fields.

COPYRIGHT
=========

Copyright (c) 1995 Gisle Aas. All rights reserved.

This library is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

AUTHOR
======

Gisle Aas <aas@oslonett.no>

Maintained by Graham Barr <bodg@tiuk.ti.com>


File: pm.info,  Node: Mail/Field,  Next: Mail/Folder,  Prev: Mail/Cap,  Up: Module List

Base class for manipulation of mail header fields
*************************************************

NAME
====

Mail::Field - Base class for manipulation of mail header fields

SYNOPSIS
========

     use Mail::Field;
     
     $field = Mail::Field->new('Subject', 'some subject text');
     print $field->tag,": ",$field->stringify,"\n";

     $field = Mail::Field->subject('some subject text');

DESCRIPTION
===========

`Mail::Field' is a base class for packages that create and manipulate
fields from Email (and MIME) headers. Each different field will have its
own sub-class, defining its own interface.

This document describes the minimum interface that each sub-class should
provide, and also guidlines on how the field specific interface should be
defined.

CONSTRUCTOR
===========

Mail::Field, and it's sub-classes define several methods which return new
objects. These can all be termed to be constructors.

new ( TAG [, STRING | OPTIONS ] )
     The new constructor will create an object in the class which defines
     the field specified by the tag argument.

     After creation of the object :-

     If the tag argument is followed by a single string then the parse
     method will be called with this string.

     If the tag argument is followed by more than one arguments then the
     create method will be called with these arguments.

extract ( TAG, HEAD [, INDEX ] )
     This constuctor takes as arguments the tag name, a `Mail::Head' object
     and optionally an index.

     If the index argument is given then extract will retrieve the given
     tag from the `Mail::Head' object and create a new `Mail::Field' based
     object.  undef will be returned in the field does not exist.

     If the index argument is not given the the result depends on the
     context in which extract is called. If called in a scalar context the
     result will be as if extract was called with an index value of zero.
     If called in an array context then all tags will be retrieved and a
     list of `Mail::Field' objects will be returned.

combine ( FIELD_LIST )
     This constructor takes as arguments a list of `Mail::Field' objects,
     which should all be of the same sub-class, and creates a new object
     in that same class.

     This constructor is nor defined in `Mail::Field' as there is no
     generic way to combine the various field types. Each sub-class should
     define its own combine constructor, if combining is possible/allowed.

METHODS
=======

parse
set
tag
stringify
SUB-CLASS PACKAGE NAMES
=======================

All sub-classes should be called Mail::Field::*name* where *name* is
derived from the tag using these rules.

   * Consider a tag as being made up of elements separated by '-'

   * Convert all characters to lowercase except the first in each element,
     which should be uppercase.

   * *name* is then created from these elements by using the first N
     characters from each element.

   * N is calculated by using the formula :-

          int((7 + #elements) / #elements)

   * *name* is then limited to a maximum of 8 characters, keeping the
     first 8 characters

For an example of this take a look at the definition of the
`_header_pkg_name' subroutine in `Mail::Field'

AUTHOR
======

Graham Barr <Graham.Barr@tiuk.ti.com>

REVISION
========

$Revision: 1.2 $

The revision and the VERSION are not the same but the VERSION is derived
from the revision number. This is because the revision number is not a real
number. The method used for doing this is to turn each number after the
first period into a 2 digit number with leading zeros and then removing
all but the first period. For example

     Revision 1.8   => VERSION 1.08
     Revision 1.2.3 => VERSION 1.0203

SEE ALSO
========

`MIME::*' in this nodes

CREDITS
=======

Eryq <eryq@rhine.gsfc.nasa.gov> - for all the help in defining this package
so that Mail::* and MIME::* can be integrated together.

COPYRIGHT
=========

Copyright (c) 1995 Graham Barr. All rights reserved. This program is free
software; you can redistribute it and/or modify it under the same terms as
Perl itself.


File: pm.info,  Node: Mail/Folder,  Next: Mail/Folder/Emaul,  Prev: Mail/Field,  Up: Module List

A folder-independant interface to email folders.
************************************************

NAME
====

Mail::Folder - A folder-independant interface to email folders.

*WARNING: This code is in alpha release. Expect the interface to change*

SYNOPSIS
========

`use Mail::Folder;'

DESCRIPTION
===========

This base class, and it's subclasses provide an object-oriented interface
to email folders independant of the underlying folder implementation.

There are currently two folder interfaces provided with this package:

Mail::Folder::Emaul
Mail::Folder::Mbox
Here's a snippet of code that retrieves the third message from a mythical
emaul folder and outputs it to stdout:

     use Mail::Folder::Emaul;

     $folder = new Mail::Folder('emaul', "mythicalfolder");
     $message = $folder->get_message(3);
     $message->print(\*STDOUT);
     $folder->close;

METHODS
=======

new([%options])
---------------

new($folder_name [, %options])
------------------------------

Create a new, empty *Mail::Folder* object.  If `$folder_name' is
specified, then the open method will be automatically called with that
argument.

Options are specified as hash items using key and value pairs.  Currently,
the only builtin option is `Create', which is used by open.

open($folder_name)
------------------

Open the given folder and populate internal data structures with
information about the messages in the folder.  If the `Create' option is
set, then the folder will be created if it does not already exist.

The readonly attribute will be set if the underlying folder interface
determines that the folder is readonly.

close
-----

Perform any housecleaning to affect a 'closing' of the folder.  It does
not perform an implicit sync.  Make sure you do a sync before the close if
you want the pending deletes, appends, updates, and the like to be
performed on the folder.

sync
----

Synchronize the folder with the internal data structures.  The folder
interface will process deletes, updates, appends, refiles, and dups.  It
also reads in any new messages that have arrived in the folder since the
last time it was either opened or synced.

pack
----

For folder formats that may have holes in the message number sequence
(like mh) this will rename the files in the folder so that there are no
gaps in the message number sequence.  For folder formats that won't have
these holes (like mbox) it does nothing.

get_message($msg_number)
------------------------

Retrieve a message.  Returns a reference to a *Mail::Internet* object.

get_header($msg_number)
-----------------------

Retrieve a message header.  Returns a reference to a *Mail::Internet*
object.

append_message($message_ref)
----------------------------

Add a message to a folder.  Given a reference to a *Mail::Internet*
object, append it to the end of the folder.  The result is not committed
to the original folder until a sync is performed.

update_message($msg_number, $message_ref)
-----------------------------------------

Replaces the message identified by `$msg_number' with the contents of the
message in reference to a *Mail::Internet* object $message_ref.  The
result is not committed to the original folder until a sync is performed.

refile($msg_number, $folder_ref)
--------------------------------

Moves a message from one folder to another.  Note that this method uses
`delete_message' and `append_message' so the changes will show up in the
folder objects, but will need a syncs performed in order for the changes
to show up in the actual folders.

dup($msg_number, $folder_ref)
-----------------------------

Copies a message to a folder.  Works like `refile', but doesn't delete the
original message.  Note that this method uses `append_message' so the
change will show up in the folder object, but will need a sync performed
in order for the change to show up in the actual folder.

init
----

This is a stub entry called by new.  The primary purpose is to provide a
method for subclasses to override for initialization to be performed at
constructor time.  It is called after the object members variables have
been initialized and before the optional call to open.  The new method
will return undef if the init method returns `0'.

delete_message($msg_number)
---------------------------

Mark a message for deletion.  The actual deletion will be done by the sync
method.  The actual delete in the original folder is not performed until a
sync is performed.

message_list
------------

Returns a list of the message numbers in the folder.

first_message
-------------

Returns the message number of the first message in the folder.

last_message
------------

Returns the message number of the last message in the folder.

next_message($msg_number)
-------------------------

Returns the message number of the next message in the folder relative to
`$msg_number'.  It returns `0' is there is no next message (ie. at the end
of the folder).

prev_message($msg_number)
-------------------------

Returns the message number of the previous message in the folder relative
to `$msg_number'.  It returns `0' is there is no previous message (ie. at
the beginning of the folder).

first_labeled_message($label)
-----------------------------

Returns the message number of the first message in the folder that has the
label $label associated with it.  Returns `0' is there are no messages
with the given label.

first_labeled_message($label)
-----------------------------

Returns the message number of the last message in the folder that has the
label $label associated with it.  Returns `0' if there are no messages
with the given label.

next_labeled_message($msg_number, $label)
-----------------------------------------

Returns the message number of the next message (relative to `$msg_number')
in the folder that has the label `$label' associated with it.  It returns
`0' is there is no next message with the given label.

prev_labeled_message($msg_number, $label)
-----------------------------------------

Returns the message number of the previous message (relative to
`$msg_number') in the folder that has the label `$label' associated with
it.  It returns `0' is there is no previous message with the given label.

current_message
---------------

current_message($msg_number)
----------------------------

When called with no arguments returns the message number of the current
message in the folder.  When called with an argument set the current
message number for the folder to the value of the argument.

For folder mechanisms that provide persistant storage of the current
message, the underlying folder interface will update that storage.  For
those that don't changes to current_message will be affect while the
folder is open.

sort($func_ref)
---------------

Returns a sorted list of messages.  It works conceptually similar to the
regular perl sort.  The `$func_ref' that is passed to sort must be a
reference to a function.  The function will be passed two *Mail::Internet*
message references containing only the headers and it must return an
integer less than, equal to, or greater than 0, depending on how the
elements of the array are to be ordered.

select($func_ref)
-----------------

Returns a list of message numbers that match a set of criteria.  The
method is passed a reference to a function that is used to determine the
match criteria.  The function will be passed a reference to a
*Mail::Internet* message object containing only a header.

add_label($msg_number, $label)
------------------------------

Associates `$label' with `$msg_number'.  The label must have a length > 0
and should be a printable string, although there are currently no
requirements for this.

`add_label' will return `0' if `$label' is of zero length, otherwise it
returns 1.

The persistant storage of labels is dependant on the underlying folder
interface.  Some folder interfaces may not support arbitrary labels.  In
this case, the labels will not exist when the folder is reopened.

There are a few standard labels that have implied meaning.  Unless stated,
these labels are not actually acted on my the module interface, rather
represent a standard set of labels for MUAs to use.

   * deleted

     This is used by the `delete_message' and sync to process the deletion
     of messages.  These will not be reflected in any persistant storage
     of message labels.

   * edited

     This tag is added by update_message to reflect that the message has
     been altered.  This behaviour may go away.

   * seen

     This means that the message has been viewed by the user.  This should
     only be set by MUAs that present the entire message body to the user.

   * filed

   * replied

   * forwarded

   * printed

delete_label($msg_number, $label)
---------------------------------

Deletes the association of `$label' with `$msg_number'.

Returns `0' if the label `$label' wasn't associated with `$msg_number',
otherwise returns a 1.

clear_label($label)
-------------------

Deletes the association of `$label' for all of the messages in the folder.

Returns the quantity of messages that were associated with the label
before they were cleared.

label_exists($msg_number, $label)
---------------------------------

Returns 1 if the label `$label' is associated with `$msg_number' otherwise
returns `0'.

list_labels($msg_number)
------------------------

Returns a list of the labels that are associated with `$msg_number'.

list_all_labels
---------------

Returns a list of all the labels that are associated with the messages in
the folder.

select_label($label)
--------------------

Returns a list of message numbers that have the given label `$label'
associated with them.

foldername
----------

Returns the name of the folder that the object has open.

message_exists($msg_number)
---------------------------

Returns 1 if the folder object contains a reference for `$msg_number',
otherwise returns `0'.

set_readonly
------------

Sets the `readonly' attribute for the folder.  This will cause the sync
command to not perform any updates to the actual folder.

is_readonly
-----------

Returns 1 if the `readonly' attribute for the folder is set, otherwise
returns `0'.

get_option($option)
-------------------

Returns the setting for the given option.  Returns undef if the option
does not exist.

set_option($option, $value)
---------------------------

Set `$option' to $value.

WRITING A FOLDER INTERFACE
==========================

The start of a new folder interface module should start with something
along the lines of the following chunk of code:

     package Mail::Folder::YOUR_FOLDER_TYPE;
     @ISA = qw(Mail::Folder);
     use Mail::Folder;

     Mail::Folder::register_folder_type(Mail::Folder::YOUR_FOLDER_TYPE,
     				       'your_folder_type_name');

In general, writing a folder interface consists of writing a set of
methods that overload some of the native ones in `Mail::Folder'.  Below is
a list of the methods and specific tasks that each must perform.  See the
code of the folder interfaces provides with the package for specific
examples.

If you go about writing a folder interface and find that something is
missing from this documentation, please let me know.

open
----

   * Call the superclass new method.

   * Call set_readonly if folder isn't writable.

   * Call `remember_message' for each message in the folder.

   * Call sort_message_list.

   * Initialize current_message.

   * Initialize any message labels from the folder's persistant storage.

close
-----

   * Call the superclass close method.

sync
----

   * Call the superclass sync method.

   * Lock the folder.

   * Absorb any new messages

   * Perform any pending deletes and updates.

   * Update the folder's persistant storage of current message.

   * Update the folder's persistant storage of message labels.

   * Unlock the folder.

pack
----

   * Call the superclass pack method.

   * Perform the guts of the pack

   * Renumber the `Messages' member of $self.

   * Call sort_message_list

   * Don't forget to reset current_message based on the renumbering.

get_header
----------

   * Call the superclass get_header method.

   * Return the cached entry if it exists.

   * Extract the header into a `Mail::Internet' object.

   * Cache it.

get_message
-----------

   * Call the superclass get_message method.

   * Extract the message into a `Mail::Internet' object.

update_message
--------------

   * Call the superclass update_message method.

   * Replace the specified message in the working copy of the folder.

create
------

   * Create a folder in a manner specific to the folder interface.

init
----

This isn't really a method that needs to be overloaded.  It is a method
that is called by new to perform any initialization specific to the folder
interface.  For example of a typical use, see the init routine in
Mail::Folder::Mbox.

FOLDER INTERFACE METHODS
========================

These routines are intended for use by implementers of finder interfaces.

register_folder_type($class, $type)
-----------------------------------

Registers a folder interface with Mail::Folder.

sort_message_list
-----------------

This is used to resort the internal sorted list of messages.  It needs to
be called whenever the list of messages is changed.  It's a separate
routine to allow large updates to the list of messages (like during an
open) with only one trailing call to sort_message_list.

cache_header($msg_number, $header_ref)
--------------------------------------

Associates `$header_ref' with `$msg_number' in the object's internal
header cache.

invalidate_header($msg_number)
------------------------------

Clobbers the header cache entry for `$msg_number'.

AUTHOR
======

Kevin Johnson <`kjj@primenet.com'>

COPYRIGHT
=========

Copyright (c) 1996 Kevin Johnson <kjj@primenet.com>.

All rights reserved. This program is free software; you can redistribute
it and/or modify it under the same terms as Perl itself.


File: pm.info,  Node: Mail/Folder/Emaul,  Next: Mail/Folder/Mbox,  Prev: Mail/Folder,  Up: Module List

An Emaul folder interface for Mail::Folder.
*******************************************

NAME
====

Mail::Folder::Emaul - An Emaul folder interface for Mail::Folder.

*WARNING: This code is in alpha release. Expect the interface to change.*

SYNOPSYS
========

`use Mail::Folder::Emaul;'

DESCRIPTION
===========

This module provides an interface to the *emaul* folder mechanism.  It is
currently intended to be used as an example of hooking a folder interface
into Mail::Folder.

*Emaul*'s folder structure is styled after *mh*.  It uses directories for
folders and numerically-named files for the individual mail messages.  The
current message for a particular folder is stored in a file `.current_msg'
in the folder directory.

METHODS
=======

open($folder_name)
------------------

Populates the `Mail::Folder' object with information about the folder.

   * Call the superclass open method

   * For every message file in the `$folder_name' directory, add the
     message_number to the object's list of messages.

   * Load the contents of `$folder_dir/.current_msg' into
     `$self->{Current}'.

close
-----

Does nothing except call the close method of the superclass.

sync
----

Flushes any pending changes out to the original folder.

   * Call the superclass sync method

   * For every pending delete, unlink that file in the folder directory

   * Clear out the 'pending delete' list.

   * Scan the folder directory for message files that weren't present the
     last time the folder was either opened or synced.

   * Add each new file found to the list of messages being slung around in
     the Mail::Folder object.

   * Update the contents of the folder's `.current_msg' file.

   * Return the number of new messages found.

pack
----

Calls the superclass pack method.

Renames the message files in the folder so that there are no gaps in the
numbering sequence.

Old deleted message files (ones that start with `,') are also renamed as
necessary.

It also tweaks current_message accordingly.

It will abandon the operation and return `0' if a rename fails, otherwise
it returns 1.

Please note that pack acts on the real folder.

get_message($msg_number)
------------------------

Calls the superclass get_message method.

Retrieves the given mail message file into a *Mail::Internet* object
reference and returns the reference.

get_header($msg_number)
-----------------------

If the particular header has never been retrieved then get_header loads
the header of the given mail message into a member of
`$self->{Messages}{$msg_number}' and returns the object reference

If the header for the given mail message has already been retrieved in a
prior call to get_header, then the cached entry is returned.

It also calls the superclass get_header method.

append_message($message_ref)
----------------------------

Appends the contents of the mail message contained `$message_ref' to the
the folder.

   * Call the superclass `append_message' method.

   * Retrieve the highest message number in the folder

   * increment it

   * Create a new mail message file in the folder with the contents of
     `$message_ref'.

Please note that, contrary to other documentation for *Mail::Folder*, the
Emaul `append_message' method actually updates the real folder, rather
than queueing it up for a subsequent sync.  The dup and `refile' methods
are also affected. This will be fixed soon.

update_message($msg_number, $message_ref)
-----------------------------------------

Replaces the message pointed to by `$msg_number' with the contents of the
`Mail::Internet' object reference `$message_ref'.

   * Call the superclass update_message method.

   * Replaces the contents of the given mail file with the contents of
     `$message_ref'.

Please note that, contrary to other documentation for *Mail::Folder*, the
Emaul update_message method actually updates the real folder, rather than
queueing it up for a subsequent sync.  This will be fixed soon.

create($foldername)
-------------------

Creates a new folder named `$foldername'.  Returns `0' if the folder
already exists, otherwise returns of the folder creation was successful.

AUTHOR
======

Kevin Johnson <`kjj@primenet.com'>

COPYRIGHT
=========

Copyright (c) 1996 Kevin Johnson <kjj@primenet.com>.

All rights reserved. This program is free software; you can redistribute
it and/or modify it under the same terms as Perl itself.


File: pm.info,  Node: Mail/Folder/Mbox,  Next: Mail/Header,  Prev: Mail/Folder/Emaul,  Up: Module List

A Unix mbox interface for Mail::Folder.
***************************************

NAME
====

Mail::Folder::Mbox - A Unix mbox interface for Mail::Folder.

*WARNING: This code is in alpha release. Expect the interface to change.*

SYNOPSYS
========

`use Mail::Folder::Mbox;'

DESCRIPTION
===========

This module provides an interface to unix *mbox* folders.

The *mbox* folder format is the standard monolithic folder structure
prevalent on Unix.  A single folder is contained within a single file.
Each message starts with a line matching `/^From /'.

The folder architecture doesn't provide any persistantly stored current
message variable, so the current message in this folder interface defaults
to 1 and is not retained between opens of a folder.

`Mbox' needs the following module packages:

`TimeDate'
`File-Tools'
`File-BasicFLock'
METHODS
=======

init
----

Initializes various items specific to *Mbox*.

   * Determines an appropriate temporary directory.

   * Bumps a sequence number used for unique temporary filenames.

   * Initializes `$self->{WorkingFile}' to the name of a file that will be
     used to hold the temporary working of the folder.

   * Initializes `$self->{MsgFilePrefix}' to a string that will be used to
     create temporary filenames when extracting messages from the folder.

open($folder_name)
------------------

   * Call the superclass open method.

   * Lock the folder.

   * Copy the folder to a temporary location as a working copy.

   * Unlock the folder.

   * For every message in the folder, add the message_number to the
     object's list of messages.

close
-----

Deletes the working copy of the folder and calls the superclass close
method.

sync
----

   * Call the superclass sync method

   * Lock the folder

   * Append new messages to the working copy that have been appended to
     the folder since the last time the folder was either opened or synced.

   * Create a new copy of the folder and populate it with the messages in
     the working copy that aren't flagged for deletion.

   * Move the original folder to a temp location

   * Move the new folder into place

   * Delete the old original folder

   * Unlock the folder

pack
----

Calls the superclass pack method.  This is essentially a no-op since mbox
folders don't need to be packed.

get_message($msg_number)
------------------------

   * Call the superclass get_message method.

   * Create a temporary file with the contents of the given mail message.

   * Absorb the temporary file into a *Mail::Internet* object reference.

   * Delete the temporary file.

   * Return the *Mail::Internet* object reference.

get_header($msg_number)
-----------------------

If the particular header has never been retrieved then get_header loads
(in a manner similar to get_message) the header of the given mail message
into `$self->{Messages}{$msg_number}{Header}' and returns the object
reference.

If the header for the given mail message has already been retrieved in a
prior call to get_header, then the cached entry is returned.

It also calls the superclass get_header method.

append_message($message_ref)
----------------------------

   * Call the superclass `append_message' method.

   * Lock the folder.

   * If a 'From ' line isn't present in `$message_ref' then synthesize one.

   * Append the contents of `$message_ref' to the folder.

   * Adds a record of the new message in the internal data structures of
     `$self'.

   * Unlock the folder.

update_message($msg_number, $message_ref)
-----------------------------------------

   * Call the superclass update_message method.

   * Writes a new copy of the working folder file replacing the given
     message with the contents of the given *Mail::Internet* message
     reference.  It will synthesize a 'From ' line if one isn't present in
     $message_ref.

create($foldername)
-------------------

Creates a new folder named `$foldername'.  Returns `0' if the folder
already exists, otherwise returns of the folder creation was successful.

AUTHOR
======

Kevin Johnson <`kjj@primenet.com'>

COPYRIGHT
=========

Copyright (c) 1996 Kevin Johnson <kjj@primenet.com>.

All rights reserved. This program is free software; you can redistribute
it and/or modify it under the same terms as Perl itself.


File: pm.info,  Node: Mail/Header,  Next: Mail/Internet,  Prev: Mail/Folder/Mbox,  Up: Module List

manipulate mail RFC822 compliant headers
****************************************

NAME
====

Mail::Header - manipulate mail RFC822 compliant headers

SYNOPSIS
========

     use Mail::Header;
     
     $head = new Mail::Header;
     $head = new Mail::Header \*STDIN;
     $head = new Mail::Header [<>], Modify => 0;

DESCRIPTION
===========

This package provides a class object which can be used for reading,
creating, manipulating and writing RFC822 compliant headers.

CONSTRUCTOR
===========

new ( [ ARG ], [ OPTIONS ] )
     `ARG' may be either a file descriptor (reference to a GLOB) or a
     reference to an array. If given the new object will be initialized
     with headers either from the array of read from the file descriptor.

     OPTIONS is a list of options given in the form of key-value pairs,
     just like a hash table. Valid options are

    Reformat
          If this value is *true* then the headers will be re-formatted,
          otherwise the format of the header lines will remain unchanged.

    MailFrom
          This option specifies what to do when a header in the form `From
          ' is encountered. Valid values are `IGNORE' - ignore and discard
          the header, `ERROR' - invoke an error (call die), `COERCE' -
          rename them as Mail-From and `KEEP' - keep them.

    FoldLength
          The default length of line to be used when folding header lines

METHODS
=======

modify ( [ VALUE ] )
mail_from ( OPTION )
fold ( [ LENGTH ] )
extract ( ARRAY_REF )
read ( FD )
empty ()
header ( [ ARRAY_REF ] )
add ( TAG, LINE [, INDEX ] )
replace ( TAG, LINE [, INDEX ] )
combine ( TAG [, WITH ] )
get ( TAG [, INDEX ] )
exists ( TAG )
delete ( TAG [, INDEX ] )
print ( [ FD ] )
fold_length ( [ LENGTH ] )
tags ()
dup ()
cleanup ()
AUTHOR
======

Graham Barr <Graham.Barr@tiuk.ti.com>

COPYRIGHT
=========

Copyright (c) 1996 Graham Barr. All rights reserved. This program is free
software; you can redistribute it and/or modify it under the same terms as
Perl itself.

REVISION
========

$Revision: 1.1 $ $Date: 1996/08/13 09:26:15 $

The VERSION is derived from the revision turning each number after the
first dot into a 2 digit number so

     Revision 1.8   => VERSION 1.08
     Revision 1.2.3 => VERSION 1.0203


File: pm.info,  Node: Mail/Internet,  Next: Mail/MIME,  Prev: Mail/Header,  Up: Module List

manipulate Internet format (RFC 822) mail messages
**************************************************

NAME
====

Mail::Internet - manipulate Internet format (RFC 822) mail messages

SYNOPSIS
========

use Mail::Internet;

DESCRIPTION
===========

This package provides a class object which can be used for reading,
creating, manipulating and writing a message with RFC822 compliant headers.

METHODS
-------

body ()
     Returns the body of the message. This is a reference to an array.
     Each entry in the array represents a single line in the message.

print_header ( [ FILEHANDLE ] )
print_body ( [ FILEHANDLE ] )
print ( [ FILEHANDLE ] )
     Print the header, body or whole message to file descriptor
     *FILEHANDLE*.  *$fd* should be a reference to a GLOB. If *FILEHANDLE*
     is not given the output will be sent to STDOUT.

          $mail->print( \*STDOUT );  # Print message to STDOUT

head ()
     Returns the `Mail::Header' object which holds the headers for the
     current message

UTILITY METHODS
===============

The following methods are more a utility type that a manipulation type of
method.

remove_sig ( [ NLINES ] )
     Attempts to remove a users signature from the body of a message. It
     does this by looking for a line equal to `'-- '' within the last
     `NLINES' of the message. If found then that line and all lines after
     it will be removed. If `NLINES' is not given a default value of 10
     will be used. This would be of most use in auto-reply scripts.

tidy_body ()
     Removes all leading and trailing lines from the body that only contain
     white spaces.

reply ()
     Create a new object with header initialised for a reply to the current
     object. And the body will be a copy of the current message indented.

add_signature ( [ FILE ] )
     Append a signature to the message. FILE is a file which contains the
     signature, if not given then the file "$ENV{HOME}/.signature" will be
     checked for.

smtpsend ()
     Send a Mail::Internet message via SMTP

     The message will be sent to all addresses on the To, Cc and Bcc
     lines. The SMTP host is found by attempting connections first to
     hosts specified in `$ENV{SMTPHOSTS}', a colon separated list, then
     `mailhost' and `localhost'.

nntppost ()
     Post an article via NNTP, require News::NNTPClient.

SEE ALSO
========

*Note Mail/Header: Mail/Header, *Note Mail/Address: Mail/Address,

AUTHOR
======

Graham Barr <Graham.Barr@tiuk.ti.com>

REVISION
========

$Revision: 1.23 $

The VERSION is derived from the revision turning each number after the
first dot into a 2 digit number so

     Revision 1.8   => VERSION 1.08
     Revision 1.2.3 => VERSION 1.0203

COPYRIGHT
=========

Copyright (c) 1995 Graham Barr. All rights reserved. This program is free
software; you can redistribute it and/or modify it under the same terms as
Perl itself.


File: pm.info,  Node: Mail/MIME,  Next: Mail/Mailer,  Prev: Mail/Internet,  Up: Module List

manipulate MIME (RFC 1521) mail messages
****************************************

NAME
====

Mail::MIME - manipulate MIME (RFC 1521) mail messages

SYNOPSIS
========

use Mail::MIME;

DESCRIPTION
===========

This package provides a class object to implement MIME message as
specified in RFC 1521 *Multipurpose Internet Mail Extensions*

THIS PACKAGE IS EXPERIMENTAL AND ONLY HERE AS A PLACE HOLDER
============================================================


File: pm.info,  Node: Mail/Mailer,  Next: Mail/POP3Client,  Prev: Mail/MIME,  Up: Module List

Simple interface to electronic mailing mechanisms
*************************************************

NAME
====

Mail::Mailer - Simple interface to electronic mailing mechanisms

SYNOPSIS
========

     require Mail::Mailer;

     $mailer = new Mail::Mailer;

     $mailer = new Mail::Mailer $type, @args;

     $mailer->open(\%headers);

     print $mailer $body;

     $mailer->close;

DESCRIPTION
===========

Sends mail using any of the built-in methods.  You can alter the behaviour
of a method by passing `$command' to the new method.

`sendmail'
     Use the `sendmail' program to deliver the mail.  `$command' is the
     path to `sendmail'.

mail
     Use the Unix system mail program to deliver the mail.  `$command' is
     the path to mail.

`telnet'
     Telnet to the SMTP port of the local machine.  `$command' is the path
     to the `telnet' command.  `$Mail::Mailer' calls `$command localhost
     smtp'.

test
     Used for debugging, this calls `/bin/echo' to display the data.  No
     mail is ever sent.  `$command' is ignored.

ARGUMENTS
---------

new can optionally be given a `$command' and `$type'.  `$type' is one
`sendmail', mail, ... given above.  The meaning of `$command' depends on
`$type'.

open is given a reference to a hash.  The hash consists of key and value
pairs, the key being the name of the header field (eg, `To'), and the
value being the corresponding contents of the header field.  The value can
either be a scalar (eg, `gnat@frii.com') or a reference to an array of
scalars (`eg, [gnat@frii.com, Tim.Bunce@ig.co.uk]').

TO DO
=====

Assist formatting of fields in ...::rfc822:send_headers to ensure valid in
the face of newlines and longlines etc.

Secure all forms of send_headers() against hacker attack and invalid
contents. Especially "\n~..." in ...::mail::send_headers.

SEE ALSO
========

Mail::Send

AUTHORS
=======

Tim Bunce <Tim.Bunce@ig.co.uk>, with a kick start from Graham Barr
<bodg@tiuk.ti.com>. With contributions by Gerard Hickey <hickey@ctron.com>
For support please contact comp.lang.perl.misc.  Small fix and
documentation by Nathan Torkington <gnat@frii.com>.

REVISION
========

$Revision: 1.7 $

The VERSION is derived from the revision turning each number after the
first dot into a 2 digit number so

     Revision 1.8   => VERSION 1.08
     Revision 1.2.3 => VERSION 1.0203


File: pm.info,  Node: Mail/POP3Client,  Next: Mail/Send,  Prev: Mail/Mailer,  Up: Module List

Perl 5 module to talk to a POP3 (RFC1081) server
************************************************

NAME
====

Mail::POP3Client - Perl 5 module to talk to a POP3 (RFC1081) server

DESCRIPTION
===========

This module implements an Object-Oriented interface to a POP3 server.  It
is based on RFC1081.

USAGE
=====

Here is a simple example to list out the headers in your remote mailbox:

     #!/usr/local/bin/perl
     
     use Mail::POP3Client;
     
     $pop = new Mail::POP3Client("me", "mypassword", "pop3.do.main");
     for ($i = 1; $i <= $pop->Count; $i++) {
     	print $pop->Head($i), "\n";
     }

POP3Client Commands
-------------------

These commands are intended to make writing a POP3 client easier.  They do
not necessarily map directly to POP3 commands defined in RFC1081.  Some
commands return multiple lines as an array in an array context, but there
may be missing places.

new
     Construct a new POP3 connection with this.  You should give it at
     least 2 arguments: username and password.  The next 2 optional
     arguments are the POP3 host and port number.  A final fifth argument
     of a positive integer enables debugging on the object (to STDERR).

Head
     Get the headers of the specified message.  Here is a simple Biff
     program:

          #!/usr/local/bin/perl
          
          use Mail::POP3Client;
          
          $pop = new Mail::POP3Client("me", "mypass", "pop3.do.main");
          for ($i = 1; $i <= $pop->Count; $i++) {
          	foreach ($pop->Head($i)) {
          		/^(From|Subject): / and print $_, "\n";
          	}
          	print "\n";
          }

Body
     Get the body of the specified message.

HeadAndBody
     Get the head and body of the specified message.

Retrieve
     Same as HeadAndBody.

Delete
     Mark the specified message number as DELETED.  Becomes effective upon
     QUIT.  Can be reset with a Reset message.

Connect
     Start the connection to the POP3 server.  You can pass in the host and
     port.

Close
     Close the connection gracefully.  POP3 says this will perform any
     pending deletes on the server.

Alive
     Return true or false on whether the connection is active.

Socket
     Return the file descriptor for the socket.

Size
     Set/Return the size of the remote mailbox.  Set by POPStat.

Count
     Set/Return the number of remote messages.  Set during Login.

Message
     The last status message received from the server.

State
     The internal state of the connection: DEAD, AUTHORIZATION,
     TRANSACTION.

POPStat
     Return the results of a POP3 STAT command.  Sets the size of the
     mailbox.

List
     Return a list of sizes of each message.

Last
     Return the number of the last message, retrieved from the server.

Reset
     Tell the server to unmark any message marked for deletion.

User
     Set/Return the current user name.

Pass
     Set/Return the current user name.

Login
     Attempt to login to the server connection.

Host
     Set/Return the current host.

Port
     Set/Return the current port number.

AUTHOR
======

Sean Dowd <ssd@mmts.eds.com>

COPYRIGHT
=========

Copyright (c) 1995,1996 Electonic Data Systems, Inc.  All rights reserved.
This module is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

CREDITS
=======

Based loosely on News::NNTPClient by Rodger Anderson <rodger@boi.hp.com>.


File: pm.info,  Node: Mail/Send,  Next: Mail/Util,  Prev: Mail/POP3Client,  Up: Module List

Simple electronic mail interface
********************************

NAME
====

Mail::Send - Simple electronic mail interface

SYNOPSIS
========

     require Mail::Send;

     $msg = new Mail::Send;

     $msg = new Mail::Send Subject=>'example subject', To=>'timbo';

     $msg->to('user@host');
     $msg->subject('user@host');
     $msg->cc('user@host');
     $msg->bcc('someone@else');

     $msg->set($header, @values);
     $msg->add($header, @values);
     $msg->delete($header);

     # Launch mailer and set headers. The filehandle returned
     # by open() is an instance of the Mail::Mailer class.

     $fh = $msg->open;

     print $fh "Body of message";

     $fh->close;         # complete the message and send it

     $fh->cancel;        # not yet implemented

DESCRIPTION
===========

$Revision: 1.4 $

SEE ALSO
========

Mail::Mailer

AUTHORS
=======

Tim Bunce <Tim.Bunce@ig.co.uk>, with a kick start from Graham Barr
<bodg@tiuk.ti.com>. With contributions by Gerard Hickey <hickey@ctron.com>
For support please contact comp.lang.perl.misc.


File: pm.info,  Node: Mail/Util,  Next: Make,  Prev: Mail/Send,  Up: Module List

mail utility functions
**********************

NAME
====

Mail::Util - mail utility functions

SYNOPSIS
========

use Mail::Util qw( ... );

DESCRIPTION
===========

This package provides several mail related utility functions. Any function
required must by explicitly listed on the use line to be exported into the
calling package.

read_mbox( $file )
------------------

Read `$file', a binmail mailbox file, and return a list of  references.
Each reference is a reference to an array containg one message.

maildomain()
------------

Attempt to determine the current uers mail domain string via the following
methods

     Look for a sendmail.cf file and extract DH parameter
     Look for a smail config file and usr the first host defined in hostname(s)
     Try an SMTP connect (if Net::SMTP exists) first to mailhost then localhost
     Use value from Net::Domain::domainname (if Net::Domain exists)

mailaddress()
-------------

Return a guess at the current users mail address. The user can force the
return value by setting `$ENV{MAILADDRESS}'

AUTHOR
======

Graham Barr <bodg@tiuk.ti.com>

COPYRIGHT
=========

Copyright (c) 1995 Graham Barr. All rights reserved. This program is free
software; you can redistribute it and/or modify it under the same terms as
Perl itself.

REVISION
========

$Revision: 1.10 $


File: pm.info,  Node: Make,  Next: Math/Amoeba,  Prev: Mail/Util,  Up: Module List

module for processing makefiles
*******************************

NAME
====

Make - module for processing makefiles

SYNOPSIS
========

     require Make;
     my $make = Make->new(...);
     $make->parse($file);
     $make->Script(@ARGV)
     $make->Make(@ARGV)
     $make->Print(@ARGV)

     my $targ = $make->Target($name);
     $targ->colon([dependancy...],[command...]);
     $targ->dolon([dependancy...],[command...]);
     my @depends  = $targ->colon->depend;
     my @commands = $targ->colon->command;

DESCRIPTION
===========

Make->new creates an object if `new(Makefile => $file)' is specified then
it is parsed. If not the usual makefile Makefile sequence is used. (If GNU
=> 1 is passed to new then GNUmakefile is look for first.)

`$make->Make(target...)' 'makes' the target(s) specified (or the first
'real' target in the makefile).

`$make->Print' can be used to 'print' to current select'ed stream a form
of the makefile with all variables expanded.

`$make->Script(target...)' can be used to 'print' to current select'ed
stream the equivalent bourne shell script that a make would perform i.e.
the output of `make -n'.

There are other methods (used by parse) which can be used to add and
manipulate targets and their dependants. There is a hierarchy of classes
which is still evolving. These classes and their methods will be
documented when they are a little more stable.

The syntax of makefile accepted is reasonably generic, but I have not
re-read any documentation yet, rather I have implemented my own mental
model of how make works (then fixed it...).

In addition to traditional

     .c.o :
     	$(CC) -c ...

GNU make's 'pattern' rules e.g.

     %.o : %.c
     	$(CC) -c ...

Likewise a subset of GNU makes $(function arg...) syntax is supported.

Via pmake Make has built perl/Tk from the `MakeMaker' generated
Makefiles...

BUGS
====

At present new must always find a makefile, and `$make->parse($file)' can
only be used to augment that file.

More attention needs to be given to using the package to write makefiles.

The rules for matching 'dot rules' e.g. .c.o   and/or pattern rules e.g.
%.o : %.c are suspect. For example give a choice of .xs.o vs .xs.c + .c.o
behaviour seems a little odd.

Variables are probably substituted in different 'phases' of the process
than in make(1) (or even GNU make), so 'clever' uses will probably not
work.

UNIXisms abound.

SEE ALSO
========

`pmake' in this node

AUTHOR
======

Nick Ing-Simmons


File: pm.info,  Node: Math/Amoeba,  Next: Math/Approx,  Prev: Make,  Up: Module List

SYNOPSIS
========

     use Math::Amoeba qw(ConstructVertices EvaluateVertices Amoeba MinimiseND);
     my ($vertice,$y)=MinimiseND(\@guess,\@scales,\&func,$tol,$itmax);
     my @vertices=ConstructVertices(\@vector,\@offsets);
     my @y=EvaluateVertices(\@vertices,\&func);
     my ($vertice,$y)=Amoeba(\@vertices,\@y,\&func,$tol,$itmax);

DESCRIPTION
===========

This is an implimenation of the Downhill Simpex Method in Multidimensions
(Nelder and Mead) for finding the (local) minimum of a function. Doing
this in Perl makes it easy for that function to actually be the output of
another program such as a simulator.

Arrays and the function are passed by reference to the routines.

The simplest use is the *MinimiseND* function. This takes a reference to
an array of guess values for the parameters at the function minimum, a
reference to an array of scales for these parameters (sensible ranges
around the guess in which to look), a reference to the function, a
convergence tolerence for the minimum and the maximum number of iterations
to be taken. It returns an array consisting of a reference to the function
parameters at the minimum and the value there.

The *Amoeba* function is the actual implimentation of the Downhill Simpex
Method in Multidimensions. It takes a reference to an array of references
to arrays which are the initial n+1 vertices (where n is the number of
function parameters), a reference to the function valuation at these
vertices, a reference to the function, a convergence tolerence for the
minimum and the maximum number of iterations to be taken. It returns an
array consisting of a reference to the function parameters at the minimum
and the value there.

The *ConstructVertices* is used by *MinimiseND* to construct the initial
vertices for *Amoeba* as the initial guess plus the parameter scale
parameters as vectors along the parameter axis.

The *EvaluateVertices* takes these set of vertices, calling the function
for each one and returning the vector of results.

EXAMPLE
=======

     use Math::Amoeba qw(MinimiseND);
     sub afunc {
       my ($a,$b)=@_;
       print "$a\t$b\n";
       return ($a-7)**2+($b+3)**2;
     }
     my @guess=(1,1);
     my @scale=(1,1);
     ($p,$y)=MinimiseND(\@guess,\@scale,\&afunc,1e-7,100);
     print "(",join(',',@{$p}),")=$y\n";

produces the output

(6.99978191653352,-2.99981241563247)=1.00000008274829

HISTORY
=======

$Log: Amoeba.pm,v $ Revision 1.2  1995/12/24 12:37:46  willijar General
fixup. Added documentation.

BUGS
====

If the function value converges to exactly zero then the condition for
convergence fails and maximum iterations will be exceeded or there will be
a divide by zero error. There is no obvious way to test for convergence in
this case however adding 1 onto the function value gives expected
behaviour. i.e. replace '\&afunc' with 'sub { 1+afunc(@_); }' when calling
the routines.

Let me know.

AUTHOR
======

John A.R. Williams <J.A.R.Williams@aston.ac.uk>

SEE ALSO
========

"Numerical Recipies: The Art of Scientific Computing" W.H. Press, B.P.
Flannery, S.A. Teukolsky, W.T. Vetterling.  Cambridge University Press.
ISBN 0 521 30811 9.


File: pm.info,  Node: Math/Approx,  Next: Math/BigFloat,  Prev: Math/Amoeba,  Up: Module List

Math::Approx
************

NAME
====

Math::Approx

METHODS
=======

new
---

     new Math::Approx (\&poly, 5, %x);

The first argument after the class name must be a reference to function
which takes two arguments: The *degree* and the x value.

For interpolation with plain polynomials *poly* can be defined as:

     sub poly {
         my($n,$x) = @_;
     
         return $x ** $n;
     }

The second argument is the maximum degree which should be used for
interpolation. Degrees start with *0*.

The rest of the arguments are treated as pairs of x and *y* samples which
should be approximated.

The method returns a Math::Approx reference.

approx
------

     $approximation->approx(17);

The method returns the approximated  *y* value for the x value given as
argument.

fit
---

     $approximation->fit;

Returns the medim square error for the data points.

plot
----

     $approximation->plot("tmp/app");

Prints all data pairs and the corresponding approximation pairs in a file
whichs filename is given as argument. The file should be suitable for
usage with gnuplot(1).

print
-----

     $approximation->print;

Prints information about the approximation on *STDOUT*

EXAMPLE
=======

     use Math::Approx;
     
     sub poly {
         my($n,$x) = @_;
     
         return $x ** $n;
     }
     
     for (1..20) {
         $x{$_} = sin($_/10)*cos($_/30)+0.3*rand;
     }
     
     $a = new Math::Approx (\&poly, 5, %x);
     $a->print;
     $a->plot("mist");
     print "Fit: ", $a->fit, "\n";

SEE ALSO
========

gnuplot(1).

AUTHOR
======

Ulrich Pfeifer <pfeifer@ls6.informatik.uni-dortmund.de>


File: pm.info,  Node: Math/BigFloat,  Next: Math/BigInt,  Prev: Math/Approx,  Up: Module List

Arbitrary length float math package
***********************************

NAME
====

Math::BigFloat - Arbitrary length float math package

SYNOPSIS
========

     use Math::BogFloat;
     $f = Math::BigFloat->new($string);

     $f->fadd(NSTR) return NSTR            addition
     $f->fsub(NSTR) return NSTR            subtraction
     $f->fmul(NSTR) return NSTR            multiplication
     $f->fdiv(NSTR[,SCALE]) returns NSTR   division to SCALE places
     $f->fneg() return NSTR                negation
     $f->fabs() return NSTR                absolute value
     $f->fcmp(NSTR) return CODE            compare undef,<0,=0,>0
     $f->fround(SCALE) return NSTR         round to SCALE digits
     $f->ffround(SCALE) return NSTR        round at SCALEth place
     $f->fnorm() return (NSTR)             normalize
     $f->fsqrt([SCALE]) return NSTR        sqrt to SCALE places

DESCRIPTION
===========

All basic math operations are overloaded if you declare your big floats as

     $float = new Math::BigFloat "2.123123123123123123123123123123123";

number format
     canonical strings have the form /[+-]\d+E[+-]\d+/ .  Input values can
     have inbedded whitespace.

Error returns 'NaN'
     An input parameter was "Not a Number" or divide by zero or sqrt of
     negative number.

Division is computed to
     `max($div_scale,length(dividend)+length(divisor))' digits by default.
     Also used for default sqrt scale.

BUGS
====

The current version of this module is a preliminary version of the real
thing that is currently (as of perl5.002) under development.

AUTHOR
======

Mark Biggar


File: pm.info,  Node: Math/BigInt,  Next: Math/BigInteger,  Prev: Math/BigFloat,  Up: Module List

Arbitrary size integer math package
***********************************

NAME
====

Math::BigInt - Arbitrary size integer math package

SYNOPSIS
========

     use Math::BigInt;
     $i = Math::BigInt->new($string);

     $i->bneg return BINT               negation
     $i->babs return BINT               absolute value
     $i->bcmp(BINT) return CODE         compare numbers (undef,<0,=0,>0)
     $i->badd(BINT) return BINT         addition
     $i->bsub(BINT) return BINT         subtraction
     $i->bmul(BINT) return BINT         multiplication
     $i->bdiv(BINT) return (BINT,BINT)  division (quo,rem) just quo if scalar
     $i->bmod(BINT) return BINT         modulus
     $i->bgcd(BINT) return BINT         greatest common divisor
     $i->bnorm return BINT              normalization

DESCRIPTION
===========

All basic math operations are overloaded if you declare your big integers
as

     $i = new Math::BigInt '123 456 789 123 456 789';

Canonical notation
     Big integer value are strings of the form `/^[+-]\d+$/' with leading
     zeros suppressed.

Input
     Input values to these routines may be strings of the form
     `/^\s*[+-]?[\d\s]+$/'.

Output
     Output values always always in canonical form

Actual math is done in an internal format consisting of an array whose
first element is the sign (/^[+-]$/) and whose remaining elements are base
100000 digits with the least significant digit first.  The string 'NaN' is
used to represent the result when input arguments are not numbers, as well
as the result of dividing by zero.

EXAMPLES
========

     '+0'                            canonical zero value
     '   -123 123 123'               canonical value '-123123123'
     '1 23 456 7890'                 canonical value '+1234567890'

BUGS
====

The current version of this module is a preliminary version of the real
thing that is currently (as of perl5.002) under development.

AUTHOR
======

Mark Biggar, overloaded interface by Ilya Zakharevich.


File: pm.info,  Node: Math/BigInteger,  Next: Math/Brent,  Prev: Math/BigInt,  Up: Module List

Arbitrary length integer extension module for Perl
**************************************************

NAME
====

BigInteger - Arbitrary length integer extension module for Perl

SYNOPSIS
========

     use Math::BigInteger;

DESCRIPTION
===========

The BigInteger extension module gives access to Eric Young's bignum
library.  This provides a faster alternative to the Math::BigInt library.

The basic object in this library is a BigInteger.  It is used to hold a
single large integer.

It is not intended that this package be used directly, but instead be used
by a wrapper package, such as the Math::BigInteger class.

FUNCTIONS
=========

Many of the following functions can be used in two styles, by calling the
function on an object, or by calling the function explicitly; for example,
here are two ways of assigning to $a the sum of $b and $c:

     $a->add($b, $c);
     or

     BigInteger::add($a, $b, $c);

Creation/Destruction routines.
------------------------------

new
          my $bi = new BigInteger;	# Create a new BigInteger object.

clone
          my $b = $a->clone();

     Create a new BigInteger object from another BigInteger object.

copy
          copy($a, $b);

     Copy one BigInteger object to another.

save
          my $data = $bi->save();

     Save a BigInteger object as a MSB-first string.

restore
          my $bi = restore BigInteger $data;

     Create a new BigInteger object from a MSB-first string.

Comparison functions
--------------------

ucmp
          ucmp($a, $b);

     Return -1 if $a is less than $b, 0 if $a and $b are the same and 1 is
     $a is greater than $b.  This is an *unsigned* comparison.

cmp
          cmp($a, $b);

     Return -1 if $a is less than $b, 0 if $a and $b are the same and 1 is
     $a is greater than $b.  This is a *signed* comparison.

Arithmetic Functions
--------------------

inc 	$bi->inc();
     Increment $bi by one:

dec 	$bi->dec();
     Decrement $bi by one:

add
          $r->add($a, $b);

     Add $a and $b and return the result in $r.

mul
          $r->mul($a, $b);

     Multiply $a by $b and return the result in $r.  Note that $r must not
     be the same object as $a or $b.

div
          div($dv, $rem, $m, $d);

     Divide $m by $d and return the result in $dv and the remainder in
     $rem.  Either of $dv or $rem can be undef, in which case that value
     is not returned.

mod
          $rem->mod($m, $d);

     Find the remainder of $m divided by $d and return it in $rem.  This
     function is more efficient than div.

lshift
          $r->lshift($a, $n);

     Shift $a left by $n bits.

lshift1
          $r->lshift1($a);

     Shift $a left by 1 bit.  This form is more efficient than `lshift($r,
     $a, 1)'.

rshift
          $r->rshift($a, $n);

     Shift $a right by $n bits.

rshift1
          $r->rshift1($a);

     Shift $a right by 1 bit.  This form is more efficient than
     `rshift($r, $a, 1)'.

mod_exp
          $r->mod_exp($a, $p, $mod);

     Raise $a to the $p power and return the remainder into $r when
     divided by $m.

modmul_recip
          modmul_recip($r, $x, $y, $m, $i, $nb);

     This function is used to perform an efficient `mod_mul' operation.
     If one is going to repeatedly perform `mod_mul' with the same modulus
     is worth calculating the reciprocal of the modulus and then using this
     function.  This operation uses the fact that a/b == a*r where r is the
     reciprocal of b.  On modern computers multiplication is very fast and
     big number division is very slow.  $x is multiplied by $y and then
     divided by $m and the remainder is returned in $r.  $i is the
     reciprocal of $m and $nb is the number of bits as returned from
     `reciprocal'.  This function is used in mod_exp.

mul_mod
          $r->mul_mod($a, $b, $m);

     Multiply $a by $b and return the remainder into $r when divided by $m.

reciprical
          $r->reciprical($m);

     Return the reciprocal of $m into $r.

Miscellaneous Routines
----------------------

num_bits
          my $size = $bi->numbits();

     Return the size (in bits) of the BigInteger.

gcd
          $r->gcd($a, $b);

     $r has the greatest common divisor of $a and $b.

inverse_modn
          $r->inverse_modn($a, $n);

     This function creates a new BigInteger and returns it in $r.  This
     number is the inverse mod $n of $a.  By this it is meant that the
     returned value $r satisfies (a*r)%n == 1.  This function is used in
     the generation of RSA keys.

BUGS
====

Negative numbers cannot be saved or restored.  To fix this requires
modification of Eric Young's library.

The documentation.

COPYRIGHT
=========

Systemics Ltd ( http://www.systemics.com/ ).

Portions copyright Eric Young (eay@mincom.oz.au).


File: pm.info,  Node: Math/Brent,  Next: Math/Complex,  Prev: Math/BigInteger,  Up: Module List

SYNOPSIS
========

     use Math::Brent qw(FindMinima BracketMinimum Brent Minimise1D);
     my ($x,$y)=Minimise1D($guess,$scale,\&func,$tol,$itmax);
     my ($ax,$bx,$cx,$fa,$fb,$fc)=BracketMinimum($ax,$bx,$cx,\&func);
     my ($x,$y)=Brent($ax,$bx,$cx,\&func,$tol,$itmax);

DESCRIPTION
===========

This is an implementation of Brents method for One-Dimensional
minimisation of a function without using derivatives. This algorithm
cleverly uses both the Golden Section Search and parabolic interpolation.

The main function *Brent*, given a function reference *\&func* and a
bracketing triplet of abcissas *$ax*, *$bx*, *$cx* (such that *$bx* is
between *$ax* and *$cx* and *func($bx)* is less than both *func($ax)* and
*func($cx)*), isolates the minimum to a fractional precision of about
*$tol* using Brents method. A maximum number of iterations *$itmax* may be
specified for this search - it defaults to 100. Returned is an array
consisting of the abcissa of the minum and the function value there.

The function *BracketMinimum*, given a function *\&func* and distinct
initial points *$ax* and *$bx* searches in the downhill direction (defined
by the function as evaluated at the initial points) and returns an array
of the three points *$ax*, *$bx*, *$cx* which bracket the minimum of the
function and the function values at those points.

The function *Minimise1D* provides a simple interface to the above two
routines. Given a function *\&func*, an initial guess for its minimum, and
its scaling (*$guess*,*$scale*) this routine isolates the minimum to a
fractional precision of about *$tol* using Brents method. A maximum number
of iterations *$itmax* may be specified for this search - it defaults to
100. It returns an array consisting of the abcissa of the minum and the
function value there.

EXAMPLE
=======

     use Math::Brent qw(Minimise1D);
     sub func {
       my $x=shift ;
       return $x ? sin($x)/$x: 1;
     }
        my ($x,$y)=Minimise1D(1,1,\&func,1e-7);
        print "Minimum is func($x)=$y\n";

produces the output

     Minimum is func(5.236068)=-.165388470697432
     
     =head1 HISTORY

$Log: Brent.pm,v $ Revision 1.1  1995/12/26 10:06:36  willijar Initial
revision

BUGS
====

Let me know of any problems.

AUTHOR
======

John A.R. Williams <J.A.R.Williams@aston.ac.uk>

SEE ALSO
========

"Numerical Recipies: The Art of Scientific Computing" W.H. Press, B.P.
Flannery, S.A. Teukolsky, W.T. Vetterling.  Cambridge University Press.
ISBN 0 521 30811 9.


File: pm.info,  Node: Math/Complex,  Next: Math/DVector,  Prev: Math/Brent,  Up: Module List

complex numbers and associated mathematical functions
*****************************************************

NAME
====

Math::Complex - complex numbers and associated mathematical functions

SYNOPSIS
========

     use Math::Complex;
     $z = Math::Complex->make(5, 6);
     $t = 4 - 3*i + $z;
     $j = cplxe(1, 2*pi/3);

DESCRIPTION
===========

This package lets you create and manipulate complex numbers. By default,
Perl limits itself to real numbers, but an extra use statement brings full
complex support, along with a full set of mathematical functions typically
associated with and/or extended to complex numbers.

If you wonder what complex numbers are, they were invented to be able to
solve the following equation:

     x*x = -1

and by definition, the solution is noted *i* (engineers use *j* instead
since *i* usually denotes an intensity, but the name does not matter). The
number *i* is a pure *imaginary* number.

The arithmetics with pure imaginary numbers works just like you would
expect it with real numbers... you just have to remember that

     i*i = -1

so you have:

     5i + 7i = i * (5 + 7) = 12i
     4i - 3i = i * (4 - 3) = i
     4i * 2i = -8
     6i / 2i = 3
     1 / i = -i

Complex numbers are numbers that have both a real part and an imaginary
part, and are usually noted:

     a + bi

where a is the *real* part and b is the *imaginary* part. The arithmetic
with complex numbers is straightforward. You have to keep track of the
real and the imaginary parts, but otherwise the rules used for real
numbers just apply:

     (4 + 3i) + (5 - 2i) = (4 + 5) + i(3 - 2) = 9 + i
     (2 + i) * (4 - i) = 2*4 + 4i -2i -i*i = 8 + 2i + 1 = 9 + 2i

A graphical representation of complex numbers is possible in a plane (also
called the *complex plane*, but it's really a 2D plane).  The number

     z = a + bi

is the point whose coordinates are (a, b). Actually, it would be the
vector originating from (0, 0) to (a, b). It follows that the addition of
two complex numbers is a vectorial addition.

Since there is a bijection between a point in the 2D plane and a complex
number (i.e. the mapping is unique and reciprocal), a complex number can
also be uniquely identified with polar coordinates:

     [rho, theta]

where `rho' is the distance to the origin, and `theta' the angle between
the vector and the x axis. There is a notation for this using the
exponential form, which is:

     rho * exp(i * theta)

where *i* is the famous imaginary number introduced above. Conversion
between this form and the cartesian form `a + bi' is immediate:

     a = rho * cos(theta)
     b = rho * sin(theta)

which is also expressed by this formula:

     z = rho * exp(i * theta) = rho * (cos theta + i * sin theta)

In other words, it's the projection of the vector onto the x and *y* axes.
Mathematicians call *rho* the *norm* or *modulus* and *theta* the
*argument* of the complex number. The *norm* of `z' will be noted `abs(z)'.

The polar notation (also known as the trigonometric representation) is
much more handy for performing multiplications and divisions of complex
numbers, whilst the cartesian notation is better suited for additions and
substractions. Real numbers are on the x axis, and therefore *theta* is
zero.

All the common operations that can be performed on a real number have been
defined to work on complex numbers as well, and are merely *extensions* of
the operations defined on real numbers. This means they keep their natural
meaning when there is no imaginary part, provided the number is within
their definition set.

For instance, the sqrt routine which computes the square root of its
argument is only defined for positive real numbers and yields a positive
real number (it is an application from *R+* to *R+*).  If we allow it to
return a complex number, then it can be extended to negative real numbers
to become an application from R to C (the set of complex numbers):

     sqrt(x) = x >= 0 ? sqrt(x) : sqrt(-x)*i

It can also be extended to be an application from C to C, whilst its
restriction to R behaves as defined above by using the following
definition:

     sqrt(z = [r,t]) = sqrt(r) * exp(i * t/2)

Indeed, a negative real number can be noted `[x,pi]' (the modulus x is
always positive, so `[x,pi]' is really -x, a negative number) and the
above definition states that

     sqrt([x,pi]) = sqrt(x) * exp(i*pi/2) = [sqrt(x),pi/2] = sqrt(x)*i

which is exactly what we had defined for negative real numbers above.

All the common mathematical functions defined on real numbers that are
extended to complex numbers share that same property of working *as usual*
when the imaginary part is zero (otherwise, it would not be called an
extension, would it?).

A new operation possible on a complex number that is the identity for real
numbers is called the *conjugate*, and is noted with an horizontal bar
above the number, or `~z' here.

     z = a + bi
     	~z = a - bi

Simple... Now look:

     z * ~z = (a + bi) * (a - bi) = a*a + b*b

We saw that the norm of `z' was noted `abs(z)' and was defined as the
distance to the origin, also known as:

     rho = abs(z) = sqrt(a*a + b*b)

so

     z * ~z = abs(z) ** 2

If z is a pure real number (i.e. `b == 0'), then the above yields:

     a * a = abs(a) ** 2

which is true (abs has the regular meaning for real number, i.e. stands
for the absolute value). This example explains why the norm of `z' is
noted `abs(z)': it extends the abs function to complex numbers, yet is the
regular abs we know when the complex number actually has no imaginary
part... This justifies *a posteriori* our use of the abs notation for the
norm.

OPERATIONS
==========

Given the following notations:

     z1 = a + bi = r1 * exp(i * t1)
     z2 = c + di = r2 * exp(i * t2)
     z = <any complex or real number>

the following (overloaded) operations are supported on complex numbers:

     z1 + z2 = (a + c) + i(b + d)
     z1 - z2 = (a - c) + i(b - d)
     z1 * z2 = (r1 * r2) * exp(i * (t1 + t2))
     z1 / z2 = (r1 / r2) * exp(i * (t1 - t2))
     z1 ** z2 = exp(z2 * log z1)
     ~z1 = a - bi
     abs(z1) = r1 = sqrt(a*a + b*b)
     sqrt(z1) = sqrt(r1) * exp(i * t1/2)
     exp(z1) = exp(a) * exp(i * b)
     log(z1) = log(r1) + i*t1
     sin(z1) = 1/2i (exp(i * z1) - exp(-i * z1))
     cos(z1) = 1/2 (exp(i * z1) + exp(-i * z1))
     abs(z1) = r1
     atan2(z1, z2) = atan(z1/z2)

The following extra operations are supported on both real and complex
numbers:

     Re(z) = a
     Im(z) = b
     arg(z) = t

     cbrt(z) = z ** (1/3)
     log10(z) = log(z) / log(10)
     logn(z, n) = log(z) / log(n)

     tan(z) = sin(z) / cos(z)
     cotan(z) = 1 / tan(z)

     asin(z) = -i * log(i*z + sqrt(1-z*z))
     acos(z) = -i * log(z + sqrt(z*z-1))
     atan(z) = i/2 * log((i+z) / (i-z))
     acotan(z) = -i/2 * log((i+z) / (z-i))

     sinh(z) = 1/2 (exp(z) - exp(-z))
     cosh(z) = 1/2 (exp(z) + exp(-z))
     tanh(z) = sinh(z) / cosh(z)
     cotanh(z) = 1 / tanh(z)
     
     asinh(z) = log(z + sqrt(z*z+1))
     acosh(z) = log(z + sqrt(z*z-1))
     atanh(z) = 1/2 * log((1+z) / (1-z))
     acotanh(z) = 1/2 * log((1+z) / (z-1))

The root function is available to compute all the nth roots of some
complex, where n is a strictly positive integer.  There are exactly n such
roots, returned as a list. Getting the number mathematicians call `j' such
that:

     1 + j + j*j = 0;

is a simple matter of writing:

     $j = ((root(1, 3))[1];

The *k*th root for `z = [r,t]' is given by:

     (root(z, n))[k] = r**(1/n) * exp(i * (t + 2*k*pi)/n)

The *spaceshift* operation is also defined. In order to ensure its
restriction to real numbers is conform to what you would expect, the
comparison is run on the real part of the complex number first, and
imaginary parts are compared only when the real parts match.

CREATION
========

To create a complex number, use either:

     $z = Math::Complex->make(3, 4);
     $z = cplx(3, 4);

if you know the cartesian form of the number, or

     $z = 3 + 4*i;

if you like. To create a number using the trigonometric form, use either:

     $z = Math::Complex->emake(5, pi/3);
     $x = cplxe(5, pi/3);

instead. The first argument is the modulus, the second is the angle (in
radians).  (Mnmemonic: `e' is used as a notation for complex numbers in
the trigonometric form).

It is possible to write:

     $x = cplxe(-3, pi/4);

but that will be silently converted into `[3,-3pi/4]', since the modulus
must be positive (it represents the distance to the origin in the complex
plane).

STRINGIFICATION
===============

When printed, a complex number is usually shown under its cartesian form
*a+bi*, but there are legitimate cases where the polar format *[r,t]* is
more appropriate.

By calling the routine `Math::Complex::display_format' and supplying either
`"polar"' or `"cartesian"', you override the default display format, which
is `"cartesian"'. Not supplying any argument returns the current setting.

This default can be overridden on a per-number basis by calling the
`display_format' method instead. As before, not supplying any argument
returns the current display format for this number. Otherwise whatever you
specify will be the new display format for *this* particular number.

For instance:

     use Math::Complex;

     Math::Complex::display_format('polar');
     $j = ((root(1, 3))[1];
     print "j = $j\n";		# Prints "j = [1,2pi/3]
     $j->display_format('cartesian');
     print "j = $j\n";		# Prints "j = -0.5+0.866025403784439i"

The polar format attempts to emphasize arguments like *k*pi/n* (where n is
a positive integer and *k* an integer within [-9,+9]).

USAGE
=====

Thanks to overloading, the handling of arithmetics with complex numbers is
simple and almost transparent.

Here are some examples:

     use Math::Complex;

     $j = cplxe(1, 2*pi/3);	# $j ** 3 == 1
     print "j = $j, j**3 = ", $j ** 3, "\n";
     print "1 + j + j**2 = ", 1 + $j + $j**2, "\n";

     $z = -16 + 0*i;			# Force it to be a complex
     print "sqrt($z) = ", sqrt($z), "\n";

     $k = exp(i * 2*pi/3);
     print "$j - $k = ", $j - $k, "\n";

BUGS
====

Saying `use Math::Complex;' exports many mathematical routines in the
caller environment.  This is construed as a feature by the Author,
actually... ;-)

The code is not optimized for speed, although we try to use the cartesian
form for addition-like operators and the trigonometric form for all
multiplication-like operators.

The arg() routine does not ensure the angle is within the range [-pi,+pi]
(a side effect caused by multiplication and division using the
trigonometric representation).

All routines expect to be given real or complex numbers. Don't attempt to
use BigFloat, since Perl has currently no rule to disambiguate a '+'
operation (for instance) between two overloaded entities.

AUTHOR
======

Raphael Manfredi <`Raphael_Manfredi@grenoble.hp.com'>


File: pm.info,  Node: Math/DVector,  Next: Math/Derivative,  Prev: Math/Complex,  Up: Module List

Fast, compact vectors using arrays of double.
*********************************************

NAME
====

Math::DVector - Fast, compact vectors using arrays of double.

DESCRIPTION
===========

*Math::DVector* implements a very simple class of vectors (arrays of
double).  Indexing starts from zero.

The interface is somewhat arbitrary, I hope to remove some of the
redundant functions later and have a better interface to this class.

Methods:

new(size)
     Creates a new vector with initial size size

aslist
     Returns a list with the elements of the vector.

setlist(list)
     Sets the vector values to list. If list is different size than the
     vector, the surplus elements are ignored.

asstr
     Returns a string with the elements of the vector separated by spaces,
     the whole string surrounded by brackets.  (useful in print commands)

copy
     Returns a new vector that is a copy of this vector

getelem(*i*)
     Returns the *i*th element of the vector

putelem(*i*,*el*)
     Set the *i*th element of the vector to *el*.

resize(n)
     Resize the vector to contain exactly n elements.  Existing elements
     are preserved.  New elements have undefined values.

zero
     Zero all elements of the vector.

getsize
     Returns the size of the vector

add_vec(vec,s)
     Add the values of vector vec multiplied by s to this vector.  Vectors
     needn't be same size.

set_vec(vec,s)
     Set this vector to the values of vector vec multiplied by s.  No
     resizing.

add_step(vec,s)
     Add the value of vec scaled so that its euclidean length is s to this
     vector. Result is undefined if |vec| is very small.

mul_dbl(s)
     Multiply the vector by a scale.

randomize(min,max)
     Set all the elements of this vector to evenly distributed random
     values between min and max.

BUGS
====

Very arbitrary interface

Currently, the only mode of operation is "safe", checking the indices on
each element access, which is a pain in some operations.  This should be
an external pragma, so that there are two different DVector objects.

AUTHOR
======

Tuomas J. Lukka (Tuomas.Lukka@Helsinki.FI)


File: pm.info,  Node: Math/Derivative,  Next: Math/Fortran,  Prev: Math/DVector,  Up: Module List

SYNOPSIS
========

     use Math::Derivative qw(Derivative1 Derivative2);
     @dydx=Derivative1(\@x,\@y);
     @d2ydx2=Derivative2(\@x,\@y);
     @d2ydx2=Derivative2(\@x,\@y,$yp0,$ypn);

DESCRIPTION
===========

This Perl package exports functions for performing numerical first
(*Derivative1*) and second *Derivative2*) order differentiation on vectors
of data. They both take references to two arrays containing the x and y
ordinates of the data and return an array of the 1st or 2nd derivative at
the given x ordinates. *Derivative2* may optionally be given values to use
for the first dervivative at the start and end points of the data -
otherwiswe 'natural' values are used.

HISTORY
=======

$Log: Derivative.pm,v $ Revision 1.1  1995/12/26 16:26:59  willijar
Initial revision

BUGS
====

Let me know.

AUTHOR
======

John A.R. Williams <J.A.R.Williams@aston.ac.uk>


File: pm.info,  Node: Math/Fortran,  Next: Math/Matrix,  Prev: Math/Derivative,  Up: Module List

SYNOPSIS
========

     use Math::Fortran qw(log10 sign);
     $v=log10($x);
     $v=sign($y);
     $v=sign($x,$y);

DESCRIPTION
===========

This module provides and exports some mathematical functions which are
built in in Fortran but not in Perl. Currently there are only 2 included.

log10 log to the base of 10 =item *sign* with 1 parameter, +1 if $y>=0, -1 otherwise, with 2 parameters +abs($x) if $y>=0, -abs($x) otherwise.
HISTORY
=======

$Log: Fortran.pm,v $ Revision 1.1  1995/12/26 09:43:01  willijar Initial
revision

BUGS
====

I welcome other entries for this module and bug reports.

AUTHOR
======

John A.R. Williams <J.A.R.Williams@aston.ac.uk>


File: pm.info,  Node: Math/Matrix,  Next: Math/PRSG,  Prev: Math/Fortran,  Up: Module List

Multiply and invert Matrices
****************************

NAME
====

Math::Matrix - Multiply and invert Matrices

DESCRIPTION
===========

The following methods are available:

new
---

Constructor arguments are a list of references to arrays of the same
length.  The arrays are copied. The method returns undef in case of error.

     $a = new Math::Matrix ([rand,rand,rand],
                            [rand,rand,rand],
                            [rand,rand,rand]);

concat
------

Concatenates two matrices of same row count. The result is a new matrix or
undef in case of error.

     $b = new Math::Matrix ([rand],[rand],[rand]);
     $c = $a->concat($b);

transpose
---------

Returns the transposed matrix. This is the matrix where colums and rows of
the argument matrix are swaped.

multiply
--------

Multiplies two matrices where the length of the rows in the first matrix
is the same as the length of the columns in the second matrix. Returns the
product or undef in case of error.

solve
-----

Solves a equation system given by the matrix. The number of colums must be
greater than the number of rows. If variables are dependent from each
other, the second and all further of the dependent coefficients are 0.
This means the method can handle such systems. The method returns a matrix
containing the solutions in its columns or undef in case of error.

print
-----

Prints the matrix on STDOUT. If the method has additional parameters,
these are printed before the matrix is printed.

EXAMPLE
=======

     use Math::Matrix;

     srand(time);
     $a = new Math::Matrix ([rand,rand,rand],
                      [rand,rand,rand],
                      [rand,rand,rand]);
     $x = new Math::Matrix ([rand,rand,rand]);
     $a->print("A\n");
     $E = $a->concat($x->transpose);
     $E->print("Equation system\n");
     $s = $E->solve;
     $s->print("Solutions s\n");
     $a->multiply($s)->print("A*s\n");

AUTHOR
======

Ulrich Pfeifer <pfeifer@ls6.informatik.uni-dortmund.de>


File: pm.info,  Node: Math/PRSG,  Next: Math/Spline,  Prev: Math/Matrix,  Up: Module List

Perl interface to pseudo random sequence generator function.
************************************************************

NAME
====

PRSG - Perl interface to pseudo random sequence generator function.

SYNOPSIS
========

     use Math::PRSG;

DESCRIPTION
===========

This perl extension implements a (159, 31, 0) LFSR, giving a period of 160
bits.  This can then be used as a RNG if seeded well (ie. with 160 bits of
entropy) and if the output is fed through a message digest function (in
order to prevent any prediction).

FUNCTIONS
=========

new
          my $prsg = new PRSG $seed;

     Create a new PRSG object.  A 160 bit (20-byte) $seed must be provided,
     which is used to seed the LFSR.

seed
          $prsg->seed($rnd);

     Seed the LFSR with $rnd.

clock
          $value = $prsg->clock();

     Clock the LFSR, returning the new register value as a 20-byte string.

COPYRIGHT
=========

Systemics Ltd ( http://www.systemics.com/ )


File: pm.info,  Node: Math/Spline,  Next: Math/Trig,  Prev: Math/PRSG,  Up: Module List

SYNOPSIS          require Math::Spline;     $spline=new Math::Spline(\@x,\@y)     $y_interp=$spline->evaluate($x);
==================================================================================================================

     use Math::Spline qw(spline linsearch binsearch);
     use Math::Derivative qw(Derivative2);
     @y2=Derivative2(\@x,\@y);
     $index=binsearch(\@x,$x);
     $index=linsearch(\@x,$x,$index);
     $y_interp=spline(\@x,\@y,\@y2,$index,$x);

DESCRIPTION
===========

This package provides cubic spline interpolation of numeric data. The data
is passed as references to two arrays containing the x and y ordinates. It
may be used as an exporter of the numerical functions or, more easily as a
class module.

The *Math::Spline* class constructor new takes references to the arrays of
x and y ordinates of the data. An interpolation is performed using the
*evaluate* method, which, when given an x ordinate returns the interpolate
y ordinate at that value.

The *spline* function takes as arguments references to the x and y
ordinate array, a reference to the 2nd derivatives (calculated using
*Derivative2*, the low index of the interval in which to interpolate and
the x ordinate in that interval. Returned is the interpolated y ordinate.
Two functions are provided to look up the appropriate index in the array
of x data. For random calls *binsearch* can be used - give a reference to
the x ordinates and the x loopup value it returns the low index of the
interval in the data in which the value lies. Where the lookups are
strictly in ascending sequence (e.g. if interpolating to produce a higher
resolution data set to draw a curve) the *linsearch* function may more
efficiently be used. It performs like *binsearch*, but requires a third
argument being the previous index value, which is incremented if necessary.

NOTE
====

requires Math::Derivative module

EXAMPLE
=======

     require Math::Spline;
     my @x=(1,3,8,10);
     my @y=(1,2,3,4);
     $spline=new Math::Spline(\@x,\@y);
     print $spline->evaluate(5)."\n";

produces the output

2.44

HISTORY
=======

$Log: Spline.pm,v $ Revision 1.1  1995/12/26 17:28:17  willijar Initial
revision

BUGS
====

Bug reports or constructive comments are welcome.

AUTHOR
======

John A.R. Williams <J.A.R.Williams@aston.ac.uk>

SEE ALSO
========

"Numerical Recipies: The Art of Scientific Computing" W.H. Press, B.P.
Flannery, S.A. Teukolsky, W.T. Vetterling.  Cambridge University Press.
ISBN 0 521 30811 9.


File: pm.info,  Node: Math/Trig,  Next: Math/TrulyRandom,  Prev: Math/Spline,  Up: Module List

SYNOPSIS
========

     use Math::Trig qw(tan asin acos sinh cosh tanh sech cosech);
     $v=tan($x);
     $v=asin($x);
     $v=acos($x);
     $v=sinh($x);
     $v=cosh($x);
     $v=tanh($x);
     $v=sech($x);
     $v=cosech($x);

DESCRIPTION
===========

This module exports the missing inverse and hyperbolic trigonemtric
functions of real numbers.

tan returns tan of real argument =item asin returns inverse sine of real argument =item acos returns inverse cosine of real argument =item sinh returns hyperbolic sine of real argument =item cosh returns hyperbolic cosine of real argument =item tanh returns hyperbolic tan of real argument =item *sech* returns hyperbolic secant of real argument =item *cosech* returns hyperbolic cosecant of real argument
HISTORY
=======

$Log: Trig.pm,v $ Revision 1.2  1995/12/28 16:32:37  willijar Moved
hyoerbolic functions into here.

Revision 1.1  1995/12/24 16:06:26  willijar Initial revision

BUGS
====

Let me know.

I welcome additions such as the inverse trigonemetric functions and the
complex versions of the functions to be included in this module.

AUTHOR
======

John A.R. Williams <J.A.R.Williams@aston.ac.uk>


File: pm.info,  Node: Math/TrulyRandom,  Next: Math/VecStat,  Prev: Math/Trig,  Up: Module List

Perl interface to a truly random number generator function
**********************************************************

NAME
====

TrulyRandom - Perl interface to a truly random number generator function

SYNOPSIS
========

     use Math::TrulyRandom;
     
     $random = truly_random_value();

DESCRIPTION
===========

The *TrulyRandom* module provides an ability to generate truly random
numbers from within Perl programs.  The source of the randomness is from
interrupt timing discrepancies.

EXAMPLE
=======

     $random = truly_random_value();

BUGS
====

The random numbers take a long time (in computer terms) to generate, so
are only really useful for seeding pseudo random sequence generators.

COPYRIGHT
=========

This implementation derives from the truly random number generator function
developed by Matt Blaze and Don Mitchell, and is copyright of AT&T.  Other
parts of this perl extension are copyright of Systemics Ltd (
http://www.systemics.com/ ).


File: pm.info,  Node: Math/VecStat,  Next: Mmap,  Prev: Math/TrulyRandom,  Up: Module List

SYNOPSIS
========

     use Math::VecStat qw(max min maxabs minabs sum average);
     $max=max(@vector);
     $max=max(\@vector);
     ($max,$imax)=max(@vector);
     ($max,$imax)=max(\@vector);
     $min=min(@vector);
     $min=min(\@vector);
     ($max,$imin)=min(@vector);
     ($max,$imin)=min(\@vector);
     $max=maxabs(@vector);
     $max=maxabs(\@vector);
     ($max,$imax)=maxabs(@vector);
     ($max,$imax)=maxabs(\@vector);
     $min=minabs(@vector);
     $min=minabs(\@vector);
     ($max,$imin)=minabs(@vector);
     ($max,$imin)=minabs(\@vector);
     $sum=sum($v1,$v2,...);
     $sum=sum(@vector);
     $sum=sum(\@vector);
     $average=average($v1,$v2,...);
     $av=average(@vector);
     $av=average(\@vector);

DESCRIPTION
===========

     This package procides some basic statistics on numerical
     vectors. All the subroutines can take a copy of the vector, or,
     preferably for efficiency, a reference to the vector to be operated
     on.

max(@vector), max(\@vector)
     return the maximum value of given values or vector. In an array
     context returns the value and the index in the array where it occurs.

min(@vector), min(\@vector)
     return the minimum value of given values or vector, In an array
     context returns the value and the index in the array where it occurs.

maxabs(@vector), maxabs(\@vector)
     return the maximum value of absolute of the given values or vector. In
     an array context returns the value and the index in the array where it
     occurs.

minabs(@vector), minabs(\@vector)
     return the minimum value of the absolute of the given values or
     vector, In an array context returns the value and the index in the
     array where it occurs.

sum($v1,$v2,...), sum(@vector), sum(\@vector)
     return the sum of the given values or vector

average($v1,$v2,..), average(@vector), average(\@vector)
     return the average of the given values or vector

HISTORY
=======

     $Log: VecStat.pm,v $
     Revision 1.4  1996/02/20 07:53:10  willijar
     Added ability to return index in array contex to max and min
     functions. Added minabs and maxabs functions.
     Thanks to Mark Borges <mdb@cdc.noaa.gov> for these suggestions.

     Revision 1.3  1996/01/06 11:03:30  willijar
     Fixed stupid bug that crept into looping in min and max functions

     Revision 1.2  1995/12/26 09:56:38  willijar
     Oops - removed xy data functions.

     Revision 1.1  1995/12/26 09:39:07  willijar
     Initial revision

BUGS
====

Let me know. I welcome any appropriate additions for this package.

AUTHOR
======

John A.R. Williams <J.A.R.Williams@aston.ac.uk>


File: pm.info,  Node: Mmap,  Next: Msql/RDBMS,  Prev: Math/VecStat,  Up: Module List

uses mmap to map in a file as a perl variable
*********************************************

NAME
====

Mmap - uses mmap to map in a file as a perl variable

SYNOPSIS
========

     use Mmap;

     mmap($foo, 0, PROT_READ, MAP_SHARED, FILEHANDLE) or die "mmap: $!";
     @tags = $foo =~ /<(.*?)>/g;
     munmap($foo) or die "munmap: $!";
     
     mmap($bar, 8192, PROT_READ|PROT_WRITE, MAP_SHARED, FILEHANDLE);
     substr($bar, 1024, 11) = "Hello world";

DESCRIPTION
===========

The Mmap module lets you use mmap to map in a file as a perl variable
rather than reading the file into dynamically allocated memory. It depends
on your operating system supporting UNIX or POSIX.1b mmap, of course. You
need to be careful how you use such a variable. Some programming
constructs may create copies of a string which, while unimportant for
smallish strings, are far less welcome if you're mapping in a file which
is a few gigabytes big. If you use PROT_WRITE and attempt to write to the
file via the variable you need to be even more careful. One of the few
ways in which you can safely write to the string in-place is by using
substr as an lvalue and ensuring that the part of the string that you
replace is exactly the same length.

mmap(VARIABLE, LENGTH, PROTECTION, FLAGS, FILEHANDLE, OFFSET)
     Maps LENGTH bytes of (the underlying contents of) FILEHANDLE into your
     address space, starting at offset OFFSET and makes VARIABLE refer to
     that memory. The OFFSET argument can be omitted in which case it
     defaults to zero. The LENGTH argument can be zero in which case a
     stat is done on FILEHANDLE and the size of the underlying file is
     used instead.

     The PROTECTION argument should be some ORed combination of the
     constants PROT_READ, PROT_WRITE and PROT_EXEC or else PROT_NONE. The
     constants PROT_EXEC and PROT_NONE are unlikely to be useful here but
     are included for completeness.

     The FLAGS argument must include either MAP_SHARED or MAP_PRIVATE (the
     latter is unlikely to be useful here).  If your platform supports it,
     you may also use MAP_ANON or MAP_ANONYMOUS.  If your platform
     supplies MAP_FILE as a non-zero constant (necessarily non-POSIX) then
     you should also include that in FLAGS. POSIX.1b does not specify
     MAP_FILE as a FLAG argument and most if not all versions of Unix have
     MAP_FILE as zero.

     mmap returns 1 on success and undef on failure.

munmap(VARIABLE)
     Unmaps the part of your address space which was previously mapped in
     with a call to `mmap(VARIABLE, ...)' and makes VARIABLE become
     undefined.

     munmap returns 1 on success and undef on failure.

Constants
     The Mmap module exports the following constants into your namespace
      MAP_SHARED MAP_PRIVATE MAP_ANON MAP_ANONYMOUS MAP_FILE
     PROT_EXEC PROT_NONE PROT_READ PROT_WRITE

     Of the constants beginning MAP_, only MAP_SHARED and MAP_PRIVATE are
     defined in POSIX.1b and only MAP_SHARED is likely to be useful.

AUTHOR
======

Malcolm Beattie, 21 June 1996.


File: pm.info,  Node: Msql/RDBMS,  Next: NDBM_File,  Prev: Mmap,  Up: Module List

Relational Database Management System for Msql
**********************************************

NAME
====

*Msql::RDBMS* - Relational Database Management System for Msql

SYNOPSIS
========

     use Msql::RDBMS;

     $rdbms = new Msql::RDBMS;
     $rdbms->show;

DESCRIPTION
===========

This is a fully catalog driven database management system for Perl 5 and
mini-SQL. You should use it in conjunction with the sqldef.pl script,
found in the utility/ subdirectory of the installation; this script will
generate data definition language for your tables.

GENERATING DATA DEFINITION LANGUAGE
===================================

You must pass the name of a schema definition file to sqldef.pl (an
example, *schema.def*, is included in the examples/ subdirectory of the
distribution).  Example usage:

     sqldef.pl schema.def

The above example will send the data definition language to STDOUT. To
send it to mini-SQL (this will wipe out all of the data in the specified
database):

     sqldef.pl schema.def | msql database-name

The *schema.def* file contains a little bit of documentation on how the
data is organized within the file, and how you can set up your own tables.

USAGE
=====

You can call up the entire Relational Database Management System from your
browser with a URL like this:

     http://bozos.on.the.bus/sample.cgi?db=demo

Where *sample.cgi* is a Perl script containing the three lines of code
shown in SYNOPSIS.

DEBUGGING
=========

You can get some debugging information, which consists of a CGI::dump, and
an SQL statement, if relevant, by including debug=1 in the URL.

TODO
====

     Generate forms for interactive data definition.
     Enforce referential integrity (cascade/block deletes).
     * Add support for many-to-many relationships.
     * Enforce uniqueness for label columns.
     * Add fancy display options that support automagic hyperlinking of
        URLs and email addresses.

* denotes feature present in the original PHP/FI version.

AUTHOR
======

Brian Jepson <bjepson@conan.ids.net>

You may distribute this under the same terms as Perl itself.

SEE ALSO
========

CGI::CGI, CGI::Carp, Msql, File::Counterfile


File: pm.info,  Node: NDBM_File,  Next: NNML/Server,  Prev: Msql/RDBMS,  Up: Module List

Tied access to ndbm files
*************************

NAME
====

NDBM_File - Tied access to ndbm files

SYNOPSIS
========

     use NDBM_File;

     tie(%h, 'NDBM_File', 'Op.dbmx', O_RDWR|O_CREAT, 0640);

     untie %h;

DESCRIPTION
===========

See `tie', *Note Perlfunc: (perl.info)perlfunc,


File: pm.info,  Node: NNML/Server,  Next: Net/Cmd,  Prev: NDBM_File,  Up: Module List

a minimal NNTP server
*********************

NAME
====

NNML::Server - a minimal NNTP server

SYNOPSIS
========

     perl -MNNML::Server -e 'server()'

DESCRIPTION
===========

*NNML::Server* server implements a minimal NNTP server. It is (hope-)
fully conformant to rfc977. In addition the commands `XOVER' and
`AUTHINFO' are implemented.

Supported commands:

     ARTICLE, AUTHINFO, BODY, GROUP, HEAD, HELP, IHAVE, LAST, LIST,
     MODE, NEWGROUPS, NEWNEWS, NEXT, POST, QUIT, SLAVE, STAT, XOVER

The main reason for writing this was to synchronize my mail directories
across different hosts. The Mail directories are MH-Style with a
`.overview' file in each folder and an active file in the base directory.
These are maintained by the *Emacs* *Gnus* backend *NNML*. To get started,
you can generate/update this files using the *overview* program. Upon POST
and `IHAVE' commands this files will also be updated.

To start from scratch use:

     touch /tmp/active;
     perl -MNNML::Server -e 'server(base => "/tmp", port => 3000)'

To export your mh-Mail use:

     perl overview -base ~/Mail
     perl -MNNML::Server -e 'server(base => "$ENV{HOME}/Mail", port => 3000)'

The command POST and *IHAVE* honour the `Newsgroups' header *if* not
overwritten by the `X-Nnml-Groups' header. Articles will contain an
appropriate `X-Nnml-Groups' header when retrieved by message-id.

AUTHORIZATION
=============

To enable access restrictions use:

     perl -MNNML::Auth -e "NNML::Auth::add_user($ENV{LOGANME}, 'passwd', \
       'read', 'write', 'admin')"

If *base*`/passwd' exists, three levels of authorization are recognized:

admin
     Users with permission admin may shut down the server using `SHUT'.
     Also these users may create new groups simply by posting to them.

write
     Users with permission write may use the POST and *IHAVE* commands.

read
     All other commands require the read permission.

FEATURES
========

Version 1.06 implements the `MODE GZIP' command. After submiting this
commands, all articles, heads and bodies will be piped through `gzip -cf |
mimencode'. The server will recognize post requeste using the same pipe
automatically. This will speed up *nnmirror* if the line is sufficiant
slow.

BUGS
====

The server handles multiple connections in a single thread. So a hung POST
or `IHAVE' would block all connections. Therfore a post request is
interrupted if the server could not read any bytes for 30 seconds. The
Client is notified by message 441. If the client continues to send the
article, it is interpreted by the command loop.

SEE ALSO
========

The *overview*(1) and *nnmirror*(1) manpages.

AUTHOR
======

Ulrich Pfeifer <`pfeifer@ls6.informatik.uni-dortmund.de'>


File: pm.info,  Node: Net/Cmd,  Next: Net/Domain,  Prev: NNML/Server,  Up: Module List

Network Command class (as used by FTP, SMTP etc)
************************************************

NAME
====

Net::Cmd - Network Command class (as used by FTP, SMTP etc)

SYNOPSIS
========

     use Net::Cmd;
     
     @ISA = qw(Net::Cmd);

DESCRIPTION
===========

`Net::Cmd' is a collection of methods that can be inherited by a sub class
of `IO::Handle'. These methods implement the functionality required for a
command based protocol, for example FTP and SMTP.

USER METHODS
============

These methods provide a user interface to the `Net::Cmd' object.

debug ( VALUE )
     Set the level of debug information for this object. If `VALUE' is not
     given then the current state is returned. Otherwise the state is
     changed to `VALUE' and the previous state returned. If `VALUE' is
     undef then the debug level will be set to the default debug level for
     the class.

     This method can also be called as a static method to set/get the
     default debug level for a given class.

message ()
     Returns the text message returned from the last command

code ()
     Returns the 3-digit code from the last command. If a command is
     pending then the value 0 is returned

ok ()
     Returns non-zero if the last code value was greater than zero and
     less than 400. This holds true for most command servers. Servers
     where this does not hold may override this method.

status ()
     Returns the most significant digit of the current status code. If a
     command is pending then `CMD_PENDING' is returned.

datasend ( DATA )
     Send data to the remote server, delimiting lines with CRLF. Any lin
     starting with a '.' will be prefixed with another '.'.

dataend ()
     End the sending of data to the remote server. This is done by
     ensureing that the data already sent ends with CRLF then sending
     '.CRLF' to end the transmission. Once this data has been sent dataend
     calls `response' and returns true if `response' returns CMD_OK.

CLASS METHODS
=============

These methods are not intended to be called by the user, but used or
over-ridden by a sub-class of `Net::Cmd'

debug_print ( DIR, TEXT )
     Print debugging information. DIR denotes the direction *true* being
     data being sent to the server. Calls debug_text before printing to
     STDERR.

debug_text ( TEXT )
     This method is called to print debugging information. TEXT is the
     text being sent. The method should return the text to be printed

     This is primarily meant for the use of modules such as FTP where
     passwords are sent, but we do not want to display them in the
     debugging information.

command ( CMD [, ARGS, ... ])
     Send a command to the command server. All arguments a first joined
     with a space character and CRLF is appended, this string is then sent
     to the command server.

     Returns undef upon failure

unsupported ()
     Sets the status code to 580 and the response text to 'Unsupported
     command'.  Returns zero.

responce ()
     Obtain a responce from the server. Upon success the most significant
     digit of the status code is returned. Upon failure, timeout etc.,
     undef is returned.

parse_response ( TEXT )
     This method is called by `response' as a method with one argument. It
     should return an array of 2 values, the 3-digit status code and a
     flag which is true when this is part of a multi-line response and
     this line is not the list.

getline ()
     Retreive one line, delimited by CRLF, from the remote server. Returns
     undef upon failure.

     NOTE: If you do use this method for any reason, please remember to add
     some debug_print calls into your method.

ungetline ( TEXT )
     Unget a line of text from the server.

read_until_dot ()
     Read data from the remote server until a line consisting of a single
     '.'.  Any lines starting with '..' will have one of the '.'s removed.

     Returns a reference to a list containing the lines, or undef upon
     failure.

EXPORTS
=======

`Net::Cmd' exports six subroutines, five of these, `CMD_INFO', `CMD_OK',
`CMD_MORE', `CMD_REJECT' and `CMD_ERROR' ,correspond to possible results
of `response' and status. The sixth is `CMD_PENDING'.

AUTHOR
======

Graham Barr <Graham.Barr@tiuk.ti.com>

REVISION
========

$Revision: 2.2 $

COPYRIGHT
=========

Copyright (c) 1995 Graham Barr. All rights reserved. This program is free
software; you can redistribute it and/or modify it under the same terms as
Perl itself.


File: pm.info,  Node: Net/Domain,  Next: Net/DummyInetd,  Prev: Net/Cmd,  Up: Module List

Attempt to evaluate the current host's internet name and domain
***************************************************************

NAME
====

Net::Domain - Attempt to evaluate the current host's internet name and
domain

SYNOPSIS
========

     use Net::Domain qw(hostname hostfqdn hostdomain);

DESCRIPTION
===========

Using various methods *attempt* to find the Fully Qualified Domain Name
(FQDN) of the current host. From this determine the host-name and the
host-domain.

Each of the functions will return undef if the FQDN cannot be determined.

hostfqdn ()
     Identify and return the FQDN of the current host.

hostname ()
     Returns the smallest part of the FQDN which can be used to identify
     the host.

hostdomain ()
     Returns the remainder of the FQDN after the hostname has been removed.

AUTHOR
======

Graham Barr <bodg@tiuk.ti.com>.  Adapted from Sys::Hostname by David
Sundstrom <sunds@asictest.sc.ti.com>

REVISION
========

$Revision: 2.0 $

COPYRIGHT
=========

Copyright (c) 1995 Graham Barr. All rights reserved.  This library is free
software; you can redistribute it and/or modify it under the same terms as
Perl itself.


File: pm.info,  Node: Net/DummyInetd,  Next: Net/FTP,  Prev: Net/Domain,  Up: Module List

A dummy Inetd server
********************

NAME
====

Net::DummyInetd - A dummy Inetd server

SYNOPSIS
========

     use Net::DummyInetd;
     use Net::SMTP;
     
     $inetd = new Net::DummyInetd qw(/usr/lib/sendmail -ba -bs);
     
     $smtp  = Net::SMTP->new('localhost', Port => $inetd->port);

DESCRIPTION
===========

`Net::DummyInetd' is just what it's name says, it is a dummy inetd server.
Creation of a `Net::DummyInetd' will cause a child process to be spawned
off which will listen to a socket. When a connection arrives on this socket
the specified command is fork'd and exec'd with STDIN and STDOUT file
descriptors duplicated to the new socket.

This package was added as an example of how to use `Net::SMTP' to connect
to a `sendmail' process, which is not the default, via SIDIN and STDOUT.
A `Net::Inetd' package will be avaliable in the next release of `libnet'

CONSTRUCTOR
===========

new ( CMD )
     Creates a new object and spawns a child process which listens to a
     socket.  `CMD' is a list, which will be passed to exec when a new
     process needs to be created.

METHODS
=======

port
     Returns the port number on which the *DummyInet* object is listening

AUTHOR
======

Graham Barr <Graham.Barr@tiuk.ti.com>

REVISION
========

$Revision: 1.2 $

The VERSION is derived from the revision by changing each number after the
first dot into a 2 digit number so

     Revision 1.8   => VERSION 1.08
     Revision 1.2.3 => VERSION 1.0203

COPYRIGHT
=========

Copyright (c) 1995 Graham Barr. All rights reserved. This program is free
software; you can redistribute it and/or modify it under the same terms as
Perl itself.


File: pm.info,  Node: Net/FTP,  Next: Net/NIS,  Prev: Net/DummyInetd,  Up: Module List

FTP Client class
****************

NAME
====

Net::FTP - FTP Client class

SYNOPSIS
========

     use Net::FTP;
     
     $ftp = Net::FTP->new("some.host.name");
     $ftp->login("anonymous","me@here.there");
     $ftp->cwd("/pub");
     $ftp->get("that.file");
     $ftp->quit;

DESCRIPTION
===========

`Net::FTP' is a class implementing a simple FTP client in Perl as described
in RFC959

`Net::FTP' provides methods that will perform various operations. These
methods could be split into groups depending the level of interface the
user requires.

CONSTRUCTOR
===========

new (HOST [,OPTIONS])
     This is the constructor for a new Net::SMTP object. `HOST' is the
     name of the remote host to which a FTP connection is required.

     OPTIONS are passed in a hash like fasion, using key and value pairs.
     Possible options are:

     *Firewall* - The name of a machine which acts as a FTP firewall. This
     can be overridden by an environment variable `FTP_FIREWALL'. If
     specified, and the given host cannot be directly connected to, then
     the connection is made to the firwall machine and the string
     `@hostname' is appended to the login identifier.

     Port - The port number to connect to on the remote machine for the
     FTP connection

     *Timeout* - Set a timeout value (defaults to 120)

     Debug - Debug level

     *Passive* - If set to *true* then all data transfers will be done
     using passive mode. This is required for some *dumb* servers.

METHODS
=======

Unless otherwise stated all methods return either a *true* or *false*
value, with *true* meaning that the operation was a success. When a method
states that it returns a value, falure will be returned as undef or an
empty list.

login ([LOGIN [,PASSWORD [, ACCOUNT] ] ])
     Log into the remote FTP server with the given login information. If
     no arguments are given then the `Net::FTP' uses the `Net::Netrc'
     package to lookup the login information for the connected host.  If
     no information is found then a login of *anonymous* is used.  If no
     password is given and the login is *anonymous* then the users Email
     address will be used for a password.

     If the connection is via a firewall then the authorize method will be
     called with no arguments.

authorize ( [AUTH [, RESP]])
     This is a protocol used by some firewall ftp proxies. It is used to
     authorise the user to send data out.  If both arguments are not
     specified then authorize uses `Net::Netrc' to do a lookup.

type (TYPE [, ARGS])
     This method will send the TYPE command to the remote FTP server to
     change the type of data transfer. The return value is the previous
     value.

ascii ([ARGS]) binary([ARGS]) ebcdic([ARGS]) byte([ARGS])
     Synonyms for type with the first arguments set correctly

     NOTE ebcdic and byte are not fully supported.

rename ( OLDNAME, NEWNAME )
     Rename a file on the remote FTP server from `OLDNAME' to `NEWNAME'.
     This is done by sending the RNFR and RNTO commands.

delete ( FILENAME )
     Send a request to the server to delete `FILENAME'.

cwd ( [ DIR ] )
     Change the current working directory to DIR, or / if not given.

cdup ()
     Change directory to the parent of the current directory.

pwd ()
     Returns the full pathname of the current directory.

rmdir ( DIR )
     Remove the directory with the name DIR.

mkdir ( DIR [, RECURSE ])
     Create a new directory with the name DIR. If `RECURSE' is *true* then
     mkdir will attempt to create all the directories in the given path.

     Returns the full pathname to the new directory.

ls ( [ DIR ] )
     Get a directory listing of DIR, or the current directory.

     Returns a reference to a list of lines returned from the server.

dir ( [ DIR ] )
     Get a directory listing of DIR, or the current directory in long
     format.

     Returns a reference to a list of lines returned from the server.

get ( REMOTE_FILE [, LOCAL_FILE ] )
     Get `REMOTE_FILE' from the server and store locally. `LOCAL_FILE' may
     be a filename or a filehandle. If not specified the the file will be
     stored in the current directory with the same leafname as the remote
     file.

     Returns `LOCAL_FILE', or the generated local file name if `LOCAL_FILE'
     is not given.

put ( LOCAL_FILE [, REMOTE_FILE ] )
     Put a file on the remote server. `LOCAL_FILE' may be a name or a
     filehandle.  If `LOCAL_FILE' is a filehandle then `REMOTE_FILE' must
     be specified. If `REMOTE_FILE' is not specified then the file will be
     stored in the current directory with the same leafname as
     `LOCAL_FILE'.

     Returns `REMOTE_FILE', or the generated remote filename if
     `REMOTE_FILE' is not given.

put_unique ( LOCAL_FILE [, REMOTE_FILE ] )
     Same as put but uses the `STOU' command.

     Returns the name of the file on the server.

append ( LOCAL_FILE [, REMOTE_FILE ] )
     Same as put but appends to the file on the remote server.

     Returns `REMOTE_FILE', or the generated remote filename if
     `REMOTE_FILE' is not given.

unique_name ()
     Returns the name of the last file stored on the server using the
     `STOU' command.

mdtm ( FILE )
     Returns the *modification time* of the given file

size ( FILE )
     Returns the size in bytes for the given file.

The following methods can return different results depending on how they
are called. If the user explicitly calls either of the pasv or port
methods then these methods will return a *true* or *false* value. If the
user does not call either of these methods then the result will be a
reference to a `Net::FTP::dataconn' based object.

nlst ( [ DIR ] )
     Send a `NLST' command to the server, with an optional parameter.

list ( [ DIR ] )
     Same as nlst but using the LIST command

retr ( FILE )
     Begin the retrieval of a file called FILE from the remote server.

stor ( FILE )
     Tell the server that you wish to store a file. FILE is the name of
     the new file that should be created.

stou ( FILE )
     Same as stor but using the `STOU' command. The name of the unique
     file which was created on the server will be avalaliable via the
     unique_name method after the data connection has been closed.

appe ( FILE )
     Tell the server that we want to append some data to the end of a file
     called FILE. If this file does not exist then create it.

If for some reason you want to have complete control over the data
connection, this includes generating it and calling the `response' method
when required, then the user can use these methods to do so.

However calling these methods only affects the use of the methods above
that can return a data connection. They have no effect on methods get, put,
put_unique and those that do not require data connections.

port ( [ PORT ] )
     Send a `PORT' command to the server. If `PORT' is specified then it
     is sent to the server. If not the a listen socket is created and the
     correct information sent to the server.

pasv ()
     Tell the server to go into passive mode. Returns the text that
     represents the port on which the server is listening, this text is in
     a suitable form to sent to another ftp server using the port method.

The following methods can be used to transfer files between two remote
servers, providing that these two servers can connect directly to each
other.

pasv_xfer ( SRC_FILE, DEST_SERVER [, DEST_FILE ] )
     This method will do a file transfer between two remote ftp servers. If
     `DEST_FILE' is omitted then the leaf name of `SRC_FILE' will be used.

pasv_wait ( NON_PASV_SERVER )
     This method can be used to wait for a transfer to complete between a
     passive server and a non-passive server. The method should be called
     on the passive server with the `Net::FTP' object for the non-passive
     server passed as an argument.

abort ()
     Abort the current data transfer.

quit ()
     Send the QUIT command to the remote FTP server and close the socket
     connection.

Methods for the adventurous
---------------------------

`Net::FTP' inherits from `Net::Cmd' so methods defined in `Net::Cmd' may
be used to send commands to the remote FTP server.

quot (CMD [,ARGS])
     Send a command, that Net::FTP does not directly support, to the remote
     server and wait for a response.

     Returns most significant digit of the response code.

     WARNING This call should only be used on commands that do not require
     data connections. Misuse of this method can hang the connection.

THE dataconn CLASS
==================

Some of the methods defined in `Net::FTP' return an object which will be
derived from this class.The dataconn class itself is derived from the
IO::Socket::INET class, so any normal IO operations can be performed.
However the following methods are defined in the dataconn class and IO
should be performed using these.

read ( BUFFER, SIZE [, TIMEOUT ] )
     Read `SIZE' bytes of data from the server and place it into `BUFFER',
     also performing any <CRLF> translation necessary. `TIMEOUT' is
     optional, if not given the the timeout value from the command
     connection will be used.

     Returns the number of bytes read before any <CRLF> translation.

write ( BUFFER, SIZE [, TIMEOUT ] )
     Write `SIZE' bytes of data from `BUFFER' to the server, also
     performing any <CRLF> translation necessary. `TIMEOUT' is optional,
     if not given the the timeout value from the command connection will
     be used.

     Returns the number of bytes written before any <CRLF> translation.

abort ()
     Abort the current data transfer.

close ()
     Close the data connection and get a response from the FTP server.
     Returns *true* if the connection was closed sucessfully and the first
     digit of the response from the server was a '2'.

AUTHOR
======

Graham Barr <Graham.Barr@tiuk.ti.com>

REVISION
========

$Revision: 2.8 $ $Date: 1996/09/05 06:53:58 $

The VERSION is derived from the revision by changing each number after the
first dot into a 2 digit number so

     Revision 1.8   => VERSION 1.08
     Revision 1.2.3 => VERSION 1.0203

SEE ALSO
========

*Note Net/Netrc: Net/Netrc, *Note Net/Cmd: Net/Cmd,

CREDITS
=======

Henry Gabryjelski <henryg@WPI.EDU> - for the suggestion of creating
directories recursively.

COPYRIGHT
=========

Copyright (c) 1995 Graham Barr. All rights reserved. This program is free
software; you can redistribute it and/or modify it under the same terms as
Perl itself.


File: pm.info,  Node: Net/NIS,  Next: Net/NISPlus/Table,  Prev: Net/FTP,  Up: Module List

Interface to Sun's Network Information Service
**********************************************

NAME
====

Net::NIS - Interface to Sun's Network Information Service

DESCRIPTION
===========

The Net::NIS interface comes in two parts.  The first part is the raw
implementation of the NIS API.  The second is the object interface,
described in `Net::NIS::Table' in this node.  This document describes the
NIS API implementation.

The NIS package implements all functions described in the `ypclnt(3N)' in
this node manual page.

The following commands have been implemented:

yp_bind($domain)
     Bind the process to a NIS server for the domain $domain.  This
     function is rarely needed.  See `yp_bind(3N)' in this node.

yp_unbind($domain)
     Unbind the process from the specified $domain.  This function is also
     rarely required.  See `yp_unbind(3N)' in this node.

$domain = yp_get_default_domain()
     Return the host's local domain.  (The same as the `domainname' in
     this node program).  See `yp_get_default_domain(3N)' in this node.

($status, $value) = yp_match($domain, $map, $key)
     Return the $value for the given $key in the $map for the domain
     $domain.  The $key must be an exact match for an item in the map
     (*i.e.* yp_match does no partial matching.  The $value is only valid
     if $status is equal to $YP_SUCCESS.

($status, $key, $value) = yp_first($domain, $map)
     Return the first key-value pair from $map in $domain.  As the NIS maps
     are stored in a DBM table, the order of the returned values is not
     obvious.

($status, $key, $value) = yp_next($domain, $map, $key)
     Return the next key-value pair from $map in $domain.  The $key must be
     provided from the previous `yp_first' in this node or `yp_next' in
     this node.  The `yp_first' in this node/`yp_next' in this node method
     is not recommended, as under some circumstances, entries can be
     skipped or returned twice.  `yp_all' in this node is a better
     interface to use.

($status, \%values) = yp_all($domain, $map)
     The `yp_all' in this node call returns an entire map in the %values
     associative array.

($status, $order) = yp_order($domain, $map)
     This function returns the order number for $domain.  Whatever that is.
     It mustn't be very important, since it's not implemented on NIS+
     servers running in "YP-compatibility mode".  I put it in for
     completeness.

($status, $name) = yp_master($domain, $map)
     Returns the machine name of the master server for a map.

$error = yperr_string($status)
     Returns a string representation of the error code passed in $status.

$status = ypprot_err($code)
     Translates a NIS name service protocol error code to a ypclnt layer
     error code.  Only used for the C version of `yp_all' in this node,
     and it is only implemented here for completeness.

ERROR CODES
===========

The $status variable returned by the above functions can have one of the
following values:

     $Net::NIS::ERR_ACCESS		Access violation
     $Net::NIS::ERR_BADARGS	Args to function are bad
     $Net::NIS::ERR_BADDB		yp data base is bad
     $Net::NIS::ERR_BUSY		Database is busy
     $Net::NIS::ERR_DOMAIN		Can't bind to a server which serves this domain
     $Net::NIS::ERR_KEY		No such key in map
     $Net::NIS::ERR_MAP		No such map in server's domain
     $Net::NIS::ERR_NODOM		Local domain name not set
     $Net::NIS::ERR_PMAP		Can't communicate with portmapper
     $Net::NIS::ERR_NOMORE		No more records in map database
     $Net::NIS::ERR_RESRC		Local resource allocation failure
     $Net::NIS::ERR_RPC		RPC failure
     $Net::NIS::ERR_YPBIND		Can't communicate with ypbind
     $Net::NIS::ERR_YPERR		Internal yp server or client interface error
     $Net::NIS::ERR_YPSERV		Can't communicate with ypserv
     $Net::NIS::ERR_VERS		YP version mismatch

AUTHOR
======

Copyright (c) 1995 Rik Harris (*rik.harris@fulcrum.com.au*). All rights
reserved.  This program is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.

The Network Information Service (NIS) was formerly known as Sun Yellow
Pages (YP). The functionality of the two remains the same; only the name
has changed.  The name Yellow Pages is a registered trademark in the
United Kingdom of British Telecommunications plc, and may not be used
without permission.


File: pm.info,  Node: Net/NISPlus/Table,  Next: Net/NISTable,  Prev: Net/NIS,  Up: Module List

colnames
--------

colnames returns the column headings for the NIS+ table.  If called in an
array context, it returns an array containing the column names in the
order in which they appear in the table.  If called in a scalar context,
it returns a reference to a hash with keys being column names, and values
being an integer representing the column's position.

e.g.

$table = Net::NISPLus::Table('hosts.org_dir'); $cols = $table->colnames;

will end up with $cols being:

$cols->{'cname'} = 0; $cols->{'name'} = 1; $cols->{'addr'} = 2;
$cols->{'comment'} = 3;

and

$table = Net::NISPLus::Table('hosts.org_dir');  @cols = $table->colnames;

will end up with @cols being:

@cols = ('cname', 'name', 'addr', 'comment')

NOTE: as the colnames method behaves differently depending on what context
it is called in, it may not always behave as you expect.  For example, the
following two code fragments are not equivalent:

my($colnames) = $table->colnames;

and

my($colnames); $colnames = $table->colnames;

The first calls colnames in an array context, and the second in a scalar
context.

add
---

Add an entry to the table.  Any columns not specified will be set to null
strings.

$table->add('key1' => 'value1', 'key2' => 'value2');

remove
------

Remove a single entry from the table.  If the key/value pairs match more
that one entry, an error occurs, and no entries are removed.  Use removem
to remove multiple entries with a single command.

$table->remove('key1' => 'value1', 'key2' => 'value2');

removem
-------

Remove one or more entries from the table. All entries which match the
key/value pairs will be removed. Use removem to remove a single entry.

$table->removem('key1' => 'value1', 'key2' => 'value2');

clear
-----

Remove all entries from the table

$table->clear();


File: pm.info,  Node: Net/NISTable,  Next: Net/NNTP,  Prev: Net/NISPlus/Table,  Up: Module List

Object Interface to Sun's Network Information Service
*****************************************************

NAME
====

Net::NIS::Table - Object Interface to Sun's Network Information Service

DESCRIPTION
===========

The NIS interface comes in two parts.  The first part is the raw
implementation of the NIS API, described in *Note Net/NIS: Net/NIS,.  The
second is the object interface.  This document describes the object
interface implementation.

The Table object represents an individual NIS map.  A NIS map is bound to
a Table object with the new method:

     $obj = Net::NIS::Table->new($map, [ $domain ]);

For example,

     $hostsmap = Net::NIS::Table->new("hosts.byname");

This will create a Table object bound to the `hosts.byname' NIS map in the
default NIS domain.  All operations on the $hostsmap object will relate to
the `hosts.byname' map.

You can also specify a non-default domain:

     $hostsmap = Net::NIS::Table->new("hosts.byname", "my.domain.com.au");

Once a Table object has been bound to a NIS map, the following methods are
available:

$value = $obj->match($key)
     Returns the value for a given key.  If you only wish to look up one or
     two values, this function is more efficient, as it retrieves the items
     one at a time.  If you wish to retrieve many items (where many is
     dependent on the size of the map, and probably what sort of machine
     you are on), it is better to use the `list' in this node interface,
     which uses just one RPC call to retreive the entire map.

\%data = $obj->list()
     Return a reference to an associative array which contains the entire
     NIS map.  The keys in the %data array correspond to the keys in the
     NIS map.  If any error occurs that prevents the retrieval of the map,
     then the undefined value is returned.  In this case, your program can
     use the status method to determine the cause of the error.

\%data = $obj->search($srchkey)
     Return a reference to an associative array which contains all entries
     that have keys that contain the $srchkey.  If any error occurs that
     prevents the retrieval of the map, then the undefined value is
     returned.  In this case, your program can use the status method to
     determine the cause of the error.

$status = $obj->status()
     Returns the status code for the last operation.  If the last operation
     succeeded, then the status code is 0.  The status codes returned by
     this method are described below in the ERROR CODES section.

$status = $obj->status_string()
     Returns the character representation of the status code for the last
     operation.  If the last operation succeeded, then the status code is
     something like "operation succeeded".  The exact strings returned by
     this function are implementation dependent, and should not be used
     for comparison purposes.  Use the status call, as described above.

ERROR CODES
===========

The status method described above can return one of the following values:

     $Net::NIS::ERR_ACCESS		Access violation
     $Net::NIS::ERR_BADARGS	Args to function are bad
     $Net::NIS::ERR_BADDB		yp data base is bad
     $Net::NIS::ERR_BUSY		Database is busy
     $Net::NIS::ERR_DOMAIN		Can't bind to a server which serves this domain
     $Net::NIS::ERR_KEY		No such key in map
     $Net::NIS::ERR_MAP		No such map in server's domain
     $Net::NIS::ERR_NODOM		Local domain name not set
     $Net::NIS::ERR_PMAP		Can't communicate with portmapper
     $Net::NIS::ERR_NOMORE		No more records in map database
     $Net::NIS::ERR_RESRC		Local resource allocation failure
     $Net::NIS::ERR_RPC		RPC failure
     $Net::NIS::ERR_YPBIND		Can't communicate with ypbind
     $Net::NIS::ERR_YPERR		Internal yp server or client interface error
     $Net::NIS::ERR_YPSERV		Can't communicate with ypserv
     $Net::NIS::ERR_VERS		YP version mismatch

AUTHOR
======

Copyright (c) 1995 Rik Harris (*rik.harris@fulcrum.com.au*). All rights
reserved.  This program is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.

The Network Information Service (NIS) was formerly known as Sun Yellow
Pages (YP). The functionality of the two remains the same; only the name
has changed.  The name Yellow Pages is a registered trademark in the
United Kingdom of British Telecommunications plc, and may not be used
without permission.


File: pm.info,  Node: Net/NNTP,  Next: Net/Netrc,  Prev: Net/NISTable,  Up: Module List

NNTP Client class
*****************

NAME
====

Net::NNTP - NNTP Client class

SYNOPSIS
========

     use Net::NNTP;
     
     $nntp = Net::NNTP->new("some.host.name");
     $nntp->quit;

DESCRIPTION
===========

`Net::NNTP' is a class implementing a simple NNTP client in Perl as
described in RFC977. `Net::NNTP' inherits its communication methods from
`Net::Cmd'

CONSTRUCTOR
===========

new ( [ HOST ] [, OPTIONS ])
     This is the constructor for a new Net::NNTP object. `HOST' is the
     name of the remote host to which a NNTP connection is required. If not
     given two environment variables are checked, first `NNTPSERVER' then
     `NEWSHOST', if neither are set `news' is used.

     OPTIONS are passed in a hash like fasion, using key and value pairs.
     Possible options are:

     *Timeout* - Maximum time, in seconds, to wait for a response from the
     NNTP server, a value of zero will cause all IO operations to block.
     (default: 120)

     Debug - Enable the printing of debugging information to STDERR

METHODS
=======

Unless otherwise stated all methods return either a *true* or *false*
value, with *true* meaning that the operation was a success. When a method
states that it returns a value, falure will be returned as undef or an
empty list.

article ( [ MSGID|MSGNUM ] )
     Retreive the header, a blank line, then the body (text) of the
     specified article.

     If no arguments are passed then the current aricle in the current
     newsgroup is returned.

     `MSGNUM' is a numeric id of an article in the current newsgroup, and
     will change the current article pointer.  `MSGID' is the message id
     of an article as shown in that article's header.  It is anticipated
     that the client will obtain the `MSGID' from a list provided by the
     newnews command, from references contained within another article, or
     from the message-id provided in the response to some other commands.

     Returns a reference to an array containing the article.

body ( [ MSGID|MSGNUM ] )
     Retreive the body (text) of the specified article.

     Takes the same arguments as article

     Returns a reference to an array containing the body of the article.

head ( [ MSGID|MSGNUM ] )
     Retreive the header of the specified article.

     Takes the same arguments as article

     Returns a reference to an array containing the header of the article.

nntpstat ( [ MSGID|MSGNUM ] )
     The nntpstat command is similar to the article command except that no
     text is returned.  When selecting by message number within a group,
     the nntpstat command serves to set the "current article pointer"
     without sending text.

     Using the nntpstat command to select by message-id is valid but of
     questionable value, since a selection by message-id does *not* alter
     the "current article pointer".

     Returns the message-id of the "current article".

group ( [ GROUP ] )
     Set and/or get the current group. If `GROUP' is not given then
     information is returned on the current group.

     In a scalar context it returns the group name.

     In an array context the return value is a list containing, the number
     of articles in the group, the number of the first article, the number
     of the last article and the group name.

ihave ( MSGID [, MESSAGE ])
     The ihave command informs the server that the client has an article
     whose id is `MSGID'.  If the server desires a copy of that article,
     and `MESSAGE' has been given the it will be sent.

     Returns *true* if the server desires the article and `MESSAGE' was
     successfully sent,if specified.

     If `MESSAGE' is not specified then the message must be sent using the
     datasend and dataend methods from *Note Net/Cmd: Net/Cmd,

     `MESSAGE' can be either an array of lines or a reference to an array.

last ()
     Set the "current article pointer" to the previous article in the
     current newsgroup.

     Returns the message-id of the article.

date ()
     Returns the date on the remote server. This date will be in a UNIX
     time format (seconds since 1970)

postok ()
     postok will return *true* if the servers initial response indicated
     that it will allow posting.

authinfo ( USER, PASS )
list ()
     Obtain information about all the active newsgroups. The results is a
     reference to a hash where the key is a group name and each value is a
     reference to an array. The elements in this array are:- the first
     article number in the group, the last article number in the group and
     any information flags about the group.

newgroups ( SINCE [, DISTRIBUTIONS ])
     `SINCE' is a time value and `DISTRIBUTIONS' is either a distribution
     pattern or a reference to a list of distribution patterns.  The
     result is the same as list, but the groups return will be limited to
     those created after `SINCE' and, if specified, in one of the
     distribution areas in `DISTRIBUTIONS'.

newnews ( SINCE [, GROUPS [, DISTRIBUTIONS ]])
     `SINCE' is a time value. `GROUPS' is either a group pattern or a
     reference to a list of group patterns. `DISTRIBUTIONS' is either a
     distribution pattern or a reference to a list of distribution
     patterns.

     Returns a reference to a list which contains the message-ids of all
     news posted after `SINCE', that are in a groups which matched
     `GROUPS' and a distribution which matches `DISTRIBUTIONS'.

next ()
     Set the "current article pointer" to the next article in the current
     newsgroup.

     Returns the message-id of the article.

post ( [ MESSAGE ] )
     Post a new article to the news server. If `MESSAGE' is specified and
     posting is allowed then the message will be sent.

     If `MESSAGE' is not specified then the message must be sent using the
     datasend and dataend methods from *Note Net/Cmd: Net/Cmd,

     `MESSAGE' can be either an array of lines or a reference to an array.

slave ()
     Tell the remote server that I am not a user client, but probably
     another news server.

quit ()
     Quit the remote server and close the socket connection.

Extension methods
-----------------

These methods use commands that are not part of the RFC977 documentation.
Some servers may not support all of them.

newsgroups ( [ PATTERN ] )
     Returns a reference to a hash where the keys are all the group names
     which match PATTERN, or all of the groups if no pattern is specified,
     and each value contains the description text for the group.

distributions ()
     Returns a reference to a hash where the keys are all the possible
     distribution names and the values are the distribution descriptions.

subscriptions ()
     Returns a reference to a list which contains a list of groups which
     are reccomended for a new user to subscribe to.

overview_fmt ()
     Returns a reference to an array which contain the names of the fields
     returnd by xover.

active_times ()
     Returns a reference to a hash where the keys are the group names and
     each value is a reference to an array containg the time the groups
     was created and an identifier, possibly an Email address, of the
     creator.

active ( [ PATTERN ] )
     Similar to list but only active groups that match the pattern are
     returned.  PATTERN can be a group pattern.

xgtitle ( PATTERN )
     Returns a reference to a hash where the keys are all the group names
     which match PATTERN and each value is the description text for the
     group.

xhdr ( HEADER, MESSAGE-RANGE )
     Obtain the header field `HEADER' for all the messages specified.

     Returns a reference to a hash where the keys are the message numbers
     and each value contains the header for that message.

xover ( MESSAGE-RANGE )
     Returns a reference to a hash where the keys are the message numbers
     and each value is a reference to an array which contains the overview
     fields for that message. The names of these fields can be obtained by
     calling overview_fmt.

xpath ( MESSAGE-ID )
     Returns the path name to the file on the server which contains the
     specified message.

xpat ( HEADER, PATTERN, MESSAGE-RANGE)
     The result is the same as xhdr except the is will be restricted to
     headers that match PATTERN

xrover
listgroup
reader
UNSUPPORTED
===========

The following NNTP command are unsupported by the package, and there are
no plans to do so.

     AUTHINFO GENERIC
     XTHREAD
     XSEARCH
     XINDEX

DEFINITIONS
===========

MESSAGE-RANGE
     `MESSAGE-RANGE' is either a single message-id, a single mesage
     number, or two message numbers.

     If `MESSAGE-RANGE' is two message numbers and the second number in a
     range is less than or equal to the first then the range represents all
     messages in the group after the first message number.

PATTERN
     The `NNTP' protocol uses the `WILDMAT' format for patterns.  The
     WILDMAT format was first developed by Rich Salz based on the format
     used in the UNIX "find" command to articulate file names. It was
     developed to provide a uniform mechanism for matching patterns in the
     same manner that the UNIX shell matches filenames.

     Patterns are implicitly anchored at the beginning and end of each
     string when testing for a match.

     There are five pattern matching operations other than a strict
     one-to-one match between the pattern and the source to be checked for
     a match.

     The first is an asterisk * to match any sequence of zero or more
     characters.

     The second is a question mark `?' to match any single character. The
     third specifies a specific set of characters.

     The set is specified as a list of characters, or as a range of
     characters where the beginning and end of the range are separated by
     a minus (or dash) character, or as any combination of lists and
     ranges. The dash can also be included in the set as a character it if
     is the beginning or end of the set. This set is enclosed in square
     brackets. The close square bracket `]' may be used in a set if it is
     the first character in the set.

     The fourth operation is the same as the logical not of the third
     operation and is specified the same way as the third with the
     addition of a caret character `^' at the beginning of the test string
     just inside the open square bracket.

     The final operation uses the backslash character to invalidate the
     special meaning of the a open square bracket `[', the asterisk,
     backslash or the question mark. Two backslashes in sequence will
     result in the evaluation of the backslash as a character with no
     special meaning.

    Examples
    `[^]-]'
          matches any single character other than a close square bracket
          or a minus sign/dash.


          matches any string that ends with the string "bdc" including the
          string "bdc" (without quotes).

    `[0-9a-zA-Z]'
          matches any single printable alphanumeric ASCII character.

    `a??d'
          matches any four character string which begins with a and ends
          with d.

SEE ALSO
========

*Note Net/Cmd: Net/Cmd,

AUTHOR
======

Graham Barr <Graham.Barr@tiuk.ti.com>

REVISION
========

$Revision: 2.5 $

COPYRIGHT
=========

Copyright (c) 1995 Graham Barr. All rights reserved. This program is free
software; you can redistribute it and/or modify it under the same terms as
Perl itself.


File: pm.info,  Node: Net/Netrc,  Next: Net/POP3,  Prev: Net/NNTP,  Up: Module List

OO interface to users netrc file
********************************

NAME
====

Net::Netrc - OO interface to users netrc file

SYNOPSIS
========

     use Net::Netrc;
     
     $mach = Net::Netrc->lookup('some.machine');
     $login = $mach->login;
     ($login, $password, $account) = $mach->lpa;

DESCRIPTION
===========

`Net::Netrc' is a class implementing a simple interface to the .netrc file
used as by the ftp program.

`Net::Netrc' also implements security checks just like the ftp program,
these checks are, first that the .netrc file must be owned by the user and
second the ownership permissions should be such that only the owner has
read and write access. If these conditions are not met then a warning is
output and the .netrc file is not read.

THE .netrc FILE
===============

The .netrc file contains login and initialization information used by the
auto-login process.  It resides in the user's home directory.  The
following tokens are recognized; they may be separated by spaces, tabs, or
new-lines:

machine name
     Identify a remote machine name. The auto-login process searches the
     .netrc file for a machine token that matches the remote machine
     specified.  Once a match is made, the subsequent .netrc tokens are
     processed, stopping when the end of file is reached or an- other
     machine or a default token is encountered.

default
     This is the same as machine name except that default matches any
     name.  There can be only one default token, and it must be after all
     machine tokens.  This is normally used as:

          default login anonymous password user@site

     thereby giving the user automatic anonymous login to machines not
     specified in .netrc.

login name
     Identify a user on the remote machine.  If this token is present, the
     auto-login process will initiate a login using the specified name.

password string
     Supply a password.  If this token is present, the auto-login process
     will supply the specified string if the remote server requires a
     password as part of the login process.

account string
     Supply an additional account password.  If this token is present, the
     auto-login process will supply the specified string if the remote
     server requires an additional account password.

macdef name
     Define a macro. `Net::Netrc' only parses this field to be compatible
     with *ftp*.

CONSTRUCTOR
===========

The constructor for a `Net::Netrc' object is not called new as it does not
really create a new object. But instead is called lookup as this is
essentially what it deos.

lookup ( MACHINE [, LOGIN ])
     Lookup and return a reference to the entry for `MACHINE'. If `LOGIN'
     is given then the entry returned will have the given login. If
     `LOGIN' is not given then the first entry in the .netrc file for
     `MACHINE' will be returned.

     If a matching entry cannot be found, and a default entry exists, then
     a reference to the default entry is returned.

METHODS
=======

login ()
     Return the login id for the netrc entry

password ()
     Return the password for the netrc entry

account ()
     Return the account information for the netrc entry

lpa ()
     Return a list of login, password and account information fir the
     netrc entry

AUTHOR
======

Graham Barr <Graham.Barr@tiuk.ti.com>

REVISION
========

$Revision: 2.1 $

SEE ALSO
========

*Note Net/Netrc: Net/Netrc, *Note Net/Cmd: Net/Cmd,

COPYRIGHT
=========

Copyright (c) 1995 Graham Barr. All rights reserved. This program is free
software; you can redistribute it and/or modify it under the same terms as
Perl itself.


File: pm.info,  Node: Net/POP3,  Next: Net/Ping,  Prev: Net/Netrc,  Up: Module List

Post Office Protocol 3 Client class (RFC1081)
*********************************************

NAME
====

Net::POP3 - Post Office Protocol 3 Client class (RFC1081)

SYNOPSIS
========

     use Net::POP3;
     
     # Constructors
     $pop = Net::POP3->new('pop3host');
     $pop = Net::POP3->new('pop3host', Timeout => 60);

DESCRIPTION
===========

This module implements a client interface to the POP3 protocol, enabling a
perl5 application to talk to POP3 servers. This documentation assumes that
you are familiar with the POP3 protocol described in RFC1081.

A new Net::POP3 object must be created with the new method. Once this has
been done, all POP3 commands are accessed via method calls on the object.

EXAMPLES
========

     Need some small examples in here :-)

CONSTRUCTOR
===========

new ( HOST, [ OPTIONS ] )
     This is the constructor for a new Net::POP3 object. `HOST' is the
     name of the remote host to which a POP3 connection is required.

     OPTIONS are passed in a hash like fasion, using key and value pairs.
     Possible options are:

     *Timeout* - Maximum time, in seconds, to wait for a response from the
     POP3 server (default: 120)

     Debug - Enable debugging information

METHODS
=======

Unless otherwise stated all methods return either a *true* or *false*
value, with *true* meaning that the operation was a success. When a method
states that it returns a value, falure will be returned as undef or an
empty list.

user ( USER )
     Send the USER command.

pass ( PASS )
     Send the PASS command. Returns the number of messages in the mailbox.

login ( [ USER [, PASS ]] )
     Send both the the USER and PASS commands. If `PASS' is not given the
     `Net::POP3' uses `Net::Netrc' to lookup the password using the host
     and username. If the username is not specified then the current user
     name will be used.

     Returns the number of messages in the mailbox.

top ( MSGNUM [, NUMLINES ] )
     Get the header and the first `NUMLINES' of the body for the message
     `MSGNUM'. Returns a reference to an array which contains the lines of
     text read from the server.

list ( [ MSGNUM ] )
     If called with an argument the list returns the size of the messsage
     in octets.

     If called without arguments the a refererence to a hash is returned.
     The keys will be the `MSGNUM''s of all undeleted messages and the
     values will be their size in octets.

get ( MSGNUM )
     Get the message `MSGNUM' from the remote mailbox. Returns a reference
     to an array which contains the lines of text read from the server.

last ()
     Returns the highest `MSGNUM' of all the messages accessed.

popstat ()
     Returns an array of two elements. These are the number of undeleted
     elements and the size of the mbox in octets.

delete ( MSGNUM )
     Mark message `MSGNUM' to be deleted from the remote mailbox. All
     messages that are marked to be deleted will be removed from the
     remote mailbox when the server connection closed.

reset ()
     Reset the status of the remote POP3 server. This includes reseting the
     status of all messages to not be deleted.

quit ()
     Quit and close the connection to the remote POP3 server. Any messages
     marked as deleted will be deleted from the remote mailbox.

NOTES
=====

If a `Net::POP3' object goes out of scope before quit method is called
then the reset method will called before the connection is closed. This
means that any messages marked to be deleted will not be.

SEE ALSO
========

*Note Net/Netrc: Net/Netrc, *Note Net/Cmd: Net/Cmd,

AUTHOR
======

Graham Barr <Graham.Barr@tiuk.ti.com>

REVISION
========

$Revision: 2.1 $ $Date: 1996/07/26 06:44:44 $

The VERSION is derived from the revision by changing each number after the
first dot into a 2 digit number so

     Revision 1.8   => VERSION 1.08
     Revision 1.2.3 => VERSION 1.0203

COPYRIGHT
=========

Copyright (c) 1995 Graham Barr. All rights reserved. This program is free
software; you can redistribute it and/or modify it under the same terms as
Perl itself.


File: pm.info,  Node: Net/Ping,  Next: Net/SMTP,  Prev: Net/POP3,  Up: Module List

check a host for upness
***********************

NAME
====

Net::Ping, pingecho - check a host for upness

SYNOPSIS
========

     use Net::Ping;
     print "'jimmy' is alive and kicking\n" if pingecho('jimmy', 10) ;

DESCRIPTION
===========

This module contains routines to test for the reachability of remote hosts.
Currently the only routine implemented is pingecho().

pingecho() uses a TCP echo (*not* an ICMP one) to determine if the remote
host is reachable. This is usually adequate to tell that a remote host is
available to rsh(1), ftp(1), or telnet(1) onto.

Parameters
----------

hostname
     The remote host to check, specified either as a hostname or as an IP
     address.

timeout
     The timeout in seconds. If not specified it will default to 5 seconds.

WARNING
=======

pingecho() uses alarm to implement the timeout, so don't set another alarm
while you are using it.


File: pm.info,  Node: Net/SMTP,  Next: Net/SNPP,  Prev: Net/Ping,  Up: Module List

Simple Mail transfer Protocol Client
************************************

NAME
====

Net::SMTP - Simple Mail transfer Protocol Client

SYNOPSIS
========

     use Net::SMTP;
     
     # Constructors
     $smtp = Net::SMTP->new('mailhost');
     $smtp = Net::SMTP->new('mailhost', Timeout => 60);

DESCRIPTION
===========

This module implements a client interface to the SMTP protocol, enabling a
perl5 application to talk to SMTP servers. This documentation assumes that
you are familiar with the SMTP protocol described in RFC821.

A new Net::SMTP object must be created with the new method. Once this has
been done, all SMTP commands are accessed through this object.

EXAMPLES
========

This example prints the mail domain name of the SMTP server known as
mailhost:

     #!/usr/local/bin/perl -w
     
     use Net::SMTP;
     
     $smtp = Net::SMTP->new('mailhost');
     
     print $smtp->domain,"\n";
     
     $smtp->quit;

This example sends a small message to the postmaster at the SMTP server
known as mailhost:

     #!/usr/local/bin/perl -w
     
     use Net::SMTP;
     
     $smtp = Net::SMTP->new('mailhost');
     
     $smtp->mail($ENV{USER});
     
     $smtp->to('postmaster');
     
     $smtp->data();
     
     $smtp->datasend("To: postmaster\n");
     $smtp->datasend("\n");
     $smtp->datasend("A simple test message\n");
     
     $smtp->dataend();
     
     $smtp->quit;

CONSTRUCTOR
===========

new ( HOST, [ OPTIONS ] )
     This is the constructor for a new Net::SMTP object. `HOST' is the
     name of the remote host to which a SMTP connection is required.

     OPTIONS are passed in a hash like fasion, using key and value pairs.
     Possible options are:

     *Hello* - SMTP requires that you identify yourself. This option
     specifies a string to pass as your mail domain. If not given a guess
     will be taken.

     *Timeout* - Maximum time, in seconds, to wait for a response from the
     SMTP server (default: 120)

     Debug - Enable debugging information

     Example:

          $smtp = Net::SMTP->new('mailhost',
          			   Hello => 'my.mail.domain'
          			  );

METHODS
=======

Unless otherwise stated all methods return either a *true* or *false*
value, with *true* meaning that the operation was a success. When a method
states that it returns a value, falure will be returned as undef or an
empty list.

domain ()
     Returns the domain that the remote SMTP server identified itself as
     during connection.

hello ( DOMAIN )
     Tell the remote server the mail domain which you are in using the HELO
     command.

mail ( ADDRESS )
send ( ADDRESS )
send_or_mail ( ADDRESS )
send_and_mail ( ADDRESS )
     Send the appropriate command to the server MAIL, SEND, SOML or SAML.
     `ADDRESS' is the address of the sender. This initiates the sending of
     a message. The method recipient should be called for each address
     that the message is to be sent to.

reset ()
     Reset the status of the server. This may be called after a message
     has been initiated, but before any data has been sent, to cancel the
     sending of the message.

recipient ( ADDRESS [, ADDRESS [ ...]] )
     Notify the server that the current message should be sent to all of
     the addresses given. Each address is sent as a separate command to
     the server.  Should the sending of any address result in a failure
     then the process is aborted and a *false* value is returned. It is up
     to the user to call reset if they so desire.

to ()
     A synonym for recipient

data ( [ DATA ] )
     Initiate the sending of the data fro the current message.

     `DATA' may be a reference to a list or a list. If specified the
     contents of `DATA' and a termination string `".\r\n"' is sent to the
     server. And the result will be true if the data was accepted.

     If `DATA' is not specified then the result will indicate that the
     server wishes the data to be sent. The data must then be sent using
     the datasend and dataend methods defined in `Net::Cmd'.

expand ( ADDRESS )
     Request the server to expand the given address Returns a reference to
     an array which contains the text read from the server.

verify ( ADDRESS )
     Verify that `ADDRESS' is a legitimate mailing address.

help ( [ $subject ] )
     Request help text from the server. Returns the text or undef upon
     failure

quit ()
     Send the QUIT command to the remote SMTP server and close the socket
     connection.

SEE ALSO
========

*Note Net/Cmd: Net/Cmd,

AUTHOR
======

Graham Barr <Graham.Barr@tiuk.ti.com>

REVISION
========

$Revision: 2.1 $ $Date: 1996/08/20 20:23:56 $

The VERSION is derived from the revision by changing each number after the
first dot into a 2 digit number so

     Revision 1.8   => VERSION 1.08
     Revision 1.2.3 => VERSION 1.0203

COPYRIGHT
=========

Copyright (c) 1995 Graham Barr. All rights reserved. This program is free
software; you can redistribute it and/or modify it under the same terms as
Perl itself.


File: pm.info,  Node: Net/SNPP,  Next: Net/SSLeay,  Prev: Net/SMTP,  Up: Module List

Simple Network Pager Protocol Client
************************************

NAME
====

Net::SNPP - Simple Network Pager Protocol Client

SYNOPSIS
========

     use Net::SNPP;
     
     # Constructors
     $snpp = Net::SNPP->new('snpphost');
     $snpp = Net::SNPP->new('snpphost', Timeout => 60);

NOTE
====

This module is not complete, yet !

DESCRIPTION
===========

This module implements a client interface to the SNPP protocol, enabling a
perl5 application to talk to SNPP servers. This documentation assumes that
you are familiar with the SNPP protocol described in RFC1861.

A new Net::SNPP object must be created with the new method. Once this has
been done, all SNPP commands are accessed through this object.

EXAMPLES
========

This example will send a pager message in one hour saying "Your lunch is
ready"

     #!/usr/local/bin/perl -w
     
     use Net::SNPP;
     
     $snpp = Net::SNPP->new('snpphost');
     
     $snpp->send( Pager   => $some_pager_number,
     	         Message => "Your lunch is ready",
     	         Alert   => 1,
     	         Hold    => time + 3600, # lunch ready in 1 hour :-)
     	       ) || die $snpp->message;
     
     $snpp->quit;

CONSTRUCTOR
===========

new ( HOST, [ OPTIONS ] )
     This is the constructor for a new Net::SNPP object. `HOST' is the
     name of the remote host to which a SNPP connection is required.

     OPTIONS are passed in a hash like fasion, using key and value pairs.
     Possible options are:

     *Timeout* - Maximum time, in seconds, to wait for a response from the
     SNPP server (default: 120)

     Debug - Enable debugging information

     Example:

          $snpp = Net::SNPP->new('snpphost',
          			   Debug => 1,
          			  );

METHODS
=======

Unless otherwise stated all methods return either a *true* or *false*
value, with *true* meaning that the operation was a success. When a method
states that it returns a value, falure will be returned as undef or an
empty list.

reset ()
help ()
     Request help text from the server. Returns the text or undef upon
     failure

quit ()
     Send the QUIT command to the remote SNPP server and close the socket
     connection.

EXPORTS
=======

`Net::SNPP' exports all that `Net::CMD' exports, plus three more
subroutines that can bu used to compare against the result of status.
These are :- `CMD_2WAYERROR', `CMD_2WAYOK', and `CMD_2WAYQUEUED'.

SEE ALSO
========

*Note Net/Cmd: Net/Cmd, RFC1861

AUTHOR
======

Graham Barr <Graham.Barr@tiuk.ti.com>

REVISION
========

$Revision: 1.1 $ $Date: 1996/07/26 06:49:13 $

The VERSION is derived from the revision by changing each number after the
first dot into a 2 digit number so

     Revision 1.8   => VERSION 1.08
     Revision 1.2.3 => VERSION 1.0203

COPYRIGHT
=========

Copyright (c) 1995 Graham Barr. All rights reserved. This program is free
software; you can redistribute it and/or modify it under the same terms as
Perl itself.


File: pm.info,  Node: Net/SSLeay,  Next: Net/Socket,  Prev: Net/SNPP,  Up: Module List

Perl extension for using Eric Young's implementation of SSL
***********************************************************

NAME
====

Net::SSLeay - Perl extension for using Eric Young's implementation of SSL

SYNOPSIS
========

     use Net::SSLeay;

See ssl.h header from SSLeay C distribution for list of functions to call.

SSLeay names are stripped of the initial `SSL_', generally you should use
Net::SSLeay:: in place. For example:

In C:

     #include <ssl.h>
     
     err = SSL_set_verify (ssl, SSL_VERIFY_CLIENT_ONCE,
     			   &your_call_back_here);
     
     In perl:

     use Net::SSLeay;

     $err = Net::SSLeay::set_verify ($ssl,
     				&Net::SSLeay::VERIFY_CLIENT_ONCE,
     				\&your_call_back_here);

If the function does not start by SSL_ you should use the full function
name, e.g.:

     $err = &Net::SSLeay::ERR_get_error;

Following new functions behave in perlish way:

     $got = Net::SSLeay::read($ssl);
                                         # Performs SSL_read, but returns $got
                                         # resized according to data received.
                                         # Returns undef on failure.

     Net::SSLeay::write($ssl, $foo) || die;
                                         # Performs SSL_write, but automatically
                                         # figures out the size of $foo

     $got = Net::SSLeay::cat($dest_host, $port, $foo);
                                         # Sends $foo and gets response

DESCRIPTION
===========

Perl glue to call some of the functions in SSLeay library. Note: this
module is still under construction. I'll implement more of SSLeay and
associated libraries once I understand better how to use them. Also
documentation will improve once the SSLeay documentation improves.

Currently much of the stuff that is implemented as C macros is missing.
Interface to supporting libraries is also missing.

This module uses SSLeay-0.6.0, be sure you get it first.

Sockets
-------

Perl uses filehandles for all I/O. While SSLeay has quite flexible BIO
mechanism, this extension still sticks to using file descriptors. Thus to
attach SSLeay to socket you should use fileno to extract the underlying
file descriptor:

     Net::SSLeay::set_fd($ssl, fileno(S));   # Must use fileno

Callbacks
---------

At the moment the implementation of verify_callback is crippeled in the
sense that at any given time there can be only one call back which is
shared by all SSLeay contexts, sessions ans connections. This is due to us
having to keep the reference to the perl call back in a static variable so
that the callback C glue can find it. To remove this restriction would
require either a more complex data structure (like a hash?) in XSUB to map
the call backs to their owners or, cleaner, adding a context pointer in
the SSL structure. This context would then be passed to the C callback,
which in our case would be the glue to look up the proper Perl function
from the context and call it.

The verify call back looks like this in C:

     int (*callback)(int ok,X509 *subj_cert,X509 *issuer_cert,
                             int depth,int errorcode)

The corresponding Perl function should be something like this:

     sub verify {
     	my ($ok, $subj_cert, $issuer_cert, $depth, $errorcode) = @_;
     	print "Verifying certificate...\n";
     	...
     }

It is used like this:

     Net::SSLeay::set_verify ($ssl, Net::SSLeay::VERIFY_PEER, \&verify);

No other callbacks are implemented yet.

EXAMPLES
========

Following is a simple SSLeay client (with too little error checking :-(

     #!/usr/local/bin/perl
     use Socket;
     use Net::SSLeay;
     
     ($dest_serv, $port, $msg) = @ARGV;      # Read command line
     $port = getservbyname  ($port, 'tcp')   unless $port =~ /^\d+$/;
     $dest_ip = gethostbyname ($dest_serv);
     
     $sockaddr_template = 'S n a4 x8';
     $dest_serv_params  = pack ($sockaddr_template, &AF_INET, $port, $dest_ip);
     
     socket  (S, &AF_INET, &SOCK_STREAM, 0)  or die "socket: $!";
     connect (S, $dest_serv_params)          or die "connect: $!";
     select  (S); $| = 1; select (STDOUT);
     
     # The network connection is now open, lets fire up SSL

     $ctx = Net::SSLeay::CTX_new() or die "Failed to create SSL_CTX $!";
     $ssl = Net::SSLeay::new($ctx) or die "Failed to create SSL $!";
     Net::SSLeay::set_fd($ssl, fileno(S));   # Must use fileno
     $res = Net::SSLeay::connect($ssl);
     print "Cipher '" . Net::SSLeay::get_cipher($ssl) . "'\n";
     
     # Exchange data
     
     $res = Net::SSLeay::write($ssl, $msg);  # Perl knows how long $msg is
     shutdown S, 1;  # Half close --> No more output, sends EOF to server
     $got = Net::SSLeay::read($ssl);         # Perl returns undef on failure
     print $got;
     
     Net::SSLeay::free ($ssl);               # Tear down connection
     Net::SSLeay::CTX_free ($ctx);
     close S;

Following is a simple SSLeay echo server (non forking):

     #!/usr/local/bin/perl -w
     use Socket;
     use Net::SSLeay;

     $our_hostname = `hostname`; chop($our_hostname);
     $our_ip = gethostbyname($our_hostname);
     $port = 1235;
     $sockaddr_template = 'S n a4 x8';
     $our_serv_params = pack ($sockaddr_template, &AF_INET, $port, $our_ip);

     socket (S, &AF_INET, &SOCK_STREAM, 0)  or die "socket: $!";
     bind (S, $our_serv_params)             or die "bind:   $!";
     listen (S, 5)                          or die "listen: $!";
     $ctx = Net::SSLeay::CTX_new ()         or die "CTX_new ($ctx): $!";

     while (1) {
         print "Accepting connections...\n";
         ($addr = accept (NS, S))           or die "accept: $!";
         select (NS); $| = 1; select (STDOUT);  # Piping hot!
     
         ($af,$client_port,$client_ip) = unpack($sockaddr_template,$addr);
         @inetaddr = unpack('C4',$client_ip);
         print "$af connection from " .
     	    join ('.', @inetaddr) . ":$client_port\n";
     
     	# We now have a network connection, lets fire up SSLeay...

     $ssl = Net::SSLeay::new($ctx)      or die "SSL_new ($ssl): $!";
     Net::SSLeay::set_fd($ssl, fileno(NS));
     
     Net::SSLeay::use_RSAPrivateKey_file ($ssl, 'plain-rsa.pem',
                                          &Net::SSLeay::FILETYPE_PEM);
     Net::SSLeay::use_certificate_file ($ssl, 'plain-cert.pem',
     	 				   &Net::SSLeay::FILETYPE_PEM);
     $err = Net::SSLeay::accept($ssl);
     print "Cipher '" . Net::SSLeay::get_cipher($ssl) . "'\n";
     
     # Connected. Exchange some data.
     
     $got = Net::SSLeay::read($ssl);     # Returns undef on fail
     print "Got '$got' (" . length ($got) . " chars)\n";
     
     Net::SSLeay::write ($ssl, uc ($got)) or die "write: $!";
     
     Net::SSLeay::free ($ssl);           # Tear down connection
     close NS;
         }

Yet another echo server. This one runs from /etc/inetd.conf so it avoids
all the socket code over head. Only caveat is opening rsa key file - it
had better be without any encryption or else it won't know where to ask
for the password.

     #!/usr/local/bin/perl
     # /etc/inetd.conf
     #    ssltst stream tcp nowait root /path/to/server.pl server.pl
     # /etc/services
     #    ssltst		1234/tcp
     use Net::SSLeay;
     chdir '/key/dir' or die "chdir: $!";
     $| = 1;  # Piping hot!
     open LOG, ">>/dev/console" or die "Can't open log file $!";
     select LOG; print "server.pl started\n";

     $ctx = Net::SSLeay::CTX_new()     or die "CTX_new ($ctx) ($!)";
         $ssl = Net::SSLeay::new($ctx)     or die "new ($ssl) ($!)";

     # We get already open network connection from inetd, now we just
     # need to attach SSLeay to STDIN and STDOUT
     Net::SSLeay::set_rfd($ssl, fileno(STDIN));
     Net::SSLeay::set_wfd($ssl, fileno(STDOUT));

     Net::SSLeay::use_RSAPrivateKey_file ($ssl, 'plain-rsa.pem',
     				         &Net::SSLeay::FILETYPE_PEM);
     Net::SSLeay::use_certificate_file ($ssl, 'plain-cert.pem',
     				       &Net::SSLeay::FILETYPE_PEM);
     Net::SSLeay::accept($ssl) or die "accept: $!";
     print "Cipher '" . Net::SSLeay::get_cipher($ssl) . "'\n";
     
     $got = Net::SSLeay::read($ssl);
     print "Got '$got' (" . length ($got) . " chars)\n";

     Net::SSLeay::write ($ssl, uc($got)) or die "write: $!";

     Net::SSLeay::free ($ssl);         # Tear down the connection
     Net::SSLeay::CTX_free ($ctx);
     close LOG;

AUTHOR
======

Sampo Kellomaki <sampo@iki.fi>

COPYRIGHT
=========

Copyright (c) 1996 Sampo Kellomaki <sampo@iki.fi>, All Rights Reserved.

Distribution and use of this module is under the same terms as the SSLeay
package itself (i.e. free, but mandatory attribution; NO WARRANTY). Please
consult COPYRIGHT file in the root of the SSLeay distribution.

While the source distribution of this perl module does not contain Eric's
code, if you use this module you will use Eric's library. Please give him
credit.

SEE ALSO
========

     perl-source-root/ext/Net/SSLeay/examples - Example servers and a client
     doc directory of SSLeay distribution
     <http://www.psy.uq.oz.au/~ftp/Crypto/>   - SSLeay online documentation
     <ftp://ftp.psy.uq.oz.au/pub/Crypto/SSL>  - current SSLeay source
     <http://www.netscape.com/info/SSL.html>  - SSL Draft specification
     <http://www.neuronio.pt/SSLeay.pm.html/> - SSLeay.pm home


File: pm.info,  Node: Net/Socket,  Next: Net/Telnet,  Prev: Net/SSLeay,  Up: Module List

TEMPORARY Socket filedescriptor class, so Net::FTP still works while IO::Socket is having a re-fit <GBARR>
**********************************************************************************************************

NAME
====

Net::Socket - TEMPORARY Socket filedescriptor class, so Net::FTP still
works while IO::Socket is having a re-fit <GBARR>

DESCRIPTION
===========

NO TEXT -- THIS MODULE IS TEMPORARY

new( %args )
------------

The new constructor takes its arguments in the form of a hash. Accepted
arguments are

     Peer     => remote host name for a 'connect' socket
     Proto    => specifiy protocol by it self (but override by Service)
     Service  => require service eg 'ftp' or 'ftp/tcp', overrides Proto
     Port     => port num for connect eg 'ftp' or 21, defaults to Service
     Bind     => port to bind to, defaults to INADDR_ANY
     Listen   => queue size for listen

autoflush( [$val] )
-------------------

Set the file descriptor to autoflush, depending on `$val'

accept
------

perform the system call accept on the socket and return a new Net::Socket
object. This object can be used to communicate with the client that was
trying to connect.

close
-----

Close the file descriptor

dup
---

Create a duplicate of the socket object

sockname
--------

Return a packed sockaddr structure for the socket

sockaddr
--------

Return the address part of the sockaddr structure for the socket

sockport
--------

Return the port number that the socket is using on the local host

sockhost
--------

Return the address part of the sockaddr structure for the socket in a text
form xx.xx.xx.xx

peername, peeraddr, peerport, peerhost
--------------------------------------

Same as for the sock* functions, but returns the data about the peer host
instead of the local host.

send( $buf [, $flags [, $to]] )
-------------------------------

For a udp socket, send the contents of `$buf' to the remote host `$to'
using flags `$flags'.

If `$to' is not specified then the data is sent to the host which the
socket last communicated with, ie sent to or recieved from.

If `$flags' is ommited then 0 is used

recv( $buf, $len [, $flags] )
-----------------------------

Receive `$len' bytes of data from the socket and place into `$buf'

If `$flags' is ommited then 0 is used

AUTHOR
======

Graham Barr <Graham.Barr@tiuk.ti.com>

REVISION
========

$Revision: 1.2 $

COPYRIGHT
=========

Copyright (c) 1995 Graham Barr. All rights reserved. This program is free
software; you can redistribute it and/or modify it under the same terms as
Perl itself.


File: pm.info,  Node: Net/Telnet,  Next: Net/Time,  Prev: Net/Socket,  Up: Module List

Defines constants for the telnet protocol
*****************************************

NAME
====

Net::Telnet - Defines constants for the telnet protocol

SYNOPSIS
========

     use Telnet qw(TELNET_IAC TELNET_DO TELNET_DONT);

DESCRIPTION
===========

This module is *VERY* preliminary as I am not 100% sure how it should be
implemented.

Currently it just exports constants used in the telnet protocol.

Should it contain sub's for packing and unpacking commands ?

Please feel free to send me any suggestions

NOTE
====

This is not an implementation of the 'telnet' command but of the telnet
protocol as defined in RFC854

AUTHOR
======

Graham Barr <Graham.Barr@tiuk.ti.com>

REVISION
========

$Revision: 2.0 $

COPYRIGHT
=========

Copyright (c) 1995 Graham Barr. All rights reserved. This program is free
software; you can redistribute it and/or modify it under the same terms as
Perl itself.


File: pm.info,  Node: Net/Time,  Next: News/NNTPClient,  Prev: Net/Telnet,  Up: Module List

time and daytime network client interface
*****************************************

NAME
====

Net::Time - time and daytime network client interface

SYNOPSIS
========

     use Net::Time qw(inet_time inet_daytime);
     
     print inet_time('localhost');
     print inet_time('localhost', 'tcp');
     
     print inet_daytime('localhost');
     print inet_daytime('localhost', 'tcp');

DESCRIPTION
===========

`Net::Time' provides subroutines that obtain the time on a remote machine.

inet_time ( HOST [, PROTOCOL])
     Obtain the time on `HOST' using the protocol as defined in RFC868. The
     optional argument `PROTOCOL' should define the protocol to use, either
     `tcp' or `udp'. The result will be a unix-like time value or undef
     upon failure.

inet_daytime ( HOST [, PROTOCOL])
     Obtain the time on `HOST' using the protocol as defined in RFC867. The
     optional argument `PROTOCOL' should define the protocol to use, either
     `tcp' or `udp'. The result will be an ASCII string or undef upon
     failure.

AUTHOR
======

Graham Barr <Graham.Barr@tiuk.ti.com>

REVISION
========

$Revision: 2.0 $

COPYRIGHT
=========

Copyright (c) 1995 Graham Barr. All rights reserved. This program is free
software; you can redistribute it and/or modify it under the same terms as
Perl itself.


File: pm.info,  Node: News/NNTPClient,  Next: News/Newsrc,  Prev: Net/Time,  Up: Module List

Perl 5 module to talk to NNTP (RFC977) server
*********************************************

NAME
====

News::NNTPClient - Perl 5 module to talk to NNTP (RFC977) server

DESCRIPTION
===========

This module implements a client interface to NNTP, enabling a Perl 5
application to talk to NNTP servers.  It uses the OOP (Object Oriented
Programming) interface introduced with Perl 5.

USAGE
=====

To use it in your programs, you can use either:

     use News::NNTPClient;

or

     require News::NNTPClient;

NNTPClient exports nothing.

A new NNTPClient object must be created with the new method.  Once this
has been done, all NNTP commands are accessed through this object.

Here are a couple of short examples.  The first prints all articles in the
"test" newsgroup:

     #!/usr/local/bin/perl -w
     
     use News::NNTPClient;
     
     $c = new News::NNTPClient;
     
     ($first, $last) = ($c->group("test"));
     
     for (; $first <= $last; $first++) {
         print $c->article($first);
     }
     
     __END__

This example prints the body of all articles in the "test" newsgroup newer
than one hour:

     #!/usr/local/bin/perl -w
     
     require News::NNTPClient;
     
     $c = new News::NNTPClient;
     
     foreach ($c->newnews("test", time - 3600)) {
         print $c->body($_);
     }
     
     __END__

NNTPClient Commands
-------------------

These commands are used to manipulate the NNTPClient object, and aren't
directly related to commands available on any NNTP server.

new
     Use this to create a new NNTP connection. It takes three arguments, a
     hostname, a port and a debug flag.  It calls initialize.  Use an
     empty argument to specify defaults.

     If port is omitted or blank (""), looks for environment variable
     NNTPPORT, service "nntp", or uses 119.

     If host is omitted or empty (""), looks for environment variable
     NNTPSERVER or uses "news".

     Examples:

          $c = new News::NNTPClient;
          or
          $c = new News::NNTPClient("newsserver.some.where");
          or
          $c = new News::NNTPClient("experimental", 9999);
          or
          # Specify debug but use defaults.
          $c = new News::NNTPClient("", "", 2);

     Returns a blessed reference, representing a new NNTP connection.

initialize
     Calls port, host, connect, and *response*, in that order.  If any of
     these fail, initialization is aborted.

connect
     Connects to current host/port.  Not normally needed, as the new
     method does this for you.  Closes any existing connection.  Sets the
     posting status.  See the postok method.

host
     Sets the host that will be used on the next connect.  Not normally
     needed, as the new method does this for you.

     Without an argument, returns current host.

     Argument can be hostname or dotted quad, for example, "15.2.174.218".

     Returns fully qualified host name.

port
     Sets the port that will be used on the next connect.  Not normally
     needed, as the new method does this for you.

     Without an argument, returns current port.

     Argument can be port number or name.  If it is a name, it must be a
     valid service.

     Returns port number.

debug
     Sets the debug level.

     Without an argument, returns current debug level.

     There are currently three debug levels.  Level 0, level 1, and level
     2.

     At level 0 the messages described for level 1 are not produced.  Debug
     level 0 is a way of turning off messages produced by the default debug
     level 1.  Serious error messages, such as EOF (End Of File) on the
     file handle, are still produced.

     At level 1, any NNTP command that results in a result code of 400 or
     greater prints a warning message.  This is the default.

     At level 2, in addition to level 1 messages, status messages are
     printed to indicate actions taking place.

     Returns old debug value.

ok
     Returns boolean status of most recent command.  NNTP return codes less
     than 400 are considered OK.  Not often needed as most commands return
     false upon failure anyway.

okprint
     Returns boolean status of most recent command.  NNTP return codes less
     than 400 are considered OK.  Prints an error message for return codes
     of 400 or greater unless debug level is set to zero (0).

     This method is used internally by most commands, and could be
     considered to be "for internal use only".  You should use the return
     status of commands directly to determine pass-fail, or if needed the
     ok method can be used to check status later.

message
     Returns the NNTP response message of the most recent command.

     Example, as returned by NNTP server version 1.5.11t:

          $c->slave;
          print $c->message;

          Kinky, kinky.  I don't support such perversions.

code
     Returns the NNTP response code of the most recent command.

     Example:

          $c->article(1);
          print $c->code, "\n";

          412

postok
     Returns the post-ability status that was reported upon connection or
     after the mode_reader command.

eol
     Sets the End-Of-Line termination for text returned from the server.

     Returns the old EOL setting.

     Default is \n.

     To set EOL to nothing, pass it the empty string.

     To query current EOL without setting it, call with no arguments.

     Returns the old EOL termination.

     Example:

          $old_eol = $c->eol();     # Get original.
          $c->eol("");              # Set EOL to nothing.
          @article = $c->article(); # Fetch an article.
          $c->eol($old_eol);        # Restore value.

version
     Returns version number.

     This document represents @(#) $Revision: 0.26 $.

NNTP Commands
-------------

These commands directly correlate to NNTP server commands.  They return a
false value upon failure, true upon success.  The truth value is usually
some bit of useful information.  For example, the stat command returns
Message-ID if it is successful.

Some commands return multiple lines.  These lines are returned as an array
in array context, and as a reference to an array in scalar context.  For
example, if you do this:

     @lines = $c->article(14);

then @lines will contain the article, one line per array element.
However, if you do this:

     $lines = $c->article(14);

then $lines will contain a *reference* to an array.  This feature is for
those that don't like passing arrays from routine to routine.

mode_reader
     Some servers require this command to process NNTP client commands.
     Sets postok status.  See postok.

     Returns OK status.

article
     Retrieves an article from the server.  This is the main command for
     fetching articles.  Expects a single argument, an article number or
     Message-ID.  If you use an article number, you must be in a news
     group.  See group.

     Returns the header, a separating blank line, and the body of the
     article as an array of lines terminated by the current EOL.

     In scalar context a reference to the array is returned instead of the
     array itself.

     Examples:

          print $c->article('<art1234@soom.oom>');

          $c->group("test");

          print $c->article(99);

body
     Expects a single argument, an article number or Message-ID.

     Returns the body of an article as an array of lines terminated by the
     current EOL.

     In scalar context a reference to the array is returned instead of the
     array itself.

     See article.

head
     Expects a single argument, an article number or Message-ID.

     Returns the head of the article as an array of lines terminated by the
     current EOL.

     In scalar context a reference to the array is returned instead of the
     array itself.

     See article.

stat
     Expects a single argument, an article number or Message-ID.

     The STAT command is like the ARTICLE command except that it does not
     return any text.  It can be used to set the "current article pointer"
     if passed an article number, or to validate a Message-ID if passed a
     Message-ID.

     Returns Message-ID if successful, otherwise returns false.

last
     The "current article pointer" maintained by the server is moved to the
     previous article in the current news group.

     Returns Message-ID if successful, otherwise returns false.

next
     The "current article pointer" maintained by the server is moved to the
     next article in the current news group.

     Returns Message-ID if successful, otherwise returns false.

group
     Expects a single argument, the name of a valid news group.

     This command sets the current news group as maintained by the server.
     It also sets the server maintained "current article pointer" to the
     first article in the group.  This enables the use of certain other
     server commands, such as article, head, body, stat, last, and next.
     Also sets the current group in the NNTPClient object, which is used
     by the newnews and xindex commands.

     Returns (first, last) in list context, or "first-last" in scalar
     context, where first and last are the first and last article numbers
     as reported by the group command.  Returns false if there is an error.

     It is an error to attempt to select a non-existent news group.

     If the estimated article count is needed, it can be extracted from the
     message.  See message.

list
     Accepts one optional argument that can be used indicate the type of
     list desired.  List type depends on server.

     With an argument of "active" or with no arguments, this command
     returns a list of valid newsgroups and associated information.  The
     format is:

          group last first p

     where group is the news group name, last is the article number of the
     last article, first is the article number of the first article, and p
     is flag indicating if posting is allowed.  A 'y' flag is an indication
     that posting is allowed.

     Other possible arguments are: newsgroups, distributions, subscriptions
     for B-News, and active.times, distributions, distrib.pats, newsgroups,
     overview.fmt for INN.

     Returns an array of lines terminated by the current EOL.

     In scalar context a reference to the array is returned instead of the
     array itself.

newgroups
     Expects at least one argument representing the date/time in seconds,
     or in "YYMMDD HHMMSS" format.  Remaining arguments are used as
     distributions.

     Example, print all new groups in the "comp" and/or "news" hierarchy as
     of one hour ago:

          print $c->newgroups(time() - 3600, "comp", "news");

     Returns list of new news group names as an array of lines terminated
     by the current EOL.

     In scalar context a reference to the array is returned instead of the
     array itself.

newnews
     Expects one, two, or more arguments.

     If the first argument is a group name, it looks for new news in that
     group, and the date/time is the second argument.  If the first
     argument represents the date/time in seconds or in "YYMMDD HHMMSS"
     format, then the group is is last group set via the group command. If
     no group command has been issued then the group is "*", representing
     all groups.  Remaining arguments are use to restrict search to
     certain distribution(s).

     Returns a list of Message-IDs of articles that have been posted or
     received since the specified time.

     Examples:

          # Hour old news in news group "test".
          $c->newnews("test", time() - 3600);
          or
          # Hour old in all groups.
          $c->newnews(time() - 3600);
          or
          $c->newnews("*", time() - 3600);
          or
          # Hour old news in news group "test".
          $c->group("test");
          $c->newnews(time() - 3600);

     The group argument can include an asterisk "*" to specify a range news
     groups.  It can also include multiple news groups, separated by a
     comma ",".

     Example:

          $c->newnews("comp.*.sources,alt.sources", time() - 3600);

     An exclamation point "!" may be used to negate the selection of
     certain groups.

     Example:

          $c->newnews("*sources*,!*.d,!*.wanted", time() - 3600);

     Any additional distribution arguments will be concatenated together
     and send as a distribution list.  The distribution list will limit
     articles to those that have a Distribution: header containing one of
     the distributions passed.

     Example:

          $c->newnews("*", time() - 3600, "local", "na");

     Returns Message-IDs of new articles as an array of lines terminated by
     the current EOL.

     In scalar context a reference to the array is returned instead of the
     array itself.

help
     Returns any server help information.  The format of the information is
     highly dependent on the server, but usually contains a list of NNTP
     commands recognized by the server.

     Returns an array of lines terminated by the current EOL.

     In scalar context a reference to the array is returned instead of the
     array itself.

post
     Post an article.  Expects data to be posted as an array of lines.
     Most servers expect, at a minimum, Newsgroups and Subject headers.
     Be sure to separate the header from the body with a neck, er blank
     line.

     Example:

          @header = ("Newsgroups: test", "Subject: test");
          @body   = ("This is the body of the article");

          $c->post(@header, "", @body);

     Any "\n" characters at the end of a line will be trimmed.

ihave
     Transfer an article.  Expects an article Message-ID and the article to
     be sent as an array of lines.

     Example:

          # Fetch article from server on $c
          @article = $c->article($artid);
          
          # Send to server on $d
          if ($d->ihave($artid, @article)) {
              print "Article transfered\n";
          } else {
              print "Article rejected: ", $d->message, "\n";
          }

slave
     Doesn't do anything on most servers.  Included for completeness.

DESTROY
     This method is called whenever the the object created by
     News::NNTPClient::new is destroyed.  It calls quit to close the
     connection.

quit
     Send the NNTP quit command and close the connection.  The connection
     can be then be re-opened with the connect method.  Quit will
     automatically be called when the object is destroyed, so there is no
     need to explicitly call quit before exiting your program.

Extended NNTP Commands
----------------------

These commands also directly correlate NNTP server commands, but are not
mentioned in RFC977, and are not part of the standard.  However, many
servers implement them, so they are included as part of this package for
your convenience.  If a command is not recognized by a server, the server
usually returns code 500, command unrecognized.

authinfo
     Expects two arguments, user and password.

date
     Returns server date in "YYYYMMDDhhmmss" format.

listgroup
     Expects one argument, a group name.  Default is current group.

     Returns article numbers as an array of lines terminated by the current
     EOL.

     In scalar context a reference to the array is returned instead of the
     array itself.

xmotd
     Expects one argument of unix time in seconds or as a string in the
     form "YYMMDD HHMMSS".

     Returns the news servers "Message Of The Day" as an array of lines
     terminated by the current EOL.

     In scalar context a reference to the array is returned instead of the
     array itself.

     For example, the following will always print the message of the day,
     if there is any:

          print $c->xmotd(1);
          NNTP Server News2

          News administrator is Joseph Blough <joeblo@news.foo.com>

xgtitle
     Expects one argument of a group pattern.  Default is current group.

     Returns group titles an array of lines terminated by the current EOL.

     In scalar context a reference to the array is returned instead of the
     array itself.

     Example:

          print $c->xgtitle("bit.listserv.v*");

          bit.listserv.valert-l   Virus Alert List. (Moderated)
          bit.listserv.vfort-l    VS-Fortran Discussion List.
          bit.listserv.vm-util    VM Utilities Discussion List.
          bit.listserv.vmesa-l    VM/ESA Mailing List.
          bit.listserv.vmslsv-l   VAX/VMS LISTSERV Discussion List.
          bit.listserv.vmxa-l     VM/XA Discussion List.
          bit.listserv.vnews-l    VNEWS Discussion List.
          bit.listserv.vpiej-l    Electronic Publishing Discussion

xpath
     Expects one argument of an article Message-ID.  Returns the path name
     of the file on the server.

     Example:

          print print $c->xpath(q(<43bq5l$7b5@news.dtc.hp.com>))'
          hp/test/4469

xhdr
     Fetch header for a range of articles.  First argument is name of
     header to fetch.  If omitted or blank, default to Message-ID.  Second
     argument is start of article range.  If omitted, defaults to 1.  Next
     argument is end of range.

     Returns headers as an array of lines terminated by the current EOL.

     In scalar context a reference to the array is returned instead of the
     array itself.

     Examples:

          # Fetch Message-ID of article 1.
          $c->xhdr();

          # Fetch Subject of article 1.
          $c->xhdr("Subject");

          # Fetch Subject of article 3345.
          $c->xhdr("Subject", 3345);

          # Fetch Subjects of articles 3345-9873
          $c->xhdr("Subject", 3345, 9873);

          # Fetch Message-ID of articles 3345-9873
          $c->xhdr("", 3345,9873);

xpat
     Fetch header for a range of articles matching one or more patterns.
     First argument is name of header to fetch.  If omitted or blank,
     default to Subject.  Second argument is start of article range.  If
     omitted, defaults to 1.  Next argument is end of range.  Remaining
     arguments are patterns to match.  Some servers use "*" for wildcard.

     Returns headers as an array of lines terminated by the current EOL.

     In scalar context a reference to the array is returned instead of the
     array itself.

     Examples:

          # Fetch Subject header of article 1.
          $c->xpat();

          # Fetch "From" header of article 1.
          $c->xpat("From");

          # Fetch "From" of article 3345.
          $c->xpat("From", 3345);

          # Fetch "From" of articles 3345-9873 matching *foo*
          $c->xpat("From", 3345, 9873, "*foo*");

          # Fetch "Subject" of articles 3345-9873 matching
          # *foo*, *bar*, *and*, *stuff*
          $c->xpat("", 3345,9873, qw(*foo* *bar* *and* *stuff*));

xover
     Expects an article number or a starting and ending article number
     representing a range of articles.

     Returns overview information for each article as an array of lines
     terminated by the current EOL.

     In scalar context a reference to the array is returned instead of the
     array itself.

     Xover generally returns items separated by tabs.  Here is an example
     that prints out the xover fields from all messages in the "test" news
     group.

          #!/usr/local/bin/perl

          require News::NNTPClient;

          $c = new News::NNTPClient;

          @fields = qw(numb subj from date mesg refr char line xref);

          foreach $xover ($c->xover($c->group("test"))) {
              %fields = ();
              @fields{@fields} = split /\t/, $xover;
              print map { "$_: $fields{$_}\n" } @fields;
              print "\n";
          }

          __END__

xthread
     Expects zero or one argument.  Value of argument doesn't matter.  If
     present, *dbinit* command is sent.  If absent, *thread* command is
     sent.

     Returns binary data as a scalar value.

     Format of data returned is unknown at this time.

xindex
     Expects one argument, a group name.  If omitted, defaults to the group
     set by last group command.  If there hasn't been a group command, it
     returns an error;

     Returns index information for group as an array of lines terminated by
     the current EOL.

     In scalar context a reference to the array is returned instead of the
     array itself.

xsearch
     Expects a query as an array of lines which are sent to the server,
     much like post.  Returns the result of the search as an array of lines
     or a reference to same.

     Format of query is unknown at this time.

AUTHOR
======

Rodger Anderson  <rodger@boi.hp.com>

SOURCE
======

The latest version may be retrieved by sending mail to:

     <rodger@boi.hp.com>

with the body of the message starting with:

     send nntpclient

COPYRIGHT
=========

Copyright (c) 1995 Rodger Anderson. All rights reserved.  This module is
free software; you can redistribute it and/or modify it under the same
terms as Perl itself.


File: pm.info,  Node: News/Newsrc,  Next: ODBM_File,  Prev: News/NNTPClient,  Up: Module List

manage newsrc files
*******************

NAME
====

News::Newsrc - manage newsrc files

SYNOPSIS
========

     use News::Newsrc;

     $newsrc = new News::Newsrc;
     
     $newsrc->load();
     $newsrc->load($file);
     
     $newsrc->save();
     $newsrc->save_as($file);

     $newsrc->add_group($group);
     $newsrc->del_group($group);
     
     $newsrc->subscribe  ($group);
     $newsrc->unsubscribe($group);

     $newsrc->mark        ($group,  $article);
     $newsrc->mark_list   ($group, \@articles);
     $newsrc->mark_range  ($group, $from, $to);
     
     $newsrc->unmark      ($group,  $article);
     $newsrc->unmark_list ($group, \@articles);
     $newsrc->unmark_range($group, $from, $to);
     
     ... if $newsrc->exists    ($group);
     ... if $newsrc->subscribed($group);
     ... if $newsrc->marked    ($group, $article);
     
     @groups   = $newsrc->groups();
     @groups   = $newsrc->sub_groups();
     @groups   = $newsrc->unsub_groups();
     @articles = $newsrc->marked_articles($group);
     @articles = $newsrc->unmarked_articles($group, $from, $to);

REQUIRES
========

Perl 5.002, Exporter, Set::IntSpan 1.01

EXPORTS
=======

None

DESCRIPTION
===========

News::Newsrc manages newsrc files, of the style

     alt.foo: 1-21,28,31-34
     alt.bar! 3,5,9-2900,2902

Methods are provided for

   * reading and writing newsrc files

   * adding and removing newsgroups

   * subscribing and unsubscribing from newsgroups

   * testing whether groups exist and are subscribed

   * marking and unmarking articles

   * testing whether articles are marked

   * returning lists of newsgroups

   * returning lists of articles

NEWSRC FILES
============

A newsrc file is an ASCII file that lists newsgroups and article numbers.
Each line of a newsrc file describes a single newsgroup.  Each line is
divided into three fields: a group, a *subscription mark* and an *article
list*.

Lines containing only whitespace are ignored.  Whitespace within a line is
ignored.

Group
     The group is the name of the newsgroup.  A group name may not contain
     colons (:) or exclamation points (!).  Group names must be unique
     within a newsrc file.  The group name is required.

Subscription mark
     The *subscription mark* is either a colon (:), for subscribed groups,
     or an exclamation point (!), for unsubscribed groups.  The
     subscription mark is required.

Article list
     The *article list* is a comma-separated list of positive integers.
     The integers must be listed in increasing order.  Runs of consecutive
     integers may be abbreviated a-b, where a is the first integer in the
     run and b is the last.  The article list may be empty.

METHODS
=======

new News::Newsrc
     Creates and returns a News::Newsrc object.  The object contains no
     newsgroups.

load()
load($file)
     Loads the newsgroups in $file into a newsrc object.  If $file is
     omitted, reads $ENV{HOME}/.newsrc.  Any existing data in the object
     is discarded.  Returns non-null on success.

     If $file can't be opened, load() discards existing data from the
     newsrc object and returns null.

     If $file contains invalid lines, load() will die().  When this
     happens, the state of the newsrc object is undefined.

save()
     Writes the contents of a newsrc object back to the file from which it
     was load()ed.  If load() has not been called, writes to
     $ENV{HOME}/.newsrc.  In either case, if the destination *file* exists,
     it is renamed to *file*.bak

save_as($file)
     Writes the contents of a newsrc object to $file.  If $file exists, it
     is renamed to $file.bak.  Subsequent calls to save() will write to
     $file.

add_group($group)
     Adds $group to the list of newsgroups in a newsrc object.  $group is
     initially subscribed.  The article list for $group is initially empty.

del_group($group)
     Removes $group from the list of groups in a newsrc object.  The
     article list for $group is lost.

subscribe($group)
     Subscribes to $group.  $group will be created if it does not exist.

unsubscribe($group)
     Unsubscribes from $group.  $group will be created if it does not
     exist.

mark($group, $article)
     Adds $article to the article list for $group.  $group will be created
     if it does not exist.

mark_list($group, \@articles)
     Adds @articles to the article list for $group.  $group will be
     created if it does not exist.

mark_range($group, $from, $to)
     Adds all the articles from $from to $to, inclusive, to the article
     list for $group.  $group will be created if it does not exist.

unmark($group, $article)
     Removes $article from the article list for $group.  $group will be
     created if it does not exist.

unmark_list($group, \@articles)
     Removes @articles from the article list for $group.  $group will be
     created if it does not exist.

unmark_range($group, $from, $to)
     Removes all the articles from $from to $to, inclusive, from the
     article list for $group.  $group will be created if it does not exist.

exists($group)
     Returns true if $group exists in the newsrc object.

subscribed($group)
     Returns true if $group exists and is subscribed.

marked($group, $article)
     Returns true if $group exists and its article list contains $article.

groups()
     Returns the list of groups in a newsrc object.  In scalar context,
     returns an array reference.

sub_groups()
     Returns the list of subscribed groups in a newsrc object.  In scalar
     context, returns an array reference.

unsub_groups()
     Returns the list of unsubscribed groups in a newsrc object.  In
     scalar context, returns an array reference.

marked_articles($group)
     Returns the list of articles in the article list for $group.  In
     scalar context, returns an array reference.

unmarked_articles($group, $from, $to)
     Returns the list of articles from $from to $to, inclusive, that do
     *not* appear in the article list for $group.  In scalar context,
     returns an array reference.

DIAGNOSTICS
===========

load() returns null if it can't open the newsrc file.

load() will die() if the newsrc file contains invalid lines.

save() and save_as() will die() if they can't backup or write the newsrc
file.

ERROR HANDLING
==============

"Don't test for errors that you can't handle."

load() returns null if it can't open the newsrc file, and dies if the
newsrc file contains invalid data.  This isn't as schizophrenic as it
seems.

There are several ways a program could handle an open failure on the
newsrc file.  It could prompt the user to reenter the file name.  It could
assume that the user doesn't have a newsrc file yet.  If it doesn't want
to handle the error, it could go ahead and die.

On the other hand, it is very difficult for a program to do anything
sensible if the newsrc file opens successfully and then turns out to
contain invalid data.  Was there a disk error?  Is the file corrupt?  Did
the user accidentally specify his kill file instead of his newsrc file?
And what are you going to do about it?

Rather than try to handle an error like this, it's probably better to die
and let the user sort things out.  By the same rational, save() and
save_as() die on failure.

Programs that must retain control can use eval{...} to protect calls that
may die.  For example, Perl/Tk runs all callbacks inside an eval{...}.  If
a callback dies, Perl/Tk regains control and displays $@ in a dialog box.
The user can then decide whether to continue or quit from the program.

AUTHOR
======

Steven McDougall, swm@cric.com

SEE ALSO
========

perl(1), Set::IntSpan

COPYRIGHT
=========

Copyright (c) 1996 Steven McDougall. All rights reserved.  This module is
free software; you can redistribute it and/or modify it under the same
terms as Perl itself.


File: pm.info,  Node: ODBM_File,  Next: OS2/Attrib,  Prev: News/Newsrc,  Up: Module List

Tied access to odbm files
*************************

NAME
====

ODBM_File - Tied access to odbm files

SYNOPSIS
========

     use ODBM_File;

     tie(%h, 'ODBM_File', 'Op.dbmx', O_RDWR|O_CREAT, 0640);

     untie %h;

DESCRIPTION
===========

See `tie', *Note Perlfunc: (perl.info)perlfunc,


File: pm.info,  Node: OS2/Attrib,  Next: OS2/SoftInstaller,  Prev: ODBM_File,  Up: Module List

Get or set OS/2 file attributes
*******************************

NAME
====

OS2::Attrib - Get or set OS/2 file attributes

SYNOPSIS
========

     use OS2::Attrib qw(get_attribs set_attribs);
     $attribs = get_attribs($path);
     set_attribs($attribs, $path1, $path2, ...);

DESCRIPTION
===========

OS2::Attrib provides access to OS/2 file attributes.  While the read-only
attribute can be handled by chmod and stat, the hidden, system, and
archive attributes cannot.

$attribs = get_attribs($path)
     Returns the attributes of `$path', or the empty string if `$path'
     does not exist.  Attributes are returned as a five-character string in
     this format: "RHSAD".  Each letter is replaced by an underscore (`_')
     if the file does not have the corresponding attribute.  (This is the
     same format as a 4OS2 directory listing.)  The attributes are:

          R  The file is read-only (not writable)
          H  The file is hidden (does not appear in directory listings)
          S  The file is a system file (does not appear in directory listings)
          A  The file needs to be archived (it has changed since last backup)
          D  The file is a directory

$count = set_attribs($attribs, $path1, [$path2, ...])
     Sets the attributes of `$path1', `$path2', etc.  You can either
     specify the complete set of attributes, or add and subtract attributes
     by using + and -.  The case and order of the attributes is not
     important.  For example, '-s+ra' will remove the system attribute and
     add the read-only and archive attributes.  You should not use
     whitespace between attributes, although underscores are OK.  See
     `get_attribs' for an explanation of the attribute values.  You cannot
     change the directory attribute; if you specify it, it is ignored.
     Returns the number of files successfully changed.

AUTHOR
======

Christopher J. Madsen <`ac608@yfn.ysu.edu'>

SEE ALSO
========

The `OS2::ExtAttr' in this node module provides access to extended
attributes.


File: pm.info,  Node: OS2/SoftInstaller,  Next: Opcode,  Prev: OS2/Attrib,  Up: Module List

Perl extension for generation of daughter packages for IBM's Software Installer.
********************************************************************************

NAME
====

OS2::SoftInstaller - Perl extension for generation of daughter packages
for IBM's Software Installer.

SYNOPSIS
========

     use OS2::SoftInstaller;
     open PKG, 'my.pkg';
     select PKG;
     make_pkg toplevel => '.', zipfile => 'my.zip', packid => 'myzip',
       nozip => 0, exclude => undef, dirid => 'FILE';
     select STDOUT;
     close PKG;

DESCRIPTION
===========

The function make_pkg() takes a hash-like list of arguments. The
recognized keys are:

toplevel
     toplevel directory of the tree to duplicate.

zipfile
     name of the zipfile which corresponds to this directory in the
     distribution.

packid
     symbolic name for this zipfile, autogenerated if needed.

nozip
     Do not generate toplevel description of the ZIP file (useful if the
     same zipfile is used in multiple components).

exclude
     if defined, is a regexp for files to exclude from the generated
     package file.

dirid
     id of the directory to install to (eg, FILE or AUX7).

We suppose that `%unzip%' has the value of something like `unzip -oj',
`%unzip_d%' is something like -d (directory to extract), and the output of
this script is included like this:

     FILE
       EXIT = 'setvar unzip=unzip -oj'

     FILE
       EXIT = 'setvar unzip_d=-d'

     INCLUDE
       NAME = 'my.pkg'

into the parent package file.

AUTHOR
======

Ilya Zakharevich, ilya@math.ohio-state.edu

SEE ALSO
========

perl(1).


File: pm.info,  Node: Opcode,  Next: PDL,  Prev: OS2/SoftInstaller,  Up: Module List

Disable named opcodes when compiling perl code
**********************************************

NAME
====

Opcode - Disable named opcodes when compiling perl code

SYNOPSIS
========

     use Opcode;

DESCRIPTION
===========

Perl code is always compiled into an internal format before execution.

Evaluating perl code (e.g. via "eval" or "do 'file'") causes the code to
be compiled into an internal format and then, provided there was no error
in the compilation, executed.  The internal format is based on many
distinct opcodes.

By default no opmask is in effect and any code can be compiled.

The Opcode module allow you to define an *operator mask* to be in effect
when perl next compiles any code.  Attempting to compile code which
contains a masked opcode will cause the compilation to fail with an error.
The code will not be executed.

NOTE
====

The Opcode module is not usually used directly. See the ops pragma and
Safe modules for more typical uses.

WARNING
=======

The authors make *no warranty*, implied or otherwise, about the
suitability of this software for safety or security purposes.

The authors shall not in any case be liable for special, incidental,
consequential, indirect or other similar damages arising from the use of
this software.

Your mileage will vary. If in any doubt *do not use it*.

Operator Names and Operator Lists
=================================

The canonical list of operator names is the contents of the array op_name
defined and initialised in file `opcode.h' of the Perl source distribution
(and installed into the perl library).

Each operator has both a terse name (its opname) and a more verbose or
recognisable descriptive name. The opdesc function can be used to return a
list of descriptions for a list of operators.

Many of the functions and methods listed below take a list of operators as
parameters. Most operator lists can be made up of several types of
element. Each element can be one of

an operator name (opname)
     Operator names are typically small lowercase words like enterloop,
     leaveloop, last, next, redo etc. Sometimes they are rather cryptic
     like gv2cv, i_ncmp and ftsvtx.

an operator tag name (optag)
     Operator tags can be used to refer to groups (or sets) of operators.
     Tag names always being with a colon. The Opcode module defines several
     optags and the user can define others using the define_optag function.

a negated opname or optag
     An opname or optag can be prefixed with an exclamation mark, e.g.,
     !mkdir.  Negating an opname or optag means remove the corresponding
     ops from the accumulated set of ops at that point.

an operator set (opset)
     An opset as a binary string of approximately 43 bytes which holds a
     set or zero or more operators.

     The opset and opset_to_ops functions can be used to convert from a
     list of operators to an opset and *vice versa*.

     Wherever a list of operators can be given you can use one or more
     opsets.  See also Manipulating Opsets below.

Opcode Functions
================

The Opcode package contains functions for manipulating operator names tags
and sets. All are available for export by the package.

opcodes
     In a scalar context opcodes returns the number of opcodes in this
     version of perl (around 340 for perl5.002).

     In a list context it returns a list of all the operator names.  (Not
     yet implemented, use @names = opset_to_ops(full_opset).)

opset (OP, ...)
     Returns an opset containing the listed operators.

opset_to_ops (OPSET)
     Returns a list of operator names corresponding to those operators in
     the set.

opset_to_hex (OPSET)
     Returns a string representation of an opset. Can be handy for
     debugging.

full_opset
     Returns an opset which includes all operators.

empty_opset
     Returns an opset which contains no operators.

invert_opset (OPSET)
     Returns an opset which is the inverse set of the one supplied.

verify_opset (OPSET, ...)
     Returns true if the supplied opset looks like a valid opset (is the
     right length etc) otherwise it returns false. If an optional second
     parameter is true then verify_opset will croak on an invalid opset
     instead of returning false.

     Most of the other Opcode functions call verify_opset automatically
     and will croak if given an invalid opset.

define_optag (OPTAG, OPSET)
     Define OPTAG as a symbolic name for OPSET. Optag names always start
     with a colon `:'.

     The optag name used must not be defined already (define_optag will
     croak if it is already defined). Optag names are global to the perl
     process and optag definitions cannot be altered or deleted once
     defined.

     It is strongly recommended that applications using Opcode should use a
     leading capital letter on their tag names since lowercase names are
     reserved for use by the Opcode module. If using Opcode within a module
     you should prefix your tags names with the name of your module to
     ensure uniqueness and thus avoid clashes with other modules.

opmask_add (OPSET)
     Adds the supplied opset to the current opmask. Note that there is
     currently no mechanism for unmasking ops once they have been masked.
     This is intentional.

opmask
     Returns an opset corresponding to the current opmask.

opdesc (OP, ...)
     This takes a list of operator names and returns the corresponding list
     of operator descriptions.

opdump (PAT)
     Dumps to STDOUT a two column list of op names and op descriptions.
     If an optional pattern is given then only lines which match the (case
     insensitive) pattern will be output.

     It's designed to be used as a handy command line utility:

          perl -MOpcode=opdump -e opdump
          perl -MOpcode=opdump -e 'opdump Eval'

Manipulating Opsets
===================

Opsets may be manipulated using the perl bit vector operators & (and), |
(or), ^ (xor) and ~ (negate/invert).

However you should never rely on the numerical position of any opcode
within the opset. In other words both sides of a bit vector operator
should be opsets returned from Opcode functions.

Also, since the number of opcodes in your current version of perl might
not be an exact multiple of eight, there may be unused bits in the last
byte of an upset. This should not cause any problems (Opcode functions
ignore those extra bits) but it does mean that using the ~ operator will
typically not produce the same 'physical' opset 'string' as the
invert_opset function.

TO DO (maybe)
=============

     $bool = opset_eq($opset1, $opset2)	true if opsets are logically eqiv

     $yes = opset_can($opset, @ops)	true if $opset has all @ops set

     @diff = opset_diff($opset1, $opset2) => ('foo', '!bar', ...)

Predefined Opcode Tags
======================

:base_core
          null stub scalar pushmark wantarray const defined undef

          rv2sv sassign

          rv2av aassign aelem aelemfast aslice av2arylen

          rv2hv helem hslice each values keys exists delete

          preinc i_preinc predec i_predec postinc i_postinc postdec i_postdec
          int hex oct abs pow multiply i_multiply divide i_divide
          modulo i_modulo add i_add subtract i_subtract

          left_shift right_shift bit_and bit_xor bit_or negate i_negate
          not complement

          lt i_lt gt i_gt le i_le ge i_ge eq i_eq ne i_ne ncmp i_ncmp
          slt sgt sle sge seq sne scmp

          substr vec stringify study pos length index rindex ord chr

          ucfirst lcfirst uc lc quotemeta trans chop schop chomp schomp

          match split

          list lslice splice push pop shift unshift reverse

          cond_expr flip flop andassign orassign and or xor

          warn die lineseq nextstate unstack scope enter leave

          rv2cv anoncode prototype

          entersub leavesub return method -- XXX loops via recursion?

          leaveeval -- needed for Safe to operate, is safe without entereval

:base_mem
     These memory related ops are not included in :base_core because they
     can easily be used to implement a resource attack (e.g., consume all
     available memory).

          concat repeat join range

          anonlist anonhash

     Note that despite the existance of this optag a memory resource attack
     may still be possible using only :base_core ops.

     Disabling these ops is a *very* heavy handed way to attempt to prevent
     a memory resource attack. It's probable that a specific memory limit
     mechanism will be added to perl in the near future.

:base_loop
     These loop ops are not included in :base_core because they can easily
     be used to implement a resource attack (e.g., consume all available
     CPU time).

          grepstart grepwhile
          mapstart mapwhile
          enteriter iter
          enterloop leaveloop
          last next redo
          goto

:base_io
     These ops enable *filehandle* (rather than filename) based input and
     output. These are safe on the assumption that only pre-existing
     filehandles are available for use.  To create new filehandles other
     ops such as open would need to be enabled.

          readline rcatline getc read

          formline enterwrite leavewrite

          print sysread syswrite send recv eof tell seek

          readdir telldir seekdir rewinddir

:base_orig
     These are a hotchpotch of opcodes still waiting to be considered

          gvsv gv gelem

          padsv padav padhv padany

          rv2gv refgen srefgen ref

          bless -- could be used to change ownership of objects (reblessing)

          pushre regcmaybe regcomp subst substcont

          sprintf prtf -- can core dump

          crypt

          tie untie

          dbmopen dbmclose
          sselect select
          pipe_op sockpair

          getppid getpgrp setpgrp getpriority setpriority localtime gmtime

          entertry leavetry -- can be used to 'hide' fatal errors

:base_math
     These ops are not included in :base_core because of the risk of them
     being used to generate floating point exceptions (which would have to
     be caught using a $SIG{FPE} handler).

          atan2 sin cos exp log sqrt

     These ops are not included in :base_core because they have an effect
     beyond the scope of the compartment.

          rand srand

:default
     A handy tag name for a *reasonable* default set of ops.  (The current
     ops allowed are unstable while development continues. It will change.)

          :base_core :base_mem :base_loop :base_io :base_orig

     If safety matters to you (and why else would you be using the Opcode
     module?) then you should not rely on the definition of this, or
     indeed any other, optag!

:filesys_read
          stat lstat readlink

          ftatime ftblk ftchr ftctime ftdir fteexec fteowned fteread
          ftewrite ftfile ftis ftlink ftmtime ftpipe ftrexec ftrowned
          ftrread ftsgid ftsize ftsock ftsuid fttty ftzero ftrwrite ftsvtx

          fttext ftbinary

          fileno

:sys_db
          ghbyname ghbyaddr ghostent shostent ehostent      -- hosts
          gnbyname gnbyaddr gnetent snetent enetent         -- networks
          gpbyname gpbynumber gprotoent sprotoent eprotoent -- protocols
          gsbyname gsbyport gservent sservent eservent      -- services

          gpwnam gpwuid gpwent spwent epwent getlogin       -- users
          ggrnam ggrgid ggrent sgrent egrent                -- groups

:browse
     A handy tag name for a *reasonable* default set of ops beyond the
     :default optag.  Like :default (and indeed all the other optags) its
     current definition is unstable while development continues. It will
     change.

     The :browse tag represents the next step beyond :default. It it a
     superset of the :default ops and adds :filesys_read the :sys_db.  The
     intent being that scripts can access more (possibly sensitive)
     information about your system but not be able to change it.

          :default :filesys_read :sys_db

:filesys_open
          sysopen open close
          umask binmode

          open_dir closedir -- other dir ops are in :base_io

:filesys_write
          link unlink rename symlink truncate

          mkdir rmdir

          utime chmod chown

          fcntl -- not strictly filesys related, but possibly as dangerous?

:subprocess
          backtick system

          fork

          wait waitpid

          glob -- access to Cshell via <`rm *`>

:ownprocess
          exec exit kill

          time tms -- could be used for timing attacks (paranoid?)

:others
     This tag holds groups of assorted specialist opcodes that don't
     warrant having optags defined for them.

     SystemV Interprocess Communications:

          msgctl msgget msgrcv msgsnd

          semctl semget semop

          shmctl shmget shmread shmwrite

:still_to_be_decided
          chdir
          flock ioctl

          socket getpeername ssockopt
          bind connect listen accept shutdown gsockopt getsockname

          sleep alarm -- changes global timer state and signal handling
          sort -- assorted problems including core dumps
          tied -- can be used to access object implementing a tie
          pack unpack -- can be used to create/use memory pointers

          entereval -- can be used to hide code from initial compile
          require dofile

          caller -- get info about calling environment and args

          reset

          dbstate -- perl -d version of nextstate(ment) opcode

:dangerous
     This tag is simply a bucket for opcodes that are unlikely to be used
     via a tag name but need to be tagged for completness and
     documentation.

          syscall dump chroot

SEE ALSO
========

ops(3) - perl pragma interface to Opcode module.

Safe(3) - Opcode and namespace limited execution compartments

AUTHORS
=======

Originally designed and implemented by Malcolm Beattie,
mbeattie@sable.ox.ac.uk as part of Safe version 1.

Split out from Safe module version 1, named opcode tags and other changes
added by Tim Bunce <`Tim.Bunce@ig.co.uk'>.


File: pm.info,  Node: PDL,  Next: PGP,  Prev: Opcode,  Up: Module List

Perl Data Language extension module
***********************************

NAME
====

PDL - Perl Data Language extension module
-----------------------------------------

Version 1.00 alpha

"Why is it that we entertain the belief that for every purpose odd numbers
are the most effectual?" - Pliny the Elder.

*Karl Glazebrook, AAO, 4/10/1996. [kgb@aaoepp.aao.gov.au]*

DESCRIPTION
===========

The perlDL concept is to give standard perl5 the ability to COMPACTLY
store and SPEEDILY manipulate the large N-dimensional data sets which are
the bread and butter of scientific computing. e.g. `$a=$b+$c' can add two
2048x2048 images in only a fraction of a second.

It is hoped to eventually provide tons of useful functionality for
scientific and numeric analysis.

Introduction
------------

The fundamental perl data structures are scalar variables, e.g. `$x',
which can hold numbers or strings, lists or arrays of scalars, e.g. `@x',
and associative arrays/hashes of scalars, e.g. `%x'.

perl v5 introduces to perl data structures and objects. A simple scalar
variable `$x' now be a user-defined data type or full blown object*.

The fundamental idea behind perlDL is to allow $x to hold a whole 1D
spectrum, or a 2D image, a 3D data cube, and so on up to large
N-dimensional data sets. These can be manipulated all at once, e.g.  `$a =
$b + 2' does a vector operation on each value in the spectrum/image/etc.

You may well ask: "Why not just store a spectrum as a simple perl `@x'
style list with each pixel being a list item?"  The two key answers to
this are MEMORY and SPEED.  Because we know our spectrum consists of pure
numbers we can compactly store them in a single block of memory
corresponding to a C style numeric array. This takes up a LOT less memory
than the equivalent perl list. It is then easy to pass this block of
memory to a fast addition routine, or to any other C function which deals
with arrays.  As a result perlDL is very fast -- for example one can
mulitiply a 2048*2048 image in exactly the same time as it would take in C
or FORTRAN (0.1 sec on my SPARC). A further advantage of this is that for
simple operations (e.g. `$x += 2') one can manipulate the whole array
without caring about its dimensionality.

I find when using perlDL it is most useful to think of standard perl `@x'
variables as "lists" of generic "things" and PDL variables like `$x' as
"arrays" which can be contained in lists or hashes. Quite often in my
perlDL scripts I have `@x' contain a list of spectra, or a list of images
(or even a mix!). Or perhaps one could have a hash (e.g.  `%x') of
images... the only limit is memory!

perlDL variables support a range of data types - arrays can be bytes,
short intgers (signed or unsigned), long integers, floats or double
precision floats.

* It actually holds a reference (a smart "pointer") to this but that is
not relevant for ordinary use of perlDL.

Usage
-----

perlDL is loaded into your perl script using these commands:

     use PDL;  # use the standard perlDL modules (Core Examples Io Graphics::PG)
     
     use PDL::Examples; # use only the Examples module (this will load
                        # internally whatever other modules it needs).
     
     % perldl  # Invoke interactive shell from system command line.

The default is to import all the function names from a module. If you only
want certain names imported just say:

     use PDL::Io qw(rfits rgrep) # Get only rfits() and rgrep from PDL::Io

Also see below on "Object-Orientation".

To create a new PDL variable
----------------------------

Here are some ways of creating a PDL variable:

     $a = pdl [1..10];             # 1D array
     $a = pdl (1,2,3,4);           # Ditto
     $b = pdl [[1,2,3],[4,5,6]];   # 2D 3x2 array
     $c = pdl $a;                  # Make a new copy
     
     $d = byte [1..10];            # See "Type conversion"
     $e = zeroes(3,2,4);           # 3x2x4 zero-filled array
     
     $c = rfits $file;             # Read FITS file
     
     @x = ( pdl(42), zeroes(3,2,4), rfits($file) ); # Is a LIST of PDL variables!

The `pdl()' function is used to initialise a PDL variable from a scalar,
list, list reference or another PDL variable.

In addition all PDL functions automatically convert normal perl scalars to
PDL variables on-the-fly.

(also see "Type Conversion" and "Input/Output" sections below)

Arithmetic
----------

     $a = $b + 2; $a++; $a = $b / $c; # Etc.
     
     $c=sqrt($a); $d = log10($b+100); # Etc
     
     $e = $a>42; # Vector condtional (like MATLAB) -
                 # note I think this is much nicer than IDLs WHERE(), e.g.:
     
     $e = 42*($a>42) + $a*($a<=42); # Cap top
     
     $a = $a / ( max($a) - min($a) );
     
     print $a; # $a in string context prints it in a N-dimensional format

(and other perl operators/functions)

Matrix functions
----------------

`'x'' is hijacked as the matrix multiplication operator. e.g.  `$c = $a x
$b';

perlDL is row-major not column major so this is actually `c(i,j) = sum_k
a(k,j) b(i,k)' - but when matrices are printed the results will look
right. Just remember the indices are reversed.  e.g.:

     $a = [                   $b = [
           [ 1  2  3  0]            [1 1]
           [ 1 -1  2  7]            [0 2]
           [ 1  0  0  1]            [0 2]
          ]                         [1 1]
                                   ]

     gives $c = [
                 [ 1 11]
                 [ 8 10]
                 [ 2  2]
                ]

Note: transpose() does what it says and is a convenient way to turn row
vectors into column vectors. It is bound to the unary operator `'~'' for
convenience.

How to write a simple function
------------------------------

     sub dotproduct {
         my ($a,$b) = @_;
         return sum($a*$b) ;
     }
     1;

If put in file dotproduct.pdl would be autoloaded (see below).

Type Conversion
---------------

Default for pdl() is double. Conversions are:

     $a = float($b);
     $c = long($d);   # "long" is 4 byte int
     $d = byte($a);

Also double(), short(), ushort().

These routines also automatically convert perl lists to allow the
convenient shorthand:

     $a = byte [[1..10],[1..10]];  # Create 2D byte array
     $a = float [1..1000];         # Create 1D float array

etc.

Rules for automatic conversion during arithmetic:

     If INT = any of byte/short/ushort/int and X is generic op

     For VECTOR x SCALAR these rules avoid overpromotion of vector types:

     VECTOR INT   X SCALAR INT            Return is same type as VECTOR
     VECTOR INT   X SCALAR float/double   Return float
     VECTOR float X SCALAR float/double   Return float

     For other VECTORxSCALAR and VECTORxVECTOR returns "highest" of
     two data types. i.e. VECTOR double x float returns float etc.

Printing
--------

Automatically expands array in N-dimensional format:

     print $a;
     
     $b = "Answer is = $a ";

Sections
--------

perlDL betrays its perl/C heritage in that arrays are zero-offset.  Thus a
100x100 image has indices `0..99,0..99'.

Further I adopt the convention that the center of the pixel (0,0) IS at
coordinate (0.0,0.0). Thus the above image ranges from `-0.5..99.5,
-0.5..99.5' in real space. All perlDL graphics functions conform to this
defintion and hide away the unit-offsetness of, for example, the PGPLOT
FORTRAN library.

Again following the usual convention coordinate (0,0) is displayed at the
bottom left when displaying an image. It appears at the top right when
using "`print $a'" etc.

     $b  = sec($a,  $x1, $x2, $y1, $y2, $z1, $z2, ... ) # Take subsection
     $newimage = ins($bigimage,$smallimage,$x,$y,$z...) # Insert at x,y,z
     
     $c  = nelem ($a); # Number of pixels
     
     $val = at($object, $x,$y,$z...)    # Pixel value at position
     set($myimage, $x, $y, ... $value)  # Set value in image
     
     $b = xvals($a); # Fill array with X-coord values (also yvals(), zvals(),
                     # axisvals($x,$axis) and rvals() for radial distance
                     # from centre).

(Note: I hope to enable syntax like `$$a{'0..200,3..200'}' using `tie()'
but I am still thinking about the ramifications of this)

Input/Output
------------

The PDL::Io module currently implements the following useful I/O functions:

     $a  = rfits($file)  # Read a FITS file into a PDL variable
                         # (only IEEE float machines as yet)

     wfits ($a, $file)  # Write FITS file
     
     ([$xaxis],$data) = rdsa($file)   # Read a STARLINK/FIGARO file using
                                      # perl DSA module (available seperately)
     
     Read ASCII columns into $x, $y, etc.:

     ($x,$y,...) = rcols($file,[[$pattern],[$col1, $col2,] ...)

Read $1, $2, etc. pattern matches into $x, $y, etc.

     ($x,$y,...) = rgrep($file, $pattern)
     
     e.g.:
     
     ($x,$y) = rcols $file, '/Mumble/', 2,3;
     ($a,$b) = rgrep $file, '/Foo (.*) Bar (.*) Mumble/';

Graphics
--------

The philosophy behind perlDL is to make it work with a variety of existing
graphics libraries since no single package will satisfy all needs and all
people and this allows one to work with packages one already knows and
likes.  Obviously there will be some overlaps in functionality and some
lack of consistency and uniformity. This also saves the author from too
much work in time he doesn't have!

  1. PGPLOT

     PGPLOT provdes a simple library for line graphics and image display.

     There is an easy interface to this in the interna;l module
     PDL::Graphics::PG. (This calls routines in the separately available
     PGPLOT top-level module.)

     Current display commands:

          imag         -  Display an image (uses pgimag()/pggray() as appropriate)
          ctab         -  Load an image colour table
          line         -  Plot vector as connected points
          points       -  Plot vector as points
          errb         -  Plot error bars
          cont         -  Display image as contour map
          bin          -  Plot vector as histogram ( e.g. bin(hist($data)) )
          hi2d         -  Plot image as 2d histogram (not very good IMHO...)
          poly         -  Draw a polygon
          vect         -  Display 2 images as a vector field

     Device manipulation commands:

          hold         -  Hold current plot window range - allows overlays etc.
          release      -  Release back to autoscaling of new plot window for each command
          rel          -  short alias for 'release'
          env          -  Define a plot window, put on 'hold'
          dev          -  Explicitly set a new PGPLOT graphics device
          
          e.g:

          perldl> $a = pdl [1..100]
          perldl> $b = sqrt($a)
          perldl> line $b
          perldl> hold
          Graphics on HOLD
          perldl> $c = sin($a/10)*2 + 4
          perldl> line $c

     Notes: $transform for image/cont etc. is used in the same way as the
     TR() array in the underlying PGPLOT FORTRAN routine but is,
     fortunately, zero-offset.

     It is also hoped to use other graphic libraries to enable more
     sophisticated plots then is possible with PGPLOT. Some ideas:

  2. IIS

     Many astronomers like to use SAOimage and Ximtool (or there
     derivations/clones). These are useful free widgets for inspection and
     visualisation of images. (They are not provided with perlDL but can
     easily be obtained from their official sites off the Net.)

     The PDL::Graphics::IIS package provides allows one to display images
     in these ("IIS" is the name of an ancient item of image display
     hardware whose protocols these tools conform to.)

     Commands are:

          iis         - display image
          iiscur      - return a cursor position
          iiscirc     - draw circles on image display
          saoimage    - start SAOimage
          ximtool     - start Ximtool

     Variables are:

          $stdimage  - frame buffer configuration
          $iisframe  - frame buffer number to display in

     The frame buffer configuration is set by the variable $stdimage
     (analagous to iraf) whose default is "imt1024". System and user
     imtoolrc files are parsed so if you know about these you can do the
     same tricks as you can in with IRAF.

  3. Karma

     To come?


Autoloading
-----------

If a PDL function, e.g. `foo()', is currently undefined a file "foo.pdl"
is searched for in the current directory, and any directories in $PDLLIB,
$PERL5LIB and $PERLLIB enviroment variables.  (These are ":" seperated
lists of directories.)

If you want to change the path within perldl simply change the lists
@PDLLIB and @INC.

Note: "foo.pdl" is require'd so it must return a true value (see "require"
perl documentation).

Call External
-------------

This provides a simple way to pass the data arrays from pdl variables to
external C routines. It uses perl's built-in dynamic loader to load
compiled C code.

The syntax is:

     callext($file,$symbol, @pdl_list)

@pdl_list is a list of pdl variables. Numbers get converted automatically.
The file must be dynamically loadable object code - how the C compiler
generates this will be different from system to system so see your man
pages.

The C routine takes args `(int nargs, pdl *args)'. The C type `"pdl"' is a
simple data structure representing the perl pdl variable. It is defined in
file "pdl.h" which is included in the perlDL distribution and has no perl
dependencies.  It is trivial to cast the data array (pdl.data) to (float),
(double) etc. and pass to any other C routine.

This is all demonstrated in the files "testcallext.*" in the perlDL
distribution.

Note: This is only intended as a quick and dirty prototyping interface for
the scientist/hacker. perlDL developers should write a module along the
lines of the example PDL::Examples.

perldl shell
------------

The perl script `perldl' provides a simple command line - if the latest
Readlines/ReadKey modules have beeen installed `perldl' detects this and
enables command line recall and editing.

e.g.:

     % perldl
     ReadLines enabled
     perldl> $a = rfits "foo.fits"
     BITPIX =  -32  size = 88504 pixels
     Reading  354016 bytes
     BSCALE =  &&  BZERO =
     
     perldl> imag log($a+400)
     Displaying 299 x 296 image from 4.6939525604248 to 9.67116928100586 ...

You can also run it from the perl debugger (`perl -MPDL -d -e 1') if you
want.

Miscellaneous shell features:

  1. The command `perldl -oo' starts perldl in Object-Oriented mode. It
     does `use PDL::OO' instead of `use PDL'.

  2. The shell aliases p to be a convenient short form of print, e.g.

          perldl> p ones 5,3
          
          [
           [1 1 1 1 1]
           [1 1 1 1 1]
           [1 1 1 1 1]
          ]

  3. The files `~/.perldlrc' and `local.perldlrc' (in the current
     directory) are sourced if found. This allows the user to have global
     and local PDL code for startup.

  4. Any line starting with the `#' character is treated as a shell
     escape. This character is configurable by setting the perl variable
     $PERLDL_ESCAPE. This could, for example, be set in `~/.perldlrc'.


Overload operators
------------------

I have overloaded the following builtin perl operators and functions in
order that they work on PDL variables:

     + - * / > < >= <= << >> & | ^ == != <=> ** % ! ~
     sin log abs atan2 sqrt cos exp

[All the unary functions (sin etc.) may be used with inplace() - see
"Memory" below.]

Object-Orientation and perlDL
-----------------------------

[Astronomers can ignore this bit! :-)]

pdl variables such as $x are implemented via Perl objects. However I have
chosen to use an all-functional approach to perlDL syntax yo be  more
astronomer friendly.

However you can use perlDL in an OO fashion. In fact if you say:

     use PDL::OO;

It will load PDL functions as OO methods in the PDL class. This means you
can say things like:

     $a = PDL->rfits('m51.fits');
     $b = PDL->new([1,2,2,1],[1,2,2,1],[1,2,2,1],[1,2,2,1]);
     $smooth = $a->convolve($b);
     $smooth->iis;

You can start the perldl shell in this mode with "perldl -oo".

Note: as you can see from the above all functions which create pdl
variables are used with construct syntax in the OO mode. Finally you can
even use both forms by simply saying "use PDL; use PDL::OO".

You can inherit from PDL methods (e.g. to a class Foo) by simply saying:

     @Foo::ISA = ('PDL');               # Method path
     %Foo::OVERLOAD = %PDL::OVERLOAD;   # Copy overload

Then PDL methods will work on Foo objects as long as you simply build on
the existing PDL data structure (see below) components.

So it would be possible to provide USER written modules to do really cool
stuff for specific application areas, e.g. PDL::Spectrum might provide a
$a which understands X-axes and error bars and +-/+ etc.  might be
overriden to do the Right Thing (tm). And writing the module would not be
rocket science - just some cool perl hacking.

And you would not have to even use method syntax - if $a came out of my
hypothetical PDL::Spectrum all the standard pdl functions (like hist() to
give a concreate example) would work on it in the standard way provided
they simply built on the existing PDL data structure (which means simply
containing a $$a{Data} etc. PDL::Spectrum could even export it's own
hist() function to override the built-in which might do something more
sophisticated using the X-axis for example.

If you were feeling really ambitious you might do PDL::Ir::Spectrum which
understood about the gaps between the J H and K bands!

Memory usage and references
---------------------------

Messing around with really huge data arrays may require some care.  perlDL
provides some facilities to let you perform operations on big arrays
without generating extra copies though this does require a bit more
thought are care from the programmer.

NOTE: On some most systems it is better to configure perl (during the
build options) to use the system malloc() function rather than perl's
built-in one. This is because perl's one is optimised for speed rather
than consumption of virtual memory - this can result in a factor of two
improvement in the amount of memory storage you can use.

  1. Simple arithmetic

     If $a is a big image (e.g. occupying 10MB) and I say:

          $a = $a + 1;

     then the total malloc()'d memory usage grows to 20MB. This is because
     the expression "$a+1" creates a temporary copy of $a to hold the
     result, then $a is assigned a reference to that. It is obviously done
     this way so "$c=$a+1" works as expected.

     Also if one says:

          $b = $a;     # $b and $a now point to same data
          $a = $a + 1;

     Then $b and $a end up being different, as one naively expects,
     because a new reference is created and $a is assigned to it.

     However if $a was a huge memory hog (e.g. a 3D volume) creating a copy
     of it may not be a good thing. One can avoid this memory overhead in
     the above example by saying:

          $a++;

     The operations `++,+=,--,-=', etc. all call a special "in-place"
     version of the arithmetic subroutine. This means no more memory is
     needed - the downside of this is that if $b=$a then $b is also
     incremented. To force a copy explicitly:

          $b = pdl $a; # Real copy

  2. Functions

     Most functions, e.g. log(), return a result which is a transformation
     of their argument. This makes for good programming practice. However
     many operations can be done "in-place" and this may be required when
     large arrays are in use and memory is at a premium. For these
     circumstances the operator inplace() is provided which prevents the
     extra copy and allows the argument to be modified. e.g.:

          $x = log($array);          # $array unaffected
          log( inplace($bigarray) ); # $bigarray changed in situ

     WARNINGS:

  1. The usual caveats about duplicate references apply.

  2. Obviously when used with some functions which can not be applied in
     situ (e.g. convolve()) unexpected effects may occur! I try to
     indicate inplace() safe functions below.

  3. Type conversions [e.g. float()] may cause hidden copying.

Data Structure Guts
-------------------

(For born fiddlers only.)

The data structure for $a is implemented by a hash (associative array)
which $a is a (blessed) reference too.

PDL reserves for it's own use:

     $$a{Data} ; # The DATA (byte list) - can be passed directly to F77/C
                 # subroutine as long as type matches. e.g. line() does a
                 # float() and then calls PGPLOT::pgline_r (bypassing packing)
     
     $$a{Datatype}; # Holds numeric data type, $PDL_F, $PDL_D, etc...
     
     $$a{Dims} ; # List reference holding dimensions.
                 # E.g. @mydims = @{ $$a{Dims} };
     
     $$a{Hdr}  ; # Optional extra hash reference holding header, e.g.
                 # $airmass = $$a{Hdr}{'AIRMASS'}; %myhdr = %{ $$a{Hdr} };
                 # rfits() populates this from the FITS header.
     
     $$a{Inplace}; # Flag - inplace() sets this. Next time a copy is attempted
                   # it does not occur and the flag is unset.

Anything else stored in the structure will be copied to new objects (e.g.
by $b = $a + 1) automatically as long as PDL knows how to copy it.  [If it
is a reference to another object PDL tries the ->copy method.]

If your perl routine manipulates the data structure guts directly, you
don't want it to blow up in your face if you pass it a simple number
rather than a PDL variable. Simply call the function topdl() first to make
it safe. e.g.:

     sub myfiddle { my $pdl = topdl(shift); $$pdl{Data} = ... }

topdl() does NOT perform a copy if a pdl variable is passed - it just
falls through - which is obviosuly the desired behaviour. The routine is
not of course necessary in normal user defined functions which do not care
about internals.

Finally there is no reason why the data structure should not contain
another PDL variable!

Complete List of Exported Functions
-----------------------------------

Defined in PDL::Core

     byte short ushort long float double convert   - Type Conversions
     
     pdl          - Create/copy a pdl
     topdl        - Coerce to pdl if scalar
     howbig       - Size of pdl datatype in bytes
     nelem        - Number of elements
     dims         - Return list of dimensions, e.g. @mydims = dims($x);
     list         - Convert pdl to list - e.g. for (list $x) {..}
     listindices  - Return list of index values (1D) - e.g. for $i
                    (listindices $x) {..}
     log10*       - Take log base 10
     min max sum  - Min/max/sum of pdl array
     zeroes/ones  - Create zero/one-filled pdl array
     sequence     - Create sequence-filled pdl array
     reshape      - reshape the dimensions of a pdl array
     sec          - subsection
     ins* / set   - insertion / setting
     at           - return pixel value at (x,y,z...)
     
     axisvals* xvals* yvals* zvals* - Fill pdl with axis values
     
     rvals        - Fill pdl with distance from it's center
     callext      - Call external C routine in dynamically loadable object
     convolve     - convolve image with kernel (real space)
     inplace      - Flag for inplace operation
     hist         - histogram of data
     stats        - return mean + standard deviation
     transpose    - matrix transpose

Defined in PDL::Examples

This contains examples of how to add C functiions via XS including use of
the generic preprocessor (.g files are automatically converted to .c files
with code automatically generated for each datatype).

     fibonacci*    - Compute Fibonacci series (simple 1D example)
     cc8compt*     - Connected 8-component labelling (2D example)

Defined in PDL::Io

[See "Io" section above]

Defined in PDL::Graphics::*

[See "Graphics" section above]

Footnotes:

* = indicates `inplace()' safe & useful with this function


File: pm.info,  Node: PGP,  Next: POSIX,  Prev: PDL,  Up: Module List

perl module to work with PGP messages
*************************************

NAME
====

PGP - perl module to work with PGP messages

SYNOPSIS
========

use PGP;

$message = new PGP $pgppath;

DESCRIPTION
===========

The PGP module allow a perl script to work with PGP related files.

   * PGP::new
          $pgp = new PGP [$pgppath], [$pgpexec];

     Create the PGP encapsulation object. The standard location for the
     PGP executable is /usr/local/bin/pgp.

   * PGP::Exec
          $pid = Exec $pgp $args, $in, $out, $err;

     Execute the PGP command and attach the `$in', `$out', `$err' file
     handles.  This should be fine for the moment, but need to look into
     making sure that data is not written to a temporary file anywhere.

     The $args variable can have several substituted strings:

          %p	PGP path variable
          %r	Path to PGP keyring
          %k	Specified user

     The file handle variables-`$in', `$out' and `$err'-are send as normal
     filehandle names, but they reside in the PGP package. For example,
     the following procedure call is made:

          PGP->Exec ($args, FIN, FOUT, FERR);

     Even though the file handles were specified as `FIN', `FOUT' and
     `FERR'; they must be referred to as `PGP::FIN', `PGP::FOUT' and
     `PGP::FERR' in the orignal procedure that made the call.

   * PGP::Sign
          $signed_document = Sign $pgp %args;

     The `Sign' procedure will take a file or data and sign with a PGP
     secret key. The default behavior is to sign the data with the last
     secret key added to the keyring, but that can be overridden with the
     *Key* argument. This method always returns the signed document.

     The `%args' consist of a series of keys and values. Since there are
     several variations in the way data can be signed, not all the
     following options must be specified. This approach also makes it much
     easier to scale to new versions of PGP with more options.

          Armor		The output should be ASCII armored
          Clear		Produce a "clear" signature
          Encrypt		Encrypt the resulting signed document with
          		the given keyobj
          Detach		Create a detached signature
          File		Sign the specified file
          Key		Sign with the specified key object
          Nosave		Do not allow user to save message
          Password	The password to use for signing
          Signfile	The filename of the signed document
          Text		Data to be signed.
          Wipe		Remove the orignal file

     The only absolute argument that is always required is the `Password'.

     Examples

          Sign $pgp Password => 'xyz', File => '/etc/motd', Clear => 1, Armor => 1;

     This would return a signed copy of the `/etc/motd' file. In this
     case, we use a file as the input, but the output is returned at the
     method's termination. The orignal file remains in the clear, and the
     signature is ASCII armored (Base64).

          Sign $pgp Password => 'abc', Text => 'Important info', Armor => 1,
                    Signfile => 'signed.asc', Key => $keyobj;

     This is sort of the reverse of the first example. It takes what is in
     the `Text' field and signs it. It then puts the result in the file
     `signed.asc' and returns it to the caller. In this case, the entire
     message is ASCII armored including the orignal text (i.e. `Text').
     We also specify another secret key to produce the signature. For more
     information on the the key objects, please see `"PGP::Key"' in this
     node section.

   * PGP::Encrypt
          $encrypted_document = Encrypt $pgp %args;

     The `Encrypt' method produces an encrypted document with the given
     public keys specified by `Key'. The `Encrypt' method follow the same
     conventions as the `Sign' method. The data to be encrypted can be
     sent to the method or can reside in a file. The resulting encrypted
     data can also reside in a file or be sent back to the caller.

     In addition to encrypting a document, the document can also be signed
     by using the `Sign' key in the `%args' array. If the document is to
     be signed by the default secret key (last key added to the secret
     keyring), then `Sign' can be left undefined or contain something
     other than a reference to a key object. Otherwise the `Sign' key
     should contain a reference to a specific key object (see `"PGP::Key"'
     in this node).

          Armor		The output should be ASCII armored
          Encryptfile	The filename of the encrypted document
          File		Encrypt the specified file
          Key		Encrypt with the specified key object
          Nosave		Do not allow user to save message
          Password	The password to use for signing
          Sign		In addition to encrypting, sign the document
          Text		Data to be encrypted
          Wipe		Remove orignal file

   * PGP::Document_Info
          \%doc = Document_Info $pgp %args;

     `Document_Info' returns an associative array or a reference to an
     associative array to the caller. This returned structure contains
     information about the document that is sent to the `Document_Info'
     method. The returned structure is fairly straight forward:

          Text		The decrypted document
          Signature	PGP::Key object of the signer (if any)
          Time		Time document was signed (if any)
          Key		PGP::Key object used to decrypt document

     The `Document_Info' method currently accepts the following arguments:

          File		File to decrypt
          Text		Document to decrypt
          
          At this point, we cheat with the C<Document_Info> method. Basically
          we send the document through the C<Decrypt> method and grab the
          results.

PGP::Keyring
------------

The PGP::Keyring object is used to perform key management functions.

   * PGP::Keyring::new
          $Keyring = new PGP::Keyring $pgpkeyring;

   * PGP::Keyring::Add_Key
          $signature = Add_Key $Keyring $signature;

     Add a signature to the keyring. At this point, there is no error
     checking or verification that the key has been added.

   * PGP::Remove_Key
          Remove_Key $Keyring $key;

     Remove a signature from a keyring.

   * PGP::Extract_Key
          $key = Extract_Key $Keyring $keyobj;

     Extract a key from the specified keyring. A real simple dirty way of
     extracting the key.

   * PGP::Generate_Key
          Generate_Key $Keyring;

     Generate a new secret and public key set. This routine will not be
     present in the first rev of code. It is also subject to change.

   * PGP::Revoke_Key
          $certificate = Revoke_Key $Keyring $Keyobj;

     Produce a revocation certificate for the given key. Revocation is
     actually a two step process. We must first mark the key as revoked.
     This is the same as the `Remove_Key' method. After flaging the key,
     the key must be extracted to produce a revocation certificate.

   * PGP::Keyring::Find
          @keys = Find $keyring %criteria;
          \@keys = Find $keyring %criteria;
          $key = Find $keyring %criteria; (Single match)

     Function to locate a single key.

PGP::Key
--------

The PGP::Key object is used to store the individual key information. It is
primarily used by the PGP::Keyring object and for passing to the various
methods that accept key parameters to encrypt and sign documents.

Future revisions will provide actual methods to do key comparison for the
trust and validity factors. These methods will provide a standardized way
to determine which keys can be trusted and which keys should not be used
at all.

   * PGP::Key::new
          $key = new PGP::Key $keyline;

     This is the constructor for the PGP::Key object. This is primarily
     used by the PGP::Keyring methods. The PGP::Keyring methods keep track
     of the keys and maintain the Trust and Validity components.  About
     the only useful method is the `PGP::Key::Fingerprint', which will
     return a string that is the finger print of the given key.

   * + PGP::Key::Add_ID
          Add_ID $key $desc;

     The `Add_ID' method will add identification information to the owner
     and email portions of the given PGP::Key object. This is to support
     keys that multiple identification packets associated with them.

   * PGP::Key::Trust

     This will set and/or retrieve the trust factor. Currently, this
     routine will just store what is sent to it. Need to define some
     "trust" variables and provide useful routines to use them.

   * PGP::Key::Validity

     This function will set and/or return the validity factor. This
     subroutine is very much like PGP::Key::Trust. It also needs to be
     worked on quite a bit.

   * PGP::Key::Fingerprint
          $fingerprint = Fingerprint $key;

Known Bugs and Limitations
--------------------------

+ Hopefully none, proabably many!
Author
------

     Gerard Hickey
     RR 2  Box 409
     Lower Main St.
     North Berwick, ME   03906
     hickey@ctron.com

Copyrights
----------

     Copyleft (l) 1996, by Gerard Hickey

What this means is that this program may be copied freely given that there
is no payment in exchange for this program, and that all the source is
left intact with all comments and documentation. If you wish to modify
this program to correct bugs or to extend it's usefullness, please
coordinate such actions with the author.


File: pm.info,  Node: POSIX,  Next: Parext,  Prev: PGP,  Up: Module List

Perl interface to IEEE Std 1003.1
*********************************

NAME
====

POSIX - Perl interface to IEEE Std 1003.1

SYNOPSIS
========

     use POSIX;
     use POSIX qw(setsid);
     use POSIX qw(:errno_h :fcntl_h);

     printf "EINTR is %d\n", EINTR;

     $sess_id = POSIX::setsid();

     $fd = POSIX::open($path, O_CREAT|O_EXCL|O_WRONLY, 0644);
     	# note: that's a filedescriptor, *NOT* a filehandle

DESCRIPTION
===========

The POSIX module permits you to access all (or nearly all) the standard
POSIX 1003.1 identifiers.  Many of these identifiers have been given
Perl-ish interfaces.  Things which are `#defines' in C, like EINTR or
O_NDELAY, are automatically exported into your namespace.  All functions
are only exported if you ask for them explicitly.  Most likely people will
prefer to use the fully-qualified function names.

This document gives a condensed list of the features available in the POSIX
module.  Consult your operating system's manpages for general information
on most features.  Consult *Note Perlfunc: (perl.info)perlfunc, for
functions which are noted as being identical to Perl's builtin functions.

The first section describes POSIX functions from the 1003.1 specification.
The second section describes some classes for signal objects, TTY objects,
and other miscellaneous objects.  The remaining sections list various
constants and macros in an organization which roughly follows IEEE Std
1003.1b-1993.

NOTE
====

The POSIX module is probably the most complex Perl module supplied with
the standard distribution.  It incorporates autoloading, namespace games,
and dynamic loading of code that's in Perl, C, or both.  It's a great
source of wisdom.

CAVEATS
=======

A few functions are not implemented because they are C specific.  If you
attempt to call these, they will print a message telling you that they
aren't implemented, and suggest using the Perl equivalent should one
exist.  For example, trying to access the setjmp() call will elicit the
message "setjmp() is C-specific: use eval {} instead".

Furthermore, some evil vendors will claim 1003.1 compliance, but in fact
are not so: they will not pass the PCTS (POSIX Compliance Test Suites).
For example, one vendor may not define EDEADLK, or the semantics of the
errno values set by open(2) might not be quite right.  Perl does not
attempt to verify POSIX compliance.  That means you can currently
successfully say "use POSIX",  and then later in your program you find
that your vendor has been lax and there's no usable ICANON macro after
all.  This could be construed to be a bug.

FUNCTIONS
=========

_exit
     This is identical to the C function `_exit()'.

abort
     This is identical to the C function `abort()'.

abs
     This is identical to Perl's builtin `abs()' function.

access
     Determines the accessibility of a file.

          if( POSIX::access( "/", &POSIX::R_OK ) ){
          	print "have read permission\n";
          }

     Returns undef on failure.

acos
     This is identical to the C function `acos()'.

alarm
     This is identical to Perl's builtin `alarm()' function.

asctime
     This is identical to the C function `asctime()'.

asin
     This is identical to the C function `asin()'.

assert
     Unimplemented.

atan
     This is identical to the C function `atan()'.

atan2
     This is identical to Perl's builtin `atan2()' function.

atexit
     atexit() is C-specific: use END {} instead.

atof
     atof() is C-specific.

atoi
     atoi() is C-specific.

atol
     atol() is C-specific.

bsearch
     bsearch() not supplied.

calloc
     calloc() is C-specific.

ceil
     This is identical to the C function `ceil()'.

chdir
     This is identical to Perl's builtin `chdir()' function.

chmod
     This is identical to Perl's builtin `chmod()' function.

chown
     This is identical to Perl's builtin `chown()' function.

clearerr
     Use method `FileHandle::clearerr()' instead.

clock
     This is identical to the C function `clock()'.

close
     Close the file.  This uses file descriptors such as those obtained by
     calling `POSIX::open'.

          $fd = POSIX::open( "foo", &POSIX::O_RDONLY );
          POSIX::close( $fd );

     Returns undef on failure.

closedir
     This is identical to Perl's builtin `closedir()' function.

cos
     This is identical to Perl's builtin `cos()' function.

cosh
     This is identical to the C function `cosh()'.

creat
     Create a new file.  This returns a file descriptor like the ones
     returned by `POSIX::open'.  Use `POSIX::close' to close the file.

          $fd = POSIX::creat( "foo", 0611 );
          POSIX::close( $fd );

ctermid
     Generates the path name for the controlling terminal.

          $path = POSIX::ctermid();

ctime
     This is identical to the C function `ctime()'.

cuserid
     Get the character login name of the user.

          $name = POSIX::cuserid();

difftime
     This is identical to the C function `difftime()'.

div
     div() is C-specific.

dup
     This is similar to the C function `dup()'.

     This uses file descriptors such as those obtained by calling
     `POSIX::open'.

     Returns undef on failure.

dup2
     This is similar to the C function `dup2()'.

     This uses file descriptors such as those obtained by calling
     `POSIX::open'.

     Returns undef on failure.

errno
     Returns the value of errno.

          $errno = POSIX::errno();

execl
     execl() is C-specific.

execle
     execle() is C-specific.

execlp
     execlp() is C-specific.

execv
     execv() is C-specific.

execve
     execve() is C-specific.

execvp
     execvp() is C-specific.

exit
     This is identical to Perl's builtin `exit()' function.

exp
     This is identical to Perl's builtin `exp()' function.

fabs
     This is identical to Perl's builtin `abs()' function.

fclose
     Use method `FileHandle::close()' instead.

fcntl
     This is identical to Perl's builtin `fcntl()' function.

fdopen
     Use method `FileHandle::new_from_fd()' instead.

feof
     Use method `FileHandle::eof()' instead.

ferror
     Use method `FileHandle::error()' instead.

fflush
     Use method `FileHandle::flush()' instead.

fgetc
     Use method `FileHandle::getc()' instead.

fgetpos
     Use method `FileHandle::getpos()' instead.

fgets
     Use method `FileHandle::gets()' instead.

fileno
     Use method `FileHandle::fileno()' instead.

floor
     This is identical to the C function `floor()'.

fmod
     This is identical to the C function `fmod()'.

fopen
     Use method `FileHandle::open()' instead.

fork
     This is identical to Perl's builtin `fork()' function.

fpathconf
     Retrieves the value of a configurable limit on a file or directory.
     This uses file descriptors such as those obtained by calling
     `POSIX::open'.

     The following will determine the maximum length of the longest
     allowable pathname on the filesystem which holds `/tmp/foo'.

          $fd = POSIX::open( "/tmp/foo", &POSIX::O_RDONLY );
          $path_max = POSIX::fpathconf( $fd, &POSIX::_PC_PATH_MAX );

     Returns undef on failure.

fprintf
     fprintf() is C-specific-use printf instead.

fputc
     fputc() is C-specific-use print instead.

fputs
     fputs() is C-specific-use print instead.

fread
     fread() is C-specific-use read instead.

free
     free() is C-specific.

freopen
     freopen() is C-specific-use open instead.

frexp
     Return the mantissa and exponent of a floating-point number.

          ($mantissa, $exponent) = POSIX::frexp( 3.14 );

fscanf
     fscanf() is C-specific-use <> and regular expressions instead.

fseek
     Use method `FileHandle::seek()' instead.

fsetpos
     Use method `FileHandle::setpos()' instead.

fstat
     Get file status.  This uses file descriptors such as those obtained by
     calling `POSIX::open'.  The data returned is identical to the data
     from Perl's builtin stat function.

          $fd = POSIX::open( "foo", &POSIX::O_RDONLY );
          @stats = POSIX::fstat( $fd );

ftell
     Use method `FileHandle::tell()' instead.

fwrite
     fwrite() is C-specific-use print instead.

getc
     This is identical to Perl's builtin `getc()' function.

getchar
     Returns one character from STDIN.

getcwd
     Returns the name of the current working directory.

getegid
     Returns the effective group id.

getenv
     Returns the value of the specified enironment variable.

geteuid
     Returns the effective user id.

getgid
     Returns the user's real group id.

getgrgid
     This is identical to Perl's builtin `getgrgid()' function.

getgrnam
     This is identical to Perl's builtin `getgrnam()' function.

getgroups
     Returns the ids of the user's supplementary groups.

getlogin
     This is identical to Perl's builtin `getlogin()' function.

getpgrp
     This is identical to Perl's builtin `getpgrp()' function.

getpid
     Returns the process's id.

getppid
     This is identical to Perl's builtin `getppid()' function.

getpwnam
     This is identical to Perl's builtin `getpwnam()' function.

getpwuid
     This is identical to Perl's builtin `getpwuid()' function.

gets
     Returns one line from STDIN.

getuid
     Returns the user's id.

gmtime
     This is identical to Perl's builtin `gmtime()' function.

isalnum
     This is identical to the C function, except that it can apply to a
     single character or to a whole string.

isalpha
     This is identical to the C function, except that it can apply to a
     single character or to a whole string.

isatty
     Returns a boolean indicating whether the specified filehandle is
     connected to a tty.

iscntrl
     This is identical to the C function, except that it can apply to a
     single character or to a whole string.

isdigit
     This is identical to the C function, except that it can apply to a
     single character or to a whole string.

isgraph
     This is identical to the C function, except that it can apply to a
     single character or to a whole string.

islower
     This is identical to the C function, except that it can apply to a
     single character or to a whole string.

isprint
     This is identical to the C function, except that it can apply to a
     single character or to a whole string.

ispunct
     This is identical to the C function, except that it can apply to a
     single character or to a whole string.

isspace
     This is identical to the C function, except that it can apply to a
     single character or to a whole string.

isupper
     This is identical to the C function, except that it can apply to a
     single character or to a whole string.

isxdigit
     This is identical to the C function, except that it can apply to a
     single character or to a whole string.

kill
     This is identical to Perl's builtin `kill()' function.

labs
     labs() is C-specific, use abs instead.

ldexp
     This is identical to the C function `ldexp()'.

ldiv
     ldiv() is C-specific, use / and int instead.

link
     This is identical to Perl's builtin `link()' function.

localeconv
     Get numeric formatting information.  Returns a reference to a hash
     containing the current locale formatting values.

     The database for the *de* (Deutsch or German) locale.

          $loc = POSIX::setlocale( &POSIX::LC_ALL, "de" );
          print "Locale = $loc\n";
          $lconv = POSIX::localeconv();
          print "decimal_point	= ", $lconv->{decimal_point},	"\n";
          print "thousands_sep	= ", $lconv->{thousands_sep},	"\n";
          print "grouping	= ", $lconv->{grouping},	"\n";
          print "int_curr_symbol	= ", $lconv->{int_curr_symbol},	"\n";
          print "currency_symbol	= ", $lconv->{currency_symbol},	"\n";
          print "mon_decimal_point = ", $lconv->{mon_decimal_point}, "\n";
          print "mon_thousands_sep = ", $lconv->{mon_thousands_sep}, "\n";
          print "mon_grouping	= ", $lconv->{mon_grouping},	"\n";
          print "positive_sign	= ", $lconv->{positive_sign},	"\n";
          print "negative_sign	= ", $lconv->{negative_sign},	"\n";
          print "int_frac_digits	= ", $lconv->{int_frac_digits},	"\n";
          print "frac_digits	= ", $lconv->{frac_digits},	"\n";
          print "p_cs_precedes	= ", $lconv->{p_cs_precedes},	"\n";
          print "p_sep_by_space	= ", $lconv->{p_sep_by_space},	"\n";
          print "n_cs_precedes	= ", $lconv->{n_cs_precedes},	"\n";
          print "n_sep_by_space	= ", $lconv->{n_sep_by_space},	"\n";
          print "p_sign_posn	= ", $lconv->{p_sign_posn},	"\n";
          print "n_sign_posn	= ", $lconv->{n_sign_posn},	"\n";

localtime
     This is identical to Perl's builtin `localtime()' function.

log
     This is identical to Perl's builtin `log()' function.

log10
     This is identical to the C function `log10()'.

longjmp
     longjmp() is C-specific: use die instead.

lseek
     Move the read/write file pointer.  This uses file descriptors such as
     those obtained by calling `POSIX::open'.

          $fd = POSIX::open( "foo", &POSIX::O_RDONLY );
          $off_t = POSIX::lseek( $fd, 0, &POSIX::SEEK_SET );

     Returns undef on failure.

malloc
     malloc() is C-specific.

mblen
     This is identical to the C function `mblen()'.

mbstowcs
     This is identical to the C function `mbstowcs()'.

mbtowc
     This is identical to the C function `mbtowc()'.

memchr
     memchr() is C-specific, use index() instead.

memcmp
     memcmp() is C-specific, use eq instead.

memcpy
     memcpy() is C-specific, use = instead.

memmove
     memmove() is C-specific, use = instead.

memset
     memset() is C-specific, use x instead.

mkdir
     This is identical to Perl's builtin `mkdir()' function.

mkfifo
     This is similar to the C function `mkfifo()'.

     Returns undef on failure.

mktime
     Convert date/time info to a calendar time.

     Synopsis:

          mktime(sec, min, hour, mday, mon, year, wday = 0, yday = 0, isdst = 0)

     The month (`mon'), weekday (`wday'), and yearday (`yday') begin at
     zero.  I.e. January is 0, not 1; Sunday is 0, not 1; January 1st is
     0, not 1.  The year (`year') is given in years since 1900.  I.e. The
     year 1995 is 95; the year 2001 is 101.  Consult your system's
     `mktime()' manpage for details about these and the other arguments.

     Calendar time for December 12, 1995, at 10:30 am.

          $time_t = POSIX::mktime( 0, 30, 10, 12, 11, 95 );
          print "Date = ", POSIX::ctime($time_t);

     Returns undef on failure.

modf
     Return the integral and fractional parts of a floating-point number.

          ($fractional, $integral) = POSIX::modf( 3.14 );

nice
     This is similar to the C function `nice()'.

     Returns undef on failure.

offsetof
     offsetof() is C-specific.

open
     Open a file for reading for writing.  This returns file descriptors,
     not Perl filehandles.  Use `POSIX::close' to close the file.

     Open a file read-only with mode 0666.

          $fd = POSIX::open( "foo" );

     Open a file for read and write.

          $fd = POSIX::open( "foo", &POSIX::O_RDWR );

     Open a file for write, with truncation.

          $fd = POSIX::open( "foo", &POSIX::O_WRONLY | &POSIX::O_TRUNC );

     Create a new file with mode 0640.  Set up the file for writing.

          $fd = POSIX::open( "foo", &POSIX::O_CREAT | &POSIX::O_WRONLY, 0640 );

     Returns undef on failure.

opendir
     Open a directory for reading.

          $dir = POSIX::opendir( "/tmp" );
          @files = POSIX::readdir( $dir );
          POSIX::closedir( $dir );

     Returns undef on failure.

pathconf
     Retrieves the value of a configurable limit on a file or directory.

     The following will determine the maximum length of the longest
     allowable pathname on the filesystem which holds `/tmp'.

          $path_max = POSIX::pathconf( "/tmp", &POSIX::_PC_PATH_MAX );

     Returns undef on failure.

pause
     This is similar to the C function `pause()'.

     Returns undef on failure.

perror
     This is identical to the C function `perror()'.

pipe
     Create an interprocess channel.  This returns file descriptors like
     those returned by `POSIX::open'.

          ($fd0, $fd1) = POSIX::pipe();
          POSIX::write( $fd0, "hello", 5 );
          POSIX::read( $fd1, $buf, 5 );

pow
     Computes $x raised to the power $exponent.

          $ret = POSIX::pow( $x, $exponent );

printf
     Prints the specified arguments to STDOUT.

putc
     putc() is C-specific-use print instead.

putchar
     putchar() is C-specific-use print instead.

puts
     puts() is C-specific-use print instead.

qsort
     qsort() is C-specific, use sort instead.

raise
     Sends the specified signal to the current process.

rand
     rand() is non-portable, use Perl's rand instead.

read
     Read from a file.  This uses file descriptors such as those obtained
     by calling `POSIX::open'.  If the buffer `$buf' is not large enough
     for the read then Perl will extend it to make room for the request.

          $fd = POSIX::open( "foo", &POSIX::O_RDONLY );
          $bytes = POSIX::read( $fd, $buf, 3 );

     Returns undef on failure.

readdir
     This is identical to Perl's builtin `readdir()' function.

realloc
     realloc() is C-specific.

remove
     This is identical to Perl's builtin `unlink()' function.

rename
     This is identical to Perl's builtin `rename()' function.

rewind
     Seeks to the beginning of the file.

rewinddir
     This is identical to Perl's builtin `rewinddir()' function.

rmdir
     This is identical to Perl's builtin `rmdir()' function.

scanf
     scanf() is C-specific-use <> and regular expressions instead.

setgid
     Sets the real group id for this process.

setjmp
     setjmp() is C-specific: use eval {} instead.

setlocale
     Modifies and queries program's locale.

     The following will set the traditional UNIX system locale behavior
     (the second argument `"C"').

          $loc = POSIX::setlocale( &POSIX::LC_ALL, "C" );

     The following will query (the missing second argument) the current
     LC_CTYPE category.

          $loc = POSIX::setlocale( &POSIX::LC_CTYPE);

     The following will set the LC_CTYPE behaviour according to the locale
     environment variables (the second argument `""').  Please see your
     systems `setlocale(3)' in this node documentation for the locale
     environment variables' meaning or consult *Note Perli18n:
     (perl.info)perli18n,.

          $loc = POSIX::setlocale( &POSIX::LC_CTYPE, "");

     The following will set the LC_COLLATE behaviour to Argentinian
     Spanish. NOTE: The naming and availability of locales depends on your
     operating system. Please consult *Note Perli18n: (perl.info)perli18n,
     for how to find out which locales are available in your system.

          $loc = POSIX::setlocale( &POSIX::LC_ALL, "es_AR.ISO8859-1" );

setpgid
     This is similar to the C function `setpgid()'.

     Returns undef on failure.

setsid
     This is identical to the C function `setsid()'.

setuid
     Sets the real user id for this process.

sigaction
     Detailed signal management.  This uses POSIX::SigAction objects for
     the `action' and `oldaction' arguments.  Consult your system's
     sigaction manpage for details.

     Synopsis:

          sigaction(sig, action, oldaction = 0)

     Returns undef on failure.

siglongjmp
     siglongjmp() is C-specific: use die instead.

sigpending
     Examine signals that are blocked and pending.  This uses POSIX::SigSet
     objects for the `sigset' argument.  Consult your system's sigpending
     manpage for details.

     Synopsis:

          sigpending(sigset)

     Returns undef on failure.

sigprocmask
     Change and/or examine calling process's signal mask.  This uses
     POSIX::SigSet objects for the `sigset' and `oldsigset' arguments.
     Consult your system's sigprocmask manpage for details.

     Synopsis:

          sigprocmask(how, sigset, oldsigset = 0)

     Returns undef on failure.

sigsetjmp
     sigsetjmp() is C-specific: use eval {} instead.

sigsuspend
     Install a signal mask and suspend process until signal arrives.  This
     uses POSIX::SigSet objects for the `signal_mask' argument.  Consult
     your system's sigsuspend manpage for details.

     Synopsis:

          sigsuspend(signal_mask)

     Returns undef on failure.

sin
     This is identical to Perl's builtin `sin()' function.

sinh
     This is identical to the C function `sinh()'.

sleep
     This is identical to Perl's builtin `sleep()' function.

sprintf
     This is identical to Perl's builtin `sprintf()' function.

sqrt
     This is identical to Perl's builtin `sqrt()' function.

srand
     srand().

sscanf
     sscanf() is C-specific-use regular expressions instead.

stat
     This is identical to Perl's builtin `stat()' function.

strcat
     strcat() is C-specific, use .= instead.

strchr
     strchr() is C-specific, use index() instead.

strcmp
     strcmp() is C-specific, use eq instead.

strcoll
     This is identical to the C function `strcoll()'.

strcpy
     strcpy() is C-specific, use = instead.

strcspn
     strcspn() is C-specific, use regular expressions instead.

strerror
     Returns the error string for the specified errno.

strftime
     Convert date and time information to string.  Returns the string.

     Synopsis:

          strftime(fmt, sec, min, hour, mday, mon, year, wday = 0, yday = 0, isdst = 0)

     The month (`mon'), weekday (`wday'), and yearday (`yday') begin at
     zero.  I.e. January is 0, not 1; Sunday is 0, not 1; January 1st is
     0, not 1.  The year (`year') is given in years since 1900.  I.e. The
     year 1995 is 95; the year 2001 is 101.  Consult your system's
     `strftime()' manpage for details about these and the other arguments.

     The string for Tuesday, December 12, 1995.

          $str = POSIX::strftime( "%A, %B %d, %Y", 0, 0, 0, 12, 11, 95, 2 );
          print "$str\n";

strlen
     strlen() is C-specific, use length instead.

strncat
     strncat() is C-specific, use .= instead.

strncmp
     strncmp() is C-specific, use eq instead.

strncpy
     strncpy() is C-specific, use = instead.

stroul
     stroul() is C-specific.

strpbrk
     strpbrk() is C-specific.

strrchr
     strrchr() is C-specific, use rindex() instead.

strspn
     strspn() is C-specific.

strstr
     This is identical to Perl's builtin `index()' function.

strtod
     strtod() is C-specific.

strtok
     strtok() is C-specific.

strtol
     strtol() is C-specific.

strxfrm
     String transformation.  Returns the transformed string.

          $dst = POSIX::strxfrm( $src );

sysconf
     Retrieves values of system configurable variables.

     The following will get the machine's clock speed.

          $clock_ticks = POSIX::sysconf( &POSIX::_SC_CLK_TCK );

     Returns undef on failure.

system
     This is identical to Perl's builtin `system()' function.

tan
     This is identical to the C function `tan()'.

tanh
     This is identical to the C function `tanh()'.

tcdrain
     This is similar to the C function `tcdrain()'.

     Returns undef on failure.

tcflow
     This is similar to the C function `tcflow()'.

     Returns undef on failure.

tcflush
     This is similar to the C function `tcflush()'.

     Returns undef on failure.

tcgetpgrp
     This is identical to the C function `tcgetpgrp()'.

tcsendbreak
     This is similar to the C function `tcsendbreak()'.

     Returns undef on failure.

tcsetpgrp
     This is similar to the C function `tcsetpgrp()'.

     Returns undef on failure.

time
     This is identical to Perl's builtin `time()' function.

times
     The times() function returns elapsed realtime since some point in the
     past (such as system startup), user and system times for this
     process, and user and system times used by child processes.  All
     times are returned in clock ticks.

          ($realtime, $user, $system, $cuser, $csystem) = POSIX::times();

     Note: Perl's builtin `times()' function returns four values, measured
     in seconds.

tmpfile
     Use method `FileHandle::new_tmpfile()' instead.

tmpnam
     Returns a name for a temporary file.

          $tmpfile = POSIX::tmpnam();

tolower
     This is identical to Perl's builtin `lc()' function.

toupper
     This is identical to Perl's builtin `uc()' function.

ttyname
     This is identical to the C function `ttyname()'.

tzname
     Retrieves the time conversion information from the tzname variable.

          POSIX::tzset();
          ($std, $dst) = POSIX::tzname();

tzset
     This is identical to the C function `tzset()'.

umask
     This is identical to Perl's builtin `umask()' function.

uname
     Get name of current operating system.

          ($sysname, $nodename, $release, $version, $machine ) = POSIX::uname();

ungetc
     Use method `FileHandle::ungetc()' instead.

unlink
     This is identical to Perl's builtin `unlink()' function.

utime
     This is identical to Perl's builtin `utime()' function.

vfprintf
     vfprintf() is C-specific.

vprintf
     vprintf() is C-specific.

vsprintf
     vsprintf() is C-specific.

wait
     This is identical to Perl's builtin `wait()' function.

waitpid
     Wait for a child process to change state.  This is identical to Perl's
     builtin `waitpid()' function.

          $pid = POSIX::waitpid( -1, &POSIX::WNOHANG );
          print "status = ", ($? / 256), "\n";

wcstombs
     This is identical to the C function `wcstombs()'.

wctomb
     This is identical to the C function `wctomb()'.

write
     Write to a file.  This uses file descriptors such as those obtained by
     calling `POSIX::open'.

          $fd = POSIX::open( "foo", &POSIX::O_WRONLY );
          $buf = "hello";
          $bytes = POSIX::write( $b, $buf, 5 );

     Returns undef on failure.

CLASSES
=======

POSIX::SigAction
----------------

new
     Creates a new POSIX::SigAction object which corresponds to the C
     `struct sigaction'.  This object will be destroyed automatically when
     it is no longer needed.  The first parameter is the fully-qualified
     name of a sub which is a signal-handler.  The second parameter is a
     POSIX::SigSet object.  The third parameter contains the `sa_flags'.

          $sigset = POSIX::SigSet->new;
          $sigaction = POSIX::SigAction->new( 'main::handler', $sigset, &POSIX::SA_NOCLDSTOP );

     This POSIX::SigAction object should be used with the
     `POSIX::sigaction()' function.

POSIX::SigSet
-------------

new
     Create a new SigSet object.  This object will be destroyed
     automatically when it is no longer needed.  Arguments may be supplied
     to initialize the set.

     Create an empty set.

          $sigset = POSIX::SigSet->new;

     Create a set with SIGUSR1.

          $sigset = POSIX::SigSet->new( &POSIX::SIGUSR1 );

addset
     Add a signal to a SigSet object.

          $sigset->addset( &POSIX::SIGUSR2 );

     Returns undef on failure.

delset
     Remove a signal from the SigSet object.

          $sigset->delset( &POSIX::SIGUSR2 );

     Returns undef on failure.

emptyset
     Initialize the SigSet object to be empty.

          $sigset->emptyset();

     Returns undef on failure.

fillset
     Initialize the SigSet object to include all signals.

          $sigset->fillset();

     Returns undef on failure.

ismember
     Tests the SigSet object to see if it contains a specific signal.

          if( $sigset->ismember( &POSIX::SIGUSR1 ) ){
          	print "contains SIGUSR1\n";
          }

POSIX::Termios
--------------

new
     Create a new Termios object.  This object will be destroyed
     automatically when it is no longer needed.

          $termios = POSIX::Termios->new;

getattr
     Get terminal control attributes.

     Obtain the attributes for stdin.

          $termios->getattr()

     Obtain the attributes for stdout.

          $termios->getattr( 1 )

     Returns undef on failure.

getcc
     Retrieve a value from the c_cc field of a termios object.  The c_cc
     field is an array so an index must be specified.

          $c_cc[1] = $termios->getcc(1);

getcflag
     Retrieve the c_cflag field of a termios object.

          $c_cflag = $termios->getcflag;

getiflag
     Retrieve the c_iflag field of a termios object.

          $c_iflag = $termios->getiflag;

getispeed
     Retrieve the input baud rate.

          $ispeed = $termios->getispeed;

getlflag
     Retrieve the c_lflag field of a termios object.

          $c_lflag = $termios->getlflag;

getoflag
     Retrieve the c_oflag field of a termios object.

          $c_oflag = $termios->getoflag;

getospeed
     Retrieve the output baud rate.

          $ospeed = $termios->getospeed;

setattr
     Set terminal control attributes.

     Set attributes immediately for stdout.

          $termios->setattr( 1, &POSIX::TCSANOW );

     Returns undef on failure.

setcc
     Set a value in the c_cc field of a termios object.  The c_cc field is
     an array so an index must be specified.

          $termios->setcc( &POSIX::VEOF, 1 );

setcflag
     Set the c_cflag field of a termios object.

          $termios->setcflag( &POSIX::CLOCAL );

setiflag
     Set the c_iflag field of a termios object.

          $termios->setiflag( &POSIX::BRKINT );

setispeed
     Set the input baud rate.

          $termios->setispeed( &POSIX::B9600 );

     Returns undef on failure.

setlflag
     Set the c_lflag field of a termios object.

          $termios->setlflag( &POSIX::ECHO );

setoflag
     Set the c_oflag field of a termios object.

          $termios->setoflag( &POSIX::OPOST );

setospeed
     Set the output baud rate.

          $termios->setospeed( &POSIX::B9600 );

     Returns undef on failure.

Baud rate values
     B38400 B75 B200 B134 B300 B1800 B150 B0 B19200 B1200 B9600 B600 B4800
     B50 B2400 B110

Terminal interface values
     TCSADRAIN TCSANOW TCOON TCIOFLUSH TCOFLUSH TCION TCIFLUSH TCSAFLUSH
     TCIOFF TCOOFF

c_cc field values
     VEOF VEOL VERASE VINTR VKILL VQUIT VSUSP VSTART VSTOP VMIN VTIME NCCS

c_cflag field values
     CLOCAL CREAD CSIZE CS5 CS6 CS7 CS8 CSTOPB HUPCL PARENB PARODD

c_iflag field values
     BRKINT ICRNL IGNBRK IGNCR IGNPAR INLCR INPCK ISTRIP IXOFF IXON PARMRK

c_lflag field values
     ECHO ECHOE ECHOK ECHONL ICANON IEXTEN ISIG NOFLSH TOSTOP

c_oflag field values
     OPOST

PATHNAME CONSTANTS
==================

Constants
     _PC_CHOWN_RESTRICTED _PC_LINK_MAX _PC_MAX_CANON _PC_MAX_INPUT
     _PC_NAME_MAX _PC_NO_TRUNC _PC_PATH_MAX _PC_PIPE_BUF _PC_VDISABLE

POSIX CONSTANTS
===============

Constants
     _POSIX_ARG_MAX _POSIX_CHILD_MAX _POSIX_CHOWN_RESTRICTED
     _POSIX_JOB_CONTROL _POSIX_LINK_MAX _POSIX_MAX_CANON _POSIX_MAX_INPUT
     _POSIX_NAME_MAX _POSIX_NGROUPS_MAX _POSIX_NO_TRUNC _POSIX_OPEN_MAX
     _POSIX_PATH_MAX _POSIX_PIPE_BUF _POSIX_SAVED_IDS _POSIX_SSIZE_MAX
     _POSIX_STREAM_MAX _POSIX_TZNAME_MAX _POSIX_VDISABLE _POSIX_VERSION

SYSTEM CONFIGURATION
====================

Constants
     _SC_ARG_MAX _SC_CHILD_MAX _SC_CLK_TCK _SC_JOB_CONTROL _SC_NGROUPS_MAX
     _SC_OPEN_MAX _SC_SAVED_IDS _SC_STREAM_MAX _SC_TZNAME_MAX _SC_VERSION

ERRNO
=====

Constants
     E2BIG EACCES EAGAIN EBADF EBUSY ECHILD EDEADLK EDOM EEXIST EFAULT
     EFBIG EINTR EINVAL EIO EISDIR EMFILE EMLINK ENAMETOOLONG ENFILE
     ENODEV ENOENT ENOEXEC ENOLCK ENOMEM ENOSPC ENOSYS ENOTDIR ENOTEMPTY
     ENOTTY ENXIO EPERM EPIPE ERANGE EROFS ESPIPE ESRCH EXDEV

FCNTL
=====

Constants
     FD_CLOEXEC F_DUPFD F_GETFD F_GETFL F_GETLK F_OK F_RDLCK F_SETFD
     F_SETFL F_SETLK F_SETLKW F_UNLCK F_WRLCK O_ACCMODE O_APPEND O_CREAT
     O_EXCL O_NOCTTY O_NONBLOCK O_RDONLY O_RDWR O_TRUNC O_WRONLY

FLOAT
=====

Constants
     DBL_DIG DBL_EPSILON DBL_MANT_DIG DBL_MAX DBL_MAX_10_EXP DBL_MAX_EXP
     DBL_MIN DBL_MIN_10_EXP DBL_MIN_EXP FLT_DIG FLT_EPSILON FLT_MANT_DIG
     FLT_MAX FLT_MAX_10_EXP FLT_MAX_EXP FLT_MIN FLT_MIN_10_EXP FLT_MIN_EXP
     FLT_RADIX FLT_ROUNDS LDBL_DIG LDBL_EPSILON LDBL_MANT_DIG LDBL_MAX
     LDBL_MAX_10_EXP LDBL_MAX_EXP LDBL_MIN LDBL_MIN_10_EXP LDBL_MIN_EXP

LIMITS
======

Constants
     ARG_MAX CHAR_BIT CHAR_MAX CHAR_MIN CHILD_MAX INT_MAX INT_MIN LINK_MAX
     LONG_MAX LONG_MIN MAX_CANON MAX_INPUT MB_LEN_MAX NAME_MAX NGROUPS_MAX
     OPEN_MAX PATH_MAX PIPE_BUF SCHAR_MAX SCHAR_MIN SHRT_MAX SHRT_MIN
     SSIZE_MAX STREAM_MAX TZNAME_MAX UCHAR_MAX UINT_MAX ULONG_MAX USHRT_MAX

LOCALE
======

Constants
     LC_ALL LC_COLLATE LC_CTYPE LC_MONETARY LC_NUMERIC LC_TIME

MATH
====

Constants
     HUGE_VAL

SIGNAL
======

Constants
     SA_NOCLDSTOP SIGABRT SIGALRM SIGCHLD SIGCONT SIGFPE SIGHUP SIGILL
     SIGINT SIGKILL SIGPIPE SIGQUIT SIGSEGV SIGSTOP SIGTERM SIGTSTP
     SIGTTIN SIGTTOU SIGUSR1 SIGUSR2 SIG_BLOCK SIG_DFL SIG_ERR SIG_IGN
     SIG_SETMASK SIG_UNBLOCK

STAT
====

Constants
     S_IRGRP S_IROTH S_IRUSR S_IRWXG S_IRWXO S_IRWXU S_ISGID S_ISUID
     S_IWGRP S_IWOTH S_IWUSR S_IXGRP S_IXOTH S_IXUSR

Macros
     S_ISBLK S_ISCHR S_ISDIR S_ISFIFO S_ISREG

STDLIB
======

Constants
     EXIT_FAILURE EXIT_SUCCESS MB_CUR_MAX RAND_MAX

STDIO
=====

Constants
     BUFSIZ EOF FILENAME_MAX L_ctermid L_cuserid L_tmpname TMP_MAX

TIME
====

Constants
     CLK_TCK CLOCKS_PER_SEC

UNISTD
======

Constants
     R_OK SEEK_CUR SEEK_END SEEK_SET STDIN_FILENO STDOUT_FILENO
     STRERR_FILENO W_OK X_OK

WAIT
====

Constants
     WNOHANG WUNTRACED

Macros
     WIFEXITED WEXITSTATUS WIFSIGNALED WTERMSIG WIFSTOPPED WSTOPSIG

CREATION
========

This document generated by ./mkposixman.PL version 19960129.


File: pm.info,  Node: Parext,  Next: Pari,  Prev: POSIX,  Up: Module List

Parity (odd/even) handling functions
************************************

NAME
====

String::Parext, setSpaceParity, setMarkParity, showParext, SpaceBytes,
MarkBytes, isSpaceParity, isMarkParity - Parity (odd/even) handling
functions

SYNOPSIS
========

     use String::Parext;

DESCRIPTION
===========

setSpaceParity LIST
     Copies the elements of LIST to a new list and converts the new
     elements to strings of bytes with space parity (High bit cleared). In
     array context returns the new list.  In scalar context joins the
     elements of the new list into a single string and returns the string.

setMarkParity LIST
     Does the same as the setSpaceParity function, but converts to strings
     with mark parity (High bit set).

showParext LIST
     Does the same as the setSpaceParity function, but converts bytes with
     space parity to 's' and other bytes to 'm'.

SpaceBytes LIST
     Returns the number of space parity bytes in the elements of LIST.

MarkBytes LIST
     Returns the number of mark parity bytes in the elements of LIST.

isSpaceParity LIST
     Returns TRUE if the LIST contains no byte with mark parity, FALSE
     otherwise.

isMarkParity LIST
     Returns TRUE if the LIST contains no byte with space parity, FALSE
     otherwise.

NOTES
=====

Don't use this module unless you have to communicate with some old device
or protocol. Help the world and make your application 8 bit clean. Use the
internationally standardized ISO-8859-1 character set.

AUTHOR
======

Winfried Koenig <win@in.rhein-main.de>

     Copyright (c) 1995 Winfried Koenig. All rights reserved.
     This program is free software; you can redistribute it
     and/or modify it under the same terms as Perl itself.


File: pm.info,  Node: Pari,  Next: Parity,  Prev: Parext,  Up: Module List

Perl interface to PARI.
***********************

NAME
====

`Math::Pari' - Perl interface to PARI.

SYNOPSIS
========

     use Math::Pari;
     $a = PARI 2;
     print $a**10000;

or

     use Math::Pari qw(mod);
     $a = mod(3,5);
     print $a**10000;

DESCRIPTION
===========

This package allows use of most PARI functions as Perl functions. In what
follows we suppose prior knowledge of what PARI is (see `ftp:' in this
node).

EXPORT
======

DEFAULT
     By default the package exports functions PARI(), PARIcol() and
     PARImat() that converts its argument(s) to a PARI object. (In fact
     PARI() is just an alias for `new Math::Pari').  The function PARI()
     accepts following data as its arguments

    One integer
          Is converted to a PARI integer.

    One float
          Is converted to a PARI float.

    One string
          Is executed as a PARI expresion (so should not contain
          whitespace).

    PARI object
          Is passed unchanged.

    Reference to a Perl array
          Each element is converted using the same rules, PARI vector-row
          with these elements is returned.

    Several of above
          The same as with a reference to array.

Conflicts of rules in PARI()
     In deciding what rule of the above to apply the preference is given to
     the uppermost choice of available now, if none matches, then the
     string rule is used. So `PARI(1)' returns integer, `PARI(1.)' returns
     float, `PARI("1")' evaluates "1" as a PARI expression, though all
     these data can be converted inside Perl into integer, float or
     string. Only what the argument *is now* is important.

PARIcol() and PARImat()
     PARIcol() behaves in the same way as PARI() unless given several
     arguments. In the latter case it returns a vector-column instead of
     vector-row.

     PARImat() constructs a matrix out of the given arguments. It will work
     if PARI() will construct a vector of vectors given the same arguments.

use with arguments
     If arguments are specified in the `use Math::Pari' directive, the
     PARI functions appearing as arguments are exported in the caller
     context. In this case the function PARI() and friends is not
     exported, so if you need them, you should include them into export
     list explicitely.

Available functions
===================

Directly accessible from Perl
-----------------------------

This package supports all the functions from the PARI library with a
signature from a short list. This means that when you update the PARI
library, the newly added function will we available without any change to
this package (provided their signature is in the supported list). You can
reach unsupported functions using string argument of PARI() function.

A perl script `parifonc' is provided that lists the functions from the
current release of PARI that are unavailable with the current release of
this glue code. You should specify two arguments to this script: a path to
`anal.c' file of PARI/GP distribution, and path to the file  `Pari.xs'
from your truely package.

Arguments
---------

Arguments to PARI functions are converted to `long' or PARI type depending
on what type the actual library function requires. No error checking on
arguments is done, so if `gp' rejects your code since a particular
argument should be of `type 1' (i.e., a Pari integer), `Math::Pari' will
silently convert it to `long'. Each argument is converted by the rules
applicable to PARI().

Return values
-------------

PARI functions return PARI type or a `long' depending on what the actual
library function returns.

Additional functions
--------------------

Some PARI functions are available in `gp' (i.e., in PARI calculator) via
infix notation only. In `Math::Pari' these functions are available in
functional notations too. Some other convenience functions are also made
available.

Infix, prefix and postfix operations
     are available under names

          gneg, gadd, gsub, gmul, gdiv, gdivent, gmod, gpui,
          gle, gge, glt, ggt, geq, gne, gegal, gor, gand,
          gcmp, gcmp0, gcmp1, gcmp_1.

     `gdivent' means euclidean quotient, `gpui' is power, `gegal' checks
     whether two objects are equal, `gcmp' is applicable to two real
     numbers only, `gcmp0', `gcmp1', `gcmp_1' compare with 0, 1 and -1
     correspondingly  (see PARI user manual for details).

Convenience functions
          pari2iv, pari2nv, pari2num, pari2pv, pari2bool

     convert a PARI object to an integer, float, integer/float (whatever is
     better), string, and a boolean value correspondingly. Most the time
     you do not need these functions due to automatic conversions.

Constant functions
     Some mathematical constant appear as function without arguments in
     PARI. Corresponding functions are made available under Perl. If you
     export them like in

          use Math::Pari wq(pi i euler);

     they can be used as barewords in your program, with the usual
     restrictions that sometimes you should disambiguate the call like in

          $negOne = exp(pi() * i);

     The parentheses after `pi' are needed since Perl thinks you want to
     call `pi' with argument `*i' otherwise (since `*i' is a legal Perl
     expression, and function calls are greedy on the right).

PARI objects
============

Functions from PARI library take as arguments and/or return objects of
type `GEN' (in C notations). In Perl these data are encapsulated into
special kind of Perl variables: PARI objects. You can check for a variable
`$obj' to be a PARI object using

     ref $obj eq 'Math::Pari';

Most the time you do not need this due to automatic conversions.

PARI polynomials and Perl barewords
===================================

Some bareletters denote Perl operators, like q, x, `y', s. This can lead
to errors in Perl parsing your expression. Say, while

     print sin(tan(x))-tan(sin(x))-asin(atan(x))+atan(asin(x));

parses OK (after `use Math::Pari qw(sin tan asin atan)'),

     print sin(tan(y))-tan(sin(y))-asin(atan(y))+atan(asin(y));

does not. You should avoid lower-case barewords used as PARI variables.

Overloading and automatic conversion
====================================

Whenever an arithmetic operation includes a PARI object the other
arguments are converted to a PARI type and the corresponding PARI library
functions is used to implement the operation. Numeric comparison
operations use `gcmp' and friends, string comparisons compare in
lexicographical order using `lex'. Currently the following arithmetic
operations are overloaded:

     unary -, +, -, *, /, %, **, abs, cos, sin, exp, log, sqrt.

Whenever a PARI object appears in a situation that requires integer,
numeric, boolean or string data, it is converted to the corresponding
type. Boolean conversion is subject to usual PARI pitfalls related to
imprecise zeros (see documentation of `gcmp0' in PARI reference).

PREREQUISITES
=============

Perl
----

To compile the extension you need to have at least `MakeMaker' version
3.7. In the versions of perl earlier than 5.001 negative constants were
converted to floats, so to use PARI operations that do different things on
integers and floats you would like to use a more recent version of perl.
Overloading was buggy in 5.000.

PARI
----

You need at least version 1.39 of PARI. (See `ftp:' in this node.)

ENVIRONMENT
===========

No environment variables are used.

BUGS
====

   * Not all the PARI functions are directly available.

   * Many others...

AUTHOR
======

Ilya Zakharevich, *ilya@math.mps.ohio-state.edu*


File: pm.info,  Node: Parity,  Next: Penguin/Easy,  Prev: Pari,  Up: Module List

Parity (mark/space) handling functions
**************************************

NAME
====

String::Parity, setEvenParity, setOddParity, showParity, EvenBytes,
OddBytes, isEvenParity, isOddParity - Parity (mark/space) handling
functions

SYNOPSIS
========

     use String::Parity;

DESCRIPTION
===========

setEvenParity LIST
     Copies the elements of LIST to a new list and converts the new
     elements to strings of bytes with even parity. In array context
     returns the new list.  In scalar context joins the elements of the
     new list into a single string and returns the string.

setOddParity LIST
     Does the same as the setEvenParity function, but converts to strings
     with odd parity.

showParity LIST
     Does the same as the setEvenParity function, but converts bytes with
     even parity to 'e' and other bytes to 'o'.

EvenBytes LIST
     Returns the number of even parity bytes in the elements of LIST.

OddBytes LIST
     Returns the number of odd parity bytes in the elements of LIST.

isEvenParity LIST
     Returns TRUE if the LIST contains no byte with odd parity, FALSE
     otherwise.

isOddParity LIST
     Returns TRUE if the LIST contains no byte with even parity, FALSE
     otherwise.

NOTES
=====

Don't use this module unless you have to communicate with some old device
or protocol. Help the world and make your application 8 bit clean. Use the
internationally standardized ISO-8859-1 character set.

AUTHOR
======

Winfried Koenig <win@in.rhein-main.de>

     Copyright (c) 1995 Winfried Koenig. All rights reserved.
     This program is free software; you can redistribute it
     and/or modify it under the same terms as Perl itself.


File: pm.info,  Node: Penguin/Easy,  Next: Pg,  Prev: Parity,  Up: Module List

provides easy access to Penguin module.
***************************************

NAME
====

     Penguin::Easy -- provides easy access to Penguin module.

SYNOPSIS
========

     use Penguin::Easy;
     my $ep = new Penguin::Easy Title => 'Easy Program',
     			     Name => 'James Duncan',
     			     Sig => $my_pgp_sig,
     			     Code => $my_perl_code;
     $results = $ep->run;
     print "$results\n";

DESCRIPTION
===========

`Penguin::Easy' is an OO module, that provides quick-and-dirty access to
the penguin module for those not wanting to learn the nittygrittys about
it.  The `Easy' module provides transparent access to the `Penguin'
module, even to the extent of deciding whether the Penguin code should be
transparently wrapped, or PGP wrapped (if you include a sig in the call to
the new method,  it will use PGP).

NOTES
=====

While writing this little module,  I've decided that `Wrapper' is perhaps
one of the funniest words I have ever seen.  It has completly lost all
meaning.


File: pm.info,  Node: Pg,  Next: Pod/Parse,  Prev: Penguin/Easy,  Up: Module List

Perl extension for Postgres95
*****************************

NAME
====

Pg - Perl extension for Postgres95

SYNOPSIS
========

use Pg;

DESCRIPTION
===========

The Pg module permits you to access all functions of the libpq-interface
of Postgres95. It tries to resemble the libpq-interface as close as
possible. For examples of how to use this module, look at the file test.pl.

GUIDELINES
==========

There are two exceptions, where the perl-functions differs from the
C-counterpart: PQprint and PQnotifies. These functions deal with
structures, which have been implemented in perl using lists.

All functions and constants are imported into the calling packages
namespace. In order to to get a uniform naming, all functions start with
'PQ' (e.g. PQlo_open) and all constants start with 'PGRES_' (e.g.
PGRES_CONNECTION_OK).

There are two functions, which allocate memory, that has to be freed by
the user:

     PQsetdb, use PQfinish to free memory.
     PQexec,  use PQclear to free memory.

Pg.pm contains one convenience function: doQuery. It fills a
two-dimensional array with the result of your query. Usage:

Pg::doQuery($conn, "select attr1, attr2 from tbl", \@ary);

for $i ( 0 .. $#ary ) {     for $j ( 0 .. $#{$ary[$i]} ) {         print
"$ary[$i][$j]\t";     }     print "\n"; }

Notice the inner loop !

FUNCTIONS
=========

The functions have been divided into four categories: Connections,
Execution, Miscellaneous, Large Objects.

1. Connection
-------------

With these functions you can establish and close a connection to a
database. In libpq a connection is represented by a structure called
PGconn. Using the appropriate functions you can access almost all fields
of this structure.

*$conn = PQsetdb($pghost, $pgport, $pgoptions, $pgtty, $dbname)*

Opens a new connection to the backend. You may use an empty string for any
argument, in which case first the environment is checked and then
hardcoded defaults are used. The connection identifier $conn ( a pointer
to the PGconn structure ) must be used in subsequent commands for unique
identification. Before using $conn you should call PQstatus to ensure,
that the connection was properly made. Use the functions below to access
the contents of the PGconn structure.

*$pghost = PQhost($conn)*

Returns the host name of the connection.

*$pgtty = PQtty($conn)*

Returns the tty of the connection.

*$pgport = PQport($conn)*

Returns the port of the connection.

*$pgoptions = PQoptions($conn)*

Returns the options used in the connection.

*$dbName = PQdb($conn)*

Returns the database name of the connection.

*$status = PQstatus($conn)*

Returns the status of the connection. For comparing the status you may use
the following constants:  - PGRES_CONNECTION_OK  - PGRES_CONNECTION_BAD

*$errorMessage = PQerrorMessage($conn)*

Returns the last error message associated with this connection.

*PQfinish($conn)*

Closes the connection to the backend and frees all memory.

*PQreset($conn)*

Resets the communication port with the backend and tries to establish a
new connection.

2. Execution
------------

With these functions you can send commands to a database and investigate
the results. In libpq the result of a command is represented by a
structure called PGresult. Using the appropriate functions you can access
almost all fields of this structure.

*$result = PQexec($conn, $query)*

Submits a query to the backend. The return value is a pointer to the
PGresult structure, which contains the complete query-result returned by
the backend. In case of failure, the pointer points to an empty structure.
In this, the perl implementation differs from the C-implementation. In
perl, even the empty structure has to be freed using PQfree. Before using
$result you should call PQresultStatus to ensure, that the query was
properly executed.

Use the functions below to access the contents of the PGresult structure.

*$ntups = PQntuples($result)*

Returns the number of tuples in the query result.

*$nfields = PQnfields($result)*

Returns the number of fields in the query result.

*$fname = PQfname($result, $field_num)*

Returns the field name associated with the given field number.

*$fnumber = PQfnumber($result, $field_name)*

Returns the field number associated with the given field name.

*$ftype = PQftype($result, $field_num)*

Returns the oid of the type of the given field number.

*$fsize = PQfsize($result, $field_num)*

Returns the size in bytes of the type of the given field number.  It
returns -1 if the field has a variable length.

*$value = PQgetvalue($result, $tup_num, $field_num)*

Returns the value of the given tuple and field. This is a null-terminated
ASCII string. Binary cursors will not work.

*$length = PQgetlength($result, $tup_num, $field_num)*

Returns the length of the value for a given tuple and field.

*$null_status = PQgetisnull($result, $tup_num, $field_num)*

Returns the NULL status for a given tuple and field.

*$result_status = PQresultStatus($result)*

Returns the status of the result. For comparing the status you may use one
of the following constants depending upon the command executed:  -
PGRES_EMPTY_QUERY  - PGRES_COMMAND_OK  - PGRES_TUPLES_OK  - PGRES_COPY_OUT
- PGRES_COPY_IN  - PGRES_BAD_RESPONSE  - PGRES_NONFATAL_ERROR  -
PGRES_FATAL_ERROR

*$cmdStatus = PQcmdStatus($result)*

Returns the command status of the last query command.

*$oid = PQoidStatus($result)*

In case the last query was an INSERT command it returns the oid of the
inserted tuple.

*PQprintTuples($result, $fout, $printAttName, $terseOutput, $width)*

Kept for backward compatibility. Use PQprint.

*PQprint($fout, $result, $header, $align, $standard, $html3, $expanded,
$pager, $fieldSep, $tableOpt, $caption, ...)*

Prints out all the tuples in an intelligent  manner. This function differs
from the C-counterpart. The struct PQprintOpt has been implemented by a
list. This list is of variable length, in order to care for the character
array fieldName in PQprintOpt.  The arguments $header, $align, $standard,
$html3, $expanded, $pager are boolean flags. The arguments $fieldSep,
$tableOpt, $caption are strings. You may append additional strings, which
will be taken as replacement for the field names.

*PQclear($result)*

Frees all memory of the given result.

3. Miscellaneous
----------------

These functions cover the topic of copying data from or into a table, as
well as the debugging using traces. Also there is a function for
asynchronous notification.

*PQputline($conn, $string)*

Sends a string to the backend. The application must explicitly send the
single character "." to indicate to the backend that it has finished
sending its data.

*$ret = PQgetline($conn, $string, $length)*

Reads a string up to $length - 1 characters from the backend.  PQgetline
returns EOF at EOF, 0 if the entire line has been read, and 1 if the
buffer is full. If a line consists of the single character "." the backend
has finished sending the results of the copy command.

*$ret = PQendcopy($conn)*

This function waits  until the backend has finished the copy.  It should
either be issued when the last string has been sent to  the  backend
using  PQputline or when the last string has been received from the
backend using PQgetline. PQendcopy returns 0 on success, nonzero otherwise.

*PQtrace($conn, $debug_port)*

Messages passed between frontend and backend are echoed to the debug_port
file stream.

*PQuntrace($conn)*

Disables tracing.

*($table, $pid) = PQnotifies($conn)*

Checks for asynchronous notifications. This functions differs from the
C-counterpart which returns a pointer to a new allocated structure,
whereas the perl implementation returns a list. $table is the table which
has been listened to and $pid is the process id of the backend.

4. Large Objects
----------------

These functions provide file-oriented access to user data.  The large
object interface is modeled after the Unix file system interface with
analogues of open, close, read, write, lseek, tell. In order to get a
consistent naming, all function names have been prepended with 'PQ'.

*$lobjId = PQlo_creat($conn, $mode)*

Creates a new large object. $mode is a bitmask describing different
attributes of the new object. Use the following constants:  -
PGRES_INV_SMGRMASK  - PGRES_INV_ARCHIVE  - PGRES_INV_WRITE  -
PGRES_INV_READ

Upon failure it returns PGRES_InvalidOid.

*$ret = PQlo_unlink($conn, $lobjId)*

Deletes a large object. Returns -1 upon failure.

*$lobj_fd = PQlo_open($conn, $lobjId, $mode)*

Opens an existing large object and returns an object id.  For the mode
bits see PQlo_create. Returns -1 upon failure.

*$ret = PQlo_close($conn, $lobj_fd)*

Closes an existing large object. Returns 0 upon success and -1 upon
failure.

*$nbytes = PQlo_read($conn, $lobj_fd, $buf, $len)*

Reads $len bytes into $buf from large object $lobj_fd.  Returns the number
of bytes read and -1 upon failure.

*$nbytes = PQlo_write($conn, $lobj_fd, $buf, $len)*

Writes $len bytes of $buf into the large object $lobj_fd.  Returns the
number of bytes written and -1 upon failure.

*$ret = PQlo_lseek($conn, $lobj_fd, $offset, $whence)*

Change the current read or write location on the large object $obj_id.
Currently $whence can only be 0 (L_SET).

*$location = PQlo_tell($conn, $lobj_fd)*

Returns the current read or write location on the large object $lobj_fd.

*$lobjId = PQlo_import($conn, $filename)*

Imports a Unix file as large object and returns the object id of the new
object.

*$ret = PQlo_export($conn, $lobjId, $filename)*

Exports a large object into a Unix file.  Returns -1 upon failure, 1
otherwise.

AUTHOR
======

Edmund Mergl <E.Mergl@bawue.de>

SEE ALSO
========

libpq(3), large_objects(3).


File: pm.info,  Node: Pod/Parse,  Next: Pod/Parser,  Prev: Pg,  Up: Module List

Parse the pod (Plain Old Documentation) portion of a file
*********************************************************

NAME
====

Pod::Parse - Parse the pod (Plain Old Documentation) portion of a file

SYNOPSIS
========

     use Parse;
     $p = new Parse;
     $p->parse_from_file_by_name(FILENAME, CALLBACK);

DESCRIPTION
===========

MARKUP
------

These are markups that are accepted. Several are introduced as internal
markup, but their use in regular pod is encouraged to help the
cross-referencing process.

     C<> = Code
     B<> = Bold
     I<> = Italics
     V<> = Variable
     P<> = Function/Procedure
     S<> = Switch
     F<> = Filename
     M<> = Manpage
     X<> = Index mark
     R<> = Hyperreference to anything
     L<> = Link to anything (old-style reference)
     W<> = Single word (non-breaking spaces)
     Z<> = No-space
     E<> = HTML Escape
     U<> = Unchanged/verbatim
     
     =without auto-indexing
     =with full-item-indexing
     =without man-warnings

The with/without commands are really generalized variable set/unset
commands. `=with X of Y' and `=without X' are the general forms. `Y'
defaults to 1.

     =head?

The new =head is generalized to any heading level. Alternate forms are
`=head', `=heading', `=subheading', `=subsubheading', etc.

     =begin
     =end
     =over
     =back
     =item
     =cut
     =pod
     =comment

Each comment is presented to the formatter so that, if possible, it can be
included in the final file as an invisible comment.

	=index

Which should have a syntax similar to X<>, if it were done.

	=resume

Opposite of =cut.

dumpout
     Q&D array dumper

wrap TEXT, WIDTH
     Wrap incoming text by turning spaces into newlines.

     DO NOT FEED TABS!

chopup TEXT
     Given text with a possible reference in it, using a reference form of

          Something(s)      for some manual section s (Fails for section 3g)
          Something;SomethingElse
          Something/SomethingElse

     return a complex set of nested arrays.

     Return TEXT if no references are found in it.

new
     Constructor for Parse objects

parse_from_file_by_name FILENAME, CALLBACK
     Method to parse a pod file, and either return the results as one big
     array, or invoke a callback every interval

deformat ARRAY
     Given flowed text, return an ASCII equivalent missing formatting.

escape STRING
     Given STRING, break it into possibly multiple elements, escaping HTML
     special characters.

flowed2 TEXT
     Sheer magic. (Undocumented technology, that is...)

flowed TEXT
     Preparation and entry function for flowed2().

     Return the result of flowed2() in an array.

start_file FILENAME
     Set up the object before parsing the file.

flow_heuristics TEXT
     Convert a block of text to the new style of markup.  The heuristics
     are specific to Perl and the existing Perl documentation.

     (This code probably isn't reliable yet. The idea is to convert old
     style implicit references into new sytle explicit references using
     R<>. Then the formatter simply has to look do references based on R<>
     fields.)

head_heuristics ARGUMENT, LEVEL
     Perform specific heuristics on the =head portion. The NAME first level
     header causes an index to this manpage entry. Other headers generate
     local indices.

parse_paragraph PARAGRAPH, DUMP-SUB
     The interesting bits. If DUMP-SUB is defined, it'll be invoked with
     each parsed record. If not, the parsed records will be returned when
     all records derived from this paragraph are complete.

     (This is the code that takes a paragraphs worth of data and parses it
     into an internal representation, possible invoking the above
     heuristic code to add formatting.

     The list/listbegun/listpending stuff is, while functional, quite
     badly done, and needs a complete rewrite from a more stable
     perspective. There are actually two goals that are currently wrapped
     up in one implementation.  First, we need to be able to keep track of
     block (=begin/=end) environments, and secondly we need to be able to
     keep a pending queue (FIFO) of parsed paragraphs if we are in a
     situation where we don't have enough information to finish parsing a
     current paragraph. This happens with lists, for example, because we
     can't deduce the type of the list (which is returned in both the
     begin and end records) until we see the first paragraph of text for
     that list.)

flush DUMP-SUB
     Post-file method to finish off anything that got started but didn't
     get closed down.

     Returns the resulting material.

BUGS/LIMITATIONS
================

FILES
=====

AUTHOR(S)
=========


File: pm.info,  Node: Pod/Parser,  Next: Pod/Select,  Prev: Pod/Parse,  Up: Module List

base class for creating pod filters and translators
***************************************************

NAME
====

Pod::Parser - base class for creating pod filters and translators

SYNOPSIS
========

     use Pod::Parser;
     package MyParser;
     @ISA = qw(Pod::Parser);

     sub new {
         ## constructor code ...
     }

     ## implementation of appropriate subclass methods ...

     package main;
     $parser = new MyParser;
     @ARGV = ('-')  unless (@ARGV > 0);
     for (@ARGV) {
         $parser->parse_from_file($_);
     }

DESCRIPTION
===========

*Pod::Parser* is an abstract base class for implementing filters and/or
translators to parse pod documentation into other formats. It handles most
of the difficulty of parsing the pod sections in a file and leaves it to
the subclasses to override various methods to provide the actual
translation. The other thing that *Pod::Parser* provides is the ability to
process only selected sections of pod documentation from the input.

SECTION SPECIFICATIONS
----------------------

Certain methods and functions provided by *Pod::Parser* may be given one
or more "section specifications" to restrict the text processed to only
the desired set of sections and their corresponding subsections.  A
section specification is a string containing one or more Perl-style
regular expressions separated by forward slashes ("/").  If you need to
use a forward slash literally within a section title you can escape it
with a backslash ("\/").

The formal syntax of a section specification is:


     *head1-title-regexp*/*head2-title-regexp*/...

Any omitted or empty regular expressions will default to ".*".  Please
note that each regular expression given is implicitly anchored by adding
"^" and "$" to the beginning and end.  Also, if a given regular expression
starts with a "!" character, then the expression is negated (so `!foo'
would match anything *except* foo).

Some example section specifications follow.

Match the NAME and SYNOPSIS sections and all of their subsections:
     `NAME|SYNOPSIS'

Match only the `Question' and `Answer' subsections of the DESCRIPTION section:
     `DESCRIPTION/Question|Answer'

Match the `Comments' subsection of all sections:
     `/Comments'

Match all subsections of DESCRIPTION *except* for `Comments':
     `DESCRIPTION/!Comments'

Match the DESCRIPTION section but do *not* match any of its subsections:
     `DESCRIPTION/!.+'

Match all top level sections but none of their subsections:
     `/!.+'

FUNCTIONS
=========

*Pod::Parser* provides the following functions (please note that these are
functions and *not* methods, they do not take an object reference as an
implicit first parameter):

version()
---------

Return the current version of this package.

INSTANCE METHODS
================

*Pod::Parser* provides several methods, some of which should be overridden
by subclasses.  They are as follows:

new()
-----

This is the the constructor for the base class. You should only use it if
you want to create an instance of a *Pod::Parser* instead of one of its
subclasses. The constructor for this class and all of its subclasses
should return a blessed reference to an associative array (hash).

initialize()
------------

This method performs any necessary base class initialization.  It takes no
arguments (other than the object instance of course).  If subclasses
override this method then they *must* be sure to invoke the superclass'
initialize() method.

select($section_spec1, $section_spec2, ...)
-------------------------------------------

This is the method that is used to select the particular sections and
subsections of pod documentation that are to be printed and/or processed.
If the *first* *argument* is the string "+", then the remaining section
specifications are *added* to the current list of selections; otherwise
the given section specifications will replace the current list of
selections.

Each of the `$section_spec' arguments should be a section specification as
described in `"SECTION SPECIFICATIONS"' in this node.  The section
specifications are parsed by this method and the resulting regular
expressions are stored in the array referenced by `$self->{SELECTED}'
(please see the description of this member variable in `"INSTANCE DATA"'
in this node).

This method should *not* normally be overridden by subclasses.

want_section($head1_title, $head2_title, ...)
---------------------------------------------

Returns a value of true if the given section and subsection titles match
any of the section specifications passed to the *select()* method (or if
no section specifications were given). Returns a value of false otherwise.
If `$headN_title' is ommitted then it defaults to the current `headN'
section title in the input.

This method should *not* normally be overridden by subclasses.

begin_input()
-------------

This method is invoked by *parse_from_filehandle()* immediately *before*
processing input from a filehandle. The base class implementation does
nothing but subclasses may override it to perform any per-file
intializations.

end_input()
-----------

This method is invoked by *parse_from_filehandle()* immediately *after*
processing input from a filehandle. The base class implementation does
nothing but subclasses may override it to perform any per-file cleanup
actions.

preprocess_line($text)
----------------------

This methods should be overridden by subclasses that wish to perform any
kind of preprocessing for each *line* of input (*before* it has been
determined whether or not it is part of a pod paragraph). The parameter
`$text' is the input line and the value returned should correspond to the
new text to use in its place. If the empty string or an undefined value is
returned then no further process will be performed for this line. If
desired, this method can call the *parse_paragraph()* method directly with
any preprocessed text and return an empty string (to indicate that no
further processing is needed).

Please note that the *preprocess_line()* method is invoked *before* the
*preprocess_paragraph()* method. After all (possibly preprocessed) lines
in a paragraph have been assembled together and it has been determined
that the paragraph is part of the pod documentation from one of the
selected sections, then *preprocess_paragraph()* is invoked.

The base class implementation of this method returns the given text.

preprocess_paragraph($text)
---------------------------

This method should be overridden by subclasses that wish to perform any
kind of preprocessing for each block (paragraph) of pod documentation that
appears in the input stream.  The parameter `$text' is the pod paragraph
from the input file and the value returned should correspond to the new
text to use in its place.  If the empty string is returned or an undefined
value is returned, then the given `$text' is ignored (not processed).

This method is invoked by *parse_paragraph()*. After it returns,
*parse_paragraph()* examines the current cutting state (which is stored in
`$self->{CUTTING}'). If it evaluates to false then input text (including
the given `$text') is cut (not processed) until the next pod directive is
encountered.

Please note that the *preprocess_line()* method is invoked *before* the
*preprocess_paragraph()* method. After all (possibly preprocessed) lines
in a paragraph have been assembled together and it has been determined
that the paragraph is part of the pod documentation from one of the
selected sections, then *preprocess_paragraph()* is invoked.

The base class implementation of this method returns the given text.

parse_pragmas($cmd, $text, $sep)
--------------------------------

This method is called when an `=pod' directive is encountered. When such a
pod directive is seen in the input, this method is called and is passed
the command name `$cmd' (which should be "pod") and the remainder of the
text paragraph `$text' which appeared immediately after the command name.
If desired, the text which separated the `=pod' directive from its
corresponding text may be found in `$sep'.  Each word in `$text' is
examined to see if it is a pragma specification.  Pragma specifications
are of the form `pragma_name=pragma_value'.

Unless the given object is an instance of the *Pod::Parser* class, the
base class implementation of this method will invoke the *pragma()* method
for each pragma specification in `$text'.  *If and only if* the given
object *is* an instance of the *Pod::Parser* class, the base class version
of this method will simply reproduce the `=pod' command exactly as it
appeared in the input.

Derived classes should *not* usually need to reimplement this method.

pragma($pragma_name, $pragma_value)
-----------------------------------

This method is invoked for each pragma encountered inside an `=pod'
paragraph (see the description of the *parse_pragmas()* method). The
pragma name is passed in `$pragma_name' (which should always be lowercase)
and the corresponding value is `$pragma_value'.

The base class implementation of this method does nothing.  Derived class
implementations of this method should be able to recognize at least the
following pragmas and take any necessary actions when they are encountered:

fill=value
     The argument value should be one of `on', `off', or `previous'.
     Specifies that "filling-mode" should set to 1, 0, or its previous
     value (respectively). If value is omitted then the default is `on'.
     Derived classes may use this to decide whether or not to perform any
     filling (wrapping) of subsequent text.

style=value
     The argument value should be one of `bold', `italic', code, `plain',
     or `previous'. Specifies that the current default paragraph font
     should be set to `bold', `italic', code, the empty string , or its
     previous value (respectively).  If value is omitted then the default
     is `plain'.  Derived classes may use this to determine the default
     font style to use for subsequent text.

indent=value
     The argument value should be an integer value (with an optional
     sign).  Specifies that the current indentation level should be reset
     to the given value. If a plus (minus) sign precedes the number then
     the indentation level should be incremented (decremented) by the given
     number. If only a plus or minus sign is given (without a number) then
     the current indentation level is incremented or decremented by some
     default amount (to be determined by subclasses).

The value returned will be 1 if the pragma name was recognized and 0 if it
wasnt (in which case the pragma was ignored).

Derived classes should override this method if they wish to implement any
pragmas. The base class implementation of this method does nothing but it
does contain some commented-out code which subclasses may want to make use
of when implementing pragmas.

command($cmd, $text, $sep)
--------------------------

This method should be overridden by subclasses to take the appropriate
action when a pod command paragraph (denoted by a line beginning with "=")
is encountered.  When such a pod directive is seen in the input, this
method is called and is passed the command name `$cmd' and the remainder
of the text paragraph `$text' which appears immediately after the command
name. If desired, the text which separated the command from its
corresponding text may be found in `$sep'.  Note that this method is *not*
called for `=pod' paragraphs.

The base class implementation of this method simply prints the raw pod
command to the output filehandle and then invokes the *textblock()*
method, passing it the `$text' parameter.

verbatim($text)
---------------

This method may be overridden by subclasses to take the appropriate action
when a block of verbatim text is encountered. It is passed the text block
`$text' as a parameter.

The base class implementation of this method simply prints the textblock
(unmodified) to the output filehandle.

textblock($text)
----------------

This method may be overridden by subclasses to take the appropriate action
when a normal block of pod text is encountered (although the base class
method will usually do what you want). It is passed the text block `$text'
as a parameter.

In order to process interior sequences, subclasses implementations of this
method will probably want invoke the *interpolate()* method, passing it
the text block `$text' as a parameter and then perform any desired
processing upon the returned result.

The base class implementation of this method simply prints the text block
as it occurred in the input stream).

interior_sequence($seq_cmd, $seq_arg)
-------------------------------------

This method should be overridden by subclasses to take the appropriate
action when an interior sequence is encountered. An interior sequence is
an embedded command within a block of text which appears as a command name
(usually a single uppercase character) followed immediately by a string of
text which is enclosed in angle brackets. This method is passed the
sequence command `$seq_cmd' and the corresponding text $seq_arg and is
invoked by the *interpolate()* method for each interior sequence that
occurs in the string that it is passed.  It should return the desired text
string to be used in place of the interior sequence.

Subclass implementationss of this method may wish to examine the the array
referenced by `$self->{SEQUENCES}' which is a stack of all the interior
sequences that are currently being processed (they may be nested). The
current interior sequence (the one given by `$seq_cmd<$seq_arg>') should
always be at the top of this stack.

The base class implementation of the *interior_sequence()* method simply
returns the raw text of the of the interior sequence (as it occurred in
the input) to the output filehandle.

interpolate($text, $end_re)
---------------------------

This method will translate all text (including any embedded interior
sequences) in the given text string `$text' and return the interpolated
result.  If a second argument is given, then it is taken to be a regular
expression that indicates when to quit interpolating the string.  Upon
return, the `$text' parameter will have been modified to contain only the
un-processed portion of the given string (which will *not* contain any
text matched by `$end_re').

This method should probably *not* be overridden by subclasses.  It should
be noted that this method invokes itself recursively to handle any nested
interior sequences.

parse_paragraph($text)
----------------------

This method takes the text of a pod paragraph to be processed and invokes
the appropriate method (one of *command()*, *verbatim()*, or
*textblock()*).

This method does *not* usually need to be overridden by subclasses.

parse_from_filehandle($infilehandle, $outfilehandle)
----------------------------------------------------

This method takes a glob to a filehandle (which is assumed to already be
opened for reading) and reads the entire input stream looking for blocks
(paragraphs) of pod documentation to be processed. For each block of pod
documentation encountered it will call the *parse_paragraph()* method.

If a second argument is given then it should be a filehandle glob where
output should be sent (otherwise the default output filehandle is
`STDOUT'). If no first argument is given the default input filehandle
`STDIN' is used.

The input filehandle that is currently in use is stored in the member
variable whose key is "INPUT" (e.g. `$self->{INPUT}').

The output filehandle that is currently in use is stored in the member
variable whose key is "OUTPUT" (e.g. `$self->{OUTPUT}').

Input is read line-by-line and assembled into paragraphs (which are
separated by lines containing nothing but whitespace). The current line
number is stored in the member variable whose key is "LINE" (e.g.
`$self->{LINE}') and the current paragraph number is stored in the member
variable whose key is "PARAGRAPH" (e.g.  `$self->{PARAGRAPH}').

This method does *not* usually need to be overridden by subclasses.

parse_from_file($filename, $outfile)
------------------------------------

This method takes a filename and does the following:

   * opens the input and output files for reading (creating the
     appropriate filehandles)

   * invokes the *parse_from_filehandle()* method passing it the
     corresponding input and output filehandles.

   * closes the input and output files.

If the special input filename "-" or "<&STDIN" is given then the STDIN
filehandle is used for input (and no open or close is performed).  If no
input filename is specified then "-" is implied.  If a reference is passed
instead of a filename then it is assumed to be a glob-style reference to a
filehandle.

If a second argument is given then it should be the name of the desired
output file.  If the special output filename "-" or ">&STDOUT" is given
then the STDOUT filehandle is used for output (and no open or close is
performed). If the special output filename ">&STDERR" is given then the
STDERR filehandle is used for output (and no open or close is performed).
If no output filename is specified then "-" is implied.  If a reference is
passed instead of a filename then it is assumed to be a glob-style
reference to a filehandle.

The name of the input file that is currently being read is stored in the
member variable whose key is "INFILE" (e.g. `$self->{INFILE}').

The name of the output file that is currently being written is stored in
the member variable whose key is "OUTFILE" (e.g.  `$self->{OUTFILE}').

This method does *not* usually need to be overridden by subclasses.

INSTANCE DATA
=============

*Pod::Parser* uses the following data members for each of its instances
(where `$self' is a reference to such an instance):

$self->{INPUT}
--------------

The current input filehandle.

$self->{OUTPUT}
---------------

The current output filehandle.

$self->{INFILE}
---------------

The name of the current input file.

$self->{OUTFILE}
----------------

The name of the current output file.

$self->{LINE}
-------------

The current line number from the input stream.

$self->{PARAGRAPH}
------------------

The current paragraph number from the input stream (which includes input
paragraphs that are *not* part of the pod documentation).

$self->{HEADINGS}
-----------------

A reference to an array of the current section heading titles for each
heading level (note that the first heading level title is at index 0).

$self->{SELECTED}
-----------------

A reference to an array of references to arrays. Each subarray is a list
of anchored regular expressions (preceded by a "!" if the regexp is to be
negated). The index of the expression in the subarray should correspond to
the index of the heading title in *$self->{HEADINGS}* that it is to be
matched against.

$self->{CUTTING}
----------------

A boolean-valued scalar which evaluates to true if text from the input
file is currently being "cut".

$self->{SEQUENCES}
------------------

An array reference to the stack of interior sequence commands that are
currently in the middle of being processed.

NOTES
=====

To create a pod translator to translate pod documentation to some other
format, you usually only need to create a subclass of *Pod::Parser* which
overrides the base class implementation for the following methods:

   * *pragma()*

   * *command()*

   * *verbatim()*

   * *textblock()*

   * *interior_sequence()*

You may also want to implement the begin_input() and end_input() methods
for your subclass (to perform any needed per-file intialization or
cleanup).

If you need to perform any preprocesssing of input before it is parsed you
may want to implement one or both of the *preprocess_line()* and/or
*preprocess_paragraph()* methods.

Also, don't forget to make sure your subclass constructor invokes the base
class' initialize() method.

Sometimes it may be necessary to make more than one pass over the input
files. This isn't a problem as long as none of the input files correspond
to `STDIN'. You can override either the *parse_from_filehandle()* method
or the *parse_from_file()* method to make the first pass yourself to
collect all the information you need and then invoke the base class method
to do the rest of the standard processing.

Feel free to add any member data fields you need to keep track of things
like current font, indentation, horizontal or vertical position, or
whatever else you like.

For the most part, the *Pod::Parser* base class should be able to do most
of the input parsing for you and leave you free to worry about how to
intepret the commands and translate the result.

AUTHOR
======

Brad Appleton <Brad_Appleton-GBDA001@email.mot.com>

Based on code for *Pod::Text* written by Tom Christiansen
<tchrist@mox.perl.com>


File: pm.info,  Node: Pod/Select,  Next: Pod/Text,  Prev: Pod/Parser,  Up: Module List

function to extract selected sections of pod documentation
**********************************************************

NAME
====

podselect - function to extract selected sections of pod documentation

SYNOPSIS
========

     use Pod::Select;
     podselect (@filelist);
     podselect ({OUTPUT => "tmp.out"}, @filelist):
     podselect ({SELECT => ["NAME|SYNOPSIS", "OPTIONS"]}, @filelist):
     podselect ({OUTPUT => ">&STDERR", SELECT => ["DESCRIPTION"]}, "-");

DESCRIPTION
===========

*podselect()* is a function which will extract specified sections of pod
documentation from an input stream. This ability is already provided in
the *Pod::Parser* module. Subclasses of *Pod::Parser* that wish to take
advantage of this feature do *not* need to derive from *Pod::Select*.
*Pod::Select* merely provides a single function named *podselect()* which
provides this capability in function form (as opposed to object form) for
extracting the raw pod docs.

podselect(\%options, @filelist)
-------------------------------

*podselect* will print the raw (untranslated) pod documentation of all pod
sections in the given input files specified by `@filelist' according to
the given options.

If any argument to *podselect* is a reference to a hash (associative
array) then the values with the following keys are processed as follows:

OUTPUT
     A string corresponding to the desired output file (or ">&STDOUT" or
     ">&STDERR"). The default is to use standard output.

`SELECT'
     A reference to an array of sections specifications (as described in
     `"SECTION SPECIFICATIONS"', *Note Pod/Parser: Pod/Parser,) which
     indicate the desired set of pod sections and subsections to be
     selected from input. If no section specifications are given, then all
     sections of pod documentation are used.

All other arguments should correspond to the names of input files
containing pod documentation. A file name of "-" or "<&STDIN" will be
interpeted to mean standard input (which is the default if no filenames
are given).

SEE ALSO
========

*Note Pod/Parser: Pod/Parser,

AUTHOR
======

Brad Appleton <Brad_Appleton-GBDA001@email.mot.com>

Based on code for *pod2text* written by Tom Christiansen
<tchrist@mox.perl.com>


File: pm.info,  Node: Pod/Text,  Next: Pod/Usage,  Prev: Pod/Select,  Up: Module List

convert POD data to formatted ASCII text
****************************************

NAME
====

Pod::Text - convert POD data to formatted ASCII text

SYNOPSIS
========

     use Pod::Text;

     pod2text("perlfunc.pod");

Also:

     pod2text < input.pod

DESCRIPTION
===========

Pod::Text is a module that can convert documentation in the POD format
(such as can be found throughout the Perl distribution) into formatted
ASCII.  Termcap is optionally supported for boldface/underline, and can
enabled via `$Pod::Text::termcap=1'. If termcap has not been enabled, then
backspaces will be used to simulate bold and underlined text.

A separate `pod2text' program is included that is primarily a wrapper for
Pod::Text.

The single function `pod2text()' can take one or two arguments. The first
should be the name of a file to read the pod from, or "<&STDIN" to read
from STDIN. A second argument, if provided, should be a filehandle glob
where output should be sent.

AUTHOR
======

Tom Christiansen <`tchrist@mox.perl.com'>

TODO
====

Cleanup work. The input and output locations need to be more flexible,
termcap shouldn't be a global variable, and the terminal speed needs to be
properly calculated.


File: pm.info,  Node: Pod/Usage,  Next: Pod/foo,  Prev: Pod/Text,  Up: Module List

print a usage message using a script's embedded pod documentation
*****************************************************************

NAME
====

pod2usage - print a usage message using a script's embedded pod
documentation

SYNOPSIS
========

     use Pod::Usage;
     pod2usage();
     pod2usage(2);
     pod2usage({EXIT => 2});
     pod2usage({EXIT => 2, VERBOSE => 0});
     pod2usage(EXIT => 1, VERBOSE => 2, OUTPUT=\*STDERR);
     pod2usage(VERBOSE => 2);

DESCRIPTION
===========

*pod2usage* will print a usage message for the invoking script (using its
embedded pod documentation) and then exit the script with the specified
exit value. It takes a single argument which is either a numeric value
corresponding to the desired exit status (which defaults to 2), or a
reference to a hash. If more than one argument is given then the entire
argument list is assumed to be a hash. If a hash is supplied it should
contain elements with one or more of the following keys:

`EXIT'
     The desired exit status to pass to the *exit()* function.

`VERBOSE'
     The desired level of "verboseness" to use when printing the usage
     message. If the corresponding value is 0, then only the "SYNOPSIS"
     section of the pod documentation is printed. If the corresponding
     value is 1, then the "SYNOPSIS" section, along with any section
     entitled "OPTIONS", "ARGUMENTS", or "OPTIONS AND ARGUMENTS" is
     printed.  If the corresponding value is 2 or more then the entire
     manpage is printed.

OUTPUT
     A reference to a filehandle, or the pathname of a file to which the
     usage message should be written. The default is `\*STDERR' unless the
     exit value is less than 2 (in which case the default is `\*STDOUT').

INPUT
     A reference to a filehandle, or the pathname of a file from which the
     invoking script's pod documentation should be read.  It defaults to
     the file indicated by $0 ($PROGRAM_NAME for `use English;' users).

If neither the exit value nor the verbose level is specified, then the
default is to use an exit value of 2 with a verbose level of 0.

If an exit value is specified but the verbose level is not, then the
verbose level will default to 1 if the exit value is less than 2 and will
default to 0 otherwise.

If a verbose level is specified but an exit value is not, then the exit
value will default to 2 if the verbose level is 0 and will default to 1
otherwise.

EXAMPLE
=======

Most scripts should print some type of usage message to STDERR when a
command line syntax error is detected. They should also provide an option
(usually -h or `-help') to print a (possibly more verbose) usage message
to STDOUT. Some scripts may even wish to go so far as to provide a means
of printing their complete documentation to STDOUT (perhaps by allowing a
`-man' option). The following example uses *pod2usage* in combination with
Getopt::Long to do all of these things:

     use Pod::Usage;
     use Getopt::Long;

     GetOptions("help", "man")  ||  pod2usage(2);
     pod2usage(1)  if ($opt_help);
     pod2usage(VERBOSE => 2)  if ($opt_man);

CAVEATS
=======

By default, *pod2usage()* will use $0 as the path to the pod input file.
Unfortunately, not all systems on which Perl runs will set $0 properly
(although if $0 isn't found, *pod2usage()* will search `$ENV{PATH}').  If
this is the case for your system, you may need to explicitly specify the
path to the pod docs for the invoking script using something similar to
the following:


     `pod2usage(EXIT => 2, INPUT => "/path/to/your/pod/docs");'

AUTHOR
======

Brad Appleton <Brad_Appleton-GBDA001@email.mot.com>

Based on code for *Pod::Text::pod2text()* written by Tom Christiansen
<tchrist@mox.perl.com>


File: pm.info,  Node: Pod/foo,  Next: Pod/newrun,  Prev: Pod/Usage,  Up: Module List

perlvar - Perl predefined variables

The following names have special meaning to Perl. Most of the
punctuational names have reasonable mnemonics, or analogues in one of the
shells. Nevertheless, if you wish to use the long variable names, you just
need to say

     use English;

at the top of your program. This will alias all the short names to the
long names in the current package. Some of them even have medium names,
generally borrowed from *awk*.

To go a step further, those variables that depend on the currently
selected filehandle may instead be set by calling an object method on the
FileHandle object. (Summary lines below for this contain the word HANDLE.)
First you must say

     use FileHandle;

after which you may use either

     method HANDLE EXPR

or

     HANDLE->method(EXPR)

Each of the methods returns the old value of the FileHandle attribute. The
methods each take an optional EXPR, which if supplied specifies the new
value for the FileHandle attribute in question. If not supplied, most of
the methods do nothing to the current value, except for *autoflush()*,
which will assume a 1 for you, just to be different.

A few of these variables are considered "read-only". This means that if
you try to assign to this variable, either directly or indirectly through
a reference, you'll raise a run-time exception.

X<$ARG>
X<$_>
     The default input and pattern-searching space. The following pairs are
     equivalent:

          while (<>) {...}    # only equivalent in while!
          while ($_ = <>) {...}

          /^Subject:/
          $_ =~ /^Subject:/

          tr/a-z/A-Z/
          $_ =~ tr/a-z/A-Z/

          chop
          chop($_)

     Here are the places where Perl will assume $_ even if you don't use
     it:


     Various unary functions, including functions like *ord()* and *int()*,
     as well as the all file tests (`-f', -d) except for `-t', which
     defaults to STDIN.


     Various list functions like *print()* and *unlink()*.


     The pattern matching operations m//, s///, and tr/// when used
     without an `=~' operator.


     The default iterator variable in a `foreach' loop if no other
     variable is supplied.


     The implicit iterator variable in the *grep()* and *map()* functions.


     The default place to put an input record when a `<FH>' operation's
     result is tested by itself as the sole criterion of a `while' test.
     Note that outside of a `while' test, this will not happen.

     (Mnemonic: underline is understood in certain operations.)

X<$<*digit*;$<digit>>
     Contains the subpattern from the corresponding set of parentheses in
     the last pattern matched, not counting patterns matched in nested
     blocks that have been exited already. (Mnemonic: like \digit.) These
     variables are all read-only.

X<$MATCH>
X<$&>
     The string matched by the last successful pattern match (not counting
     any matches hidden within a BLOCK or *eval()* enclosed by the current
     BLOCK). (Mnemonic: like & in some editors.) This variable is
     read-only.

X<$PREMATCH>
X<$`>
     The string preceding whatever was matched by the last successful
     pattern match (not counting any matches hidden within a BLOCK or eval
     enclosed by the current BLOCK). (Mnemonic: ` often precedes a quoted
     string.) This variable is read-only.

X<$POSTMATCH>
X<$'>
     The string following whatever was matched by the last successful
     pattern match (not counting any matches hidden within a BLOCK or
     *eval()* enclosed by the current BLOCK). (Mnemonic: ' often follows a
     quoted string.) Example:

          $_ = 'abcdefghi';
          /def/;
          print "$`:$&:$'\n";         # prints abc:def:ghi

     This variable is read-only.

X<$LAST_PAREN_MATCH>
X<$+>
     The last bracket matched by the last search pattern. This is useful
     if you don't know which of a set of alternative patterns matched. For
     example:

          /Version: (.*)|Revision: (.*)/ && ($rev = $+);

     (Mnemonic: be positive and forward looking.) This variable is
     read-only.

X<$MULTILINE_MATCHING>

     Set to 1 to do multiline matching within a string, 0 to tell Perl
     that it can assume that strings contain a single line, for the
     purpose of optimizing pattern matches. Pattern matches on strings
     containing multiple newlines can produce confusing results when $* is
     0. Default is 0.  (Mnemonic: * matches multiple things.) Note that
     this variable only influences the interpretation of `^' and `$'. A
     literal newline can be searched for even when `$* == 0'.

     Use of $* is deprecated in Perl 5.

X<input_line_number> HANDLE EXPR
X<$INPUT_LINE_NUMBER>
X<$NR>
X<$.>
     The current input line number of the last filehandle that was read. An
     explicit close on the filehandle resets the line number. Since `<>'
     never does an explicit close, line numbers increase across ARGV files
     (but see examples under *eof()*). Localizing $. has the effect of also
     localizing Perl's notion of "the last read filehandle". (Mnemonic:
     many programs use "." to mean the current line number.)

X<input_record_separator> HANDLE EXPR
X<$INPUT_RECORD_SEPARATOR>
X<$RS>
X<$/>
     The input record separator, newline by default. Works like *awk*'s RS
     variable, including treating blank lines as delimiters if set to the
     null string. You may set it to a multicharacter string to match a
     multi-character delimiter. Note that setting it to `"\n\n"' means
     something slightly different than setting it to `""', if the file
     contains consecutive blank lines. Setting it to `""' will treat two or
     more consecutive blank lines as a single blank line. Setting it to
     `"\n\n"' will blindly assume that the next input character belongs to
     the next paragraph, even if it's a newline. (Mnemonic: / is used to
     delimit line boundaries when quoting poetry.)

          undef $/;
          $_ = <FH>;          # whole file now here
          s/\n[ \t]+/ /g;

X<autoflush> HANDLE EXPR
X<$OUTPUT_AUTOFLUSH>
X<$|>
     If set to nonzero, forces a flush after every write or print on the
     currently selected output channel. Default is 0. Note that STDOUT will
     typically be line buffered if output is to the terminal and block
     buffered otherwise. Setting this variable is useful primarily when
     you are outputting to a pipe, such as when you are running a Perl
     script under rsh and want to see the output as it's happening. This
     has no effect on input buffering. (Mnemonic: when you want your pipes
     to be piping hot.)

X<output_field_separator> HANDLE EXPR
X<$OUTPUT_FIELD_SEPARATOR>
X<$OFS>
X<$,>
     The output field separator for the print operator. Ordinarily the
     print operator simply prints out the comma separated fields you
     specify. In order to get behavior more like *awk*, set this variable
     as you would set *awk*'s OFS variable to specify what is printed
     between fields.  (Mnemonic: what is printed when there is a , in your
     print statement.)

X<output_record_separator> HANDLE EXPR
X<$OUTPUT_RECORD_SEPARATOR>
X<$ORS>
X<$\>
     The output record separator for the print operator. Ordinarily the
     print operator simply prints out the comma separated fields you
     specify, with no trailing newline or record separator assumed. In
     order to get behavior more like *awk*, set this variable as you would
     set *awk*'s ORS variable to specify what is printed at the end of the
     print. (Mnemonic: you set $\ instead of adding \n at the end of the
     print. Also, it's just like /, but it's what you get "back" from
     Perl.)

X<$LIST_SEPARATOR>
X<$">
     This is like $, except that it applies to array values interpolated
     into a double-quoted string (or similar interpreted string). Default
     is a space. (Mnemonic: obvious, I think.)

X<$SUBSCRIPT_SEPARATOR>
X<$SUBSEP>
X<$;>
     The subscript separator for multi-dimensional array emulation. If you
     refer to a hash element as

          $foo{$a,$b,$c}

     it really means

          $foo{join($;, $a, $b, $c)}

     But don't put

          @foo{$a,$b,$c}      # a slice--note the @

     which means

          ($foo{$a},$foo{$b},$foo{$c})

     Default is "\034", the same as SUBSEP in *awk*. Note that if your keys
     contain binary data there might not be any safe value for $;.
     (Mnemonic: comma (the syntactic subscript separator) is a
     semi-semicolon.  Yeah, I know, it's pretty lame, but $, is already
     taken for something more important.)

     Consider using "real" multi-dimensional arrays in Perl 5.

X<$OFMT>
X<$#>
     The output format for printed numbers. This variable is a half-hearted
     attempt to emulate *awk*'s OFMT variable. There are times, however,
     when *awk* and Perl have differing notions of what is in fact
     numeric. Also, the initial value is %.20g rather than %.6g, so you
     need to set $# explicitly to get *awk*'s value. (Mnemonic: # is the
     number sign.)

     Use of $# is deprecated in Perl 5.

X<format_page_number> HANDLE EXPR
X<$FORMAT_PAGE_NUMBER>
X<$%>
     The current page number of the currently selected output channel.
     (Mnemonic: % is page number in *nroff*.)

X<format_lines_per_page> HANDLE EXPR
X<$FORMAT_LINES_PER_PAGE>
X<$=>
     The current page length (printable lines) of the currently selected
     output channel. Default is 60. (Mnemonic: = has horizontal lines.)

X<format_lines_left> HANDLE EXPR
X<$FORMAT_LINES_LEFT>
X<$->
     The number of lines left on the page of the currently selected output
     channel. (Mnemonic: lines_on_page - lines_printed.)

X<format_name> HANDLE EXPR
X<$FORMAT_NAME>
X<$~>
     The name of the current report format for the currently selected
     output channel. Default is name of the filehandle. (Mnemonic: brother
     to $^.)

X<format_top_name> HANDLE EXPR
X<$FORMAT_TOP_NAME>
X<$^>
     The name of the current top-of-page format for the currently selected
     output channel. Default is name of the filehandle with _TOP appended.
     (Mnemonic: points to top of page.)

X<format_line_break_characters> HANDLE EXPR
X<$FORMAT_LINE_BREAK_CHARACTERS>
X<$:>
     The current set of characters after which a string may be broken to
     fill continuation fields (starting with ^) in a format. Default is
     " \n-", to break on whitespace or hyphens. (Mnemonic: a "colon" in
     poetry is a part of a line.)

X<format_formfeed> HANDLE EXPR
X<$FORMAT_FORMFEED>
X<$^L>
     What formats output to perform a formfeed. Default is \f.

X<$ACCUMULATOR>
X<$^A>
     The current value of the *write()* accumulator for format() lines. A
     format contains *formline()* commands that put their result into $^A.
     After calling its format, *write()* prints out the contents of $^A
     and empties. So you never actually see the contents of $^A unless you
     call *formline()* yourself and then look at it. See
     L<ARRAY(0xd73c0)<>> and L<ARRAY(0xd7054)<>>.

X<$CHILD_ERROR>
X<$?>
     The status returned by the last pipe close, backtick (```') command,
     or *system()* operator. Note that this is the status word returned by
     the *wait()* system call, so the exit value of the subprocess is
     actually (`$? >> 8'). Thus on many systems, `$? & 255' gives which
     signal, if any, the process died from, and whether there was a core
     dump. (Mnemonic: similar to *sh* and *ksh*.)

X<$OS_ERROR>
X<$ERRNO>
X<$!>
     If used in a numeric context, yields the current value of errno, with
     all the usual caveats. (This means that you shouldn't depend on the
     value of $!  to be anything in particular unless you've gotten a
     specific error return indicating a system error.) If used in a string
     context, yields the corresponding system error string. You can assign
     to $! in order to set errno if, for instance, you want $! to return
     the string for error n, or you want to set the exit value for the
     *die()* operator. (Mnemonic: What just went bang?)

X<$EVAL_ERROR>
X<$@>
     The Perl syntax error message from the last *eval()* command. If null,
     the last *eval()* parsed and executed correctly (although the
     operations you invoked may have failed in the normal fashion).
     (Mnemonic: Where was the syntax error "at"?)

     Note that warning messages are not collected in this variable. You
     can, however, set up a routine to process warnings by setting
     `$SIG'{__WARN__} below.

X<$PROCESS_ID>
X<$PID>
X<$$>
     The process number of the Perl running this script. (Mnemonic: same as
     shells.)

X<$REAL_USER_ID>
X<$UID>
X<$<;$<>
     The real uid of this process. (Mnemonic: it's the uid you came
     *FROM*, if you're running setuid.)

X<$EFFECTIVE_USER_ID>
X<$EUID>
X<$>>
     The effective uid of this process. Example:

          $< = $>;       # set real to effective uid
          ($<,$>) = ($>,$<);  # swap real and effective uid

     (Mnemonic: it's the uid you went *TO*, if you're running setuid.)
     Note: `$<' and `$>' can only be swapped on machines supporting
     *setreuid()*.

X<$REAL_GROUP_ID>
X<$GID>
X<$(>
     The real gid of this process. If you are on a machine that supports
     membership in multiple groups simultaneously, gives a space separated
     list of groups you are in. The first number is the one returned by
     *getgid()*, and the subsequent ones by *getgroups()*, one of which
     may be the same as the first number. (Mnemonic: parentheses are used
     to *GROUP* things.  The real gid is the group you *LEFT*, if you're
     running setgid.)

X<$EFFECTIVE_GROUP_ID>
X<$EGID>
X<$)>
     The effective gid of this process. If you are on a machine that
     supports membership in multiple groups simultaneously, gives a space
     separated list of groups you are in. The first number is the one
     returned by *getegid()*, and the subsequent ones by *getgroups()*,
     one of which may be the same as the first number. (Mnemonic:
     parentheses are used to *GROUP* things.  The effective gid is the
     group that's *RIGHT* for you, if you're running setgid.)

     Note: `$<', `$>', $( and $) can only be set on machines that support
     the corresponding *set[re][ug]*id()** routine. $( and $) can only be
     swapped on machines supporting *setregid()*. Because Perl doesn't
     currently use *initgroups()*, you can't set your group vector to
     multiple groups.

X<$PROGRAM_NAME>
X<$0>
     Contains the name of the file containing the Perl script being
     executed.  Assigning to $0 modifies the argument area that the
     *ps(1)* program sees. This is more useful as a way of indicating the
     current program state than it is for hiding the program you're
     running. (Mnemonic: same as *sh* and *ksh*.)

X<$[>
     The index of the first element in an array, and of the first
     character in a substring. Default is 0, but you could set it to 1 to
     make Perl behave more like *awk* (or Fortran) when subscripting and
     when evaluating the *index()* and *substr()* functions. (Mnemonic: [
     begins subscripts.)

     As of Perl 5, assignment to $[ is treated as a compiler directive, and
     cannot influence the behavior of any other file. Its use is
     discouraged.

X<$PERL_VERSION>
X<$]>
     The string printed out when you say `perl -v'. (This is currently
     *BROKEN*).  It can be used to determine at the beginning of a script
     whether the perl interpreter executing the script is in the right
     range of versions. If used in a numeric context, returns the version
     + patchlevel / 1000.  Example:

          # see if getc is available
          ($version,$patchlevel) =
                   $] =~ /(\d+\.\d+).*\nPatch level: (\d+)/;
          print STDERR "(No filename completion available.)\n"
                   if $version * 1000 + $patchlevel < 2016;

     or, used numerically,

          warn "No checksumming!\n" if $] < 3.019;

     (Mnemonic: Is this version of perl in the right bracket?)

X<$DEBUGGING>
X<$^D>
     The current value of the debugging flags. (Mnemonic: value of
     -D;switches/-D;-D switch.)

X<$SYSTEM_FD_MAX>
X<$^F>
     The maximum system file descriptor, ordinarily 2. System file
     descriptors are passed to *exec()*ed processes, while higher file
     descriptors are not. Also, during an *open()*, system file
     descriptors are preserved even if the *open()* fails. (Ordinary file
     descriptors are closed before the *open()* is attempted.) Note that
     the close-on-exec status of a file descriptor will be decided
     according to the value of $^F at the time of the open, not the time
     of the exec.

X<$INPLACE_EDIT>
X<$^I>
     The current value of the inplace-edit extension. Use undef to disable
     inplace editing. (Mnemonic: value of -i;switches/-i;-i switch.)

X<$PERLDB>
X<$^P>
     The internal flag that the debugger clears so that it doesn't debug
     itself. You could conceivable disable debugging yourself by clearing
     it.

X<$BASETIME>
X<$^T>
     The time at which the script began running, in seconds since the epoch
     (beginning of 1970). The values returned by the -M;switches/-M;-M,
     -A;switches/-A;-A and -C;switches/-C;-C filetests are based on this
     value.

X<$WARNING>
X<$^W>
     The current value of the warning switch, either TRUE or FALSE.
     (Mnemonic: related to the -w;switches/-w;-w switch.)

X<$EXECUTABLE_NAME>
X<$^X>
     The name that the Perl binary itself was executed as, from C's
     `argv[0]'.

X<$ARGV>
     contains the name of the current file when reading from <>.

X<@ARGV>
     The array `@ARGV' contains the command line arguments intended for the
     script. Note that `$#ARGV' is the generally number of arguments minus
     one, since `$ARGV[0]' is the first argument, *NOT* the command name.
     See $0 for the command name.

X<@INC>
     The array `@INC' contains the list of places to look for Perl scripts
     to be evaluated by the `do EXPR', require, or use constructs. It
     initially consists of the arguments to any -I;switches/-I;-I command
     line switches, followed by the default Perl library, probably
     "/usr/local/lib/perl", followed by ".", to represent the current
     directory. If you need to modify this at runtime, you should use the
     `use lib' pragma in order to also get the machine-dependent library
     properly loaded:

          use lib '/mypath/libdir/';
          use SomeMod;

X<%INC>
     The hash %INC contains entries for each filename that has been
     included via do or require. The key is the filename you specified,
     and the value is the location of the file actually found. The require
     command uses this array to determine whether a given file has already
     been included.

X<$ENV{expr}>
     The hash `%ENV' contains your current environment. Setting a value in
     `ENV' changes the environment for child processes.

X<$SIG{expr}>
     The hash `%SIG' is used to set signal handlers for various signals.
     Example:

          sub handler {       # 1st argument is signal name
              local($sig) = @_;
              print "Caught a SIG$sig--shutting down\n";
              close(LOG);
              exit(0);
          }

          $SIG{'INT'} = 'handler';
          $SIG{'QUIT'} = 'handler';
          ...
          $SIG{'INT'} = 'DEFAULT';    # restore default action
          $SIG{'QUIT'} = 'IGNORE';    # ignore SIGQUIT

     The `%SIG' array only contains values for the signals actually set
     within the Perl script. Here are some other examples:

          $SIG{PIPE} = Plumber;       # SCARY!!
          $SIG{"PIPE"} = "Plumber";   # just fine, assumes main::Plumber
          $SIG{"PIPE"} = \&Plumber;   # just fine; assume current Plumber
          $SIG{"PIPE"} = Plumber();   # oops, what did Plumber() return??

     The one marked scary is problematic because it's a bareword, which
     means sometimes it's a string representing the function, and
     sometimes it's going to call the subroutine call right then and
     there! Best to be sure and quote it or take a reference to it.
     *Plumber works too. See L<ARRAY(0xd7228)<>>.

     Certain internal hooks can be also set using the `%SIG' hash. The
     routine indicated by `$SIG'{__WARN__} is called when a warning message
     is about to be printed. The warning message is passed as the first
     argument. The presence of a __WARN__ hook causes the ordinary
     printing of warnings to STDERR to be suppressed. You can use this to
     save warnings in a variable, or turn warnings into fatal errors, like
     this:

          local $SIG{__WARN__} = sub { die $_[0] };
          eval $proggie;

     The routine indicated by `$SIG'{__DIE__} is called when a fatal
     exception is about to be thrown. The error message is passed as the
     first argument. When a __DIE__ hook routine returns, the exception
     processing continues as it would have in the absence of the hook,
     unless the hook routine itself exits via a goto, a loop exit, or a
     *die()*. The __DIE__ handler is explicitly disabled during the call,
     so that you can die from a __DIE__ handler. Similarly for __WARN__.


File: pm.info,  Node: Pod/newrun,  Next: Pod/newvar,  Prev: Pod/foo,  Up: Module List

how to execute the Perl interpreter
***********************************

NAME
====

perlrun - how to execute the Perl interpreter

SYNOPSIS
========

*perl* [switches] filename args

DESCRIPTION
===========

Upon startup, Perl looks for your script in one of the following places:

  1. Specified line by line via -e switches on the command line.

  2. Contained in the file specified by the first filename on the command
     line.  (Note that systems supporting the #! notation invoke
     interpreters this way.)

  3. Passed in implicitly via standard input.  This only works if there are
     no filename arguments-to pass arguments to a STDIN script you must
     explicitly specify a "-" for the script name.

     With methods 2 and 3, Perl starts parsing the input file from the
beginning, unless you've specified a -x switch, in which case it scans for
the first line starting with #! and containing the word "perl", and starts
there instead.  This is useful for running a script embedded in a larger
message.  (In this case you would indicate the end of the script using the
__END__ token.)

As of Perl 5, the #! line is always examined for switches as the line is
being parsed.  Thus, if you're on a machine that only allows one argument
with the #! line, or worse, doesn't even recognize the #! line, you still
can get consistent switch behavior regardless of how Perl was invoked,
even if -x was used to find the beginning of the script.

Because many operating systems silently chop off kernel interpretation of
the #! line after 32 characters, some switches may be passed in on the
command line, and some may not; you could even get a "-" without its
letter, if you're not careful.  You probably want to make sure that all
your switches fall either before or after that 32 character boundary.
Most switches don't actually care if they're processed redundantly, but
getting a - instead of a complete switch could cause Perl to try to
execute standard input instead of your script.  And a partial -I switch
could also cause odd results.

Parsing of the #! switches starts wherever "perl" is mentioned in the line.
The sequences "-*" and "- " are specifically ignored so that you could, if
you were so inclined, say

     #!/bin/sh -- # -*- perl -*- -p
     eval 'exec perl $0 -S ${1+"$@"}'
     	if 0;

to let Perl see the -p switch.

If the #! line does not contain the word "perl", the program named after
the #! is executed instead of the Perl interpreter.  This is slightly
bizarre, but it helps people on machines that don't do #!, because they
can tell a program that their SHELL is /usr/bin/perl, and Perl will then
dispatch the program to the correct interpreter for them.

After locating your script, Perl compiles the entire script to an internal
form.  If there are any compilation errors, execution of the script is not
attempted.  (This is unlike the typical shell script, which might run
partway through before finding a syntax error.)

If the script is syntactically correct, it is executed.  If the script
runs off the end without hitting an exit() or die() operator, an implicit
`exit(0)' is provided to indicate successful completion.

Switches
--------

A single-character switch may be combined with the following switch, if
any.

     #!/usr/bin/perl -spi.bak	# same as -s -p -i.bak

Switches include:

-0*digits*
     specifies the record separator ($/) as an octal number.  If there are
     no digits, the null character is the separator.  Other switches may
     precede or follow the digits.  For example, if you have a version of
     *find* which can print filenames terminated by the null character, you
     can say this:

          find . -name '*.bak' -print0 | perl -n0e unlink

     The special value 00 will cause Perl to slurp files in paragraph mode.
     The value 0777 will cause Perl to slurp files whole since there is no
     legal character with that value.

-a
     turns on autosplit mode when used with a -n or -p.  An implicit split
     command to the @F array is done as the first thing inside the
     implicit while loop produced by the -n or -p.

          perl -ane 'print pop(@F), "\n";'

     is equivalent to

          while (<>) {
          	@F = split(' ');
          	print pop(@F), "\n";
          }

     An alternate delimiter may be specified using -F.

-c
     causes Perl to check the syntax of the script and then exit without
     executing it.  Actually, it will execute BEGIN and use blocks, since
     these are considered part of the compilation.

-d
     runs the script under the Perl debugger.  See *Note Perldebug:
     (perl.info)perldebug,.

-Dnumber
-Dlist
     sets debugging flags.  To watch how it executes your script, use
     *-D14*.  (This only works if debugging is compiled into your Perl.)
     Another nice value is *-D1024*, which lists your compiled syntax
     tree.  And *-D512* displays compiled regular expressions. As an
     alternative specify a list of letters instead of numbers (e.g. *-D14*
     is equivalent to *-Dtls*):

          1  p  Tokenizing and Parsing
          2  s  Stack Snapshots
          4  l  Label Stack Processing
          8  t  Trace Execution
                 16  o  Operator Node Construction
                 32  c  String/Numeric Conversions
                 64  P  Print Preprocessor Command for -P
                128  m  Memory Allocation
                256  f  Format Processing
                512  r  Regular Expression Parsing
               1024  x  Syntax Tree Dump
               2048  u  Tainting Checks
               4096  L  Memory Leaks (not supported anymore)
               8192  H  Hash Dump -- usurps values()
              16384  X  Scratchpad Allocation
              32768  D  Cleaning Up

-e *commandline*
     may be used to enter one line of script.  If -e is given, Perl will
     not look for a script filename in the argument list.  Multiple -e
     commands may be given to build up a multi-line script.  Make sure to
     use semicolons where you would in a normal program.

-Fregexp
     specifies a regular expression to split on if -a is also in effect.
     If regexp has `//' around it, the slashes will be ignored.

-i*extension*
     specifies that files processed by the `<>' construct are to be edited
     in-place.  It does this by renaming the input file, opening the output
     file by the original name, and selecting that output file as the
     default for print() statements.  The extension, if supplied, is added
     to the name of the old file to make a backup copy.  If no extension
     is supplied, no backup is made.  From the shell, saying

          $ perl -p -i.bak -e "s/foo/bar/; ... "

     is the same as using the script:

          #!/usr/bin/perl -pi.bak
          s/foo/bar/;

     which is equivalent to

          #!/usr/bin/perl
          while (<>) {
          	if ($ARGV ne $oldargv) {
          	    rename($ARGV, $ARGV . '.bak');
          	    open(ARGVOUT, ">$ARGV");
          	    select(ARGVOUT);
          	    $oldargv = $ARGV;
          	}
          	s/foo/bar/;
          }
          continue {
          	print;	# this prints to original filename
          }
          select(STDOUT);

     except that the -i form doesn't need to compare $ARGV to $oldargv to
     know when the filename has changed.  It does, however, use ARGVOUT for
     the selected filehandle.  Note that STDOUT is restored as the default
     output filehandle after the loop.

     You can use eof without parenthesis to locate the end of each input
     file, in case you want to append to each file, or reset line
     numbering (see example in `eof', *Note Perlfunc:
     (perl.info)perlfunc,).

-I*directory*
     may be used in conjunction with -P to tell the C preprocessor where
     to look for include files.  By default /usr/include and /usr/lib/perl
     are searched.

-l*octnum*
     enables automatic line-ending processing.  It has two effects:  first,
     it automatically chomps the line terminator when used with -n or -p,
     and second, it assigns "$\" to have the value of *octnum* so that any
     print statements will have that line terminator added back on.  If
     *octnum* is omitted, sets "$\" to the current value of "$/".  For
     instance, to trim lines to 80 columns:

          perl -lpe 'substr($_, 80) = ""'

     Note that the assignment `$\ = $/' is done when the switch is
     processed, so the input record separator can be different than the
     output record separator if the -l switch is followed by a -0 switch:

          gnufind / -print0 | perl -ln0e 'print "found $_" if -p'

     This sets $\ to newline and then sets $/ to the null character.

-n
     causes Perl to assume the following loop around your script, which
     makes it iterate over filename arguments somewhat like *sed -n* or
     *awk*:

          while (<>) {
          	...		# your script goes here
          }

     Note that the lines are not printed by default.  See -p to have lines
     printed.  Here is an efficient way to delete all files older than a
     week:

          find . -mtime +7 -print | perl -nle 'unlink;'

     This is faster than using the `-exec' switch of *find* because you
     don't have to start a process on every filename found.

     BEGIN and END blocks may be used to capture control before or after
     the implicit loop, just as in *awk*.

-p
     causes Perl to assume the following loop around your script, which
     makes it iterate over filename arguments somewhat like *sed*:

          while (<>) {
          	...		# your script goes here
          } continue {
          	print;
          }

     Note that the lines are printed automatically.  To suppress printing
     use the -n switch.  A -p overrides a -n switch.

     BEGIN and END blocks may be used to capture control before or after
     the implicit loop, just as in awk.

-P
     causes your script to be run through the C preprocessor before
     compilation by Perl.  (Since both comments and cpp directives begin
     with the # character, you should avoid starting comments with any
     words recognized by the C preprocessor such as "if", "else" or
     "define".)

-s
     enables some rudimentary switch parsing for switches on the command
     line after the script name but before any filename arguments (or
     before a *-*).  Any switch found there is removed from @ARGV and sets
     the corresponding variable in the Perl script.  The following script
     prints "true" if and only if the script is invoked with a *-xyz*
     switch.

          #!/usr/bin/perl -s
          if ($xyz) { print "true\n"; }

-S
     makes Perl use the PATH environment variable to search for the script
     (unless the name of the script starts with a slash).  Typically this
     is used to emulate #! startup on machines that don't support #!, in
     the following manner:

          #!/usr/bin/perl
          eval "exec /usr/bin/perl -S $0 $*"
          	    if $running_under_some_shell;

     The system ignores the first line and feeds the script to /bin/sh,
     which proceeds to try to execute the Perl script as a shell script.
     The shell executes the second line as a normal shell command, and thus
     starts up the Perl interpreter.  On some systems $0 doesn't always
     contain the full pathname, so the -S tells Perl to search for the
     script if necessary.  After Perl locates the script, it parses the
     lines and ignores them because the variable $running_under_some_shell
     is never true.  A better construct than $* would be `${1+"$@"}', which
     handles embedded spaces and such in the filenames, but doesn't work if
     the script is being interpreted by csh.  In order to start up sh
     rather than csh, some systems may have to replace the #! line with a
     line containing just a colon, which will be politely ignored by Perl.
     Other systems can't control that, and need a totally devious
     construct that will work under any of csh, sh or Perl, such as the
     following:

          eval '(exit $?0)' && eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
          & eval 'exec /usr/bin/perl -S $0 $argv:q'
          	if 0;

-T
     forces "taint" checks to be turned on.  Ordinarily these checks are
     done only when running setuid or setgid.  See *Note Perlsec:
     (perl.info)perlsec,.

-u
     causes Perl to dump core after compiling your script.  You can then
     take this core dump and turn it into an executable file by using the
     *undump* program (not supplied).  This speeds startup at the expense
     of some disk space (which you can minimize by stripping the
     executable).  (Still, a "hello world" executable comes out to about
     200K on my machine.)  If you want to execute a portion of your script
     before dumping, use the dump() operator instead.  Note: availability
     of *undump* is platform specific and may not be available for a
     specific port of Perl.

-U
     allows Perl to do unsafe operations.  Currently the only "unsafe"
     operations are the unlinking of directories while running as
     superuser, and running setuid programs with fatal taint checks turned
     into warnings.

-v
     prints the version and patchlevel of your Perl executable.

-w
     prints warnings about identifiers that are mentioned only once, and
     scalar variables that are used before being set.  Also warns about
     redefined subroutines, and references to undefined filehandles or
     filehandles opened readonly that you are attempting to write on.  Also
     warns you if you use values as a number that doesn't look like
     numbers, using an array as though it were a scalar, if your
     subroutines recurse more than 100 deep, and innumerable other things.
     See *Note Perldiag: (perl.info)perldiag, and *Note Perltrap:
     (perl.info)perltrap,.

-x *directory*
     tells Perl that the script is embedded in a message.  Leading garbage
     will be discarded until the first line that starts with #! and
     contains the string "perl".  Any meaningful switches on that line will
     be applied (but only one group of switches, as with normal #!
     processing).  If a directory name is specified, Perl will switch to
     that directory before running the script.  The -x switch only
     controls the the disposal of leading garbage.  The script must be
     terminated with __END__ if there is trailing garbage to be ignored
     (the script can process any or all of the trailing garbage via the
     DATA filehandle if desired).


File: pm.info,  Node: Pod/newvar,  Next: Pod/newvar2,  Prev: Pod/newrun,  Up: Module List

Perl predefined variables
*************************

NAME
====

perlvar - Perl predefined variables

DESCRIPTION
===========

Predefined Names
----------------

The following names have special meaning to Perl.  Most of the
punctuational names have reasonable mnemonics, or analogues in one of the
shells.  Nevertheless, if you wish to use the long variable names, you
just need to say

     use English;

at the top of your program.  This will alias all the short names to the
long names in the current package.  Some of them even have medium names,
generally borrowed from *awk*.

To go a step further, those variables that depend on the currently
selected filehandle may instead be set by calling an object method on the
FileHandle object.  (Summary lines below for this contain the word
HANDLE.)  First you must say

     use FileHandle;

after which you may use either

     method HANDLE EXPR

or

     HANDLE->method(EXPR)

Each of the methods returns the old value of the FileHandle attribute.
The methods each take an optional EXPR, which if supplied specifies the
new value for the FileHandle attribute in question.  If not supplied, most
of the methods do nothing to the current value, except for autoflush(),
which will assume a 1 for you, just to be different.

A few of these variables are considered "read-only".  This means that if
you try to assign to this variable, either directly or indirectly through
a reference, you'll raise a run-time exception.

$ARG
$_
     The default input and pattern-searching space.  The following pairs
     are equivalent:

          while (<>) {...}	# only equivalent in while!
          while ($_ = <>) {...}

          /^Subject:/
          $_ =~ /^Subject:/

          tr/a-z/A-Z/
          $_ =~ tr/a-z/A-Z/

          chop
          chop($_)

     (Mnemonic: underline is understood in certain operations.)

$<*digit*>
     Contains the subpattern from the corresponding set of parentheses in
     the last pattern matched, not counting patterns matched in nested
     blocks that have been exited already.  (Mnemonic: like \digit.) These
     variables are all read-only.

$MATCH
$&
     The string matched by the last successful pattern match (not counting
     any matches hidden within a BLOCK or eval() enclosed by the current
     BLOCK).  (Mnemonic: like & in some editors.)  This variable is
     read-only.

$PREMATCH
$`
     The string preceding whatever was matched by the last successful
     pattern match (not counting any matches hidden within a BLOCK or eval
     enclosed by the current BLOCK).  (Mnemonic: ` often precedes a quoted
     string.)  This variable is read-only.

$POSTMATCH
$'
     The string following whatever was matched by the last successful
     pattern match (not counting any matches hidden within a BLOCK or
     eval() enclosed by the current BLOCK).  (Mnemonic: ' often follows a
     quoted string.)  Example:

          $_ = 'abcdefghi';
          /def/;
          print "$`:$&:$'\n";  	# prints abc:def:ghi

     This variable is read-only.

$LAST_PAREN_MATCH
$+
     The last bracket matched by the last search pattern.  This is useful
     if you don't know which of a set of alternative patterns matched.  For
     example:

          /Version: (.*)|Revision: (.*)/ && ($rev = $+);

     (Mnemonic: be positive and forward looking.) This variable is
     read-only.

$MULTILINE_MATCHING

     Set to 1 to do multiline matching within a string, 0 to tell Perl
     that it can assume that strings contain a single line, for the purpose
     of optimizing pattern matches.  Pattern matches on strings containing
     multiple newlines can produce confusing results when "$*" is 0.
     Default is 0.  (Mnemonic: * matches multiple things.)  Note that this
     variable only influences the interpretation of "`^'" and "`$'".  A
     literal newline can be searched for even when `$* == 0'.

     Use of "$*" is deprecated in Perl 5.

input_line_number HANDLE EXPR
$INPUT_LINE_NUMBER
$NR
$.
     The current input line number of the last filehandle that was read.
     An explicit close on the filehandle resets the line number.  Since
     "`<>'" never does an explicit close, line numbers increase across
     ARGV files (but see examples under eof()).  Localizing $. has the
     effect of also localizing Perl's notion of "the last read
     filehandle".  (Mnemonic: many programs use "." to mean the current
     line number.)

input_record_separator HANDLE EXPR
$INPUT_RECORD_SEPARATOR
$RS
$/
     The input record separator, newline by default.  Works like *awk*'s RS
     variable, including treating blank lines as delimiters if set to the
     null string.  You may set it to a multicharacter string to match a
     multi-character delimiter.  Note that setting it to `"\n\n"' means
     something slightly different than setting it to `""', if the file
     contains consecutive blank lines.  Setting it to `""' will treat two
     or more consecutive blank lines as a single blank line.  Setting it to
     `"\n\n"' will blindly assume that the next input character belongs to
     the next paragraph, even if it's a newline.  (Mnemonic: / is used to
     delimit line boundaries when quoting poetry.)

          undef $/;
          $_ = <FH>; 		# whole file now here
          s/\n[ \t]+/ /g;

autoflush HANDLE EXPR
$OUTPUT_AUTOFLUSH
$|
     If set to nonzero, forces a flush after every write or print on the
     currently selected output channel.  Default is 0.  Note that STDOUT
     will typically be line buffered if output is to the terminal and block
     buffered otherwise.  Setting this variable is useful primarily when
     you are outputting to a pipe, such as when you are running a Perl
     script under rsh and want to see the output as it's happening.
     (Mnemonic: when you want your pipes to be piping hot.)

output_field_separator HANDLE EXPR
$OUTPUT_FIELD_SEPARATOR
$OFS
$,
     The output field separator for the print operator.  Ordinarily the
     print operator simply prints out the comma separated fields you
     specify.  In order to get behavior more like *awk*, set this variable
     as you would set *awk*'s OFS variable to specify what is printed
     between fields.  (Mnemonic: what is printed when there is a , in your
     print statement.)

output_record_separator HANDLE EXPR
$OUTPUT_RECORD_SEPARATOR
$ORS
$\
     The output record separator for the print operator.  Ordinarily the
     print operator simply prints out the comma separated fields you
     specify, with no trailing newline or record separator assumed.  In
     order to get behavior more like *awk*, set this variable as you would
     set *awk*'s ORS variable to specify what is printed at the end of the
     print.  (Mnemonic: you set "$\" instead of adding \n at the end of the
     print.  Also, it's just like /, but it's what you get "back" from
     Perl.)

$LIST_SEPARATOR
$"
     This is like "$," except that it applies to array values interpolated
     into a double-quoted string (or similar interpreted string).  Default
     is a space.  (Mnemonic: obvious, I think.)

$SUBSCRIPT_SEPARATOR
$SUBSEP
$;
     The subscript separator for multi-dimensional array emulation.  If you
     refer to a hash element as

          $foo{$a,$b,$c}

     it really means

          $foo{join($;, $a, $b, $c)}

     But don't put

          @foo{$a,$b,$c}	# a slice--note the @

     which means

          ($foo{$a},$foo{$b},$foo{$c})

     Default is "\034", the same as SUBSEP in *awk*.  Note that if your
     keys contain binary data there might not be any safe value for "$;".
     (Mnemonic: comma (the syntactic subscript separator) is a
     semi-semicolon.  Yeah, I know, it's pretty lame, but "$," is already
     taken for something more important.)

     Consider using "real" multi-dimensional arrays in Perl 5.

$OFMT
$#
     The output format for printed numbers.  This variable is a
     half-hearted attempt to emulate *awk*'s OFMT variable.  There are
     times, however, when *awk* and Perl have differing notions of what is
     in fact numeric.  Also, the initial value is %.20g rather than %.6g,
     so you need to set "$#" explicitly to get *awk*'s value.  (Mnemonic:
     # is the number sign.)

     Use of "$#" is deprecated in Perl 5.

format_page_number HANDLE EXPR
$FORMAT_PAGE_NUMBER
$%
     The current page number of the currently selected output channel.
     (Mnemonic: % is page number in *nroff*.)

format_lines_per_page HANDLE EXPR
$FORMAT_LINES_PER_PAGE
$=
     The current page length (printable lines) of the currently selected
     output channel.  Default is 60.  (Mnemonic: = has horizontal lines.)

format_lines_left HANDLE EXPR
$FORMAT_LINES_LEFT
$-
     The number of lines left on the page of the currently selected output
     channel.  (Mnemonic: lines_on_page - lines_printed.)

format_name HANDLE EXPR
$FORMAT_NAME
$~
     The name of the current report format for the currently selected
     output channel.  Default is name of the filehandle.  (Mnemonic:
     brother to "$^".)

format_top_name HANDLE EXPR
$FORMAT_TOP_NAME
$^
     The name of the current top-of-page format for the currently selected
     output channel.  Default is name of the filehandle with _TOP
     appended.  (Mnemonic: points to top of page.)

format_line_break_characters HANDLE EXPR
$FORMAT_LINE_BREAK_CHARACTERS
$:
     The current set of characters after which a string may be broken to
     fill continuation fields (starting with ^) in a format.  Default is
     " \n-", to break on whitespace or hyphens.  (Mnemonic: a "colon" in
     poetry is a part of a line.)

format_formfeed HANDLE EXPR
$FORMAT_FORMFEED
$^L
     What formats output to perform a formfeed.  Default is \f.

$ACCUMULATOR
$^A
     The current value of the write() accumulator for format() lines.  A
     format contains formline() commands that put their result into $^A.
     After calling its format, write() prints out the contents of $^A and
     empties.  So you never actually see the contents of $^A unless you
     call formline() yourself and then look at it.  See *Note Perlform:
     (perl.info)perlform, and `formline()', *Note Perlfunc:
     (perl.info)perlfunc,.

$CHILD_ERROR
$?
     The status returned by the last pipe close, backtick (```') command,
     or system() operator.  Note that this is the status word returned by
     the wait() system call, so the exit value of the subprocess is
     actually (`$? >> 8').  Thus on many systems, `$? & 255' gives which
     signal, if any, the process died from, and whether there was a core
     dump.  (Mnemonic: similar to *sh* and *ksh*.)

$OS_ERROR
$ERRNO
$!
     If used in a numeric context, yields the current value of errno, with
     all the usual caveats.  (This means that you shouldn't depend on the
     value of "$!" to be anything in particular unless you've gotten a
     specific error return indicating a system error.)  If used in a string
     context, yields the corresponding system error string.  You can assign
     to "$!" in order to set errno if, for instance, you want "$!" to
     return the string for error n, or you want to set the exit value for
     the die() operator.  (Mnemonic: What just went bang?)

$EVAL_ERROR
$@
     The Perl syntax error message from the last eval() command.  If null,
     the last eval() parsed and executed correctly (although the
     operations you invoked may have failed in the normal fashion).
     (Mnemonic: Where was the syntax error "at"?)

     Note that warning messages are not collected in this variable.  You
     can, however, set up a routine to process warnings by setting
     $SIG{__WARN__} below.

$PROCESS_ID
$PID
$$
     The process number of the Perl running this script.  (Mnemonic: same
     as shells.)

$REAL_USER_ID
$UID
$<
     The real uid of this process.  (Mnemonic: it's the uid you came
     *FROM*, if you're running setuid.)

$EFFECTIVE_USER_ID
$EUID
$>
     The effective uid of this process.  Example:

          $< = $>;		# set real to effective uid
          ($<,$>) = ($>,$<);	# swap real and effective uid

     (Mnemonic: it's the uid you went *TO*, if you're running setuid.)
     Note: "`$<'" and "`$>'" can only be swapped on machines supporting
     setreuid().

$REAL_GROUP_ID
$GID
$(
     The real gid of this process.  If you are on a machine that supports
     membership in multiple groups simultaneously, gives a space separated
     list of groups you are in.  The first number is the one returned by
     getgid(), and the subsequent ones by getgroups(), one of which may be
     the same as the first number.  (Mnemonic: parentheses are used to
     *GROUP* things.  The real gid is the group you *LEFT*, if you're
     running setgid.)

$EFFECTIVE_GROUP_ID
$EGID
$)
     The effective gid of this process.  If you are on a machine that
     supports membership in multiple groups simultaneously, gives a space
     separated list of groups you are in.  The first number is the one
     returned by getegid(), and the subsequent ones by getgroups(), one of
     which may be the same as the first number.  (Mnemonic: parentheses are
     used to *GROUP* things.  The effective gid is the group that's
     *RIGHT* for you, if you're running setgid.)

     Note: "`$<'", "`$>'", "$(" and "$)" can only be set on machines that
     support the corresponding *set[re][ug]id()* routine.  "$(" and "$)"
     can only be swapped on machines supporting setregid().

$PROGRAM_NAME
$0
     Contains the name of the file containing the Perl script being
     executed.  Assigning to "$0" modifies the argument area that the ps(1)
     program sees.  This is more useful as a way of indicating the current
     program state than it is for hiding the program you're running.
     (Mnemonic: same as *sh* and *ksh*.)

$[
     The index of the first element in an array, and of the first character
     in a substring.  Default is 0, but you could set it to 1 to make Perl
     behave more like *awk* (or Fortran) when subscripting and when
     evaluating the index() and substr() functions.  (Mnemonic: [ begins
     subscripts.)

     As of Perl 5, assignment to "$[" is treated as a compiler directive,
     and cannot influence the behavior of any other file.  Its use is
     discouraged.

$PERL_VERSION
$]
     The string printed out when you say `perl -v'.  It can be used to
     determine at the beginning of a script whether the perl interpreter
     executing the script is in the right range of versions.  If used in a
     numeric context, returns the version + patchlevel / 1000.  Example:

          # see if getc is available
          ($version,$patchlevel) =
          	     $] =~ /(\d+\.\d+).*\nPatch level: (\d+)/;
          print STDERR "(No filename completion available.)\n"
          	     if $version * 1000 + $patchlevel < 2016;

     or, used numerically,

          warn "No checksumming!\n" if $] < 3.019;

     (Mnemonic: Is this version of perl in the right bracket?)

$DEBUGGING
$^D
     The current value of the debugging flags.  (Mnemonic: value of -D
     switch.)

$SYSTEM_FD_MAX
$^F
     The maximum system file descriptor, ordinarily 2.  System file
     descriptors are passed to exec()ed processes, while higher file
     descriptors are not.  Also, during an open(), system file descriptors
     are preserved even if the open() fails.  (Ordinary file descriptors
     are closed before the open() is attempted.)  Note that the
     close-on-exec status of a file descriptor will be decided according
     to the value of $^F at the time of the open, not the time of the exec.

$INPLACE_EDIT
$^I
     The current value of the inplace-edit extension.  Use undef to disable
     inplace editing.  (Mnemonic: value of -i switch.)

$PERLDB
$^P
     The internal flag that the debugger clears so that it doesn't debug
     itself.  You could conceivable disable debugging yourself by clearing
     it.

$BASETIME
$^T
     The time at which the script began running, in seconds since the
     epoch (beginning of 1970).  The values returned by the -M, *-A* and
     *-C* filetests are based on this value.

$WARNING
$^W
     The current value of the warning switch, either TRUE or FALSE.
     (Mnemonic: related to the -w switch.)

$EXECUTABLE_NAME
$^X
     The name that the Perl binary itself was executed as, from C's
     `argv[0]'.

$ARGV
     contains the name of the current file when reading from <>.

@ARGV
     The array @ARGV contains the command line arguments intended for the
     script.  Note that `$#ARGV' is the generally number of arguments minus
     one, since `$ARGV[0]' is the first argument, *NOT* the command name.
     See "$0" for the command name.

@INC
     The array @INC contains the list of places to look for Perl scripts to
     be evaluated by the `do EXPR', require, or use constructs.  It
     initially consists of the arguments to any -I command line switches,
     followed by the default Perl library, probably "/usr/local/lib/perl",
     followed by ".", to represent the current directory.

%INC
     The hash %INC contains entries for each filename that has been
     included via do or require.  The key is the filename you specified,
     and the value is the location of the file actually found.  The
     require command uses this array to determine whether a given file has
     already been included.

$ENV{expr}
     The hash %ENV contains your current environment.  Setting a value in
     `ENV' changes the environment for child processes.

$SIG{expr}
     The hash %SIG is used to set signal handlers for various signals.
     Example:

          sub handler {	# 1st argument is signal name
          	local($sig) = @_;
          	print "Caught a SIG$sig--shutting down\n";
          	close(LOG);
          	exit(0);
          }

          $SIG{'INT'} = 'handler';
          $SIG{'QUIT'} = 'handler';
          ...
          $SIG{'INT'} = 'DEFAULT';	# restore default action
          $SIG{'QUIT'} = 'IGNORE';	# ignore SIGQUIT

     The %SIG array only contains values for the signals actually set
     within the Perl script.  Here are some other examples:

          $SIG{PIPE} = Plumber;       # SCARY!!
          $SIG{"PIPE"} = "Plumber";   # just fine, assumes main::Plumber
          $SIG{"PIPE"} = \&Plumber;   # just fine; assume current Plumber
          $SIG{"PIPE"} = Plumber();   # oops, what did Plumber() return??

     The one marked scary is problematic because it's a bareword, which
     means sometimes it's a string representing the function, and
     sometimes it's going to call the subroutine call right then and
     there!  Best to be sure and quote it or take a reference to it.
     *Plumber works too.  See `perlsubs' in this node.

     Certain internal hooks can be also set using the %SIG hash.  The
     routine indicated by $SIG{__WARN__} is called when a warning message
     is about to be printed.  The warning message is passed as the first
     argument.  The presence of a __WARN__ hook causes the ordinary
     printing of warnings to STDERR to be suppressed.  You can use this to
     save warnings in a variable, or turn warnings into fatal errors, like
     this:

          local $SIG{__WARN__} = sub { die $_[0] };
          eval $proggie;

     The routine indicated by $SIG{__DIE__} is called when a fatal
     exception is about to be thrown.  The error message is passed as the
     first argument.  When a __DIE__ hook routine returns, the exception
     processing continues as it would have in the absence of the hook,
     unless the hook routine itself exits via a goto, a loop exit, or a
     die.


File: pm.info,  Node: Pod/newvar2,  Next: Pod/test,  Prev: Pod/newvar,  Up: Module List

Perl predefined variables
*************************

NAME
====

perlvar - Perl predefined variables

DESCRIPTION
===========

Predefined Names
----------------

The following names have special meaning to Perl.  Most of the
punctuational names have reasonable mnemonics, or analogues in one of the
shells.  Nevertheless, if you wish to use the long variable names, you
just need to say

     use English;

at the top of your program.  This will alias all the short names to the
long names in the current package.  Some of them even have medium names,
generally borrowed from *awk*.

To go a step further, those variables that depend on the currently
selected filehandle may instead be set by calling an object method on the
FileHandle object.  (Summary lines below for this contain the word
HANDLE.)  First you must say

     use FileHandle;

after which you may use either

     method HANDLE EXPR

or

     HANDLE->method(EXPR)

Each of the methods returns the old value of the FileHandle attribute.
The methods each take an optional EXPR, which if supplied specifies the
new value for the FileHandle attribute in question.  If not supplied, most
of the methods do nothing to the current value, except for autoflush(),
which will assume a 1 for you, just to be different.

A few of these variables are considered "read-only".  This means that if
you try to assign to this variable, either directly or indirectly through
a reference, you'll raise a run-time exception.

$ARG
$_
     The default input and pattern-searching space.  The following pairs
     are equivalent:

          while (<>) {...}	# only equivalent in while!
          while ($_ = <>) {...}

          /^Subject:/
          $_ =~ /^Subject:/

          tr/a-z/A-Z/
          $_ =~ tr/a-z/A-Z/

          chop
          chop($_)

     (Mnemonic: underline is understood in certain operations.)

$<*digit*>
     Contains the subpattern from the corresponding set of parentheses in
     the last pattern matched, not counting patterns matched in nested
     blocks that have been exited already.  (Mnemonic: like \digit.) These
     variables are all read-only.

$MATCH
$&
     The string matched by the last successful pattern match (not counting
     any matches hidden within a BLOCK or eval() enclosed by the current
     BLOCK).  (Mnemonic: like & in some editors.)  This variable is
     read-only.

$PREMATCH
$`
     The string preceding whatever was matched by the last successful
     pattern match (not counting any matches hidden within a BLOCK or eval
     enclosed by the current BLOCK).  (Mnemonic: ` often precedes a quoted
     string.)  This variable is read-only.

$POSTMATCH
$'
     The string following whatever was matched by the last successful
     pattern match (not counting any matches hidden within a BLOCK or
     eval() enclosed by the current BLOCK).  (Mnemonic: ' often follows a
     quoted string.)  Example:

          $_ = 'abcdefghi';
          /def/;
          print "$`:$&:$'\n";  	# prints abc:def:ghi

     This variable is read-only.

$LAST_PAREN_MATCH
$+
     The last bracket matched by the last search pattern.  This is useful
     if you don't know which of a set of alternative patterns matched.  For
     example:

          /Version: (.*)|Revision: (.*)/ && ($rev = $+);

     (Mnemonic: be positive and forward looking.) This variable is
     read-only.

$MULTILINE_MATCHING

     Set to 1 to do multiline matching within a string, 0 to tell Perl
     that it can assume that strings contain a single line, for the purpose
     of optimizing pattern matches.  Pattern matches on strings containing
     multiple newlines can produce confusing results when "$*" is 0.
     Default is 0.  (Mnemonic: * matches multiple things.)  Note that this
     variable only influences the interpretation of "`^'" and "`$'".  A
     literal newline can be searched for even when `$* == 0'.

     Use of "$*" is deprecated in Perl 5.

input_line_number HANDLE EXPR
$INPUT_LINE_NUMBER
$NR
$.
     The current input line number of the last filehandle that was read.
     An explicit close on the filehandle resets the line number.  Since
     "`<>'" never does an explicit close, line numbers increase across
     ARGV files (but see examples under eof()).  Localizing $. has the
     effect of also localizing Perl's notion of "the last read
     filehandle".  (Mnemonic: many programs use "." to mean the current
     line number.)

input_record_separator HANDLE EXPR
$INPUT_RECORD_SEPARATOR
$RS
$/
     The input record separator, newline by default.  Works like *awk*'s RS
     variable, including treating blank lines as delimiters if set to the
     null string.  You may set it to a multicharacter string to match a
     multi-character delimiter.  Note that setting it to `"\n\n"' means
     something slightly different than setting it to `""', if the file
     contains consecutive blank lines.  Setting it to `""' will treat two
     or more consecutive blank lines as a single blank line.  Setting it to
     `"\n\n"' will blindly assume that the next input character belongs to
     the next paragraph, even if it's a newline.  (Mnemonic: / is used to
     delimit line boundaries when quoting poetry.)

          undef $/;
          $_ = <FH>; 		# whole file now here
          s/\n[ \t]+/ /g;

autoflush HANDLE EXPR
$OUTPUT_AUTOFLUSH
$|
     If set to nonzero, forces a flush after every write or print on the
     currently selected output channel.  Default is 0.  Note that STDOUT
     will typically be line buffered if output is to the terminal and block
     buffered otherwise.  Setting this variable is useful primarily when
     you are outputting to a pipe, such as when you are running a Perl
     script under rsh and want to see the output as it's happening.
     (Mnemonic: when you want your pipes to be piping hot.)

output_field_separator HANDLE EXPR
$OUTPUT_FIELD_SEPARATOR
$OFS
$,
     The output field separator for the print operator.  Ordinarily the
     print operator simply prints out the comma separated fields you
     specify.  In order to get behavior more like *awk*, set this variable
     as you would set *awk*'s OFS variable to specify what is printed
     between fields.  (Mnemonic: what is printed when there is a , in your
     print statement.)

output_record_separator HANDLE EXPR
$OUTPUT_RECORD_SEPARATOR
$ORS
$\
     The output record separator for the print operator.  Ordinarily the
     print operator simply prints out the comma separated fields you
     specify, with no trailing newline or record separator assumed.  In
     order to get behavior more like *awk*, set this variable as you would
     set *awk*'s ORS variable to specify what is printed at the end of the
     print.  (Mnemonic: you set "$\" instead of adding \n at the end of the
     print.  Also, it's just like /, but it's what you get "back" from
     Perl.)

$LIST_SEPARATOR
$"
     This is like "$," except that it applies to array values interpolated
     into a double-quoted string (or similar interpreted string).  Default
     is a space.  (Mnemonic: obvious, I think.)

$SUBSCRIPT_SEPARATOR
$SUBSEP
$;
     The subscript separator for multi-dimensional array emulation.  If you
     refer to a hash element as

          $foo{$a,$b,$c}

     it really means

          $foo{join($;, $a, $b, $c)}

     But don't put

          @foo{$a,$b,$c}	# a slice--note the @

     which means

          ($foo{$a},$foo{$b},$foo{$c})

     Default is "\034", the same as SUBSEP in *awk*.  Note that if your
     keys contain binary data there might not be any safe value for "$;".
     (Mnemonic: comma (the syntactic subscript separator) is a
     semi-semicolon.  Yeah, I know, it's pretty lame, but "$," is already
     taken for something more important.)

     Consider using "real" multi-dimensional arrays in Perl 5.

$OFMT
$#
     The output format for printed numbers.  This variable is a
     half-hearted attempt to emulate *awk*'s OFMT variable.  There are
     times, however, when *awk* and Perl have differing notions of what is
     in fact numeric.  Also, the initial value is %.20g rather than %.6g,
     so you need to set "$#" explicitly to get *awk*'s value.  (Mnemonic:
     # is the number sign.)

     Use of "$#" is deprecated in Perl 5.

format_page_number HANDLE EXPR
$FORMAT_PAGE_NUMBER
$%
     The current page number of the currently selected output channel.
     (Mnemonic: % is page number in *nroff*.)

format_lines_per_page HANDLE EXPR
$FORMAT_LINES_PER_PAGE
$=
     The current page length (printable lines) of the currently selected
     output channel.  Default is 60.  (Mnemonic: = has horizontal lines.)

format_lines_left HANDLE EXPR
$FORMAT_LINES_LEFT
$-
     The number of lines left on the page of the currently selected output
     channel.  (Mnemonic: lines_on_page - lines_printed.)

format_name HANDLE EXPR
$FORMAT_NAME
$~
     The name of the current report format for the currently selected
     output channel.  Default is name of the filehandle.  (Mnemonic:
     brother to "$^".)

format_top_name HANDLE EXPR
$FORMAT_TOP_NAME
$^
     The name of the current top-of-page format for the currently selected
     output channel.  Default is name of the filehandle with _TOP
     appended.  (Mnemonic: points to top of page.)

format_line_break_characters HANDLE EXPR
$FORMAT_LINE_BREAK_CHARACTERS
$:
     The current set of characters after which a string may be broken to
     fill continuation fields (starting with ^) in a format.  Default is
     " \n-", to break on whitespace or hyphens.  (Mnemonic: a "colon" in
     poetry is a part of a line.)

format_formfeed HANDLE EXPR
$FORMAT_FORMFEED
$^L
     What formats output to perform a formfeed.  Default is \f.

$ACCUMULATOR
$^A
     The current value of the write() accumulator for format() lines.  A
     format contains formline() commands that put their result into $^A.
     After calling its format, write() prints out the contents of $^A and
     empties.  So you never actually see the contents of $^A unless you
     call formline() yourself and then look at it.  See *Note Perlform:
     (perl.info)perlform, and `formline()', *Note Perlfunc:
     (perl.info)perlfunc,.

$CHILD_ERROR
$?
     The status returned by the last pipe close, backtick (```') command,
     or system() operator.  Note that this is the status word returned by
     the wait() system call, so the exit value of the subprocess is
     actually (`$? >> 8').  Thus on many systems, `$? & 255' gives which
     signal, if any, the process died from, and whether there was a core
     dump.  (Mnemonic: similar to *sh* and *ksh*.)

$OS_ERROR
$ERRNO
$!
     If used in a numeric context, yields the current value of errno, with
     all the usual caveats.  (This means that you shouldn't depend on the
     value of "$!" to be anything in particular unless you've gotten a
     specific error return indicating a system error.)  If used in a string
     context, yields the corresponding system error string.  You can assign
     to "$!" in order to set errno if, for instance, you want "$!" to
     return the string for error n, or you want to set the exit value for
     the die() operator.  (Mnemonic: What just went bang?)

$EVAL_ERROR
$@
     The Perl syntax error message from the last eval() command.  If null,
     the last eval() parsed and executed correctly (although the
     operations you invoked may have failed in the normal fashion).
     (Mnemonic: Where was the syntax error "at"?)

     Note that warning messages are not collected in this variable.  You
     can, however, set up a routine to process warnings by setting
     $SIG{__WARN__} below.

$PROCESS_ID
$PID
$$
     The process number of the Perl running this script.  (Mnemonic: same
     as shells.)

$REAL_USER_ID
$UID
$<
     The real uid of this process.  (Mnemonic: it's the uid you came
     *FROM*, if you're running setuid.)

$EFFECTIVE_USER_ID
$EUID
$>
     The effective uid of this process.  Example:

          $< = $>;		# set real to effective uid
          ($<,$>) = ($>,$<);	# swap real and effective uid

     (Mnemonic: it's the uid you went *TO*, if you're running setuid.)
     Note: "`$<'" and "`$>'" can only be swapped on machines supporting
     setreuid().

$REAL_GROUP_ID
$GID
$(
     The real gid of this process.  If you are on a machine that supports
     membership in multiple groups simultaneously, gives a space separated
     list of groups you are in.  The first number is the one returned by
     getgid(), and the subsequent ones by getgroups(), one of which may be
     the same as the first number.  (Mnemonic: parentheses are used to
     *GROUP* things.  The real gid is the group you *LEFT*, if you're
     running setgid.)

$EFFECTIVE_GROUP_ID
$EGID
$)
     The effective gid of this process.  If you are on a machine that
     supports membership in multiple groups simultaneously, gives a space
     separated list of groups you are in.  The first number is the one
     returned by getegid(), and the subsequent ones by getgroups(), one of
     which may be the same as the first number.  (Mnemonic: parentheses are
     used to *GROUP* things.  The effective gid is the group that's
     *RIGHT* for you, if you're running setgid.)

     Note: "`$<'", "`$>'", "$(" and "$)" can only be set on machines that
     support the corresponding *set[re][ug]id()* routine.  "$(" and "$)"
     can only be swapped on machines supporting setregid().

$PROGRAM_NAME
$0
     Contains the name of the file containing the Perl script being
     executed.  Assigning to "$0" modifies the argument area that the ps(1)
     program sees.  This is more useful as a way of indicating the current
     program state than it is for hiding the program you're running.
     (Mnemonic: same as *sh* and *ksh*.)

$[
     The index of the first element in an array, and of the first character
     in a substring.  Default is 0, but you could set it to 1 to make Perl
     behave more like *awk* (or Fortran) when subscripting and when
     evaluating the index() and substr() functions.  (Mnemonic: [ begins
     subscripts.)

     As of Perl 5, assignment to "$[" is treated as a compiler directive,
     and cannot influence the behavior of any other file.  Its use is
     discouraged.

$PERL_VERSION
$]
     The string printed out when you say `perl -v'.  It can be used to
     determine at the beginning of a script whether the perl interpreter
     executing the script is in the right range of versions.  If used in a
     numeric context, returns the version + patchlevel / 1000.  Example:

          # see if getc is available
          ($version,$patchlevel) =
          	     $] =~ /(\d+\.\d+).*\nPatch level: (\d+)/;
          print STDERR "(No filename completion available.)\n"
          	     if $version * 1000 + $patchlevel < 2016;

     or, used numerically,

          warn "No checksumming!\n" if $] < 3.019;

     (Mnemonic: Is this version of perl in the right bracket?)

$DEBUGGING
$^D
     The current value of the debugging flags.  (Mnemonic: value of -D
     switch.)

$SYSTEM_FD_MAX
$^F
     The maximum system file descriptor, ordinarily 2.  System file
     descriptors are passed to exec()ed processes, while higher file
     descriptors are not.  Also, during an open(), system file descriptors
     are preserved even if the open() fails.  (Ordinary file descriptors
     are closed before the open() is attempted.)  Note that the
     close-on-exec status of a file descriptor will be decided according
     to the value of $^F at the time of the open, not the time of the exec.

$INPLACE_EDIT
$^I
     The current value of the inplace-edit extension.  Use undef to disable
     inplace editing.  (Mnemonic: value of -i switch.)

$PERLDB
$^P
     The internal flag that the debugger clears so that it doesn't debug
     itself.  You could conceivable disable debugging yourself by clearing
     it.

$BASETIME
$^T
     The time at which the script began running, in seconds since the
     epoch (beginning of 1970).  The values returned by the -M, *-A* and
     *-C* filetests are based on this value.

$WARNING
$^W
     The current value of the warning switch, either TRUE or FALSE.
     (Mnemonic: related to the -w switch.)

$EXECUTABLE_NAME
$^X
     The name that the Perl binary itself was executed as, from C's
     `argv[0]'.

$ARGV
     contains the name of the current file when reading from <>.

@ARGV
     The array @ARGV contains the command line arguments intended for the
     script.  Note that `$#ARGV' is the generally number of arguments minus
     one, since `$ARGV[0]' is the first argument, *NOT* the command name.
     See "$0" for the command name.

@INC
     The array @INC contains the list of places to look for Perl scripts to
     be evaluated by the `do EXPR', require, or use constructs.  It
     initially consists of the arguments to any -I command line switches,
     followed by the default Perl library, probably "/usr/local/lib/perl",
     followed by ".", to represent the current directory.

%INC
     The hash %INC contains entries for each filename that has been
     included via do or require.  The key is the filename you specified,
     and the value is the location of the file actually found.  The
     require command uses this array to determine whether a given file has
     already been included.

$ENV{expr}
     The hash %ENV contains your current environment.  Setting a value in
     `ENV' changes the environment for child processes.

$SIG{expr}
     The hash %SIG is used to set signal handlers for various signals.
     Example:

          sub handler {	# 1st argument is signal name
          	local($sig) = @_;
          	print "Caught a SIG$sig--shutting down\n";
          	close(LOG);
          	exit(0);
          }

          $SIG{'INT'} = 'handler';
          $SIG{'QUIT'} = 'handler';
          ...
          $SIG{'INT'} = 'DEFAULT';	# restore default action
          $SIG{'QUIT'} = 'IGNORE';	# ignore SIGQUIT

     The %SIG array only contains values for the signals actually set
     within the Perl script.  Here are some other examples:

          $SIG{PIPE} = Plumber;       # SCARY!!
          $SIG{"PIPE"} = "Plumber";   # just fine, assumes main::Plumber
          $SIG{"PIPE"} = \&Plumber;   # just fine; assume current Plumber
          $SIG{"PIPE"} = Plumber();   # oops, what did Plumber() return??

     The one marked scary is problematic because it's a bareword, which
     means sometimes it's a string representing the function, and
     sometimes it's going to call the subroutine call right then and
     there!  Best to be sure and quote it or take a reference to it.
     *Plumber works too.  See `perlsubs' in this node.

     Certain internal hooks can be also set using the %SIG hash.  The
     routine indicated by $SIG{__WARN__} is called when a warning message
     is about to be printed.  The warning message is passed as the first
     argument.  The presence of a __WARN__ hook causes the ordinary
     printing of warnings to STDERR to be suppressed.  You can use this to
     save warnings in a variable, or turn warnings into fatal errors, like
     this:

          local $SIG{__WARN__} = sub { die $_[0] };
          eval $proggie;

     The routine indicated by $SIG{__DIE__} is called when a fatal
     exception is about to be thrown.  The error message is passed as the
     first argument.  When a __DIE__ hook routine returns, the exception
     processing continues as it would have in the absence of the hook,
     unless the hook routine itself exits via a goto, a loop exit, or a
     die.


File: pm.info,  Node: Pod/test,  Next: Proc/Forkfunc,  Prev: Pod/newvar2,  Up: Module List

   *   * *bold**italic***bold-italic**

     X<abc/def>

     X<foo;abc/def;xyz/qed>

     `a\bc' in this node

     `$;' in this node

     Y<a\bc/def>

     X<*abc*;abc/def>

     Back in pod.

          This is a verbatim paragraph

   * foo bar bletch This is an item.  Back to paragraphs.

   * foobar bletch.


File: pm.info,  Node: Proc/Forkfunc,  Next: Proc/Simple,  Prev: Pod/test,  Up: Module List

fork off a function
*******************

NAME
====

Proc::Forkfunk - fork off a function

SYNOPSIS
========

     use Proc::Forkfunc;

     forkfunc(\&child_func,@child_args);

DESCRIPTION
===========

Fork off a process.  Call a function on the child process the function
should be passed in as a reference.  The child function should not return.

Logic copied from somewhere, probably Larry Wall.

AUTHOR
======

David Muir Sharnoff <muir@idiom.com>


File: pm.info,  Node: Proc/Simple,  Next: Religion,  Prev: Proc/Forkfunc,  Up: Module List

launch and control background processes
***************************************

NAME
====

Proc::Simple - launch and control background processes

SYNOPSIS
========

     use Proc::Simple;

     $myproc = Proc::Simple->new();        # Create a new process object

     $myproc->start("shell-command-line"); # Launch a shell process
     $myproc->start(sub { ... });          # Launch a perl subroutine
     $myproc->start(\&subroutine);         # Launch a perl subroutine

     $running = $myproc->poll();           # Poll Running Process

     $myproc->kill();                      # Kill Process (SIGTERM)

     $myproc->kill("SIGUSR1");             # Send specified signal

     Proc::Simple->debug($level);          # Turn debug on

DESCRIPTION
===========

The Proc::Simple package provides objects that model real-life processes
from a user's point of view. A new process object is created by

     $myproc = Proc::Simple->new();

Either shell-like command lines or references to perl subroutines can be
specified for launching a process in background.  A 10-second sleep
process, for example, can be started via the shell as

     $myproc->start("sleep 10");

or, as a perl subroutine, with

     $myproc->start(sub { sleep(10); });

The *start* Method returns immediately after starting the specified
process in background, i.e. non-blocking mode.  It returns 1 if the
process has been launched sucessfully and *0* if not.

The *poll* method checks if the process is still running

     $running = $myproc->poll();

and returns 1 if it is, *0* if it's not. Finally,

     $myproc->kill();

terminates the process by sending it the SIGTERM signal. As an option,
another signal can be specified.

     $myproc->kill("SIGUSR1");

sends the SIGUSR1 signal to the running process. kill returns 1 if it
succeeds in sending the signal, *0* if it doesn't.

NOTE
====

Please keep in mind that there is no guarantee that the SIGTERM signal
really terminates a process. Processes can have signal handlers defined
that avoid the shutdown.  If in doubt, whether a process still exists,
check it repeatedly with the *poll* routine after sending the signal.

AUTHOR
======

Michael Schilli <schilli@tep.e-technik.tu-muenchen.de>


File: pm.info,  Node: Religion,  Next: Remedy/Ar,  Prev: Proc/Simple,  Up: Module List

Generate tracebacks and create and install die() and  warn() handlers.
**********************************************************************

NAME
====

Religion - Generate tracebacks and create and install die() and  warn()
handlers.

DESCRIPTION
===========

This is a second go at a module to simplify installing die() and warn()
handlers, and to make such handlers easier to write and control.

For most people, this just means that if use `use Religion;' then you'll
get noticably better error reporting from warn() and die(). This is
especially useful if you are using eval().

Religion provides four classes, WarnHandler, DieHandler, WarnPreHandler,
and DiePreHandler, that when you construct them return closures that can be
stored in variables that in turn get invoked by $SIG{__DIE__} and
$SIG{__WARN__}. Note that if Religion is in use, you should not modify
$SIG{__DIE__} or $SIG{__WARN__}, unless you are careful about invoking
chaining to the old handler.

Religion also provides a TraceBack function, which is used by a DieHandler
after you `die()' to give a better handle on the current scope of your
situation, and provide information about where you were, which might
influence where you want to go next, either returning back to where you
were, or going on to the very last. [Sorry - Ed.]

See below for usage and examples.

USAGE
=====

DieHandler SUB
     Invoke like this:

          $Die::Handler = new DieHandler sub {
          	#...
          };

     where `#...' contains your handler code. Your handler will receive the
     following arguments:

          $message, $full_message, $level, $eval,
          		    $iline, $ifile, $oline, $ofile, $oscope

     `$message' is the message provided to die(). Note that the default
     addition of " at FILE line LINE.\n" will have been stripped off if it
     was present.  If you want to add such a message back on, feel free to
     do so with $iline and $ifile.

     C<$full_message) is the message with a scope message added on if
     there was no newline at the end of `$message'. Currently, this is
     *not* the original message that die() tacked on, but something along
     the lines of " at line 3 of the eval at line 4 of Foo.pl\n".

     `$eval' is non-zero if the die() was invoked inside an eval.

     The rest of the arguments are explained in the source for
     Religion::TraceBack. Yes, I need to document these, but not just now,
     for they are a pain to explain.

     Whenever you install a DieHandler, it will automatically store the
     current value of $Die::Handler so it can chain to it. If you want to
     install a handler only temporarily, use local().

     If your handler returns data using return or by falling off the end,
     then the items returns will be used to fill back in the argument
     list, and the next handler in the chain, if any, will be invoked.
     *Don't fall off the end if you don't want to change the error
     message.*

     If your handler exits using last, then no further handlers will be
     invoked, and the program will die immediatly.

     If your handler exits using next, then the next handler in the chain
     will be invoked directly, without giving you a chance to change its
     arguments as you could if you used return.

     If your handler invokes die(), then die() will proceed as if no
     handlers were installed. If you are inside an eval, then it will exit
     to the scope enclosing the eval, otherwise it will exit the program.

WarnHandler SUB
     Invoke like this:

          $Warn::Handler = new WarnHandler sub {
          	#...
          };
          
          For the rest of its explanation, see DieHandler, and subsitute warn() for
          die(). Note that once the last DieHandler completes (or C<last> is invoked)
          then execution will return to the code that invoked warn().

DiePreHandler SUB
     Invoke like this:

          $Die::PreHandler = new DiePreHandler sub {
          	#...
          };
          
          This works identically to $Die::Handler, except that it forms a separate chain
          that is invoked I<before> the DieHandler chain. Since you can use C<last> to
          abort all the handlers and die immediately, or change the messages or scope
          details, this can be useful for modifying data that all future handlers will
          see, or to dispose of some messages from further handling.

     This is even more useful in $Warn::PreHandler, since you can just
     throw away warnings that you *know* aren't needed.

WarnPreHandler SUB
     Invoke like this:

          $Warn::PreHandler = new WarnPreHandler sub {
          	#...
          };
          
          This works identically to $Warn::Handler, except that it forms a separate
          chain that is invoked I<before> the WarnHandler chain. Since you can use
          C<last> to abort all the handlers and return to the program, or change
          the messages or scope details, this can be useful for modifying data that
          all future handlers will see, or to dispose of some messages.

     This is very useful, since you can just throw away warnings that you
     *know* aren't needed.

EXAMPLES
========

A dialog error message:
          $Die::Handler = new DieHandler sub {
             my($msg,$fmsg,$level,$eval) = @_;
             if($eval) {
          		# if we are in an eval, skip to the next handler
          		next;
          	} else {
          		# show a message box describing the error.
          	 	print "ShowMessageBox $fmsg";
          
          	 	# force the program to exit
          	 	exit 0;
          	 	next;
          	}
          };

A handler that changes die() messages back to the original format
          local($Die::Handler) = new DieHandler sub {
             my($msg,$fmsg,$level,@trace) = @_;

          $fmsg = $msg . ((substr($msg,-1,1) ne "\n") ?
          			 " at $trace[2] line $trace[1].\n"
          			 : "");
          return ($msg,$fmsg);
           };

A warn handler that does nothing.
          $Warn::Handler = new WarnHandler sub {next;};

A warn prehandler that throws away a warning.
          $Warn::PreHandler = new WarnPreHandler sub {
          	my($msg,$fmsg,$level,$eval) = @_;
          	if($msg =~ /Use of uninitialized/) {
          		last;
          	}
          	next;
          };


File: pm.info,  Node: Remedy/Ar,  Next: Resources,  Prev: Religion,  Up: Module List

Interface to Remedy's Action Request (Version 1.2)
**************************************************

NAME
====

Remedy::Ar - Interface to Remedy's Action Request (Version 1.2)

DESCRIPTION
===========

Terminology
-----------

Action Request uses terminology which may not be familiar to some people.
Action Request can be viewed as graphical interface to a RDB (although
flat files can also be used at the backend).  A *schema* is roughly
equivalent to a table in other database terminology.  In the graphical
interface only fields from one schema can be present (although it is
possible to fill some fields from other schema.  An *entry* is equivalent
to a record.

Data structures
---------------

$control
     This is a private tag which is used to keep track of multiple
     connections.  The newcontrol() returns a new $control tag, which can
     then be used for all other operations.

$schema
     The name of a schema to operate on.

$server
     The name of a server to connect to.

$entryId
     A unique string representing an individual entry.  Once you have an
     $entryId, you can use it with GetEntry to retrieve detailed
     information about the record.

$fieldList
     A $fieldList is a reference to an associative array containing field
     name/contents pairs.  The field name used is the label displayed for
     the schema, using the default display tag.

Entry Operations
----------------

$entryId = CreateEntry($control, $schema, $fieldList)
     Adds a new entry to the specified schema.

     (Not Yet Implemented)

DeleteEntry($control, $schema, $entryId)
     Removes an entry from the specified schema.  This action requires
     administrator access.

     (Not Yet Implemented)

$fieldList = GetEntry($control, $schema, $entryId)
     Returns all fields from the entry associated with $entryId in $schema.

SetEntry
     (Not Yet Implemented)

GetListEntry($control, $schema, $qualifier, $maxRetrieve)
MergeEntry
     (Not Yet Implemented)

Schema Operations
-----------------

CreateSchema
     (Not Yet Implemented)

DeleteSchema
     (Not Yet Implemented)

GetSchema(control, schema)
SetSchema
     (Not Yet Implemented)

GetListSchema(control, changedSince)
Field Operations
----------------

CreateField
     (Not Yet Implemented)

DeleteField
     (Not Yet Implemented)

GetField(control, schema, fieldId)
SetField
     (Not Yet Implemented)

GetListField(control, schema, changedSince)
Menu Operations
---------------

CreateCharMenu
     (Not Yet Implemented)

DeleteCharMenu
     (Not Yet Implemented)

ExpandCharMenu
     (Not Yet Implemented)

GetCharMenu
     (Not Yet Implemented)

SetCharMenu
     (Not Yet Implemented)

GetListCharMenu
     (Not Yet Implemented)

Filter Operations
-----------------

CreateFilter
     (Not Yet Implemented)

DeleteFilter
     (Not Yet Implemented)

GetFilter
     (Not Yet Implemented)

SetFilter
     (Not Yet Implemented)

GetListFilter
     (Not Yet Implemented)

Active Link Operations
----------------------

CreateActiveLink
     (Not Yet Implemented)

DeleteActiveLink
     (Not Yet Implemented)

GetActiveLink
     (Not Yet Implemented)

SetActiveLink
     (Not Yet Implemented)

GetListActiveLink
     (Not Yet Implemented)

AdminExt Operations
-------------------

CreateAdminExt
     (Not Yet Implemented)

DeleteAdminExt
     (Not Yet Implemented)

GetAdminExt
     (Not Yet Implemented)

SetAdminExt
     (Not Yet Implemented)

GetListAdminExt
     (Not Yet Implemented)

ExecuteAdminExt
     (Not Yet Implemented)

Miscellaneous Operations
------------------------

VerifyUser(control)
GetListServer()
Export
     (Not Yet Implemented)

Import
     (Not Yet Implemented)

GetListGroup(control)
GetServerInfo
     (Not Yet Implemented)

SetServerInfo
     (Not Yet Implemented)

DecodeStatusHistory
     (Not Yet Implemented)

DecodeDiary
     (Not Yet Implemented)

LoadARQualifierStruct(control, schema, qualString)
Miscellaneous Support Functions (Not part of the AR API)
--------------------------------------------------------

newcontrol()
printcontrol(control)
setuser(control, user, password)
setlanguage(control, language)
setserver(control, server)
AUTHOR
======

Copyright (c) 1995 Rik Harris (*rik.harris@fulcrum.com.au*). All rights
reserved.  This program is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.

The Ar perl extension, and this documentation were derived from the
information found in the Action Request include files, and the Action
Request System Programmer's Guide (Remedy Part Number: AXA-120-DA4-01).

Action Request System and AR System are tracemarks of Remedy Corporation.


File: pm.info,  Node: Resources,  Next: SDBM_File,  Prev: Remedy/Ar,  Up: Module List

handling application defaults in Perl.
**************************************

NAME
====

Resources - handling application defaults in Perl.

SYNOPSIS
========

     use Resources;

     $res = new Resources;
     $res = new Resources "resfile";

DESCRIPTION
===========

Resources are a way to specify information of interest to program or
packages.

Applications use resource files to specify and document the values of
quantities or attributes of interest.

Resources can be loaded from or saved to resource files. Methods are
provided to search, modify and create resources.

Packages use resources to hardwire in their code the default values for
their attributes, along with documentation for the attibutes themselves.

Packages inherit resources when subclassed, and the resource names are
updated dynamically to reflect a class hierarchy.

Methods are provided for interactive resource inspection and editing.

1. Resource inheritance
-----------------------

Package attributes are inherited from base and member classes, their names
are dynamically updated to reflect the inheritance, and values specified in
derived/container classes override those inherited from base/member
classes.

More precisely, there a few rules governing the inheritance of resource
names and values, and they will be explained by way of examples.

As far as resource names, the rules are:

Base class
     If Vehicle has a "speed" property, then it can use a resource named
     "vehicle.speed" to specify its default value.

Derived class
     If Car *is a* Vehicle, then Car has a "car.speed" resource
     automagically defined by inheritance from the base class.

Container class
     If Car *has a* member object called Tire, and Tire has a
     "tire.pressure" resource, then Car inherits a "car.tire.pressure"
     resource from the member class.

Application class
     All resources of Car objects used by a program named "race" have the
     prefix "race." prepended to their names, e.g. "race.car.speed",
     "race.car.tire.pressure", etc.

With regard to assigning values to resources, the rules are:

Specification in a file
     Resources specified in a resource file always override hardcoded
     resources (with the exception of "hidden" resources, see below).

Inheritance
     Resources defined in a derived class (like Car) override those
     specified in a base class. Likewise, resources defined in a container
     class override those specified in the members.

     In the above example, a default value for "car.speed" in Car
     overrides the value of "vehicle.speed" in any Car object, otherwise
     "car.speed" assumes the value of "vehicle.speed".  Same for
     "car.tire.pressure".

2. Resource Files.
------------------

A resource specification in a (text) resource file is a line of the form:

     sequence: value

There may be any number of whitespaces between the name and the colon
character, and between the colon and the value.

sequence can have four forms:
          (1) word

     A *word* not containing whitespaces, colons (':'), dots ('.') or
     asterisks ('*'), nor starting with an underscore ('_').

     Or, recursively:

          (2) word.sequence
          (3) word*sequence
          (4) *sequence

     The asterisks in a resource name act as wildcards, matching any
     sequence of characters.

     For cases (3) or (4) the *word* must be or match the current
     application class, otherwise the resource specification is silently
     ignored (this means that an applications loads from a file only its
     own resources, and those whose application class is a wildcard).

     No distinction is made between uppercase and lowercase letters.

value can be:
     An unadorned word or a quoted sequence of whitespace-separated words.
     Both single (' ') and double quotes quotes (" ") are allowed, and
     they must be paired.

     Any *constant* scalar constructor in Perl, including anon references
     to constant arrays or hashes.

     The special words *yes*, *true*, no, *false* (case insensitive) are
     treated as boolean resources and converted 1 and 0, unless they are
     quoted.

Examples of valid resource specifications:

     car*brand       : Ferrari    # A word.
     car.price       : 200K       # Another word
     car.name        : '312 BB'   # A quoted sentence
     car*runs*alot   : yes        # A boolean, converted to 1.
     car*noise*lotsa : 'yes'      # yes, taken verbatim
     car.size        : [1, [2, 3]]           # An anon array.
     car.lett        : {"P"=>1, "Q"=>[2, 3]} # An anon hash.

Examples of illegal resource names:

     car pedal    # Whitespace in the name.
     .carpedal    # Leading dot in name.
     car._pedal   # Leading underscore in _dog.
     carpedal*    # Trailing asterisk.
     carpedal.    # Trailing dot.

A resource file may contain comments: anything from a hash ('#') character
to the end of a line is ignored, unless the hash character appears inside a
quoted value string.

Resource specifications may be split across successive lines, by
terminating the split lines with a backslash, as per cpp(1).

3. The Resources hash
---------------------

A non-my hash named %Resources can be used to specify the default values
for the attributes of a package in its source code, along with
documentation for the attributes themselves. The documentation itself is
"dynamical" (as opposed to the static, pod-like variety) in that it
follows a class hyerarchy and is suitable for interactive display and
editing.

The %Resources hash is just a hash of

     $Name => [$Value, $Doc]

things. Each hash key *$Name* is a resource name in the above sequence
form. Each hash value is a reference to an anon array *[$Value, $Doc]*,
with *$Doc* being an optional resource documentation.

The resource $Name *cannot* contain wildcard ('*') or colon (':')
characters, nor start or end with a dot ('.'). Also, it must *not* be
prefixed with the package name (since this is automatically prepended by
the *merge* method, see below). Names starting with an underscore ('_')
character are special in that they define "hidden" resources. These may
not be specified in resource files, nor dynamically viewed/edited: they
come handy to specify global parameters when you do not want to use global
application-wide variables, and/or want to take advantage of the
inheritance mechanism.

The resource $Value can be any *constant* scalar Perl constructor,
including references to arrays and/or hashes of constants (or references
thereof). Boolean values must be specified as 1 or 0.

The resource documentation is a just string of any length: it will be
appropriately broken into lines for visualization purposes. It can also be
missing, in which case an inherited documentation is used (if any exists,
see the *merge* method below).

The content of a resource hash is registered in a global Resource object
using the *merge* method.

Here is an example of deafults specification for a package.

     package Car;
     @ISA = qw( Vehicle );
     use vars qw( %Resources );

     %Resources = (
         brand    => ["FIAT", "The carmaker"],
         noise    => ["Ashtmatic", "Auditory feeling"],
         sucks    => [1, "Is it any good?"],
     	 nuts     => [ { on => 2, off => [3, 5] }, "Spares"],
     	 '_ghost' => [0, "Hidden. Mr. Invisible"]
     	 'tire.flat' => [0],
     );

The last line overrides a default in member class Tire. The corresponding
doc string is supposedly in the source of that class. The last two hash
keys are quoted because of the non alphanumeric characters in them.

4. Objects and resources
------------------------

The recommended way to use resources with Perl objects is to pass a
Resource object to the "new" method of a package.  The method itself will
merge the passed resources with the package defaults, and the passed
resource will override the defaults where needed.

Resource inheritance via subclassing is then easily achieved via the
*merge* method, as shown in the EXAMPLES section.

5. Methods in class Resources
-----------------------------

5.1. Creation and initialization
--------------------------------

*new Resources ($resfile);*
     Creates a new resource database, initialized with the defaults for
     class Resources (see below for a list of them).

     If a nonempty file name is specified in $resfile, it initializes the
     object with the content of the so named resource file. For safe (non
     overwriting) loading, see the *load* method below.

     If the special file name "_RES_NODEFAULTS" is specified, the object
     is created completely empty, with not even the Resources class
     defaults in it.

     Returns the new object, or undef in case of error.

*load($resfile, $nonew);*
     Loads resources from a file named $resfile into a resource database.

     The $nonew argument controls whether loading of non already defined
     resurces is allowed. If it is true, safe loading is performed:
     attempting to load non-wildcarded resource names that do not match
     those already present in the database causes an error. This can be
     useful if you want to make sure that only pre-defined resources (for
     which you presumably have hardwired defaults) are loaded. It can be a
     safety net against typos in a resource file.

     Use is made of *Safe::reval* to parse values specified through Perl
     constructors (only constants, anon hashes and anon arrays are
     allowed).

     Returns 1 if ok, 0 if error.

*merge($class, @memberclasses);*
     Merges the %Resources hash of the package defining $class with those
     of its @memberclasses, writing the result in the resource database.

     The merging reflects the resource inheritance explained above: the
     %Resources of all base classes and member classes of $class are
     inherited along the way. Eventually all these resources have their
     names prefixed with the name of the package in which $class is
     defined (lowercased and stripped of all foo::bar:: prefixes), and
     with the application class as well.

     In the above example, the defaults of a Car object will be renamed,
     after merging as:

          car.brand, car.noise, ...,
          car.tire.flat

     and for a Civic object, where Civic is a (i.e. ISA) Car, they will be
     translated instead as

          civic.brand, civic.noise, ...,
          civic.tire.flat

     Finally, the application name ($0, a.k.a $PROGRAM_NAME in English) is
     prepended to all resource names, so, if the above Civic package is
     used by a Perl script named "ilove.pl", the final names after merging
     are

          ilove.civic.brand, ilove.civic.noise, ...,
          ilove.civic.tire.flat

     The new names are the ones to use when accessing these resources by
     name.

     The resource values are inherited accoring to the rules previously
     indicated, hence with resource files having priority over hardcoded
     defaults, nnd derived or container classes over base or member
     classes.

     Returns 1 if for success, otherwise 0.

5.2. Looking up resources
-------------------------

The values and documentation strings stored in a Resource object can be
accessed by specifying their names in three basic ways:

directly ("byname" methods)
     As in "my.nice.cosy.couch" .

by a pattern ("bypattern" methods)
     As in "m??nice.*" .

hierarchically ("byclass" methods)
     If class Nice *is a* Cosy, then asking for "couch" in package Cosy
     gets you the value/doc of "my.couch". If, instead, Nice *has a* Cosy
     member, that the method gets you "my.nice.cosy.couch". This behaviour
     is essential for the proper initialization of subclassed and member
     packages, as explained in detail below.

It is also possible to retrieve the whole content of a resource database
("names" and "each" methods)

Note that all the resource lookup methods return named (non "wildcarded")
resources only. Wildcarded resources (i.e. those specified in resource
files, and whose names contain one or more '*') are best thought as
placeholders, to be used when the value of an actual named resource is set.

For example, a line in a resource file like

     *background : yellow

fixes to yellow the color of all resources whose name ends with
"background".  However, your actual packages will never worry about unless
they really need a background. In this case they either have a
"background" resource in their defaults hash, or subclass a package that
has one.

valbyname($name);
     Retrieves the value of a named resource from a Resource database. The
     $name argument is a string containing a resource name with no
     wildcards.

     Returns the undefined value if no such resource is defined.

docbyname($name);
     Retrieves the documentation string of a named resource from a Resource
     database. The $name argument is a string containing a resource name
     with no wildcards.

     Returns the undefined value if no such resource is defined.

bypattern($pattern);
     Retrieves the full names, values and documentation strings of all the
     named (non wildcarded) resources whose name matches the given
     $pattern. The pattern itself is string containing a Perl regular
     expression, *not* enclosed in slashes.

     Returns a new Resource object containing only the matching resources,
     or the undefined value if no matches are found.

valbypattern($pattern);
     Retrieves the full names and values of all named (non wildcarded)
     resources whose name matches the given pattern.

     Returns a new Resource object containing only names and values of the
     matching resources (i.e. with undefined doc strings), or the
     undefined value if no matches are found.

docbypattern($pattern);
     Retrieves the full names and documentation strings of all named (non
     wildcarded) resources whose name matches the given pattern.

     Returns a new Resource object containing only names and docs of the
     matching resources (i.e. with undefined resource values), or the
     undefined value if no matches are found.

*byclass($object, $suffix);*
     To properly initialize the attributes of a package via resources we
     need a way to know whether the package defaults (contained in its
     %Resources hash) have been overridden by a derived or container
     class.  For example, to set a field like $dog->{Weight} in a Dog
     object, we must know if this $dog is being subclassed by Poodle or
     Bulldog, or if it is a member of Family, since all these other
     classes might override whatever "weight" default is defined in the
     %Resources hash of Dog.pm.

     This information must of course be gathered at runtime: if you tried
     to name explicitly a resource like "family.dog.weight" inside Dog.pm
     all the OOP crowd would start booing at you. Your object would not be
     reusable anymore, being explicitly tied to a particular container
     class. After all we do use objects mainly because we want to easily
     reuse code...

     Enter the "by class" resource lookup methods: *byclass*, *valbyclass*
     and *docbyclass*.

     Given an $object and a resource $suffix (i.e. a resource name
     stripped of all container and derived class prefixes), the *byclass*
     method returns a 3 element list containing the name/value/doc of that
     resource in $object. The returned name will be fully qualified with
     all derived/container classes, up to the application class.

     For example, in a program called "bark", the statements

          $dog = new Dog ($res); # $res is a Resources database
          ($name,$value,$doc) = $res->byclass($dog, "weight");

     will set $name, $value and $doc equal to those of the
     "bark.poodle.weight" resource, if this Dog is subclassed by Poodle,
     and to those of "bark.family.dog.weight", if it is a member of Family
     instead.

     The passed name suffix must not contain wildcards nor dots.

     Be careful not to confuse the "byclass" with the "byname" and
     "bypattern" retrieval methods: they are used for two radically
     different goals. See the EXAMPLES section for more.

     Returns the empty list if no resources are found for the given suffix,
     or if the suffix is incorrect.

*namebyclass($obj, $suffix);*
     As the *byclass* method above, but returns just the resource name
     (i.e. the suffix with all the subclasses prepended).

*valbyclass($obj, $suffix);*
     As the *byclass* method above, but returns just the resource value.

docbyclass($suffix);
     As the *byclass* method above, but returns just the resource
     documentation.

each;
     Returns the next name/[value,doc] pair of the named (non wildcarded)
     resources in a resource database, exactly as the each Perl routine.

names;
     Returns a list of the names of all named (non-wildcarded) resources
     in a resource database, or undef if the databasee is empty.

5.3. Assigning and removing Resources
-------------------------------------

*put($name, $value, $doc);*
     Writes the value and doc of a resource in the database.  It is
     possible to specify an empty documentation string, but name and value
     must be defined.

     Wildcards ('*' characters) are allowed in the $name, but the $doc is
     ignored in this case (documentation is intended for single resources,
     not for sets of them).

     The value is written unchanged unless the resource database already
     contains a wildcarded resource whose name includes $name (foo*bar
     includes foo.bar, foo.baz.bar, etc.). In this case the value of the
     wildcarded resource overrides the passed $value.

     Returns 1 if ok, 0 if error.

removebyname($name);
     Removes the named (non wildcarded) resources from the database.

     Returns 1 if OK, 0 if the resource is not found in the database.

removebypattern($name);
     Removes from the database all resources (both named *and* wildcarded)
     whose name mathes $pattern. An exactly matching name must be
     specified for wildcarded resources (foo*bar to remove foo*bar).

     Returns the number of removed resources.

5.6. Viewing and editing resources.
-----------------------------------

view;
     Outputs the current content of a Resource object by piping to a pager
     program.

     The environment variable $ENV{RESPAGER}, the resource
     "resources.pager" and the environment variable $ENV{PAGER} are looked
     up, in this very order, to find the pager program. Defaults to
     */bin/more* if none of them is found.

     The output format is the same of a resource file, with the resource
     names alphabetically ordered, and the resource documentation strings
     written as comments.

     Returns 1 if ok, 0 if error.

edit($nonew);
     Provides dynamical resource editing of a Resource object via an
     external editor program. Only resource names and values can be edited
     (anyway, what is the point of editing a resource comment on the fly?).

     The environment variables $ENV{RESEDITOR} and the resource
     "resouces.editor", are looked up, in this very order, to find the
     editor program. Defaults to */bin/vi* if none is found.

     The editor buffer is initialized in the same format of a resource
     file, with the resource names alphabetically ordered, and the
     resource documentation strings written as comments. The temporary
     file specified by the "resources.tmpfil" resource is used to
     initialize the editor, or '/tmp/resedit<pid>' if that resource is
     undefined.

     When the editor is exited (after saving the buffer) the method
     attempts to reload the edited resources. If an error is found the
     initial object is left unchanged, a warning with the first offending
     line in the file is printed, and the method returns with undef.
     Controlled resource loading is obtained by specifying a true value
     for the $nonew argument (see *load*).

     If the loading is successful, a new (edited) resource object is
     returned, which can be assigned to the old one for replacement.

     After a successful edit, the value of the resource
     "resources.updates" (which is always defined to 0 whenever a new
     resource is created) is increased by one. This is meant to notify
     program the and/or packages of the resource change, so they can
     proceed accordingly if they wish.

5.5. Miscellaneous methods
--------------------------

write($filename);
     Outputs all resources of a resource database into a resource file
     (overwriting it).

     The resource documentation strings are normally written as comments,
     so the file itself is immediately available for resource loading.
     However, if the boolean resource "resources.writepod" is true, then
     the (non wildcarded) resources are output in POD format for your
     documentational pleasure.

     As usual in Perl, the filename can allo be of the form "|command", in
     which case the output is piped into "comma1nd".

     For resources whose value is a reference to an anon array or hash, it
     produces the appropriate constant Perl contructor by reverse parsing.
     The parser itself is available as a separate method named *_parse*
     (see package source for documentation).

     Returns 1 if ok, 0 if error.

5. Resources of Resources
-------------------------

As you may have guessed at this point, the default configuration of this
package itself is defined by resources. The resource class is, of course,
"resources" (meaning that all the names have a leading "resources.").

To prevent chaos, however, these resources cannot be subclassed. This
should not be a problem in normal applications, since the Resource package
itself is not meant to be subclassed, but to help building a hierarchy of
classes instead.

The currently recognized resources, and their default values, are:

resources.appclass : "$PROGRAM_NAME"
     The application name of this Resource object.

resources.editor : /bin/vi
     Resource editor.

resources.mergeclass : true
     Boolean. True to merge with class inheritance.

resources.pager : /bin/more
     Resource pager.

resources.separator : ':'
     Pattern separating names from values in resource files.

resources.tmpfil : ''
     Editor temporary file.

resources.updates : 0
     Number of resource updates.

resources.verbosity : 1
     True to print warnings.

resources.viewcols : 78
     Width of view/edit window.

resources.writepod : false
     Boolean. True if the write method should output in POD format.

EXAMPLES
========

Here is an example of resource inheritance.  HotDog is a subclass of Food,
and has a member Wiener whichi happens to be a Food as well.

The subclass has defaults for two resources defined by the base classes
("edible" and "wiener.mustard"), and their values will override the base
class defaults.

Remember that after merging all resources names are prefixed with the
current class name.

     use Resources;
     package Food;
     %Resources = (
       edible => [1, "Can it be eaten."],
       tasty  => ["sort_of",  "D'ya like it?"],
     );
     
     sub new {
        my ($type, $res) = @_;
        $res || $res =  new Resources || (return undef);
        $res->merge($type) || die ("can't merge defaults");
     
        my $food= bless({}, type);
        $food->{Edible} = $res->valbyclass("edible");
        $food->{Tasty}  = $res->valbyclass("tasty");
        # Use valbyclass so a subclass like HotDog can change this by its
        # defaults.
     }
     
     # A Food method to say if it can be eaten.
     sub eatok {
        my $food=shift;
        return $food->{Edible};
     }

     package Wiener;
     @ISA = qw( Food );
     %Resources = (
          tasty => ["very"], # this overrides a base class default
          mustard => ["plenty", "How much yellow stuff?"],
     );
     # Nothing else: all methods are inherited from the base class.

     package HotDog;
     @ISA = qw( Food );

     %Resources = (
         edible    => [0],
         tasty     => ["yuck!"],
         'wiener.mustard' => ["none"], # To override member class default.
     );

     sub new {
        my ($type, $res) = @_;
     
        $res || $res =  new Resources || (return undef);
        $res->merge($type) || die ("can't merge defaults");
     
        my $hd = bless(new Food ($res), $type);
        $hd->{Wien} = new Wiener ($res);
        return $hd;
     }

     # All tastes of hotdog
     sub tastes {
        my $hd = shift;
        return ($hd->{Tasty}, $hd->{Wien}->{Tasty});
     }
     
     package main;
     # Whatever
     #
     $res = new Resources("AppDefltFile") || die;
     $snack = new HotDog($res);
     $gnam = $snack->eat();  # hotdog.edible overridees food.edible,
                             # so here $gnam equals 0

     @slurp = $snack->tastes()    # @slurp equals ("yuck!", "very")
                                  # the resources were overridden
                                  # by a subclass of HotDog , or
                                  # differently specified in
                                  # "AppDefltFile"

SEE ALSO
========

Safe(3).

BUGS
====

The underlying idea is to use a centralized resource database for the whole
application. This ensures uniformity of behaviour across kin objects, but
allow special characterizations only at the cost of subclassing.

AUTHOR
======

     Francesco Callari <franco@cim.mcgill.ca>
     Artifical Perception Laboratory,
     Center for Intelligent Machines,
     McGill University.

     WWW: http://www.cim.mcgill.ca/~franco/Home.html

COPYRIGHT
=========

Copyright 1996 Francesco Callari, McGill University

Permission to use, copy, modify, and distribute this software and its
documentation for any purpose without fee is hereby granted without fee,
provided that the above copyright notice appear in all copies and that both
that copyright notice and this permission notice appear in supporting
documentation, and that the name of McGill not be used in advertising or
publicity pertaining to distribution of the software without specific,
written prior permission.  McGill makes no representations about the
suitability of this software for any purpose.  It is provided "as is"
without express or implied warranty.

MCGILL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL
MCGILL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.


File: pm.info,  Node: SDBM_File,  Next: SHA,  Prev: Resources,  Up: Module List

Tied access to sdbm files
*************************

NAME
====

SDBM_File - Tied access to sdbm files

SYNOPSIS
========

     use SDBM_File;

     tie(%h, 'SDBM_File', 'Op.dbmx', O_RDWR|O_CREAT, 0640);

     untie %h;

DESCRIPTION
===========

See `tie', *Note Perlfunc: (perl.info)perlfunc,


File: pm.info,  Node: SHA,  Next: Safe,  Prev: SDBM_File,  Up: Module List

Perl interface to the NIST Secure Hash Algorithm
************************************************

NAME
====

SHA - Perl interface to the NIST Secure Hash Algorithm

SYNOPSIS
========

     use SHA;
     
     $context = new SHA;
     $context->reset();
     
     $context->add(LIST);
     $context->addfile(HANDLE);
     
     $digest = $context->digest();
     $string = $context->hexdigest();

     $digest = $context->hash($string);
     $string = $context->hexhash($string);

DESCRIPTION
===========

The *SHA* module allows you to use the NIST SHA message digest algorithm
from within Perl programs.

A new SHA context object is created with the new operation.  Multiple
simultaneous digest contexts can be maintained, if desired.  The context
is updated with the add operation which adds the strings contained in the
LIST parameter. Adding two strings separately is equivalent to adding
their concatenation: `add('foo', 'bar')' produces the same effect as
`add('foo')', `add('bar')', which in turn produces the same effect as
`add('foobar')'.

The final message digest value is returned by the *digest* operation as a
16-byte binary string. This operation delivers the result of operations
since the last new or reset operation. Once the operation has been
performed, the context must be reset before being used to calculate
another digest value.

Several convenience functions are also provided. The *addfile* operation
takes an open file-handle and reads it until end-of file in 8192-byte
blocks adding the contents to the context. The *hexdigest* operation calls
*digest* and returns the result as a printable string of hexdecimal digits
in eight-digit groups. The *hash* operation performs the complete series
of steps: reset, add, *digest* on the supplied scalar value, and returns
the result as a 16-byte binary string. The *hexhash* operation does the
same thing, but returns the result in the format of the *hexdigest*
operation.

EXAMPLE AND VALIDATION
======================

     use SHA 1.1;

     $sha = new SHA;

     print "EXPECT:   0164b8a9 14cd2a5e 74c4f7ff 082c4d97 f1edf880\n";

     $sha->reset();
     $sha->add("abc");
     print "RESULT 1: " . $sha->hexdigest() . "\n";

     $sha->reset();
     $sha->add("a", "bc");
     print "RESULT 2: " . $sha->hexdigest() . "\n";

     $sha->reset();
     $sha->add("ab", "c");
     print "RESULT 3: " . $sha->hexdigest() . "\n";

     $sha->reset();
     $sha->add("a", "b", "c");
     print "RESULT 4: " . $sha->hexdigest() . "\n";

     $sha->reset();
     $sha->add("ab");
     $sha->add("c");
     print "RESULT 5: " . $sha->hexdigest() . "\n";

     $sha->reset();
     $sha->add("a");
     $sha->add("bc");
     print "RESULT 6: " . $sha->hexdigest() . "\n";

     $sha->reset();
     $sha->add("a");
     $sha->add("b");
     $sha->add("c");
     print "RESULT 7: " . $sha->hexdigest() . "\n";

     print "RESULT 8: " . $sha->hexhash("abc") . "\n";

     $sha->reset();
     $sha->add("ab", "c");
     print "result a: " . unpack("H*", ($sha->digest())) . "\n";

     print "result b: " . unpack("H*", ($sha->hash("abc"))) . "\n";

The above example will produce the output

     EXPECT:   0164b8a9 14cd2a5e 74c4f7ff 082c4d97 f1edf880
     RESULT 1: 0164b8a9 14cd2a5e 74c4f7ff 082c4d97 f1edf880
     RESULT 2: 0164b8a9 14cd2a5e 74c4f7ff 082c4d97 f1edf880
     RESULT 3: 0164b8a9 14cd2a5e 74c4f7ff 082c4d97 f1edf880
     RESULT 4: 0164b8a9 14cd2a5e 74c4f7ff 082c4d97 f1edf880
     RESULT 5: 0164b8a9 14cd2a5e 74c4f7ff 082c4d97 f1edf880
     RESULT 6: 0164b8a9 14cd2a5e 74c4f7ff 082c4d97 f1edf880
     RESULT 7: 0164b8a9 14cd2a5e 74c4f7ff 082c4d97 f1edf880
     RESULT 8: 0164b8a9 14cd2a5e 74c4f7ff 082c4d97 f1edf880
     result a: 0164b8a914cd2a5e74c4f7ff082c4d97f1edf880
     result b: 0164b8a914cd2a5e74c4f7ff082c4d97f1edf880

provided that the implementation is working correctly.

NOTE
====

The SHA extension may be redistributed under the same terms as Perl.  The
SHA code is in the public domain. It was heavily modified by Uwe
Hollerbach following the implementation by Peter Gutmann.

AUTHOR
======

The SHA interface was written by Uwe Hollerbach `uh@alumni.caltech.edu',
shamelessly stealing from the MD5 interface written by Neil Winton
(`N.Winton@axion.bt.co.uk').


File: pm.info,  Node: Safe,  Next: Search/Base,  Prev: SHA,  Up: Module List

Compile and execute code in restricted compartments
***************************************************

NAME
====

Safe - Compile and execute code in restricted compartments

SYNOPSIS
========

     use Safe;

     $compartment = new Safe;

     $compartment->permit(qw(time sort :browse));

     $result = $compartment->reval($unsafe_code);

DESCRIPTION
===========

The Safe extension module allows the creation of compartments in which
perl code can be evaluated. Each compartment has

a new namespace
     The "root" of the namespace (i.e. "main::") is changed to a different
     package and code evaluated in the compartment cannot refer to
     variables outside this namespace, even with run-time glob lookups and
     other tricks.

     Code which is compiled outside the compartment can choose to place
     variables into (or share variables with) the compartment's namespace
     and only that data will be visible to code evaluated in the
     compartment.

     By default, the only variables shared with compartments are the
     "underscore" variables $_ and @_ (and, technically, the less
     frequently used %_, the _ filehandle and so on). This is because
     otherwise perl operators which default to $_ will not work and
     neither will the assignment of arguments to @_ on subroutine entry.

an operator mask
     Each compartment has an associated "operator mask". Recall that perl
     code is compiled into an internal format before execution.
     Evaluating perl code (e.g. via "eval" or "do 'file'") causes the code
     to be compiled into an internal format and then, provided there was
     no error in the compilation, executed.  Code evaulated in a
     compartment compiles subject to the compartment's operator mask.
     Attempting to evaulate code in a compartment which contains a masked
     operator will cause the compilation to fail with an error. The code
     will not be executed.

     The default operator mask for a newly created compartment is the
     ':default' optag.

     It is important that you read the Opcode(3) module documentation for
     more information, especially for detailed definitions of opnames,
     optags and opsets.

     Since it is only at the compilation stage that the operator mask
     applies, controlled access to potentially unsafe operations can be
     achieved by having a handle to a wrapper subroutine (written outside
     the compartment) placed into the compartment. For example,

          $cpt = new Safe;
          sub wrapper {
              # vet arguments and perform potentially unsafe operations
          }
          $cpt->share('&wrapper');

WARNING
=======

The authors make *no warranty*, implied or otherwise, about the
suitability of this software for safety or security purposes.

The authors shall not in any case be liable for special, incidental,
consequential, indirect or other similar damages arising from the use of
this software.

Your mileage will vary. If in any doubt *do not use it*.

RECENT CHANGES
--------------

The interface to the Safe module has changed quite dramatically since
version 1 (as supplied with Perl5.002). Study these pages carefully if you
have code written to use Safe version 1 because you will need to makes
changes.

Methods in class Safe
---------------------

To create a new compartment, use

     $cpt = new Safe;

Optional argument is (NAMESPACE), where NAMESPACE is the root namespace to
use for the compartment (defaults to "Safe::Root0", incremented for each
new compartment).

Note that version 1.00 of the Safe module supported a second optional
parameter, MASK.  That functionality has been withdrawn pending deeper
consideration. Use the permit and deny methods described below.

The following methods can then be used on the compartment object returned
by the above constructor. The object argument is implicit in each case.

permit (OP, ...)
     Permit the listed operators to be used when compiling code in the
     compartment (in *addition* to any operators already permitted).

permit_only (OP, ...)
     Permit *only* the listed operators to be used when compiling code in
     the compartment (no other operators are permitted).

deny (OP, ...)
     Deny the listed operators from being used when compiling code in the
     compartment (other operators may still be permitted).

deny_only (OP, ...)
     Deny *only* the listed operators from being used when compiling code
     in the compartment (all other operators will be permitted).

trap (OP, ...)
untrap (OP, ...)
     The trap and untrap methods are synonyms for deny and permit
     respectfully.

share (NAME, ...)
     This shares the variable(s) in the argument list with the compartment.
     This is almost identical to exporting variables using the
     `Exporter(3)' in this node module.

     Each NAME must be the *name* of a variable, typically with the leading
     type identifier included. A bareword is treated as a function name.

     Examples of legal names are '$foo' for a scalar, '@foo' for an array,
     '%foo' for a hash, '&foo' or 'foo' for a subroutine and '*foo' for a
     glob (i.e.  all symbol table entries associated with "foo", including
     scalar, array, hash, sub and filehandle).

     Each NAME is assumed to be in the calling package. See share_from for
     an alternative method (which share uses).

share_from (PACKAGE, ARRAYREF)
     This method is similar to share() but allows you to explicitly name
     the package that symbols should be shared from. The symbol names
     (including type characters) are supplied as an array reference.

          $safe->share_from('main', [ '$foo', '%bar', 'func' ]);

varglob (VARNAME)
     This returns a glob reference for the symbol table entry of VARNAME in
     the package of the compartment. VARNAME must be the *name* of a
     variable without any leading type marker. For example,

          $cpt = new Safe 'Root';
          $Root::foo = "Hello world";
          # Equivalent version which doesn't need to know $cpt's package name:
          ${$cpt->varglob('foo')} = "Hello world";

reval (STRING)
     This evaluates STRING as perl code inside the compartment.

     The code can only see the compartment's namespace (as returned by the
     root method). The compartment's root package appears to be the
     `main::' package to the code inside the compartment.

     Any attempt by the code in STRING to use an operator which is not
     permitted by the compartment will cause an error (at run-time of the
     main program but at compile-time for the code in STRING).  The error
     is of the form "%s trapped by operation mask operation...".

     If an operation is trapped in this way, then the code in STRING will
     not be executed. If such a trapped operation occurs or any other
     compile-time or return error, then $@ is set to the error message,
     just as with an eval().

     If there is no error, then the method returns the value of the last
     expression evaluated, or a return statement may be used, just as with
     subroutines and *eval()*. The context (list or scalar) is determined
     by the caller as usual.

     This behaviour differs from the beta distribution of the Safe
     extension where earlier versions of perl made it hard to mimic the
     return behaviour of the eval() command and the context was always
     scalar.

     Some points to note:

     If the entereval op is permitted then the code can use eval "..." to
     'hide' code which might use denied ops. This is not a major problem
     since when the code tries to execute the eval it will fail because the
     opmask is still in effect. However this technique would allow clever,
     and possibly harmful, code to 'probe' the boundaries of what is
     possible.

     Any string eval which is executed by code executing in a compartment,
     or by code called from code executing in a compartment, will be eval'd
     in the namespace of the compartment. This is potentially a serious
     problem.

     Consider a function foo() in package pkg compiled outside a
     compartment but shared with it. Assume the compartment has a root
     package called 'Root'. If foo() contains an eval statement like eval
     '$foo = 1' then, normally, $pkg::foo will be set to 1.  If foo() is
     called from the compartment (by whatever means) then instead of
     setting $pkg::foo, the eval will actually set $Root::pkg::foo.

     This can easily be demonstrated by using a module, such as the Socket
     module, which uses eval "..." as part of an AUTOLOAD function. You can
     'use' the module outside the compartment and share an (autoloaded)
     function with the compartment. If an autoload is triggered by code in
     the compartment, or by any code anywhere that is called by any means
     from the compartment, then the eval in the Socket module's AUTOLOAD
     function happens in the namespace of the compartment. Any variables
     created or used by the eval'd code are now under the control of the
     code in the compartment.

     A similar effect applies to all runtime symbol lookups in code called
     from a compartment but not compiled within it.

rdo (FILENAME)
     This evaluates the contents of file FILENAME inside the compartment.
     See above documentation on the reval method for further details.

root (NAMESPACE)
     This method returns the name of the package that is the root of the
     compartment's namespace.

     Note that this behaviour differs from version 1.00 of the Safe module
     where the root module could be used to change the namespace. That
     functionality has been withdrawn pending deeper consideration.

mask (MASK)
     This is a get-or-set method for the compartment's operator mask.

     With no MASK argument present, it returns the current operator mask of
     the compartment.

     With the MASK argument present, it sets the operator mask for the
     compartment (equivalent to calling the deny_only method).

Some Safety Issues
------------------

This section is currently just an outline of some of the things code in a
compartment might do (intentionally or unintentionally) which can have an
effect outside the compartment.

Memory
     Consuming all (or nearly all) available memory.

CPU
     Causing infinite loops etc.

Snooping
     Copying private information out of your system. Even something as
     simple as your user name is of value to others. Much useful
     information could be gleaned from your environment variables for
     example.

Signals
     Causing signals (especially SIGFPE and SIGALARM) to affect your
     process.

     Setting up a signal handler will need to be carefully considered and
     controlled.  What mask is in effect when a signal handler gets
     called?  If a user can get an imported function to get an exception
     and call the user's signal handler, does that user's restricted mask
     get re-instated before the handler is called?  Does an imported
     handler get called with its original mask or the user's one?

State Changes
     Ops such as chdir obviously effect the process as a whole and not just
     the code in the compartment. Ops such as rand and srand have a similar
     but more subtle effect.

AUTHOR
------

Originally designed and implemented by Malcolm Beattie,
mbeattie@sable.ox.ac.uk.

Reworked to use the Opcode module and other changes added by Tim Bunce
<`Tim.Bunce@ig.co.uk'>.


File: pm.info,  Node: Search/Base,  Next: Search/Dict,  Prev: Safe,  Up: Module List

provide framework for multiple searches
***************************************

NAME
====

Search.pm - provide framework for multiple searches

SYNOPSIS
========

     use Search::TextSearch;
     use Search::Glimpse;

DESCRIPTION
===========

This module is a base class interfacing to search engines. It defines an
interface that can be used by any of the Search search modules, such as
Search::Glimpse or Search::TextSearch, which are the standard ones included
with the module.

It exports no routines, just provides methods for the other classes.

Search Comparisons
------------------

     Text           Glimpse
                             -------        --------
      Speed                   Medium        Dependent on uniqueness of terms
      Requires add'l software No            Yes
      Search individually     Yes           Yes
       for fields
      Search multiple files   Yes           Yes
      Allows spelling errors  No            Yes
      Fully grouped matching  No            No

Methods
=======

Only virtual methods are supported by the Search::Base class. Those search
modules that inherit from it may export static methods if desired. There
are the `Global Parameter Method' in this node, `Column Setting Functions'
in this node, and `Row Setting Functions' in this node. `SEE ALSO' in this
node Search::Glimpse, Search::TextSearch.

Global Parameter Method
-----------------------

     $s->global(param,val);
     $status = $s->global(param);
     %globals = $s->global();

Allows setting of the parameters that are global to the search. The
standard ones are listed below.

base_directory
     Those engines which look for matches in index files can read this to
     get the base directory of the images.

case_sensitive
     This is a global version of the cases field. If set, the search
     engine should return only matches which exactly match, including
     distinction between lower- and upper-case letters.  The default is not
     set, to ignore case.

error_page
     A page or filename to be displayed when a user error occurs.  Passed
     along with a single string parameter to the error_routine, as in:

     &{$self->{global}->{error_routine}}
     ($self->{global}->{error_page}, $msg);

error_routine
     Reference to a subroutine which will send errors to the user. The
     default is '\&croak'.

first_match
     The number of the first match returned in a of more_matches. This
     tells the calling program where to start their increment.

history
     The number of searches to keep in the history.

head_skip
     Used for the TextSearch module to indicate lines that should be
     skipped at the beginning of the file. Allows a header to be skipped if
     it should not be searched.

     The number of searches to keep in the history.

index_delim
     The delimiter character to terminate the return code in an ascii
     index file. In Search::Glimpse and Search::TextSearch, the default is
     "\t", or TAB.  This is also the default for {return_delim} if that is
     not set.

     If field-matching is being used, this the character/string used for
     splitting the fields.  If properly escaped, and {return_delim} is
     used for joining fields, it can be a regular expression - Perl style.

index_file
     A specification of an index file (or files) to search.  The usage is
     left to the module - it could, for example, be an anonymous array (as
     in Search::TextSearch) or wild-card specification for multiple indices
     (as in Search::Glimpse).

log_routine
     A reference to a subroutine to log an error or status indication.  By
     default, it is '\&Carp::carp';

match_limit
     The number of matches to return.  Not to be confused with max_matches,
     at which number the search will terminate. Additional matches will be
     stored in the file pointed to by save_dir, session_id, and search_mod.
     The default is 50.

matches
     Set by the search routine to indicate the number of matches in the
     last search. If the engine can return the total number of matches
     (without the data) then that is the result.

min_string
     The minimum size of search string that is supported. Using a size of
     less than 4 for Glimpse, for example, is not wise.

next_pointer
     The pointer to the next list of matches. This is for engines that can
     return only a subset of the elements starting from an element.  For
     making a next match list.

next_url
     The base URL that should be used to invoke the more_matches function.
     Provided as an object-contained scratchpad value for the calling
     routine - it will not be used or modified by Search::Base.

     There are a couple of useful ways to use this to invoke the proper
     more_matches search that are shown in the example search CGI provided
     with this module set. Both involve setting the next_url and combining
     it with a random session_id and search_mod.

or_search
     If set, the search engine should return matches which match any of the
     search patterns.  The default is not set, requiring matches to all of
     the keywords for a match return.

overflow
     Set by the search routine if it matched the maximum number before
     reaching the end of the search. Set to undef if not supported.

record_delim
     This sets the type of record that will be searched. For the
     Search::TextSearch module, this is the same as Perl - in fact, the
     default is to use $/ (at the time of object creation) as the default.

     For the Search::Glimpse module, the following mappings occur:

          $/ = "\n"        Glimpse default
          $/ = "\n\n"      -d '$$'
          $/ = ""          -d '$$'
          $/ = undef       -d 'NeVAiRbE'
          anything else    passed on as is (-d 'whatever')

     One useful pattern is '^From ', which will make each email message in
     a folder a separate record.

     If you are doing this, and expect to be doing field returns, it will
     probably be useful to set "\n\n" or "\n" as the default index_delim.
     If used in combination with the obscure anonymous hash definition of
     return_fields, you can search and return mail headers on each message
     that matches.

return_delim
     The delimiter character to join fields that are cut out of the
     matched line/paragraph/page. The default is to set it to be the same
     as {index_delim} if not explicitly set.

return_fields
     The fields that will be returned from the line/paragraph/page
     matched.  This is not to be confused with the fields setting - it
     will not affect the matching, only the returned fields.  The default
     (when it is undefined) is to return only the first field.  There are
     several options for this field.

     If the value is an ARRAY reference, an integer list of the columns to
     be returned is assumed.

     If the value is a HASH reference, then all words found AFTER the
     *key* of the hash (with assumed but not required whitespace as a
     separator) up to the value of the item (used as a delimiter).  The
     following  example will print the value of the From:, Reply-to: and
     Date: headers from any message in your (UNIX) system mailbox that
     contains 'foobar'.

          $s = new Search::TextSearch
                  return_fields => {
                                  From: => "\n",
                                  Reply-To: => "\n",
                                  Date: => "\n",
                                  },
                  record_delim    => "\nFrom ",
                  search_file     => $ENV{MAIL};

          print $s->search('foobar');

return_file_name
     All return options will be ignored, and the file names of any matches
     will be returned instead. The limit match-to-field routines are still
     enabled for Search::TextSearch, but not for Glimpse, since the
     'glimpse -l' option is used for that.

save_dir
     The directory that search caches (for the more_matches function) will
     be saved in.  Only applies to file save mode.

search_history
     An anonymous array [size history] of 'unevaled' strings that contain
     the search history.  When evaled by the Search::Base module, will
     create an environment in the object that duplicates previous searches.
     It is up to the application to save the value.

search_mod
     This is used to develop a unique search save id for a user with a
     consistent session_id.  For the more_matches function.

search_port
     The port (passed to glimpse with the *-K* option) that is to be used
     for a network-attached search server.

search_server
     The host name of a network-attached search server, passed to glimpse
     with the *-J* option.

session_id
     This is used to determine the save file name or hash key used to
     cache a search (for the more_matches) function.

speed
     The speed of search desired, in an integer value from one to 10.
     Those engines that have a faster method to search (possibly at a cost
     of comprensivity) can adjust their routines accordingly.

spelling_errors
     Those engines that support "tolerant matching" can honor this
     parameter to set the number of spelling errors that they will allow
     for.  *This can slow search dramatically on big databases.* Ignored by
     search engines that don't have the capability.

substring_match
     If set, the search engine should return partial, or substring,
     matches.  The default is not set, to indicate whole word matching.
     *This can slow search dramatically on big databases.*

uneval_routine
     A reference to a subroutine to save the search history to a cache.
     By default, it is '\&uneval', the routine supplied with Search::Base.

METHODS
=======

Virtual methods provided
------------------------

more_matches
     Given a file with return codes from previous searches, one per line,
     returns an array with the correct matches in the array.  Opens the
     file in directory save_dir, with session information appended (the
     session_id and search_mod), and returns match_limit matches, starting
     at next_pointer.

search
     This is the main method defined in the individual search engine.  You
     can submit a single parameter for a quick search, which will be
     interpreted as the one and only search specification, overriding any
     settings residing in the specs array.  Options can be specified at
     object creation, or separately with the *global* method. Or a
     *search_spec* can be specified, which will temporarily override the
     setting in specs (for that invocation only).

     Otherwise, the parameters are named search options as documented
     above.  Examples:

          # Simple search with default options for 'foobar' in the named file
          $s = new Search::TextSearch search_file => '/var/adm/messages');
          @found = $s->search('foobar');

          # Search for 'foobar' in /var/adm/messages, return only fields 0 and 2
          # where fields are separated by spaces
          $s = new Search::TextSearch;
          @found = $s->search( search_file   => '/var/adm/messages',
                               search_spec   => 'foobar',
                               return_fields => [0,2],
                               return_delim  => ' ',
                               index_delim   => '\s+'                 );

          # Search for 'foobar' in any file containing 'messages' in
          # the default glimpse index, return the file names
          $s = new Search::Glimpse;
          @found = $s->search( search_spec   => 'foobar',
                               search_file   => 'messages',
                               return_file_name  => 1,       );

          # Same as above except use glimpse index located in /var directory
          $s = new Search::Glimpse;
          @found = $s->search( search_spec       => 'foobar',
                               base_directory    => '/var',
                               search_file       => 'messages',
                               return_file_name  => 1,       );

          # Search all files in /etc
          # Return file names with  lines that have 'foo' in field 1
          # and 'bar' in field 3, with case sensitivity
          # (using the default field delimiter of \t)
          $s = new Search::TextSearch;
          $s->rowpush('foo', 1);
          $s->rowpush('bar', 3);
          chop(@files = `ls /etc`);
          @found = $s->search( search_file   => [@files],
                               case_sensitive  => 1,
                               return_file_name  => 1,       );

          # Same as above using direct access to specs/fields
          $s = new Search::TextSearch;
          $s->specs('foo', 'bar');
          $s->fields(1, 3);
          chop(@files = `ls /etc`);
          @found = $s->search( search_file   => [@files],
                               case_sensitive  => 1,
                               return_file_name  => 1,       );
          # Repeat search with above settings, except for specs,
          # if less than 4 matches are found
          if(@found < 4) {
              @found = $s->search('foo');
          }

Column Setting Methods
----------------------

Column setting functions allow the setting of a series of columns of match
criteria:

     $search->specs('foo', 'foo bar', 'foobar');
     $search->fields(1, 3, 4);

This is an example for the specs and fields match criteria, which are the
search specifications and  the the fields to search, respectively. Similar
functions are provided for mods, links, cases, negates, open_parens, and
close_parens.

For the included Search::Glimpse and Search::TextSearch modules, an item
will match the above example only if field (or column) 1 contains 'foo',
field 3 contains 'foo' and/or 'bar', and field 4 contains foobar.  The
setting of the case_sensitive, or_search, and substring_match terms will
be honored as well.

For simple searches, only one term need be set, and the grouping functions
links, open_parens, and close_parens are ignored.  In most cases, if the
setting for a particular column is not defined for a row, the value in the
global setting is used.

specs
     The search text, raw, per field. This is the only item that
     necessarily needs to be set to do a search.

     If more than one specification is present, there are three forms of
     behavior supported by the included Search::TextSearch and
     Search::Glimpse modules. First, if there are multiple search
     specifications, they are combined together, just as they would if
     separated by spaces (and not quoted).  Second, if the number of specs
     matches the number of fields, each spec must match the field that it
     is associated with (subject to the or_search and case_sensitive
     settings within that field). Last, if there are more fields than
     specs, only the columns in fields are searched for the combined specs.

fields
     The column *numbers* to search, where a column is a field separated by
     index_delim. In the Search::TextSearch and Search::Glimpse modules,
     this becomes operative in one of two ways. If the number of specs
     match the number of fields, each specification is separately checked
     against its associated field.  If the number of fields is different
     from the number of specs, all specs are applied, but only to the text
     in the specified fields.  Both first match on all of the text in the
     row, then filter the match with another routine that checks for
     matches in the specified fields.

mods
     Modifies the match criteria. Recognized modifications might be:

          start   Matches when the field starts with the spec
          sub     Match substrings.

     Not supported in the included modules.

links
     The link to the previous row. If there are two fields to search, with
     two different specs, this determines whether the search is AND, OR,
     or NEAR.  For engines that support it, NEAR matches with in
     $self->global('near') words of the previous word (forward only). Not
     supported in the included modules.

cases
     For advanced search engines that support full associative
     case-sensitivity.  Determines whether the particular match in this set
     will be case-sensitive or not.  If the search engine doesn't support
     independent case-sensitivity (like the Search::TextSearch and
     Search::Glimpse modules), the value in or_search will be used. Not
     supported in the included modules.

negates
     Negates the sense of the match for that term.  Allows searches like
     "spec1 AND NOT spec2" or "NOT spec1 AND spec2". Not supported in the
     included modules.

open_parens
     Determines whether a logical parentheses will be placed on the left
     of the term. Allows grouping of search terms for more expressive
     matching, i.e. "(AUTHOR Shakespeare AND TYPE Play ) NOT TITLE
     Hamlet". Not supported in the included modules.

close_parens
     Determines whether a logical parentheses will be placed on the right
     of the term. Not supported in the included modules.

Row Setting Methods
-------------------

Row setting functions allow the setting of all columns in a row.

     $query->rowpush($field,$spec,$case,$mod,$link,$left,$right);
     ($field,$spec,$case,$mod,$link,$left,$right) = $query->rowpop();
     @oldvals = $query->rowset(n,$field,$spec,$case,$mod,$link,$left,$right);

You can ignore the trailing parameters for a simple search. For example:

     $field = 'author';
     $spec = 'forsythe';
     $limit = 25;
     $query = new Search::Glimpse;
     $query->rowpush($field,$spec);
     @rows = $query->search( match_limit => 25 );

This searches the field 'author' for the name 'forsythe', with all other
options at their defaults (ignore case, match substrings, not negated, no
links, no grouping), and will return 25 matches (sets the matchlimit
global).  For a more complex search, you can add the rest of the
parameters as needed.

SEE ALSO
========

glimpse(1), Search::Glimpse(3L), Search::TextSearch(3L)

AUTHOR
======

Mike Heins, <mikeh@iac.net>


File: pm.info,  Node: Search/Dict,  Next: SelectSaver,  Prev: Search/Base,  Up: Module List

search for key in dictionary file
*********************************

NAME
====

Search::Dict, look - search for key in dictionary file

SYNOPSIS
========

     use Search::Dict;
     look *FILEHANDLE, $key, $dict, $fold;

DESCRIPTION
===========

Sets file position in FILEHANDLE to be first line greater than or equal
(stringwise) to *$key*.  Returns the new file position, or -1 if an error
occurs.

The flags specify dictionary order and case folding:

If *$dict* is true, search by dictionary order (ignore anything but word
characters and whitespace).

If *$fold* is true, ignore case.


File: pm.info,  Node: SelectSaver,  Next: SelfLoader,  Prev: Search/Dict,  Up: Module List

save and restore selected file handle
*************************************

NAME
====

SelectSaver - save and restore selected file handle

SYNOPSIS
========

     use SelectSaver;

     {
        my $saver = new SelectSaver(FILEHANDLE);
        # FILEHANDLE is selected
     }
     # previous handle is selected

     {
        my $saver = new SelectSaver;
        # new handle may be selected, or not
     }
     # previous handle is selected

DESCRIPTION
===========

A `SelectSaver' object contains a reference to the file handle that was
selected when it was created.  If its new method gets an extra parameter,
then that parameter is selected; otherwise, the selected file handle
remains unchanged.

When a `SelectSaver' is destroyed, it re-selects the file handle that was
selected when it was created.


File: pm.info,  Node: SelfLoader,  Next: Set/IntSpan,  Prev: SelectSaver,  Up: Module List

load functions only on demand
*****************************

NAME
====

SelfLoader - load functions only on demand

SYNOPSIS
========

     package FOOBAR;
     use SelfLoader;
     
     ... (initializing code)
     
     __DATA__
     sub {....

DESCRIPTION
===========

This module tells its users that functions in the FOOBAR package are to be
autoloaded from after the `__DATA__' token.  See also `"Autoloading"',
*Note Perlsub: (perl.info)perlsub,.

The __DATA__ token
------------------

The `__DATA__' token tells the perl compiler that the perl code for
compilation is finished. Everything after the `__DATA__' token is
available for reading via the filehandle FOOBAR::DATA, where FOOBAR is the
name of the current package when the `__DATA__' token is reached. This
works just the same as __END__ does in package 'main', but for other
modules data after __END__ is not automatically retreivable , whereas data
after `__DATA__' is.  The `__DATA__' token is not recognized in versions
of perl prior to 5.001m.

Note that it is possible to have `__DATA__' tokens in the same package in
multiple files, and that the last `__DATA__' token in a given package that
is encountered by the compiler is the one accessible by the filehandle.
This also applies to __END__ and main, i.e. if the 'main' program has an
__END__, but a module 'require'd (_not_ 'use'd) by that program has a
'package main;' declaration followed by an '`__DATA__'', then the `DATA'
filehandle is set to access the data after the `__DATA__' in the module,
_not_ the data after the __END__ token in the 'main' program, since the
compiler encounters the 'require'd file later.

SelfLoader autoloading
----------------------

The SelfLoader works by the user placing the `__DATA__' token *after* perl
code which needs to be compiled and run at 'require' time, but *before*
subroutine declarations that can be loaded in later - usually because they
may never be called.

The SelfLoader will read from the FOOBAR::DATA filehandle to load in the
data after `__DATA__', and load in any subroutine when it is called. The
costs are the one-time parsing of the data after `__DATA__', and a load
delay for the _first_ call of any autoloaded function. The benefits
(hopefully) are a speeded up compilation phase, with no need to load
functions which are never used.

The SelfLoader will stop reading from `__DATA__' if it encounters the
__END__ token - just as you would expect.  If the __END__ token is
present, and is followed by the token DATA, then the SelfLoader leaves the
FOOBAR::DATA filehandle open on the line after that token.

The SelfLoader exports the AUTOLOAD subroutine to the package using the
SelfLoader, and this loads the called subroutine when it is first called.

There is no advantage to putting subroutines which will _always_ be called
after the `__DATA__' token.

Autoloading and package lexicals
--------------------------------

A 'my $pack_lexical' statement makes the variable $pack_lexical local
_only_ to the file up to the `__DATA__' token. Subroutines declared
elsewhere _cannot_ see these types of variables, just as if you declared
subroutines in the package but in another file, they cannot see these
variables.

So specifically, autoloaded functions cannot see package lexicals (this
applies to both the SelfLoader and the Autoloader).  The vars pragma
provides an alternative to defining package-level globals that will be
visible to autoloaded routines. See the documentation on vars in the
pragma section of *Note Perlmod: (perl.info)perlmod,.

SelfLoader and AutoLoader
-------------------------

The SelfLoader can replace the AutoLoader - just change 'use AutoLoader'
to 'use SelfLoader' (though note that the SelfLoader exports the AUTOLOAD
function - but if you have your own AUTOLOAD and are using the AutoLoader
too, you probably know what you're doing), and the __END__ token to
`__DATA__'. You will need perl version 5.001m or later to use this
(version 5.001 with all patches up to patch m).

There is no need to inherit from the SelfLoader.

The SelfLoader works similarly to the AutoLoader, but picks up the subs
from after the `__DATA__' instead of in the 'lib/auto' directory.  There
is a maintainance gain in not needing to run AutoSplit on the module at
installation, and a runtime gain in not needing to keep opening and
closing files to load subs. There is a runtime loss in needing to parse
the code after the `__DATA__'. Details of the AutoLoader and another view
of these distinctions can be found in that module's documentation.

__DATA__, __END__, and the FOOBAR::DATA filehandle.
---------------------------------------------------

This section is only relevant if you want to use the `FOOBAR::DATA'
together with the SelfLoader.

Data after the `__DATA__' token in a module is read using the FOOBAR::DATA
filehandle. __END__ can still be used to denote the end of the `__DATA__'
section if followed by the token DATA - this is supported by the
SelfLoader. The `FOOBAR::DATA' filehandle is left open if an __END__
followed by a DATA is found, with the filehandle positioned at the start
of the line after the __END__ token. If no __END__ token is present, or an
__END__ token with no DATA token on the same line, then the filehandle is
closed.

The SelfLoader reads from wherever the current position of the
`FOOBAR::DATA' filehandle is, until the EOF or __END__. This means that if
you want to use that filehandle (and ONLY if you want to), you should
either

1. Put all your subroutine declarations immediately after the `__DATA__'
token and put your own data after those declarations, using the __END__
token to mark the end of subroutine declarations. You must also ensure
that the SelfLoader reads first by  calling 'SelfLoader->load_stubs();',
or by using a function which is selfloaded;

or

2. You should read the `FOOBAR::DATA' filehandle first, leaving the handle
open and positioned at the first line of subroutine declarations.

You could conceivably do both.

Classes and inherited methods.
------------------------------

For modules which are not classes, this section is not relevant.  This
section is only relevant if you have methods which could be inherited.

A subroutine stub (or forward declaration) looks like

     sub stub;

i.e. it is a subroutine declaration without the body of the subroutine.
For modules which are not classes, there is no real need for stubs as far
as autoloading is concerned.

For modules which ARE classes, and need to handle inherited methods, stubs
are needed to ensure that the method inheritance mechanism works properly.
You can load the stubs into the module at 'require' time, by adding the
statement 'SelfLoader->load_stubs();' to the module to do this.

The alternative is to put the stubs in before the `__DATA__' token BEFORE
releasing the module, and for this purpose the Devel::SelfStubber module
is available.  However this does require the extra step of ensuring that
the stubs are in the module. If this is done I strongly recommend that
this is done BEFORE releasing the module - it should NOT be done at
install time in general.

Multiple packages and fully qualified subroutine names
======================================================

Subroutines in multiple packages within the same file are supported - but
you should note that this requires exporting the `SelfLoader::AUTOLOAD' to
every package which requires it. This is done automatically by the
SelfLoader when it first loads the subs into the cache, but you should
really specify it in the initialization before the `__DATA__' by putting a
'use SelfLoader' statement in each package.

Fully qualified subroutine names are also supported. For example,

     __DATA__
     sub foo::bar {23}
     package baz;
     sub dob {32}

will all be loaded correctly by the SelfLoader, and the SelfLoader will
ensure that the packages 'foo' and 'baz' correctly have the SelfLoader
AUTOLOAD method when the data after `__DATA__' is first parsed.


File: pm.info,  Node: Set/IntSpan,  Next: Shell,  Prev: SelfLoader,  Up: Module List

Manages sets of integers
************************

NAME
====

Set::IntSpan - Manages sets of integers

SYNOPSIS
========

     use Set::IntSpan;

     $Set::IntSpan::Empty_String = $string;

     $set    = new   Set::IntSpan $set_spec;
     $valid  = valid Set::IntSpan $run_list;
     copy $set $set_spec;
     
     $run_list	= run_list $set;
     @elements	= elements $set;
     
     $u_set = union	$set $set_spec;
     $i_set = intersect	$set $set_spec;
     $x_set = xor	$set $set_spec;
     $d_set = diff	$set $set_spec;
     $c_set = complement	$set;
     
     equal	$set $set_spec;
     equivalent	$set $set_spec;
     superset	$set $set_spec;
     subset	$set $set_spec;
     
     $n = cardinality $set;

     empty	$set;
     finite	$set;
     neg_inf	$set;
     pos_inf	$set;
     infinite	$set;
     universal	$set;
     
     member	$set $n;
     insert	$set $n;
     remove	$set $n;

     $min = min  $set;
     $max = max  $set;

REQUIRES
========

Perl 5.002

Exporter

EXPORTS
=======

None

DESCRIPTION
===========

Set::IntSpan manages sets of integers.  It is optimized for sets that have
long runs of consecutive integers.  These arise, for example, in .newsrc
files, which maintain lists of articles:

     alt.foo: 1-21,28,31
     alt.bar: 1-14192,14194,14196-14221

Sets are stored internally in a run-length coded form.  This provides for
both compact storage and efficient computation.  In particular, set
operations can be performed directly on the encoded representation.

Set::IntSpan is designed to manage finite sets.  However, it can also
represent some simple infinite sets, such as {x | x>n}.  This allows
operations involving complements to be carried out consistently, without
having to worry about the actual value of MAXINT on your machine.

SET SPECIFICATIONS
==================

Many of the methods take a *set specification*.  There are four kinds of
set specifications.

Empty
-----

If a set specification is omitted, then the empty set is assumed.  Thus,

     $set = new Set::IntSpan;

creates a new, empty, set.  Similarly,

     copy $set;

removes all elements from $set.

Object reference
----------------

If an object reference is given, it is taken to be a Set::IntSpan object.

Array reference
---------------

If an array reference is given, then the elements of the array are taken
to be the elements of the set.  The array may contain duplicate elements.
The elements of the array may be in any order.

Run list
--------

If a string is given, it is taken to be a *run list*.  A run list
specifies a set using a syntax similar to that in .newsrc files.

A run list is a comma-separated list of *runs*.  Each run specifies a set
of consecutive integers.  The set is the union of all the runs.

Runs may be written in any of several forms.

Finite forms
------------

n
     { n }

a-b
     {x | a<=x && x<=b}

Infinite forms
--------------

(-n
     {x | x<=n}

n-)
     {x | x>=n}

(-)
     The set of all integers

Empty forms
-----------

The empty set is consistently written as '' (the null string).  It is also
denoted by the special form '-' (a single dash).

Restrictions
------------

The runs in a run list must be disjoint, and must be listed in increasing
order.

Valid characters in a run list are 0-9, '(', ')', '-' and ','.  White
space and underscore (_) are ignored.  Other characters are not allowed.

Examples
--------

-
     { }


     { 1 }


     { 1, 2 }

-5-1
     { -5, -4, -3, -2, -1 }

(-)
     the integers

(-1
     the negative integers

4, 18-21
     { 1, 2, 3, 4, 18, 19, 20, 21 }

METHODS
=======

Creation
--------

new Set::IntSpan $set_spec;
     Creates and returns a new set.  The initial contents of the set are
     given by $set_spec.

valid Set::IntSpan $run_list;
     Returns true if $run_list is a valid run list.  Otherwise, returns
     false and leaves an error message in $@.

copy $set $set_spec;
     Copies $set_spec into $set.  The previous contents of $set are lost.
     For convenience, copy() returns $set.

$run_list = run_list $set
     Returns a run list that represents $set.  The run list will not
     contain white space.  $set is not affected.

     By default, the empty set is formatted as '-'; a different string may
     be specified in $Set::IntSpan::Empty_String.

@elements = elements $set;
     Returns an array containing the elements of $set.  The elements will
     be sorted in numerical order.  In scalar context, returns an array
     reference.  $set is not affected.

Set operations
--------------

$u_set = union $set $set_spec;
     returns the set of integers in either $set or $set_spec

$i_set = intersect $set $set_spec;
     returns the set of integers in both $set and $set_spec

$x_set = xor $set $set_spec;
     returns the set of integers in $set or $set_spec, but not both

$d_set = diff $set $set_spec;
     returns the set of integers in $set but not in $set_spec

$c_set = complement $set;
     returns the complement of $set.

For all set operations, a new Set::IntSpan object is created and returned.
The operands are not affected.

Comparison
----------

equal $set $set_spec;
     Returns true iff $set and $set_spec contain the same elements.

equivalent $set $set_spec;
     Returns true iff $set and $set_spec contain the same number of
     elements.  All infinite sets are equivalent.

superset $set $set_spec
     Returns true iff $set is a superset of $set_spec.

subset $set $set_spec
     Returns true iff $set is a subset of $set_spec.

Cardinality
-----------

$n = cardinality $set
     Returns the number of elements in $set.  Returns -1 for infinite sets.

empty $set;
     Returns true iff $set is empty.

finite $set
     Returns true iff $set is finite.

neg_inf $set
     Returns true iff $set contains {x | x<n} for some n.

pos_inf $set
     Returns true iff $set contains {x | x>n} for some n.

infinite $set
     Returns true iff $set is infinite.

universal $set
     Returns true iff $set contains all integers.

Membership
----------

member $set $n
     Returns true iff the integer $n is a member of $set.

insert $set $n
     Inserts the integer $n into $set.  Does nothing if $n is already a
     member of $set.

remove $set $n
     Removes the integer $n from $set.  Does nothing if $n is not a member
     of $set.

Extrema
-------

min $set
     Returns the smallest element of $set, or undef if there is none.

max $set
     Returns the largest element of $set, or undef if there is none.

CLASS VARIABLES
===============

$Set::IntSpan::Empty_String
     $Set::IntSpan::Empty_String contains the string that is returned when
     run_list() is called on the empty set.  $Empty_String is initially
     '-'; alternatively, it may be set to ''.  Other values should be
     avoided, to ensure that run_list() always returns a valid run list.

     run_list() accesses $Empty_String through a reference stored in
     $set->{empty_string}.  Subclasses that wish to override the value of
     $Empty_String can reassign this reference.

DIAGNOSTICS
===========

Any method (except valid()) will die() if it is passed an invalid run list.
Possible messages are:

Bad syntax
     $run_list has bad syntax

Bad order
     $run_list has overlapping runs or runs that are out of order.

elements $set will die() if $set is infinite.

elements $set can generate an "Out of memory!" message on sufficiently
large finite sets.

NOTES
=====

Traps
-----

Beware of forms like

     union $set [1..5];

This passes an element of @set to union, which is probably not what you
want.  To force interpretation of $set and [1..5] as separate arguments,
use forms like

     union $set +[1..5];

or

     $set->union([1..5]);

Error handling
--------------

There are two common approaches to error handling: exceptions and return
codes.  There seems to be some religion on the topic, so Set::IntSpan
provides support for both.

To catch exceptions, protect method calls with an eval:

     $run_list = <STDIN>;
     eval { $set = new Set::IntSpan $run_list };
     $@ and print "$@: try again\n";

To check return codes, use an appropriate method call to validate
arguments:

     $run_list = <STDIN>;
     if (valid Set::IntSpan $run_list)
        { $set = new Set::IntSpan $run_list }
     else
        { print "$@ try again\n" }

Similarly, use finite() to protect calls to elements():

     finite $set and @elements = elements $set;

Calling elements() on a large, finite set can generate an "Out of memory!"
message, which cannot be trapped.  Applications that must retain control
after an error can use intersect() to protect calls to elements():

     @elements = elements { intersect $set "-1_000_000 - 1_000_000" };

or check the size of $set first:

     finite $set and cardinality $set < 2_000_000 and @elements = elements $set;

Limitations
-----------

Although Set::IntSpan can represent some infinite sets, it does *not*
perform infinite-precision arithmetic.  Therefore, finite elements are
restricted to the range of integers on your machine.

Roots
-----

The sets implemented here are based on Macintosh data structures called
"regions".  See Inside Macintosh for more information.

AUTHOR
======

Steven McDougall <swm@cric.com>

COPYRIGHT
=========

Copyright (c) 1996 Steven McDougall.  All rights reserved.  This module is
free software; you can redistribute it and/or modify it under the same
terms as Perl itself.


File: pm.info,  Node: Shell,  Next: Socket,  Prev: Set/IntSpan,  Up: Module List

run shell commands transparently within perl
********************************************

NAME
====

Shell - run shell commands transparently within perl

SYNOPSIS
========

See below.

DESCRIPTION
===========

     Date: Thu, 22 Sep 94 16:18:16 -0700
     Message-Id: <9409222318.AA17072@scalpel.netlabs.com>
     To: perl5-porters@isu.edu
     From: Larry Wall <lwall@scalpel.netlabs.com>
     Subject: a new module I just wrote

Here's one that'll whack your mind a little out.

     #!/usr/bin/perl

     use Shell;

     $foo = echo("howdy", "<funny>", "world");
     print $foo;

     $passwd = cat("</etc/passwd");
     print $passwd;

     sub ps;
     print ps -ww;

     cp("/etc/passwd", "/tmp/passwd");

That's maybe too gonzo.  It actually exports an AUTOLOAD to the current
package (and uncovered a bug in Beta 3, by the way).  Maybe the usual
usage should be

     use Shell qw(echo cat ps cp);

Larry

AUTHOR
======

Larry Wall


File: pm.info,  Node: Socket,  Next: Sort/Versions,  Prev: Shell,  Up: Module List

load the C socket.h defines and structure manipulators
******************************************************

NAME
====

Socket, sockaddr_in, sockaddr_un, inet_aton, inet_ntoa - load the C
socket.h defines and structure manipulators

SYNOPSIS
========

     use Socket;

     $proto = getprotobyname('udp');
     socket(Socket_Handle, PF_INET, SOCK_DGRAM, $proto);
     $iaddr = gethostbyname('hishost.com');
     $port = getservbyname('time', 'udp');
     $sin = sockaddr_in($port, $iaddr);
     send(Socket_Handle, 0, 0, $sin);

     $proto = getprotobyname('tcp');
     socket(Socket_Handle, PF_INET, SOCK_STREAM, $proto);
     $port = getservbyname('smtp');
     $sin = sockaddr_in($port,inet_aton("127.1"));
     $sin = sockaddr_in(7,inet_aton("localhost"));
     $sin = sockaddr_in(7,INADDR_LOOPBACK);
     connect(Socket_Handle,$sin);

     ($port, $iaddr) = sockaddr_in(getpeername(Socket_Handle));
     $peer_host = gethostbyaddr($iaddr, AF_INET);
     $peer_addr = inet_ntoa($iaddr);

     $proto = getprotobyname('tcp');
     socket(Socket_Handle, PF_UNIX, SOCK_STREAM, $proto);
     unlink('/tmp/usock');
     $sun = sockaddr_un('/tmp/usock');
     connect(Socket_Handle,$sun);

DESCRIPTION
===========

This module is just a translation of the C `socket.h' file.  Unlike the
old mechanism of requiring a translated `socket.ph' file, this uses the
h2xs program (see the Perl source distribution) and your native C
compiler.  This means that it has a far more likely chance of getting the
numbers right.  This includes all of the commonly used pound-defines like
AF_INET, SOCK_STREAM, etc.

In addition, some structure manipulation functions are available:

inet_aton HOSTNAME
     Takes a string giving the name of a host, and translates that to the
     4-byte string (structure). Takes arguments of both the 'rtfm.mit.edu'
     type and '18.181.0.24'. If the host name cannot be resolved, returns
     undef.

inet_ntoa IP_ADDRESS
     Takes a four byte ip address (as returned by inet_aton()) and
     translates it into a string of the form 'd.d.d.d' where the 'd's are
     numbers less than 256 (the normal readable four dotted number
     notation for internet addresses).

INADDR_ANY
     Note: does not return a number, but a packed string.

     Returns the 4-byte wildcard ip address which specifies any of the
     hosts ip addresses. (A particular machine can have more than one ip
     address, each address corresponding to a particular network
     interface. This wildcard address allows you to bind to all of them
     simultaneously.) Normally equivalent to inet_aton('0.0.0.0').

INADDR_LOOPBACK
     Note - does not return a number.

     Returns the 4-byte loopback address. Normally equivalent to
     inet_aton('localhost').

INADDR_NONE
     Note - does not return a number.

     Returns the 4-byte invalid ip address. Normally equivalent to
     inet_aton('255.255.255.255').

sockaddr_in PORT, ADDRESS
sockaddr_in SOCKADDR_IN
     In an array context, unpacks its SOCKADDR_IN argument and returns an
     array consisting of (PORT, ADDRESS).  In a scalar context, packs its
     (PORT, ADDRESS) arguments as a SOCKADDR_IN and returns it.  If this
     is confusing, use pack_sockaddr_in() and unpack_sockaddr_in()
     explicitly.

pack_sockaddr_in PORT, IP_ADDRESS
     Takes two arguments, a port number and a 4 byte IP_ADDRESS (as
     returned by inet_aton()). Returns the sockaddr_in structure with
     those arguments packed in with AF_INET filled in.  For internet
     domain sockets, this structure is normally what you need for the
     arguments in bind(), connect(), and send(), and is also returned by
     getpeername(), getsockname() and recv().

unpack_sockaddr_in SOCKADDR_IN
     Takes a sockaddr_in structure (as returned by pack_sockaddr_in()) and
     returns an array of two elements: the port and the 4-byte ip-address.
     Will croak if the structure does not have AF_INET in the right place.

sockaddr_un PATHNAME
sockaddr_un SOCKADDR_UN
     In an array context, unpacks its SOCKADDR_UN argument and returns an
     array consisting of (PATHNAME).  In a scalar context, packs its
     PATHNAME arguments as a SOCKADDR_UN and returns it.  If this is
     confusing, use pack_sockaddr_un() and unpack_sockaddr_un() explicitly.
     These are only supported if your system has <`sys/un.h'>.

pack_sockaddr_un PATH
     Takes one argument, a pathname. Returns the sockaddr_un structure with
     that path packed in with AF_UNIX filled in. For unix domain sockets,
     this structure is normally what you need for the arguments in bind(),
     connect(), and send(), and is also returned by getpeername(),
     getsockname() and recv().

unpack_sockaddr_un SOCKADDR_UN
     Takes a sockaddr_un structure (as returned by pack_sockaddr_un()) and
     returns the pathname.  Will croak if the structure does not have
     AF_UNIX in the right place.


File: pm.info,  Node: Sort/Versions,  Next: Sprite,  Prev: Socket,  Up: Module List

a perl 5 module for sorting of revision-like numbers
****************************************************

NAME
====

Sort::Versions - a perl 5 module for sorting of revision-like numbers

SYNOPSIS
========

     use Sort::Versions;
     @l = sort versions qw( 1.2 1.2.0 1.2a.0 1.2.a 1.a 02.a );

     ...

     use Sort::Versions;
     print "lower" if versioncmp("1.2","1.2a")==-1;
     
     ...
     
     use Sort::Versions;
     %h = (1 => "d", 2 => "c", 3 => "b", 4 => "a");
     @h = sort {versioncmp $h{$a}, $h{$b}} keys %h;

DESCRIPTION
===========

Sort::Versions allows easy sorting of mixed non-numeric and numeric
strings, like the "version numbers" that many shared library systems and
revision control packages use. This is quite useful if you are trying to
deal with shared libraries. It can also be applied to applications that
intersperse variable-width numeric fields within text. Other applications
can undoubtedly be found.

For an explanation of the algorithm, it's simplest to look at these
examples:

     1.1   <  1.2
     1.1a  <  1.2
     1.1   <  1.1.1
     1.1   <  1.1a
     1.1.a <  1.1a
     1     <  a
     a     <  b
     1     <  2
     1     <  0002
     1.5   <  1.06

More precisely (but less comprehensibly), the two strings are treated as
subunits delimited by periods. Each subunit can contain any number of
groups of digits or non-digits. If digit groups are being compared on both
sides, a numeric comparison is used, otherwise a ASCII ordering is used. A
group or subgroup with more units will win if all comparisons are equal.

One important thing to note is that if a numeric comparison is made, then
leading zeros are ignored. Thus `1.5' sorts before `1.06', since two
separate comparisons are being made: `1 == 1', and `5 < 6'. This is *not*
the same as `if(1.5 < 1.06) {...}'.

USAGE
=====

Sort::Versions exports `versions' and `versioncmp'. The former is a
function suitable for handing directly to sort. The second function,
`versioncmp', takes two arguments and returns a cmp style comparison value.
This is handy in indirect comparisons, as shown above.

AUTHOR
======

Kenneth J. Albanowski		kjahds@kjahds.com

Copyright (c) 1996, Kenneth J. Albanowski. All rights reserved.  This
program is free software; you can redistribute it and/or modify it under
the same terms as Perl itself.


File: pm.info,  Node: Sprite,  Next: Statistics/ChiSquare,  Prev: Sort/Versions,  Up: Module List

Perl 5.0 module to manipulate text delimited databases.
*******************************************************

NAME
====

Sprite - Perl 5.0 module to manipulate text delimited databases.

SYNOPSIS
========

     use Sprite;

     $rdb = new Sprite ();

     $rdb->set_delimiter ("Read", "::");
     $rdb->set_delimiter ("Write", "::");

     $rdb->set_os ("UNIX");

     $rdb->sql (<<Query);
         .
         .
         .
     Query

     $rdb->close ();
     $rdb->close ($database);

DESCRIPTION
===========

Here is a simple database where the fields are delimted by commas:

     Player,Years,Points,Rebounds,Assists,Championships
     ...
     Larry Joe Bird,12,28,10,7,3
     Michael Jordan,10,33,6,5,3
     Earvin Magic Johnson,12,22,7,12,5
     ...

*Note:* The first line must contain the field names (case sensitive).

Supported SQL Commands
======================

Here are a list of the SQL commands that are supported by Sprite:

select - retrieves records that match specified criteria:
          select col1 [,col2] from database
              where (cond1 OPERATOR value1)
              [and|or cond2 OPERATOR value2 ...]

     The '*' operator can be used to select all columns.

     The *database* is simply the file that contains the data.  If the
     file is not in the current directory, the path must be specified.

     Sprite does *not* support multiple tables (or commonly knows as
     "joins").

     Valid column names can be used where [cond1..n] and [value1..n] are
     expected, such as:

     Example 1:

          select Player, Points from my_db
              where (Rebounds > Assists)

     The following SQL operators can be used: =, <, >, <=, >=, <> as well
     as Perl's special operators: =~ and !~. The =~ and !~ operators are
     used to specify regular expressions, such as:

     Example 2:

          select * from my_db
              where (Name =~ /Bird$/i)

     Selects records where the Name column ends with "Bird" (case
     insensitive). For more information, look at a manual on regexps.

update - updates records that match specified criteria.
          update database set (cond1 OPERATOR value1)[,(cond2 OPERATOR value2)...]*
             where (cond1 OPERATOR value1)
             [and|or cond2 OPERATOR value2 ...]

          * = This feature was added as of version 3.1.

     Example:

          update my_db
          	set Championships = (Championships + 1)
              where (Player = 'Larry Joe Bird')

          update my_db
               set Championships = (Championships + 1),
          	    Years = (12)

          where (Player = 'Larry Joe Bird')

delete - removes records that match specified criteria:
          delete from database
              where (cond1 OPERATOR value1)
              [and|or cond2 OPERATOR value2 ...]

     Example:

          delete from my_db
              where (Player =~ /Johnson$/i) or
                    (Years > 12)

alter - simplified version of SQL-92 counterpart
     Removes the specified column from the database. The other standard
     SQL functions for alter table are not supported:

          alter table database
              drop column column-name

     Example:

          alter table my_db
              drop column Championships

insert - inserts a record into the database:
          insert into database
              (col1, col2, ... coln)
          values
              (val1, val2, ... valn)

     Example:

          insert into my_db
              (Player, Years, Points, Championships)
          values
              ('Kareem Abdul-Jabbar', 21, 27, 5)

     *Note:* You do not have to specify all of the fields in the database!
     Sprite also does not require you to specify the fields in the same
     order as that of the database.

     *Note:* You should make it a habit to quote strings.

METHODS
=======

Here are the four methods that are available:

set_delimiter
     The set_delimiter function sets the read and write delimiter for the
     the SQL command. The delimiter is not limited to one character; you
     can have a string, and even a regexp (for reading only).

     *Return Value*

     None

set_os
     The set_os function can be used to notify Sprite as to the operating
     system that you're using. Valid arguments are: "UNIX", "VMS",
     "MSDOS", "NT" and "MacOS". UNIX is the default.

     *Return Value*

     The previous OS value

sql
     The sql function is used to pass a SQL command to this module. All of
     the SQL commands described above are supported. The select SQL
     command returns an array containing the data, where the first element
     is the status. All of the other other SQL commands simply return a
     status.

     *Return Value*     1 - Success     0 - Error

close
     The close function closes the file, and destroys the database object.
     You can pass a filename to the function, in which case Sprite will
     save the database to that file.

     *Return Value*

     None

EXAMPLES
========

Here are two simple examples that illustrate some of the functions of this
module:

Example 1
---------

     #!/usr/local/bin/perl5

     use Sprite;

     $rdb = new Sprite ();

     # Sets the read delimiter to a comma (,) character. The delimiter
     # is not limited to one character; you can have a string, or even
     # a regexp.

     $rdb->set_delimiter ("Read", ",");

     # Retrieves all records that match the criteria.

     @data = $rdb->sql (<<End_of_Query);

     select * from /shishir/nba
         where (Points > 25)

     End_of_Query

     # Close the database and destroy the database object (i.e $rdb).
     # Since we did not pass a argument to this function, the data
     # is not updated in any manner.

     $rdb->close ();

     # The first element of the array indicates the status.

     $status = shift (@data);
     $no_records = scalar (@data);

     if (!$status) {
     	die "Sprite database error. Check your query!", "\n";
     } elsif (!$no_records) {
     	print "There are no records that match your criteria!", "\n";
     	exit (0);
     } else {
         print "Here are the records that match your criteria: ", "\n";

     # The database returns a record where each field is
     # separated by the "\0" character.

     foreach $record (@data) {
                 $record =~ s/\0/,/g;
                 print $record, "\n";
             }
         }

Example 2
---------

     #!/usr/local/bin/perl5

     use Sprite;

     $rdb = new Sprite ();
     $rdb->set_delimiter ("Read", ",");

     # Deletes all records that match the specified criteria. If the
     # query contains an error, Sprite returns a status of 1.

     $rdb->sql (<<Delete_Query)
     		|| die "Database Error. Check your query", "\n";

     delete from /shishir/nba
         where (Rebounds <= 5)

     Delete_Query

     # Access the database again! This time, select all the records that
     # match the specified criteria. The database is updated *internally*
     # after the previous delete statement.

     # Notice the fact that the full path to the database does not
     # need to specified after the first SQL command. This
     # works correctly as of version 3.1.

     @data = $rdb->sql (<<End_of_Query);

     select Player from nba
         where (Points > 25)

     End_of_Query

     # Sets the write delimiter to the (:) character, and outputs the
     # updated information to the file: "nba.new". If you do not pass
     # an argument to the close function after you update the database,
     # the modified information will not be saved.

     $rdb->set_delimiter ("Write", ":");
     $rdb->close ("nba.new");

     # The first element of the array indicates the status.

     $status = shift (@data);
     $no_records = scalar (@data);

     if (!$status) {
     	die "Sprite database error. Check your query!", "\n";
     } elsif (!$no_records) {
     	print "There are no records that match your criteria!", "\n";
     	exit (0);
     } else {
         print "Here are the records that match your criteria: ", "\n";

     # The database returns a record where each field is
     # separated by the "\0" character.

     foreach $record (@data) {
                 $record =~ s/\0/,/g;
                 print $record, "\n";
             }
         }

ADVANTAGES
==========

Here are the advantages of Sprite over mSQL by David Hughes available on
the Net:

Allows for column names to be specified in the update command:

Perl's Regular Expressions allows for powerful pattern matching

The database is stored as text. Very Important! Information can be
added/modified/removed with a text editor.

Can add/delete columns quickly and easily

DISADVANTAGES
=============

Here are the disadvantages of Sprite compared to mSQL:

*Speed*. No where close to mSQL! Sprite was designed to be used to
manipulate very small databases (~1000-2000 records).

Does not have the ability to "join" multiple tables (databases) during a
search operation. This will be added soon!

RESTRICTIONS
============

  1. If a value for a field contains the comma (,) character or the field
     delimiter, then you need to quote the value. Here is an example:

          insert into $database
          (One, Two)
          values
          ('$some_value', $two)

     The information in the variable $some_value *might* contain the
     delimiter, so it is quoted - you can use either the single quote (')
     or the double quote (").

  2. All single quotes and double quotes within a value must be escaped.
     Looking back at the previous example, if you think the variable
     $some_value contains quotes, do the following:

          $some_value =~ s/(['"])/\\$1/g;

  3. If a field's value contains a newline character, you need to convert
     the newline to some other character (or string):

          $some_value =~ s/\n/<BR>/g;

  4. If you want to search a field by using a regular expression:

          select * from $database
              where (Player =~ /Bird/i)

     the only delimiter you are allowed is the standard one (i.e */../*).
     You *cannot* use any other delimeter:

          select * from $database
              where (Player =~ m|Bird|i)

  5. Field names can only be made up of the following characters:

          "A-Z", "a-z", and "_"

     In other words,

     [A-Za-z_]

  6. If your update value contains parentheses, you need to escape them:

          $rdb->sql (<<End_of_Query);

          update my_db
              set Phone = ('\\(111\\) 222 3333')
              where (Name = /Gundavaram\$/i)

          End_of_Query

     Notice how the "$" (matches end of line) is escaped as well!


SEE ALSO
========

RDB (available at the Metronet Perl archive)

REVISION HISTORY
================

v3.1 - June 18, 1996
     Added the following features:

        * As of this version, Sprite allows you to update multiple fields
          with a single update command. See the Supported SQL Commands
          section above.

        * You can execute your scripts with the following:

               #!/usr/local/bin/perl5 -wT

               use strict;

          Sprite no longer generates the "Use of uninitialized value..."
          errors.

        * For records that don't contain quotes or escaped strings, Perl's
          split is used to dramatically speed up database loading.

        * The set_os function will allow you to set the operating system
          that you're using.

        * Added a "require 5.002" as Sprite fails on versions of Perl older
          than 5.002 with the following error:

          "Bad free() ignored at Sprite.pm..."

     Fixed the following bugs:

        * If you call the close method with a database as an argument
          *without* opening a database first, Sprite will warn you as
          opposed to wiping out the database, as was the case in earlier
          versions of Sprite.

        * Sprite no longer chops off the trailing "0" on records.

        * The *drop column* works as it should.

        * You can safely escape parentheses in the update command.

        * Extra spaces between field names in the select command and
          values in the update command no longer cause fatal errors.

        * In earlier versions of Sprite, if you opened two databases that
          were located in different directories, *but* with the same name,
          Sprite incorrectly assumed that it was the same database.  As a
          result, the second database would never be loaded.

        * Can be used on the Mac OS and Windows NT.

v3.01 - March 5, 1996
     Fixed a bug in *parse_expression* subroutine so that it recognizes
     the "_" character as valid in field names.

v3.0 - Febraury 20, 1996
     Totally re-wrote parser; works reasonably well even in the worst case
     scenarios.

v2.0 - November 23, 1995
     Fixed *numerous* errors in parsing, and added pod style documentation.

v1.5 - September 10, 1995
     Created Perl 5 module instead of a command-line interface.

v1.0 - September 7, 1995
     Initial Release

ACKNOWLEDGEMENTS
================

I would like to thank the following for finding bugs and offering
suggestions:

Dave Moore (dmoore@videoactv.com)
Shane Hutchins (hutchins@ctron.com)
Josh Hochman (josh@bcdinc.com)
Barry Harrison (barryh@topnet.net)
Lisa Farley (lfarley@segue.com)
Loyd Gore (lgore@ascd.org)
Tanju Cataltepe (tanju@netlabs.net)
COPYRIGHT INFORMATION
=====================

     Copyright (c) 1995, 1996
                    Shishir Gundavaram and O' Reilly & Associates
        All Rights Reserved

     Permission to use, copy, modify and distribute is hereby granted,
     providing  that  no charges are involved and the above  copyright
     notice and this permission appear in all copies and in supporting
     documentation. Requests for other distribution  rights, including
     incorporation in commercial  products,  such as  books,  magazine
     articles, or CD-ROMS should be made to the authors.

     This  program  is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY;  without  even  the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.


File: pm.info,  Node: Statistics/ChiSquare,  Next: Statistics/LTU,  Prev: Sprite,  Up: Module List

How random is your data?
************************

NAME
====

`Statistics::ChiSquare' - How random is your data?

SYNOPSIS
========

     use Statistics::ChiSquare;


     print chisquare(@actual_occurrences);
     print chisquare_nonuniform([actual_occurrences], [expected_occurrences]);

The Statistics::ChiSquare module is available at a CPAN site near you.

DESCRIPTION
===========

Suppose you flip a coin 100 times, and it turns up heads 70 times.  *Is
the coin fair?*

Suppose you roll a die 100 times, and it shows 30 sixes.  *Is the die
loaded?*

In statistics, the *chi-square* test calculates "how random" a series of
numbers is.  But it doesn't simply say "random" or "not random".  Instead,
it gives you a *confidence interval*, which sets upper and lower bounds on
the likelihood that the variation in your data is due to chance.  See the
examples below.

If you've ever studied elementary genetics, you've probably heard about
Gregor Mendel.  He was a wacky Austrian botanist who discovered (in 1865)
that traits could be inherited in a predictable fashion.  He performed
lots of experiments with cross-fertilizing peas: green peas, yellow peas,
smooth peas, wrinkled peas.  A veritable Brave New World of legumes.

How many fertilizations are needed to be sure that the variations in the
results aren't due to chance?  Well, you can never be entirely sure.  But
the chi-square test tells you *how sure you should be*.

(As it turns out, Mendel faked his data.  A statistician by the name of R.
A. Fisher used the chi-square test again, in a slightly more sophisticated
way, to show that Mendel was either very very lucky or a little dishonest.)

There are two functions in this module: chisquare() and
chisquare_nonuniform().  chisquare() expects an array of occurrences: if
you flip a coin seven times, yielding three heads and four tails, that
array is (3, 4).  chisquare_nonuniform() is a bit trickier--more about it
later.

Instead of returning the bounds on the confidence interval in a tidy
little two-element array, these functions return an English string.  This
was a deliberate design choice--many people misinterpret chi-square
results; the text helps clarify the meaning.  Both chisquare() and
chisquare_nonuniform() return UNDEF if the arguments aren't "proper".

Upon success, the string returned by chisquare() will always match one of
these patterns:

     There's a >\d+% chance, and a <\d+% chance, that this data is random.

or

     There's a <\d+% chance that this data is random.

unless there's an error.  Here's one error you should know about:

     (I can't handle \d+ choices without a better table.)

That deserves an explanation.  The "modern" chi-square test uses a table
of values (based on Pearson's approximation) to avoid expensive
calculations.  Thanks to the table, the chisquare() calculation is quite
fast, but there are some collections of data it can't handle, including
any collection with more than 21 slots.  So you can't calculate the
randomness of a 30-sided die.

chisquare_nonuniform() expects *two* arguments: a reference to an array of
actual occurrences followed by a reference to an array of expected
occurrences.

chisquare_nonuniform() is used when you expect a nonuniform distribution
of your data; for instance, if you expect twice as many heads as tails and
want to see if your coin lives up to that hypothesis.  With such a coin,
you'd expect 40 heads (and 20 tails) in 60 flips; if you actually observed
42 heads (and 18 tails), you'd call

     chisquare_nonuniform([42, 18], [40, 20])

The strings returned by chisquare_nonuniform() look like this:

     There's a >\d+% chance, and a <\d+% chance,
          that this data is distributed as you expect.

EXAMPLES
========

Imagine a coin flipped 1000 times.  The most likely outcome is 500 heads
and 500 tails:

     @coin = (500, 500);
     print chisquare(@coin);

which prints

     There's a >99% chance, and a <100% chance,
          that this data is evenly distributed.

Imagine a die rolled 60 times that shows sixes just a wee bit too often.

     @die1  = (9, 8, 10, 9, 9, 15);
     print chisquare(@die1);

which prints

     There's a >50% chance, and a <70% chance,
          that this data is evenly distributed.

Imagine a die rolled 600 times that shows sixes *way* too often.

     @die2  = (80, 70, 90, 80, 80, 200);
     print chisquare(@die2);

which prints

     There's a <1% chance that this data is evenly distributed.

How random is rand()?

     srand(time ^ $$);
     @rands = ();
     for ($i = 0; $i < 60000; $i++) {
         $slot = int(rand(6));
         $rands[$slot]++;
     }
     print "@rands\n";
     print chisquare(@rands);

which prints (on my machine):

     9987 10111 10036 9975 9984 9907
       There's a >70% chance, and a <90% chance,
            that this data is evenly distributed.

(So much for pseudorandom number generation.)

All the above examples assume that you're testing a uniform
distribution--testing whether the coin is fair (i.e. a 1:1 distribution),
or whether the die is fair (i.e. a 1:1:1:1:1:1 distribution).  That's why
chisquare() could be used instead of chisquare_nonuniform().

Suppose a mother with blood type AB, and a father with blood type Ai (that
is, blood type A, but heterozygous) have one hundred children.  You'd
expect 50 kids to have blood type A, 25 to have blood type AB, and 25 to
have blood type B.  Plain old chisquare() isn't good enough when you
expect a nonuniform distribution like 2:1:1.

Let's say that couple has 40 kids with blood type A, 30 with blood type
AB, and 30 with blood type B.  Here's how you'd settle any nagging
questions of paternity:

     @data = (40, 30, 30);
     @dist = (50, 25, 25);
     print chisquare_nonuniform(\@data, \@dist);

which prints

     There's a >10% chance, and a <30% chance,
          that this data is distributed as you expect.

AUTHOR
======

Jon Orwant

MIT Media Lab

*orwant@media.mit.edu*


File: pm.info,  Node: Statistics/LTU,  Next: Storable,  Prev: Statistics/ChiSquare,  Up: Module List

An implementation of Linear Threshold Units
*******************************************

NAME
====

Statistics::LTU -  An implementation of Linear Threshold Units

SYNOPSIS
========

     use Statistics::LTU;

     my $acr_ltu = new Statistics::LTU::ACR(3, 1);    # 3 attributes, scaled

     $ltu->train([1,3,2],  $LTU_PLUS);
     $ltu->train([-1,3,0], $LTU_MINUS);
     ...
     print "LTU looks like this:\n";
     $ltu->print;

     print "[1,5,2] is in class ";
     if ($ltu->test([1,5,2]) > $LTU_THRESHOLD) { print "PLUS" }
     	                                 else { print "MINUS" };

     $ltu->save("ACR.saved") or die "Save failed!";
     $ltu2 = restore Statistics::LTU("ACR.saved");

EXPORTS
=======

For readability, LTU.pm exports three scalar constants: $LTU_PLUS (+1),
$LTU_MINUS (-1) and $LTU_THRESHOLD (0).

DESCRIPTION
===========

Statistics::LTU defines methods for creating, destroying, training and
testing Linear Threshold Units.  A linear threshold unit is a 1-layer
neural network, also called a perceptron.  LTU's are used to learn
classifications from examples.

An LTU learns to distinguish between two classes based on the data given
to it.  After training on a number of examples, the LTU can then be used
to classify new (unseen) examples.  Technically, LTU's learn to
distinguish two classes by fitting a hyperplane between examples; if the
examples have n features, the hyperplane will have n dimensions.  In
general, the LTU's weights will converge to a define the separating
hyperplane.

The LTU.pm file defines an uninstantiable base class, LTU, and four other
instantiable classes built on top of LTU.  The four individual classes
differs in the training rules used:

ACR - Absolute Correction Rule
TACR - Thermal Absolute Correction Rule (thermal annealing)
LMS - Least Mean Squares rule
RLS - Recursive Least Squares rule
Each of these training rules behaves somewhat differently.  Exact details
of how these work are beyond the scope of this document; see the
additional documentation file (`ltu.doc') for discussion.

SCALARS
=======

$LTU_PLUS and $LTU_MINUS (+1 and -1, respectively) may be passed to the
*train* method.  $LTU_THRESHOLD (set to zero) may be used to compare
values returned from the test method.

METHODS
=======

Each LTU has the following methods:

*new TYPE(n_features, scaling)*
     Creates an LTU of the given `TYPE'.  `TYPE' must be one of:

    Statistics::LTU::ACR,
    Statistics::LTU::TACR,
    Statistics::LTU::LMS,   =item Statistics::LTU::RLS.
     `n_features' sets the number of attributes in the examples.  If
     `scaling' is 1, the LTU will automatically scale the input features
     to the range (-1, +1).  For example:

          $ACR_ltu = new Statistics::LTU::ACR(5, 1);

     creates an LTU that will train using the absolute correction rule.  It
     will have 5 variables and scale features automatically.

copy
     Copies the LTU and returns the copy.

destroy
     Destroys the LTU (undefines its substructures).  This method is kept
     for compatibility; it's probably sufficient simply to call
     *undef($ltu)*.

print
     Prints a human-readable description of the LTU, including the weights.

save(filename)
     Saves the LTU to the file *filename*.  All the weights and necessary
     permanent data are saved.  Returns 1 if the LTU was saved
     successfully, else 0.

*restore LTU(filename)*
     Static method.  Creates and returns a new LTU from *filename*.  The
     new LTU will be of the same type.

test(instance)
     Tests the LTU on *instance*, the instance vector, which must be a
     reference to an array.  Returns the raw (non-thresholded) result.  A
     typical use of this is:

          if ($ltu->test($instance) >= $LTU_PLUS) {
             # instance is in class 1
          } else {
             # instance is in class 2
          }

*correctly_classifies(instance, realclass)*
     Tests the LTU against an instance vector *instance*, which must be a
     reference to an array.  *realclass* must be a number.  Returns 1 if
     the LTU classifies *instance* in the same class as *realclass*.
     Technically: Returns 1 iff instance is on the *realclass* side of the
     LTU's hyperplane.

weights
     Returns a reference to a copy of the LTU's weights.

set_origin_restriction(orig)
     Sets LTU's origin restriction to *orig*, which should be 1 or 0.  If
     an LTU is origin-restricted, its hyperplane must pass through the
     origin (ie, so its intercept is zero).  This is usually used for
     preference predicates, whose classifications must be symmetrical.

is_cycling(n)
     Returns 1 if the LTU's weights seem to be cycling.  This is a
     heuristic test, based on whether the LTU's weights have been pushed
     out in the past n training instances.  See comments with the code.

version
     Returns the version of the LTU implementation.

In addition to the methods above, each of the four classes of LTU defines a
*train* method.  The *train* method "trains" the LTU that an instance
belongs in a particular class.  For each *train* method, *instance* must
be a reference to an array of numbers, and value must be a number.  For
convenience, two constants are defined: `$LTU_PLUS' and `$LTU_MINUS', set
to +1 and -1 respectively.  These can be given as arguments to the *train*
method.  A typical *train* call looks like:

     $ltu->train([1,3,-5], $Statistics_LTU_PLUS);

which trains the LTU that the instance vector (1,3,-5) should be in the
PLUS class.

   * For ACR: 	*train(instance, value)*

     Returns 1 iff the LTU already classified the instance correctly, else
     0.

   * For RLS: 	*train(instance, value)*

     Returns undef.

   * For LMS: 	*train(instance, value, rho)*

     Returns 1 if the LTU already classified the *instance* correctly,
     else 0.  *Rho* determines how much the weights are adjusted on each
     training instance.  It must be a positive number.

   * For TACR: 	*train(instance, value, temperature, rate)*

     Uses the thermal perceptron (absolute correction) rule to train the
     specified linear threshold unit on a particular instance_vector.  The
     instance_vector is a vector of numbers; each number is one attribute.
     The desired_value should be either $LTU_PLUS (for positive instances)
     or $LTU_MINUS (for negative instances).  The *temperature* and *rate*
     must be floating point numbers.

     This method returns 1 if the linear threshold unit already classified
     the instance correctly, otherwise it returns 0.  The TACR rule only
     trains on instances that it does not already classify correctly.

AUTHOR
======

fawcett@nynexst.com (Tom Fawcett)

LTU.pm is based on a C implementation by James Callan at the University of
Massachusetts.  His version has been in use for a long time, is stable,
and seems to be bug-free.  This Perl module was created by Tom Fawcett,
and any bugs you find were probably introduced in translation.  Send bugs,
comments and suggestions to *fawcett@nynexst.com*.

BUGS
====

None known.  This Perl module has been moderately exercised but I don't
guarantee anything.


File: pm.info,  Node: Storable,  Next: String/Scanf,  Prev: Statistics/LTU,  Up: Module List

persistency for perl data structures
************************************

NAME
====

Storable - persistency for perl data structures

SYNOPSIS
========

     use Storable;
     store \%table, 'file';
     $hashref = retrieve('file');

DESCRIPTION
===========

The Storable package brings you persistency for your perl data structures
containing SCALAR, ARRAY, HASH or REF objects, i.e. anything that can be
convenientely stored to disk and retrieved at a later time.

It can be used in the regular procedural way by calling `store' with a
reference to the object to store, and providing a file name. The routine
returns undef for I/O problems or other internal error, a true value
otherwise. Serious errors are propagated as a die exception.

To retrieve data stored to disk, you use `retrieve' with a file name, and
the objects stored into that file are recreated into memory for you, and a
*reference* to the root object is returned. In case an I/O error occurred
while reading, undef is returned instead. Other serious errors are
propagated via die.

Since storage is performed recursively, you might want to stuff references
to objects that share a lot of common data into a single array or hash
table, and then store that object. That way, when you retrieve back the
whole thing, the objects will continue to share what they originally
shared.

At the cost of a slight header overhead, you may store to an already
opened file descriptor using the `store_fd' routine, and retrieve from a
file via `retrieve_fd'. Those names aren't imported by default, so you
will have to do that explicitely if you need those routines.  The file
descriptor name you supply must be fully qualified.

When using `retrieve_fd', objects are retrieved in sequence, one object
(i.e. one recursive tree) per associated `store_fd'.

If you're more from the object-oriented camp, you can inherit from
Storable and directly store your objects by invoking `store' as a method.

SPEED
=====

The heart of Storable is written in C for decent speed. Extra low-level
optimization have been made when manipulating perl internals, to sacrifice
encapsulation for the benefit of a greater speed.

Storage is usually faster than retrieval since the latter has to allocate
the objects from memory and perform the relevant I/Os, whilst the former
mainly performs I/Os.

On my HPUX machine, I can store 200K in 0.8 seconds, and I can retrieve
the same data in 1.1 seconds, approximatively.

WARNING
=======

If you're using references as keys within your hash tables, you're bound
to disapointment when retrieving your data. Indeed, Perl stringifies
references used as hash table keys. If you later wish to access the items
via another reference stringification (i.e. using the same reference that
was used for the key originally to record the value into the hash table),
it will work because both references stringify to the same string.

It won't work accross a `store' and `retrieve' operations however, because
the addresses in the retrieved objects, which are part of the stringified
references, will probably differ from the original addresses. The topology
of your structure is preserved, but not hidden semantics like those.

BUGS
====

You can't store GLOB, CODE, FORMLINE, etc... If you can define semantics
for those operations, feel free to enhance Storable so that it can deal
with those.

Due to the aforementionned optimizations, Storable is at the mercy of
perl's internal redesign or structure changes. If that bothers you, you
can try convincing Larry that what is used in Storable should be
documented and consistently kept in future revisions.  As I said, you may
try.

AUTHOR
======

Raphael Manfredi `<ram@hptnos02.grenoble.hp.com>'


File: pm.info,  Node: String/Scanf,  Next: Sx,  Prev: Storable,  Up: Module List

emulate the sscanf() of the C stdio library
*******************************************

NAME
====

sscanf - emulate the sscanf() of the C stdio library

SYNOPSIS
========

     use String::Scanf;	# this will import sscanf() into the
     			# current namespace

     @values = sscanf($scanf_format_string, $scalar_to_scan);

     # the default scan target is the $_
     @values = sscanf($scanf_format_string);

     # converting scanf formats to regexps (::format_to_re
     # is never exported to the current namespace)

     $regexp_string = String::Scanf::format_to_re($scanf_format_string);

DESCRIPTION
===========

Perl sscanf() can be used very much like the C stdio sscanf(), for
detailed sscanf() documentation please refer to your usual documentation
resources. The supported formats are: `[diuoxefgsc]' and the character
class `[]'.

*All* of the format must match. If not, an empty list is returned and all
the values end up empty.

The c format returns an anonymous list (see perlref) containing the
numeric values of the characters it matched.

The ::format_to_re() function may be helpful if one wants to develop her
own parsing routines.

FEATURES
========

Embedded underscores are accepted in numbers just like in Perl, even in
octal/hexadecimal numbers (Perl does not currently support this). Please
note the word *embedded*, not leading or trailing.

If the `oh' formats are used, the octal/hexadecimal interpretation is
forced even without the leading `0' or `0x'.

LIMITATIONS
===========

Certain features of the C sscanf() are unsupported:

     * the formats C<[npSC]>
     * in the C<[efg]> formats the C<INF> and various C<NaN>s

The numeric formats are scanned in as strings, this meaning that numeric
overflows may occur. For example: `1.2345e67890' will match the `%g'
format but in most machines Perl cannot handle that large floating point
numbers and bizarre values may end up in the Perl variable. Similar
caveats apply for integer-type numbers. Results of such huge numbers (or
very tiny numbers, say, `1.24345e-67890') are implementation-defined,
which translates quite often as *garbage*.  NOTE: if you really want *Big*
numbers please consider using the `Math::BigInt' and `Math::BigFloat',
these packages come standard with Perl 5, or the `Math::Pari' package,
available from CPAN.

For Perl <integers> and *floating point numbers* are the same thing.
Also, the possible `hl' modifiers for the *integers* mean nothing: they
are accepted but still they do nothing because Perl does not care about
short/long integer differences.

The character class format is not so rigorously checked for correctness
that an illegal character class definition could not be sneaked in. For
example `[z-a,X]' is a `bad' example: perfectly illegal as a character
class but `String::Scanf' will happily accept it. Beware.

The ::format_to_re() only does the scanf format -> regular expression
conversion. It ignores tricky things like the c format (see above) and the
%n$ argument reordering. If you want these, you may as well use the full
::sscanf().

EXAMPLES
========

     # business as usual

     ($i, $s, $x) = sscanf('%d %3s %g', ' -5_678     abc 3.14e-99 9');

     # 'skip leading whitespace': $x becomes 42 despite the leading space
     # 'the illegal character': $y becomes 'ab' despite the '3'
     # 'c' format: $z becomes [120 100], the numeric values of 'x'
     # and 'd' (assuming ASCII or ISO Latin 1)

     ($x, $y, $z) = sscanf('%i%3[a-e]%2c', ' 42acxde');

     # reordering the arguments: $a becomes 34, $b becomes 12

     ($a, $b) = sscanf('%2$d %1$d', '12 34');

     # converting scanf formats to regexps

     $re = String::Scanf::format_to_re('%x');

More examples in the test set `t/scanf.t'.

INTERNALS
=========

The Perl `sscanf()' turns the C-`stdio' style `sscanf()' format string
into a Perl regexp (see perlre) which captures the wanted values into
submatches and returns the submatches as a list.

Originally written for purposes of debugging but also useful for
educational purposes:

     String::Scanf::debug(1);	# turn on debugging: shows the regexps
     			# used and the possible reordering list
     			# and the character (%c) conversion targets
     String::Scanf::debug(0);		# turn off debugging
     print String::Scanf::debug(), "\n";	# the current debug status

VERSION
=======

v1.1, $Id: Scanf.pm,v 1.8 1995/12/27 08:32:28 jhi Exp $

AUTHOR
======

Jarkko Hietaniemi, `Jarkko.Hietaniemi@iki.fi'


File: pm.info,  Node: Sx,  Next: Sybase/BCP,  Prev: String/Scanf,  Up: Module List

front-end to all the Athena and Xlib garbage for Perl GUI progamming
********************************************************************

NAME
====

Sx - front-end to all the Athena and Xlib garbage for Perl GUI progamming

DESCRIPTION
===========

Using the Sx package is pretty simple.  At the minimum, you 'use Sx;' To
actually have X windows pop open and such, you need to do the following:

  1. To get everything started, you should call OpenDisplay().  If
     OpenDisplay() returns a non-zero value, it's ok to go on.
     OpenDisplay() creates what will eventually be your first window.

  2. After calling OpenDisplay(), you can go on to create all sorts of
     widgets with the MakeXXX() calls.  You can lay them out with calls to
     SetWidgetPos().

  3. When you are done creating the user interface, call ShowDisplay().
     This causes the window and components you've created to be displayed
     on the workstation screen.

     Until you call ShowDisplay(), the user can *NOT* see your window, and
     drawing into drawing areas has *NO* effect.

  4. If you need to, you can call any of the color allocation functions
     such as GetStandardColors(), etc.

  5. Finally, once the window is displayed and you've done all the
     initializations you wish, you must then call MainLoop(). After you
     call MainLoop(), events get processed as they come in and your
     callback functions are called as necessary.

     After calling MainLoop(), the correct way for your program to exit is
     to have one of your callback routines call exit() when appropriate
     (like after the user clicks on a "Quit" button).

     That's all you need to do.  Even though that may look like a lot to
do, it's really pretty simple in practice.  For example, here is a hello
world program with libsx:

     use Sx;

     MakeLabel("Hello World!");
     MainLoop();

Granted it's one more line than a standard printf() type of hello world
program, but it's not all that bad.

Hello world programs are nice, but you don't tend to write very many of
them.  Real applications need to be able to do much more.  Even these
"real" programs aren't all that bad in libsx.

Here is a simple program that opens a window with a quit button and a
drawing area that you could use to draw whatever graphics you wanted:

     use Sx;

     sub quit {
       exit;
     }

     sub draw_stuff {
       my($widget, $width, $height, $data)
       ClearDrawArea();
       DrawLine(0,0, $width, $height);   # just draw a diagonal line
     }

     $res = OpenDisplay("My Window",@ARGV);
     exit unless($res);

     $w[0] = MakeButton("Quit", 'quit', $Sx::Nullsx);
     $w[1] = MakeDrawArea(300,300, 'draw_stuff', $Sx::Nullsx);

     SetWidgetPos($w[1], $Sx::PLACE_UNDER, $w[0], $Sx::NO_CARE, $Sx::Nullsx);

     ShowDisplay();
     GetStandardColors();

     MainLoop();   # off we go!

The code above is the basic skeleton for a Sx program, even complicated
ones.  First you open the display with OpenDisplay().  Then you build your
interface by creating a bunch of widgets with the MakeXXX() calls.  Next
you layout the display by specifying the relative positions of the widgets
to each other.  Then you would get any fonts or colors you may need, and
finally you just enter the main loop.

In Sx, your callback functions are where all the real work happens.  The
program above has two callback functions, quit() and draw_stuff().  They
are tied to events that happen in the interface.  When the user clicks on
the "Quit" button, your quit() function is called.  When the drawing area
gets resized or needs to be redrawn, your draw_stuff() function gets
called.

Usually the process of creating the interface would get separated into a
separate function that is easy to modify (instead of cluttering up main).
However, the basic outline is the same as above.  The only real
difference with more complicated interfaces is that they usually have a
lot more calls to the MakeXXX() functions and they tend to make use of the
extra void pointer argument in the callback routines.

If you'd like more examples, take a look at the provided source code.
There are several reasonable examples of varying complexity that you can
take and modify as you like.  Each of the demos tries to demonstrate a
certain group of features, so take a look at each to find the one that
most closely matches what you want to do and start hacking from there!

LABELS
------

A label widget is a widget that displays some text or bitmap but can not
be clicked on or interacted with by the user.  Generally a label is for
informational purposes, such as saying what the current file name is.

`MakeLabel(txt)'
     This function creates a label that contains the text in the string
     pointed to by "txt".  The text will simply be displayed, with no
     fancy borders or special highlighting.  If the text contains new line
     characters, they will be interpreted properly.

     If the argument txt is NULL, then no label will be set for the widget.
     This is convienent if you plan to put a bitmap on this widget with the
     SetWidgetBitmap() function.

     This widget is useful for displaying a piece of textual information
     like a filename or user name.

     If this routine fails, FALSE is returned.

BUTTON WIDGETS
--------------

A button widget is a button that a user can click on with the left mouse
button to indicate an action.  When a button is pressed, it is drawn in
inverse video and some action takes place.

A button is connected to your code by a callback function which is called
when the user clicks on the button widget with the left mouse button.

`MakeButton(label, callback, data)'
     This function creates a small rectangular button which the user can
     click on.  The character string pointed at by "label" will be printed
     inside the button.  If the string has newline characters in it, they
     will be interpreted properly (i.e. you will get a multiline label).
     The next two arguments are a callback function, and an arbitraryperl
     value that will be passed to the function.

     If you plan to attach a bitmap to this widget, you can specify
     Sx::Nullsx for the label text (see the docs for SetWidgetBitmap()).

     When the button is pressed, the callback will be called.  This
     function will have two arguments: the widget that user clicked on
     (which you can ignore if you do not need it) and the 'data',
     specified in the call to MakeButton().

`Make3Button(label,call1,call2,call3,data)'
     This is just a convenience function to avoid some translation table
     munging.  This function will create a button, but you can specify a
     different callback (or 'undef' if unwanted) for button 1, 2 or 3.
     This should soon be superseded by the AddTrans call.

TOGGLES
-------

A toggle widget is similar to a button widget except that it maintains
state.  That is, when a user clicks a toggle widget, it remains
highlighted until it is clicked again.  This is similar to an on/off
switch.

Toggle widgets can also be used to create a group of "radio buttons".  A
radio button group is a set of toggle widgets in which at most one of them
can be selected at any one time (it is possible for none of them to be
selected).

`MakeToggle(txt, state, widget, func, data)'
     This function makes a widget that will toggle between a highlighted
     `on' state and an unhighlighted `off' state.

     The first argument is the text that will be displayed inside the
     widget. The `state' argument is a boolean value of the initial state
     of the toggle button (TRUE == on/highlighted, FALSE == off).  The next
     argument, a Widget, is NULL if this widget is a simple toggle button
     by itself and not part of a radio group (described below).

     If you plan to display a bitmap for the toggle button, you may specify
     a NULL for the txt argument (and then call SetWidgetBitmap()).

     The func argument is a standard callback function. First argument will
     be the widget, the second argument the data you specified in the
     MakeToggle call.

     Each time the widget changes state, your callback function is called.
     That is, each time the user clicks the toggle, your function is
     called.

Radio Groups
------------

It is possible to connect toggle widgets together to form a group of
widgets that are mutually exclusive.  That is to say, with a radio group,
you can have a set of widgets in which at most one of them will be
highlighted at any given time.  Therefore, if you had 3 widgets, A, B, and
C, only one could be highlighted at any one time, and clicking on another
unhighlights the current one and highlights the toggle clicked on.  This
is useful for selecting one choice of several (such as a size, which is
either small, medium or large, but not two at the same time).  Keep in
mind that it is possible for none of them to be selected.

To build a radio group, you use the Widget argument of the MakeToggle()
function.  If you specify another valid toggle widget in the call to
MakeToggle(), the new widget becomes connected to the widget you
specified.  All the widgets you connect together form a radio group.  Any
single widget can *only* be in one radio group.

Example:

     $widg1 = MakeToggleWidget("Thing 1", 1, $Sx::Nullsx, 'func1', $Sx::Nullsx);
     $widg2 = MakeToggleWidget("Thing 2", 0, $widg1, 'func2', $Sx::Nullsx);
     $widg3 = MakeToggleWidget("Thing 3", 0, $widg1, 'func3', $Sx::Nullsx);

Notice how widg2 and widg3 specify widg1 as their Widget argument.  This
connects all three into a radio group in which only one can be set at a
time.  We initialize widg1 to be initially set and the others off.  If you
specify more than one widget as `on', the results are undefined.

The callback functions are called whenever a widget is highlighted or
unhighlighted.  The callbacks to the widget being unhighlighted happen
before the callbacks to widgets being highlighted.

`SetToggleState(widget, state)'
     SetToggleState() explicitly sets the state of a widget.

     The `state' argument is either TRUE (set the toggle to its highlighted
     state), or FALSE (unhighlight the widget). The callback routine for
     the widget is only called if there is a change in state.

`GetToggleState(widget)'
     This function returns the current state of the toggle widget.  The
     return values are either TRUE (the widget is selected) or FALSE (the
     widget is not highlighted).

SCROLL LIST
-----------

A scroll list is a scrollable list of items organized in a veritical
fashion.  The user can scroll through the list of items using the mouse
and select individual items in the list of available choices.

`MakeScrollList(width, height, callback, data, list)'
     This function makes a scrollable list of items from which a user can
     select individual items.  The list contains strings of text.  The area
     given to display the list is width and height pixels large.  If the
     entire list will not fit, scrollbars appear that will let the user
     easily scroll through the list.

     The callback function, should expect to be called with a Widget
     argument, the string of text the user clicked on, the string's index
     in your table, and whatever user data you gave at widget creation time

     The list of strings passed in to MakeScrollList() must not be free()'d
     or otherwise deallocated for the entire lifetime of the widget (or
     until the list of strings is changed with ChangeScrollList()).

`GetCurrentListItem(widget)'
     This function returns the index of the currently selected item in the
     specified list widget.  The index value returned is an index into the
     table displayed by the list (specified when the widget was created or
     with ChangeScrollList()).

     If no item is selected in the list widget, this routine will return a
     -1.

`ChangeScrollList(widget, new_list)'
     This function changes the list of strings displayed by the list
     widget.  The new list of items is taken from the argument `new_list'.
     After this function is called, the old list can be free()'d.  Of
     course you can not free the new_list until the application is done or
     you change the list again.

`SetCurrentListItem(widget, index)'
     This function causes the item with specified index, to be highlighted
     in the list widget .  You must make sure that index is a valid index
     into the currently displayed list, results are undefined otherwise.

     After calling this function, the item with the this index will be
     highlighted in the list widget.

`Make3List(width,height,callback,data,array)'
     This is just a convenience function, soon to be superseded by the
     AddTrans call.  This function will do the same job as the standard
     MakeList call, but the callback function will be called on any
     button_down event and will have a new fourth argument which will be
     the event mask (see <X11/X.h> for values).

MENUS
-----

Menus provide standard drop-down style menus that let the user select from
a variety of choices.  The Athena widgets do not support cascaded menus,
so a menu is only a single list of items.  A menu contains menu items that
are tied to callback functions in the application.  Menu items must be
text and can not be bitmaps.

`MakeMenu(name)'
     This function creates a menu button that contains the text pointed to
     by the character string name.  When the button is clicked, a menu pops
     up.  The menu contains items created with MakeMenuItem().

     You need to save the return value of this function to be able to pass
     it to MakeMenuItem() so that menu items can attached to a menu.

     If this function fails, it returns NULL.

`MakeMenuItem(menu, name, func, arg)'
     This function adds a menu item to a menu.  The menu item contains the
     text pointed to by the string name.  Whenever the user selects this
     menu item, the callback function, func, is called.  The final argument
     is an arbitrary value that is passed to the callback function.

     The first argument must be a widget returned by MakeMenu() (results
     are undefined if it is not).

     If MakeMenuItem() fails for any reason, a NULL is returned.

     Whenever the user selects this menu item, the callback will be called.

     Setting of widget attributes with SetFgColor(), SetBgColor(), etc work
     normally except that only one background color may be specified and it
     takes effect for the entire menu.  You can set different fonts for
     each menu item.

     NOTE: You do not need to call SetWidgetPos() for menu items.
     Successive menu items are placed below previous menu items.

`SetMenuItemChecked(widget, state)'
     This function sets the ``checked'' state of a menu item.  If a menu
     item is in the checked state, a bitmap of a check mark appears to the
     left of the menu item text.

     The first argument, w, is a menu item widget created with
     MakeMenuItem().  The second argument, state, is a boolean value of
     either TRUE (1) or FALSE (0) indicating whether or not the check mark
     should be drawn to the left of the menu item.  If the state argument
     is TRUE, the check mark is drawn.  If the state argument is FALSE, the
     check mark is removed.

`GetMenuItemChecked(widget)'
     This function returns a boolean result indicating whether the menu
     item referred to by the specified widget, is checked or not.

     If the menu item referred to by `w' is checked, a value of TRUE (1) is
     returned.  If the menu item does not currently have a check mark next
     to it, a value of FALSE (0) is returned.

SCROLLBARS
----------

A scrollbar is a widget that allows a user to control some numeric
quantity interactively by using the mouse to scroll a slider, similar to
the volume slider on some radios.  The slider is called the "thumb" or
"thumb area" in X terminoligy.

`MakeHorizScrollbar(length, scroll_func, data)'
`MakeVertScrollbar(height,  scroll_func, data)'
     These two routines create scrollbars.  Scrollbars allow the user to
     interactively control some numeric quantity with the mouse.

     When the user presses the left mouse button, the value represented by
     the scrollbar increases.  When the press the middle mouse button, they
     can interactively adjust the value.  Clicking the right mouse button
     decreases the value represented by the scrollbar.

     The arguments to create a scrollbar are its length or height in
     pixels, a callback function to call when the scrollbar changes value
     and an extra void pointer argument that is passed to the callback
     function.

     If these routines fail, they return NULL.

     To set what values a scrollbar represents, you must use
     SetScrollbar().  These two routines only make a scrollbar and do not
     set it to return useful values.  You always have to call
     SetScrollbar() to set what a scrollbar represents (see the
     documentation for SetScrollbar() for more information).

     Your callback routine is called everytime the scrollbar changes.
     Since the calculations are done in floating point, the value may not
     have changed enough to be interesting, but your routine is still
     called.  You should take care to see that the value changed enough to
     be interesting to your applications (i.e. it is wasteful for a text
     editor to repaint the window when the new value is 0.003 different
     than the old value).

     A scrollbar callback routine should look like:

          sub scroll_func {
          	my($widget, $new_val, $data) = @_;
          }

     The first argument is the scrollbar widget that the user is
     manipulating.  The second argument is a floating point value that
     represents the new value of the scrollbar.  The third argument is the
     argument that was passed to *Make{Horiz,Vert}Scrollbar()*.

`SetScrollbar(widget, where, max, size_shown)'
     This function lets you set the values that a scrollbar represents.
     The first argument is a scrollbar widget.  The next three arguments
     are floating point numbers that specify the parameters of the
     scrollbar.

     Before discussing the details of the three float arguments, let us get
     some terms straight.  When we refer to the `container' of a scrollbar,
     we mean the entire box that makes up the scrollbar.  The `thumb' of a
     scrollbar is the gray area that the user can grab to manipulate.  We
     refer to the size or length of the thumb area (the amount of grey) as
     the `size shown'.  The total amount represented by the scrollbar is
     called `max'.

     The arguments mean the following:

    `where '
          This floating point number specifies where in the container the
          top of the thumb area should start.  If you have a maximum value
          of 100 and where is 50, the beginning of the thumb will be in
          the middle of the container.

    `max '
          The maximum value that the scroll bar can have.  You will
          receive numbers in the range 0 to max (inclusive).  Obviously
          max should be a positive, and is a float.

    `size_shown '
          This float value controls how big the grey area that the user
          can grab is.  This represents how much of whatever it is you are
          representing is visible.  For example, a text editor which shows
          24 lines of text would set size_shown to be 24 (out of whatever
          max is).  If you want the scrollbar to represent a percentage of
          something, where when it is 100%, the grey area is also 100% of
          the box, then you should set the size_shown to be equal to max.
          If this is confusing, there are examples below.

     Now, some examples to clarify things (in the following, assume that
     the argument, w, represents a scrollbar widget created with the
     MakeHorizScrollbar or MakeVertScrollbar() routines).

     For the first example, let's assume you want a scrollbar to let you
     set a color value which can range between 0 and 255 with the initial
     value at 67.  You sould set the scrollbar as follows:

          SetScrollbar($w, 67.0, 255.0, 1.0);

     The first value, 67.0, is where we would like the beginning of the
     thumb area to appear.  The next value, 255, is the maximum value the
     scrollbar can attain.  The third value, 1, is the size of the thumb
     area (the amount represented by the thumb relative to the maximum
     size).  This scrollbar will now return values in the range of 0 to 255
     (inclusive).  The thumb area will be small, and represents one value
     of the 255 possible divisions.  The position of the thumb area in the
     container represents its value.

     For the next example, suppose we wish to make a scrollbar represent
     some percentage of a value.  That is, the size of the thumb area
     should be proportional to the value of the scrollbar relative to its
     maximum (so when the value is at it maximum, the thumb area is 100% of
     the scrollbar).

     In this case we would like the size of the thumb area to represent the
     amount of the variable (note the difference from the above example).
     Let us suppose we want a scrollbar which can represent a percentage 0
     to 100, with the initial value being 50.

          SetScrollbar($w, 50.0, 100.0, 100.0);

     The first value, 50, is where the thumb area begins (in the middle of
     the container).  The next number is 100, and represents the maximum
     value of the scrollbar.  The next number, again 100, is the size
     shown.  Making this value the same as the max value (in this case
     100) causes the thumb area to vary according to the value the
     scrollbar represents.

     As a final example, let us take a text editor which is displaying a
     file.  In this case, let us assume the text file is 259 lines long,
     the window can display 47 lines, and the top line currently displayed
     is 72.  To create the correct scrollbar, we would do the following:

          SetScrollbar($w, 72.0, 259.0, 47.0);

     This creates a scrollbar which has a thumb area whose size is 47/259
     of the entire container, and is positioned 72/259'ths of the way down
     the container.

STRING ENTRY
------------

A string entry widget is a widget that lets a user enter a single line of
ASCII text.  When the user presses return in the widget, a callback is
made to your application with a pointer to the new text.  Support routines
also exist to Set and Get the text in the widget.

If you want multiple lines of text, see the text edit widget documentation.

`MakeStringEntry(txt, size, func, data)'
     This function makes a string input widget.  A string input widget is a
     widget that lets a user enter/edit a single line string value such as
     a filename.

     The first argument is any default text you would like in the string
     entry widget.  You can specify NULL or "" if you don't want anything
     to appear.

     The next argument is the width in pixels of the string entry area.  Be
     careful in specifying the width since the default font used by the
     widget may not be wide enough to contain the text you want.  It is
     best if you call GetWidgetFont() and then call TextWidth() on a string
     of reasonable length and use the value returned by TextWidth() to be
     the width of the widget.  If you're lazy, a value of 150-200 is
     usually pretty good.

     The next argument is a callback function that is called whenever the
     user presses return in the string entry widget.  The first argument to
     the callback is the widget where the user pressed return.  For the
     most part you can ignore this (unless you want to change the text).
     The second argument is the string of text the user entered.  The final
     argument is the user data you passed in to MakeStringEntry().

`SetStringEntry(widget, new_text)'
     This function allows you to change the string of text displayed in a
     string entry widget.

     The first argument is the widget in which you would like to change the
     string (this widget should be a string entry widget).  The second
     argument is a pointer to the new text you would like displayed in the
     string entry area.

`GetStringEntry(widget)'
     This function lets you retrieve the text a user entered in a string
     widget.  The widget argument should be a string entry widget.

     The return value of this function is the string that is the contents
     of the string entry widget.

     If there is a problem, the function returns NULL.

TEXT EDIT
---------

A text edit widget is an area used to display and optionally edit multiple
lines of text.  You can specify the text to be displayed as either an in
memory string or as a file name.  The text edit area manages its
scrollbars and internal affairs, you need not do anything (in fact there
are no callbacks for the text edit widget).

`MakeTextWidget(txt, is_file, editable, width, height)'
     This functions lets you create a text edit widget that will display
     some text and optionally let the user edit and manipulate it.  The
     first argument, txt, is a string (empty string is ok). The second
     argument, is_file, is a boolean value indicating if the first argument
     should be interpreted as a file name or not.  The next argument,
     editable, is a boolean value indicating whether or not the user is
     allowed to edit the text.  The final two arguments specify the width
     and height of the drawing area box.  If the area is too small to
     display the text, scrollbars will appear.

     The txt argument can either contain the entire string that you would
     like the user to edit, or it can contain the name of a file to be
     loaded into the text edit widget.  If the second argument is_file is
     TRUE (1), then the first argument gets interpreted as a file name.  If
     is_file is FALSE (0), then the first argument contains the actual text
     to be displayed.

     The argument `editable' is a boolean value indicating whether or not
     to allow editing of the text in the widget.  If you just wish to
     display some text (such as a help file), set the editable argument to
     FALSE (0) and the user will not be allowed to modify the text.

`SetTextWidgetText(widget, text, is_file)'
     This argument lets you modify the text displayed in a text edit
     widget.  The first argument identifies the text edit widget to change.
     The second argument is a string that either contains the actual text
     to display or the name of a file to read in.  If the is_file argument
     is TRUE (1), then the string pointed to by the argument, text, is
     interpreted as a file name.  If is_file is FALSE, the string pointed
     to by text is directly displayed in the text edit widget.

     If you wish to update the displayed text again, you should call
     SetTextWidgetText() again.

     BUGS: The function name is way too long.

`GetTextWidgetText(widget)'
     This function lets you retrieve the text contained in a text edit
     widget.  The only argument should be a text edit widget created with
     MakeTextWidget().

     The return from this function is a string that contains the current
     text in the widget.  If there is an error, a NULL is returned.

     BUGS: The function name is way too long.

FORMS
-----

`MakeForm(parent, where1, from1, where2, from2)'
     This function lets you create a new "form" widget in which to put
     child widgets.  A form widget is a container that holds other widgets.
     Normally there is no need to call this function, but if you want to
     have separate "groups" of widgets in your display and you can't lay
     them out that way with SetWidgetPos(), then using multiple form
     widgets may be the right thing.  In addition, a nifty little box gets
     drawn around the form widget (and all the children) and this can be a
     nice visual cue in your interface indicating what groups of widgets
     belong together.  A form widget creates a box that surrounds all the
     widgets contained inside of it (but the form widget itself is inactive
     and can't be clicked on by the user).

     If you use multiple form widgets in your display, the basic logic of
     how you create the display is a little different.  You can think of
     form widgets as miniature windows inside a larger window.

     Once you create a form widget, any other widgets you create with calls
     like MakeButton() and MakeLabel() become children of this form widget.
     Before you create another form widget, you must lay out all the
     children of the current form widget with calls to SetWidgetPos().
     After you lay out all the children of the current widget, then you can
     create another form widget, and repeat the process (or call
     SetForm()).

     Form widgets are layed out in a manner similar to regular widgets,
     except that usually their placement is relative to other form widgets.
     When you create a new form widget (after the first one), you specify
     where it should be placed relative to other form widgets that you
     created.  The first form widget is always placed in the top left
     corner of the window.

     The `parent' argument to MakeForm() specifies at what level the new
     form should be created.  If you specify $Sx::TOP_LEVEL_FORM (which is
     the usual thing to do) the new form is created at the top level of the
     window.  If you pass another form widget for `parent', then this new
     form widget will be a child of the other form widget.  This lets you
     create hierarchical "boxes" in your display.

     The arguments where1, from1, where2, from2 are the same as in
     SetWidgetPos().  That is, you specify either Sx::NO_CARE,
     Sx::PLACE_UNDER, or Sx::PLACE_RIGHT for where1 and where2 and the
     from1/from2 arguments are the widgets you would like to place
     something to the right of or under (or they are NULL if you specified
     Sx::NO_CARE).  See SetWidgetPos() for more documentation.

     Now for an example:

     Let's say we want a display something like this:

          +------------+   +-----------------------+
          | +--------+ |   | +-------------------+ |
          | |  Btn1  | |   | |                   | |
          | +--------+ |   | |                   | |
          |            |   | |                   | |
          | +--------+ |   | |                   | |
          | |  Btn2  | |   | |                   | |
          | +--------+ |   | |                   | |
          +------------+   | |                   | |
                           | |                   | |
                           | |                   | |
                           | +-------------------+ |
                           +-----------------------+

     We have two rectangles (forms) which contain other widgets.  Inside
     the leftmost form are two buttons.  The form on the right has a single
     drawing area.  Skipping some of the unnecessary details, we could
     accomplish the above display with the following code:

          $form1 = MakeForm($TOP_LEVEL_FORM, $Sx::NO_CARE,
          		      $Sx::Nullsx, $Sx::NO_CARE, $Sx::Nullsx);
          $w[0]  = MakeButton("Btn1", $Sx::Nullsx, $Sx::Nullsx);
          $w[1]  = MakeButton("Btn2", $Sx::Nullsx, $Sx::Nullsx);

          SetWidgetPos($w[1], $Sx::PLACE_UNDER, $w[0], $Sx::NO_CARE, $Sx::Nullsx);

          $form2 = MakeForm($TOP_LEVEL_FORM, $Sx::PLACE_RIGHT,
          		      $form1, $Sx::NO_CARE, $Sx::Nullsx);
          $w[2]  = MakeDrawArea(200, 200, $Sx::Nullsx, $Sx::Nullsx);

     As you can see, we create the first form and specify that we don't
     care where it goes (the first form widget is always placed in the top
     left corner of the window).  Then we create some widgets to place
     inside of our new form.  Next, and this is important, we layout all
     the widgets inside of the first form.  In this case we only need to
     make one call to SetWidgetPos().  Then we create the next form, and
     specify that we want to place it to the right of form1.  Finally we
     create a drawing area widget, which is placed inside of form2.

     If you want to create hiearchies of form widgets, you would specify
     the form widget that should be the parent for the first argument to
     MakeForm().  This can get quite complicted, so you should make sure
     you know what you're doing if you want to create big hierarchies.

     NOTE: It is important that you layout all your widgets before you
     create a new form (unless you're creating a child form).

`SetForm(widget)'
     The SetForm() function allows you to change what is considered the
     current form.  Normally you only use this function to set the current
     form to be Sx::TOP_LEVEL_FORM.  You can cause your program to crash if
     you are not careful about what you set as the current form.

     The main purpose of this function is to let you create displays that
     have both form widgets and other "normal" widgets at the same level.
     Mainly you would want to do this if you wanted a large drawing area
     (or some other type of widget) but didn't want to bother creating an
     form widget just to hold that one widget.

     After calling this function, you can position any new widgets
     relative to other widgets (usually form widgets) created at the top
     level of the window.

     The normal calling sequence is: `SetForm(Sx::TOP_LEVEL_FORM)',
     although you can specify any other form widget you like.  Be careful,
     as it is possible to confuse the X layout routines and cause your
     program to crash.

     NOTE: Before you call SetForm() and start creating new widgets and
     positioning them, any previous form widgets should be completely
     layed out (i.e. you called SetWidgetPos() for all child widgets of
     any previously created form widgets).

WINDOWS
-------

This file contains descriptions of the main high level startup and window
creation functions.

`OpenDisplay(args)'
     This function initiates everything with Sx.  You should call this
     function before you call any of the other functions.  A correctly
     written application will call OpenDisplay(), passing its command line
     arguments and count.  The return value from this function is the new
     list of arguments (or zero if an error occurred).  The X libraries
     accept various standard command line options such as -display or
     -font, and if your application passes the command line arguments to
     OpenDisplay(), these will be handled properly.  Any X options are
     removed from the return array, therefore it is best if you do your
     command line processing *after* calling OpenDisplay().

     You only need to call this function once to initialize the first
     window your program uses.  Any other windows you need should be
     created with MakeWindow().

     Technically, calling OpenDisplay() is optional (the MakeXXX() routines
     will call it for you if you didn't), but it's usually a good idea to
     call it (since it is only one line of code and it's pretty
     straightforward.

     This function returns FALSE (0) if something went wrong (like being
     unable to open the display, etc). If everything went ok, it returns
     the new list of arguments as its result.

`ShowDisplay()'
     This function displays the currently active window (user interface)
     you've created with the MakeXXX() calls.  After this call completes,
     the interface will be visible on the display.

     Until you call this function, your interface will not be visible and
     drawing into a draw area will have no effect.

     Usually one calls ShowDisplay(), allocates some colors and then
     immediately calls MainLoop().  If you do not call ShowDisplay(), but
     just directly call MainLoop(), then MainLoop() implicitly calls
     ShowDisplay().

`MainLoop()'
     After calling this function, your program yields control to the user
     interface, and it is entirely driven by what the user does and the
     callbacks associated with the various widgets.  For a single window
     application, the general flow of events is:

          OpenDisplay(argc, argv);   # initialize the first window

          MakeButton(....);          # create widgets

          ShowDisplay();             # put the window on the screen
                                     # optionally allocate colors
          MainLoop();                # start the main loop going

     When you call this after calling ShowDisplay() for your first window
     (created by OpenDisplay()), the MainLoop() function never returns and
     your application should have some callback function that will exit()
     the program (such as a quit button or menu option).

     If you did not call ShowDisplay(), MainLoop() will call it for you and
     then launch into the main loop.

     You should not call MainLoop() for Sx::NONEXCLUSIVE mode windows
     created with MakeWindow().  Those type of windows have their
     callbacks handled by the MainLoop() function that is already
     executing (i.e. the one you called for your original window).

     If the window is an Sx::EXCLUSIVE mode window, then MainLoop() keeps
     executing until CloseWindow() is called on the Sx::EXCLUSIVE mode
     window.  That is, MainLoop() blocks until the Sx::EXCLUSIVE mode
     window is closed, and then it returns.

     If you create a non-exclusive mode window, the general order of events
     is:

          MakeWindow(Sx::NONEXCLUSIVE_WINDOW, ....);
          MakeButton(...);
          ShowDisplay();

     This creates a window, puts interface objects into it, and then puts
     that window on the screen.  No other actions need to be taken, and
     when the callback that created this new window returns, all processing
     takes place normally, including the processing of the new window and
     its callbacks.

     For a window of Sx::EXCLUSIVE_WINDOW mode (like a popup), the general
     order execution is:

          MakeWindow(Sx::EXCLUSIVE_WINDOW, ....);
          MakeButton(...);
          ShowDisplay();

          MainLoop();     # blocks until CloseWindow() is called

          # do something with whatever values the popup got for us

     When MainLoop() returns for an Sx::EXCLUSIVE_WINDOW, the window has
     been closed.

`SyncDisplay(void)'
     This function synchronizes the display with all drawing requests you
     have made.  Normally it is not necessary to call this function, but if
     you make many repeated function calls to draw graphics, they will be
     updated in a chunky fashion because X buffers drawing requests and
     sends a bunch of them at once.

     After this function completes, all drawing requests you have made are
     visible on the screen.

     NOTE: Normally you do not need to call this function because X ensures
     that everything you request gets drawn, but sometimes it is necessary
     to insure the synchronization of the display.

`MakeWindow(window_name, display_name, exclusive)'
     NOTE: Do not call this function to open your first window. Your
     application's first window is opened for you by OpenDisplay().  If
     your application only needs one window, do NOT call this function.

     This function opens a new window, possibly on a different display
     (workstation).  The new window has the name specified by the argument
     window_name and is opened on the display named by display_name (a
     string usually in the form of, "machine_name:0.0").  The final
     argument indicates whether the window should be an exclusive window or
     not (described below).

     After this functions returns, the current window is the one you just
     created and you can begin adding widgets to it with the MakeXXX()
     calls.  After have created and added any widgets you want, you should
     call ShowDisplay(), and if the window is an Sx::EXCLUSIVE_MODE window,
     then you should call MainLoop() (which blocks until the window is
     closed).  If you opened the window with the Sx::NONEXCLUSIVE_WINDOW
     option, you should NOT call MainLoop().

     If you pass a $Sx::Nullsx for the window_name, it receives a default
     title of "Untitled".

     If you pass $Sx::SAME_DISPLAY, for the display name, the window opens
     on the same display as the original window opened by OpenDisplay().

     The argument, exclusive, indicates what type of window to open.  A
     normal window is a Sx::NONEXCLUSIVE_WINDOW.  That is, it will not
     block the user from interacting with your existing window.  An
     Sx::EXCLUSIVE_WINDOW is a popup window that blocks input to your main
     window until the popup is closed with CloseWindow().

     The Sx::EXCLUSIVE_WINDOW mode is useful for requestors that need an
     answer and the user should not be able to do other things in the
     application.  Of course some user-interface folks don't think modal
     windows like this are good, but tough cookies for them because some
     times it's necessary.

`SetCurrentWindow(widget)'
     This function sets the currently active window for other function
     calls such as CloseWindow().  If you have multiple windows open on
     several displays, you must call this function switch the currently
     active one when you wish to manipulate the various windows.

     The argument must be a valid value returned by MakeWindow().  If you
     would like to set the current window to be the original window opened
     by OpenDisplay(), you can pass the #define, Sx::ORIGINAL_WINDOW.

     When you change windows, the current drawing area is also changed to
     be the last current drawing area in the new window (if there is a
     drawing area in the new window).

`CloseWindow()'
     This function closes and removes from the display, the currently
     active window.

     After calling this function, you should not refer to any of the
     widgets contained in the window as they are invalid (as is the window
     handle).

PREDEFINED POP-UPS
------------------

Popup windows are simple dialog boxes that get a simple yes/no or string
answer from the user.  When these windows popup, they block input to the
previously active window.

`GetYesNo(question)'
     This function allows you to prompt the user for the answer to a simple
     yes or no type of question.  It simply pops up a dialog box with the
     text contained in the string question, and two okay/cancel buttons.

     If the user clicks Okay, this function returns TRUE.  If the user
     clicks Cancel, this function returns FALSE.  The text in the question
     string can have embedded newlines (\n characters) to break things up
     or to add spacing.

     SEE ALSO : GetString()

`GetString(msg, default)'
     This function allows you to prompt the user for a string of input.
     The first argument, msg, is a pointer to a string which will be
     displayed in the dialog box.  The next argument, default, is the
     default string to place in the text string box (it can be NULL or "").

     When you call this function, it pops up a small dialog box on the
     screen, and the user can enter the line of text.  When the user clicks
     ok or cancel, the function returns a pointer to the string of text the
     user entered.

     If the user clicks cancel, you get a NULL return value.

     SEE ALSO : GetYesNo()

DRAW AREAS
----------

A drawing area is a rectangular area that supports drawing into, receiving
input from (mouse clicks, mouse motion and keypresses) and redisplay
requests from X.  You can draw any sort of graphics into a drawing area as
well as perform various types of interaction with mouse and keyboard input.

`MakeDrawArea(width, height, callback, data)'
     The function MakeDrawArea() creates a drawing area which you can later
     use to draw graphics into and receive mouse and keyboard input from.
     The drawing are will have a width and height as you specify.  The
     callback function is called whenever the drawing area should be
     redisplayed (because it was obscured or resized).  The argument "data"
     is any kind of Sxperl object you want, and it is passed directly to
     the resize callback (and the other callbacks as well).

     The redisplay callback is where you should put all of your drawing
     code.  It is called for you when the application opens the window for
     the first time (by calling MainLoop()).  The redisplay callback
     function should looks like:

          sub redisplay {
          	my($widget, $width, $height, $data) = @_
          }

     The first argument is the drawing area widget that needs to be
     redrawn.  The second and third arguments are the new width and height
     of the drawing area (it may have been resized).  The final argument
     is the data passed to MakeDrawArea().

     If you are interested in receiving other types of input, see the
     functions, SetButtonDownCB(), SetButtonUpCB(), SetKeypressCB() and
     SetMouseMotionCB().  These functions will let you set callbacks for
     the other types of input.

     Each drawing area you create has its own state (foreground and
     background colors, drawing mode, and line width).  Only one drawing
     area can be active at any given time.  When an event happens for a
     drawing area, that drawing area becomes the active drawing area.  You
     can make other drawing areas active with SetDrawArea().

     If something goes wrong in creating the DrawArea, a FALSE value is
     returned.

`SetButtonDownCB(w, callback)'
     This function sets up a callback that will be called everytime the
     user presses a mouse button in the specified drawing area widget `w'.

     The callback function should looks like:

          sub  callback {
          	my($widget, $which_button, $x, $y, $data) = @_;
          }

     Then, whenever the user presses a mouse button in the drawing area,
     your callback is called.  The first argument is the drawing area
     widget where the event happened.  The next argument is an integer
     specifying which button was pressed.  It is a small positive integer.
     A value of one is the left mouse button, two is the middle mouse
     button and three is the right mouse button.  Technically, values of
     four and five are also possible though I've never seen a mouse with
     five buttons.  The x and y arguments are the position of the mouse
     where the user pressed the mouse button.  The final argument is the
     data argument given to MakeDrawArea().

     You can specify a null string for the function to turn off receiving
     button down events.

`SetButtonUpCB(widget, button_up)'
     This function sets up a callback that will be called everytime the
     user releases a mouse button in the specified drawing area widget `w'.

     Same behaviour as for SetButtonDownCB().

`SetKeypressCB(widget, callback)'
     This function lets you set a callback so that you will receive
     keyboard input in the drawing area.

     The callback function should looks like:

          sub  callback {
          	my($widget, $input, $up_or_down, $data) = @_;
          }

     Then, whenever the user presses keys in the drawing area, your
     callback function is called.  The first argument is the drawing area
     widget where the event happened.  The next argument is a string that
     contains what was typed by the user.  The up_or_down argument
     indicates whether the key was pressed released (a zero indicates a
     press, a 1 indicates a key release). The final argument is the
     argument given to MakeDrawArea().

     It is useful to know that the string returned to your program is not
     necessarily a single ASCII character. You will get the usual ASCII
     characters, including control characters (such as ^C or ^H).  But,
     the workstation's function keys will also be returned in a string
     such as "F11" or "F23".  You will also get other longer strings such
     as "Control_L", "Alt_R", or "Shift_L".  It is important to understand
     that even if you just press the shift key to get a capital letter,
     you will first receive the string "Shift_L" or "Shift_R", then you
     will receive a capital letter (say, "H").  You should probably ignore
     the "Shift_L" or "Shift_R" messages (but who knows, you may find some
     use for them).

     The argument, up_or_down, tells you whether the given key was pressed
     or released.  If the key was pressed down, up_or_down has a zero (0),
     if the key was released, up_or_down contains a 1.  This is useful for
     doing things like shift-clicking with the mouse or handling
     control-key combinations in an editor or other program.

     The arrow keys return strings such as "Left", "Up", "Right", or
     "Down".  Other keys on the keyboard may return strings such as "Home",
     "Prior", "Next", "Undo", "Help", etc.  Of course not all keyboards
     generate all of the strings (because they aren't set up to).

     You can specify a NULL for the function to turn off receiving keypress
     events.

`SetMouseMotionCB(widget, callback)'
     This function sets a callback so that whenever the mouse moves in your
     drawing area, the specified function will be called.  It is important
     to keep in mind that the function you specify is called *every* time
     the mouse moves in the drawing area, even if it is just passing
     through.

     The callback function should looks like:

          sub  callback {
          	my($widget, $x, $y, $data) = @_;
          }

     The first argument is (as usual) the Widget where the mouse was moved
     in.  The next two arguments are the current X and Y values of the
     mouse.  The final argument is the argument passed into MakeDrawArea().

     You should be very frugal with what happens in this function so as not
     to cause the application to lag behind the user too much.  Calling
     functions like sleep() are definitely out of the question.

     You can specify a NULL for the function to turn off receiving mouse
     motion events.

DRAWING
-------

This contains documentation about the routines that let you draw in a
drawing area.

The documentation for these functions is quite brief because they are not
all that complicated (how much can one really say about DrawLine()).

Keep in mind that for all the drawing functions, the top-left corner of a
drawing area is considered to be 0,0.

Also, all primitives are drawn in the current foreground color (set either
by SetColor() or SetFgColor().  Text is drawn with the current foreground
color and the background color.  Line, arc, and box primitives are drawn
with the current line width (as set by SetLineWidth()), and all primitives
are drawn in the current draw mode (set by SetDrawMode()).

`SetDrawArea(widget)'
     This sets the current drawing area to be that named by the Widget w.
     If `w' is not a drawing area widget, nothing happens.

     You need to call this function when you want to switch between
     multiple drawing areas.

     If you only have one drawing area you do not need to worry about this
     function at all.

     Any callbacks for a drawing area already have the current drawing area
     set to be the one where the event happened (so it is not necessary to
     call this function in a callback for a drawing area).

`SetColor(color)'
     This sets the foreground color to draw with in the current drawing
     area (each drawing area has its own foreground color).  The argument
     "color" should be a valid color obtained with one of the color
     functions (such as GetNamedColor() or GetRGBColor(), etc).

     To some extent this function duplicates the SetFgColor() function, but
     exists because it is faster than SetFgColor().

`SetLineWidth(width)'
     This functions sets the width of lines drawn in the current drawing
     area.  Each drawing area has its own line width.

     A width of zero is valid and tells the X server to draw lines as fast
     as it possibly can, possibly being a little inaccurate.  Larger
     numbers of course draw wider lines.

`SetDrawMode(mode)'
     This function sets the drawing mode for the current drawing area.  A
     drawing mode is one of:

          Sx::GXcopy, Sx::GXxor, Sx::GXinvert, Sx::GXor, Sx::GXclear,
          Sx::GXand, Sx::GXandReverse, Sx::GXnoop, Sx::GXnor, Sx::GXequiv,
          Sx::GXinvert, Sx::GXorReverse, Sx::GXcopyInverted,
          Sx::GXorInverted, Sx::GXnand, and Sx::GXset

     Most of these are stupid/useless modes defined by X (so ignore them).

     The primary mode is GXcopy (the default mode).  This causes all
     primitives to draw in the foreground color, overwriting any pixels
     already drawn.

     Libsx also defines a special mode: $Sx::SANE_XOR.  The Sx::SANE_XOR
     mode will actually draw primitives in a true XOR mode so that you can
     draw things like rubber-band boxes that the user stretches with the
     mouse.  You must use Sx::SANE_XOR if you want true XOR'ed primitives,
     GXxor will definitely NOT work as you expect.

     When you are done using Sx::SANE_XOR, you would normally call
     SetDrawMode() with an argument of GXcopy to restore normal drawing.

`GetDrawAreaSize(width, height)'
     This is a convience function that returns the size of the current
     drawing area.  The window dimension are returned in the two variables.

`ClearDisplay()'
     This function completely clears the current drawing area and sets it
     to the current background color (which may not be white).

     Generally, when your redisplay callback is called, this is the first
     thing want to do.

`DrawPixel(x1, y1)'
     This function draws a point in the current foreground color at the
     location x1, y1 in your current drawing area.  The top left corner of
     the drawing area is considered 0,0.

`GetPixel(x1, y1)'
     This function retrieves the pixel value at the location x1, y1 in the
     current drawing area.  The top left corner of the drawing area is
     considered 0,0.

     The pixel value returned to you will be between 0 and 255 (inclusive).
     The value you get back should be treated as an index to a colormap.
     To find out what actual color is displayed at that location, you need
     to look up the color in the colormap (which you should be maintaining
     as there is no way to get it after you've set it).

     NOTE: This function is *NOT* very high performance. It has to call
     GetImage() to do the bulk of the work.  This is unfortunate, but
     unavoidable because X does not provide an easy way to read individual
     pixels.

`DrawLine(x1, y1, x2, y2)'
     This function draws a line from x1,y1 to x2,y2 in the current
     foreground color in the current drawing area.  The top left corner of
     the drawing area is considered 0,0.

`DrawPolyline(n, @points)'
     This function accepts an array of points and draws them as a connected
     polyline on the display.  The line is drawn in the current foreground
     color in the current drawing area. The top left corner of the drawing
     area is considered 0,0.

     The `points' argument is an array of consecutive x, y pairs.

`DrawFilledPolygon (n, @points)'
     This function takes an array of points and draws them as a filled
     polygon on the display.  The polygon is filled with the current
     foreground color and is drawn in the current drawing area. The top
     left corner of the drawing area is considered 0,0.

`DrawBox(x, y, width, height)'
     This function draws a rectangular box starting at x,y with a width and
     height as specified.  If you make the call: `DrawBox(50,50,75,75)',
     you will get a box that starts at position 50,50 and goes for 75
     pixels in the X and Y directions (i.e the other extreme of the box
     would be at 125,125). The box is drawn in the current foreground
     color in the current drawing area. The top left corner of the drawing
     area is considered 0,0.

     If the width and height are negative, the box is still drawn properly.

`DrawFilledBox(x, y, width, height)'
     This function draws a filled rectangular box starting at x,y with a
     width and height as specified.  If you make the call:
     `DrawFilledBox(50,50,75,75)', you will get a filled box that starts at
     position 50,50 and goes for 75 pixels in the X and Y directions (i.e
     the other extreme of the box would be at 125,125). The box is filled
     with the current foreground color in the current drawing area. The top
     left corner of the drawing area is considered 0,0.

     If the width and height are negative, the box is still drawn properly.

`DrawText(string, x, y)'
     This function prints the text string "string" starting at x,y.  The
     text is drawn in the current foreground color.  The background of the
     text is filled with current background color of the drawing area
     widget.  The top left of the drawing area is 0,0.  The X,Y position
     you specify is the bottom left corner of where the text is drawn.

`DrawArc(x, y, width, height, angle1, angle2)'
     This function draws an arc/ellipse from the location x,y that is
     bounded by the box defined by the x,y, width and height.  That is, the
     arc/ellipse will always be contained in the box defined by the x,y
     position and the width and height arguments.  The X,Y arguments are
     not the center of the arc/circle.

     The arc begines at angle1 degrees and continues for angle2 degrees
     around the circle.  The arc is drawn in the current foreground color
     in the current drawing area. The top left corner of the drawing area
     is considered 0,0.

     If you want a circle, you would specify angle1 as 0, and angle2 as
     360.

     If the width and height are negative, the arc is still drawn properly.

`DrawFilledArc(x, y, width, height, angle1, angle2)'
     This function draws a filled arc/ellipse from the location x,y that is
     bounded by the box defined by the x,y, width and height.  That is, the
     arc/ellipse will always be contained in the box defined by the x,y
     position and the width and height arguments.  The X,Y arguments are
     not the center of the arc/circle.

     The arc begines at angle1 degrees and continues for angle2 degrees
     around the circle.  The arc is filled with the current foreground
     color in the current drawing area. The top left corner of the drawing
     area is considered 0,0.

     If you want a circle, you would specify angle1 as 0, and angle2 as
     360.

     If the width and height are negative, the arc is still drawn properly.

`DrawImage(data, x, y, width, height)'
     This function draws a bitmap image that has a width and height as
     specified by the arguments.  The image is drawn at location x,y in the
     current drawing area.  The "data" argument should contains at least
     width*height bytes of data.

     Each byte of the data is interpreted as a color value to draw the
     corresponding pixel with.

     Normally you would use this function when you have taken over the
     colormap with GetAllColors() (so that you can be guaranteed certain
     colors are in a given range).  If you have not taken over the
     colormap, you need to make sure that the bytes in the image data
     contain valid values that you've allocated with the color allocation
     functions (GetNamedColor(), GetRGBColor() or GetPrivateColor()).

     The top left corner of the drawing area is considered 0,0.

`GetImage(x, y, width, height, result)'
     This function retrieves a bitmap image from your drawing area that
     has a width and height as specified by the arguments.  The image is
     taken from the starting location x,y in the current drawing area.

     The 'result' variable will be filled with the 8-bit pixel values of
     the current drawing area.  Note that the pixel values are not the
     actual color values.  If you want the actual color values, you'll
     need to know what the current colormap is (which you would know if
     you've set the colormap) and then use the pixel values to index the
     colormap.

     The memory pointed to by data is packed with width*height bytes, with
     no extra padding or filling.  That is, the first width bytes
     correspond to line 0, the next width bytes correspond to line 1 of the
     image, etc.

     It is important to keep in mind that if you plan to save the pixel
     data in an image file, you need to also keep track of the colormap so
     that you can save that as well.  By themselves, the pixel values don't
     correspond to any particular color.

     A serious drawback of this function arises from the way X operates.
     If the drawing area from which you are "getting" the image is obscured
     by another window, that part of the bitmap will be empty.  The only
     way around this is to make sure that your window is in front of all
     the others before you call GetImage().  This is a serious limitation,
     but it's the way X operates.

     The top left corner of the drawing area is considered 0,0.  If you
     specify a starting x,y and width,height dimensions that are larger
     than your drawing area, you will get a BadMatch error and X will
     terminate your program (so be careful).

`ScrollDrawArea(dx, dy, x1, y1, x2, y2)'
     This function scrolls the box defined by (x1,y1) (x2,y2) by the
     amounts dx and dy in the X and Y directions respectively.  This means
     that the box whose upper left corner is (x1,y1) and whose lower right
     corner is (x2,y2) are scrolled by dx and dy pixels in X and Y.

     A positive value for dx causes the drawing area to scroll its contents
     to the left.  That is, whatever is at the left edge gets pushed off
     and the dx columns of pixels on the right hand side are cleared to the
     background color.  A negative value has the opposite effect.

     A positive value for dy corresponds to scrolling upwards.  That is,
     whatever is at the top of the drawing area is pushed up by dy pixels
     and the bottom dy rows of pixels are cleared to the background color.
     A negative value has the opposite effect.

     This function is useful for scrolling the drawing area to draw new
     information (such as a text editor might do to scroll text up or
     down).

     The new area exposed by the scroll is filled with the current
     background color of the drawing area.

COLOR STUFF
-----------

This describes the routines for managing colors in your window.  For
example if you want to change what the foreground color is, or need to get
specific colors.  To get specific colors you use the functions discussed
in here.  It is important to remember that you can not call any of these
functions until you have called ShowDisplay().

Colors are represented by integers.  When you get a color, you are
returned an integer that you can use in calls to SetFgColor(),
SetBgColor(), and SetColor().  You should attach no meaning to the
numbers, and just because green is 17 does not mean that 18 is a lighter
or darker shade of green.

There are three ways to manipulate colors with Sxperl.  The first way
handles most of the common cases, and is done with GetNamedColor() or
GetRGBColor().

The next method, GetPrivateColor(), allows your application to modify the
actual display color represented by a color number (something you cannot
do with the the previous methods).

The final method gives you complete control in specifying the entire
colormap.  That is, you can determine exactly what integers map to what
colors so you can obtain smooth gradients (so for example black is color
0, and white is 255).  These routines work best on 8 bit displays but will
work on 24 bit displays.

NOTE: You can NOT call any color function until you have called
ShowDisplay().

The way colors work for drawing is like this.  There are usually 256
available colors on a workstation.  This is called an 8-bit display
because 2 to the 8'th power == 256.  These colors are stored in a table
(array) of 256 entries.  If you allocate a color, and it is in entry 37,
then to draw with the color that is stored there, you must use 37 as an
argument to the SetColor() function.  When you ask for a color, it may be
taken from anywhere in the array of 256 entries, and there is *NO*
guarantee that if you allocate a green color that the next color in the
table will be a lighter or darker green.  Even if you allocate many colors
using GetNamedColor() or GetRGBColor(), you have i<NO> assurances about
where those colors are in the array (chances are they won't be
contiguous).  If you need to have a contiguous set of numbers, you must
use GetAllColors() and then SetColorMap() or SetMyColorMap() to set up a
custom colormap with a known set of values.  When you get a private color,
your application can specify what values that color index should have.
This is useful when you want to interactively modify a color.

It is important to remember that `getting a color' really means getting an
index into the color table where the actual color is stored.

`GetStandardColors()'
     This function sets 6 function returning standard colors, RED, GREEN,
     BLUE, YELLOW, BLACK, and WHITE.  The values returned can be used in
     calls to SetColor(), SetFgColor(), SetBgColor(), etc.

     Do not call RED, GREEN, BLUE, YELLOW, BLACK or WHITE before calling
     GetStandardColors().  The results are undefined if you do this.

     NOTE: You can only call GetStandardColors() after calling the
     ShowDisplay() function.

`GetNamedColor(name)'
     This function allocates an entry in the color table for the color
     given by the ascii string "name".  You can view the list of available
     color names with the showrgb command in a shell (some nice ones are
     "peachpuff", "burlywood3", "aquamarine", and "paleturquoise3").  Color
     names can have spaces in them.  The return value of the function is an
     integer that you can use in calls to SetColor() (or any of the other
     SetXXColor() calls). If an error occurred trying to allocate the color
     (very possible if you allocate a lot of colors), a -1 is returned.

`GetRGBColor(red, green, blue)'
     This function tries to allocate the color given by the red, green,
     blue triple r,g,b.  The arguments r,g, and b should be between 0 and
     255.  Overflow is not checked for.  The return value is an integer
     value usable in the SetColor() calls or a -1 if an error occurred.

`GetPrivateColor()'
     This function allocates a private color cell for use by the
     application.  A private color cell is one which you can change what
     color it represents.  For example, if you would like to let the user
     interactively manipulate some color, you would need to allocate a
     private color cell.

     The integer returned by this function is a reference to a color cell
     whose values you can set with SetPrivateColor().  The intial contents
     of the private color cell are undefined and you should probably call
     SetPrivateColor() immediately to set it to some known value.

     If an error occurs, a -1 is returned.

     When you are done with a private color cell, you should free it with
     FreePrivateColor().

`SetPrivateColor(which, red, green, blue)'
     This function sets the color cell referred to by `which' to have the
     r,g,b values specified.  The r,g,b values are given in the range 0-255
     (inclusive). Once this function is called, any thing drawn in the
     display with the color `which' will now have the new color determined
     by the r,g,b arguments.

`FreePrivateColor(which)'
     This function returns the color associated with the private color cell
     `which' to the system.  You should have allocated the color referred
     to by `which' with GetPrivateColor().

`GetAllColors()'
     This function is rather drastic and should be used with caution.  It
     immediately grabs an entire 256 entry colormap for private use.  This
     has the unfortunate effect of (temporarily) wiping out the colors in
     all the other windows on the display.  However this is necessary if
     you wish to get a smooth colormap to use in displaying a smooth-shaded
     or continuous tone picture.  Once GetAllColors() is called, the entire
     colormap is free for manipulation by your program.  The colormap
     remains allocated until you call FreeAllColors(), at which time
     everything goes back to normal.

     If an error occurred (quite possible), this routine returns FALSE.  If
     everything went ok and the colormap was successfully allocated, TRUE
     is returned.

     If you can avoid using this function, try to.  It is disconcerting for
     the user to have the colormap get wacked out and have most of their
     windows disappear (they don't really disappear of course, you just can
     see them usually).  However it is sometimes necessary to do this as
     there is no other way to get a smoothly continuous color map.

     Usually, you will want to call SetColorMap() or SetMyColorMap() right
     after this function.

     NOTE: On a 24 bit machine (like the SGI Indigo Elan I tested this
     with), only current drawing area gets the colormap, other widgets and
     windows are not affected.

`FreeAllColors()'
     This function frees a private colormap that was allocated with
     GetAllColors().  It has the beneficial effect of immediately restoring
     the rest of the colors on the screen and in other windows to those
     that existed prior to the call to GetAllColors().  This function is
     useful if wish to let the user restore their original colors
     temporarily (although this will happen automatically when the mouse
     moves outside the window).

`SetColorMap(num)'
     This function creates several predefined color maps that are very
     smoothly continuous.  It saves you the hassle of writing them yourself
     (even though they are mostly easy).  The "num" argument you pass in
     should be one of the following variable :

          $Sx::GREY_SCALE_1    0
          $Sx::GREY_SCALE_2    1
          $Sx::RAINBOW_1       2
          $Sx::RAINBOW_2       3

     The colormap Sx::GREY_SCALE_2 is a complete smooth color ramp from
     pure black (color 0) to pure white (color 255).  The other grey scale,
     Sx::GREY_SCALE_1 is a nearly pure ramp from black (color 0) to white
     (color 252), but also has a few additional colors thrown in near the
     end of the colormap.  The two Sx::RAINBOW_? colormaps have different
     types of smooth changing rainbows of color.  This are really only
     useful for drawing pretty patterns or doing false coloring.

     NOTE: You should call GetAllColors() before you call this routine.  It
     is not necessary, but if you don't, and GetAllColors() fails, you will
     never know about it, and your application may not work very well.

`SetMyColorMap(int, red1, green1, blue1, ..., redN, greenN, blueN)'
     Occasionally it is necessary to have absolute control over your
     colormap, and this function lets you do that.  This function lets you
     completely specify each and every color that will be in the colormap.
     The values for redi, greeni or bluei range from 0 to 255.  You need
     not specify a full list of 256 triplets, you can in fact only specify
     a few.  The integer argument "n" indicates how many triplets are
     present.  The argument "n" should be greater than 0 and less than 255.

     NOTE: You should call GetAllColors() before you call this routine.  It
     is not necessary, but if you don't and GetAllColors() fails, you will
     never know about it, and your application may not work very well.

FONTS
-----

Fonts are different type styles that can be used in various widgets.  You
load a font by name and get a handle in return. The handle you get allows
you to set the font in the various widgets and font information calls.

`GetFont(fontname)'
     This function loads the font named by fontname and returns a handle to
     the font or FALSE if there is an error.  The handle returned by this
     function is an XFont object and should be treated as an opaque data
     type.

     After you've loaded a font, you can then set that font in any widget
     that displays text.  You can also use the handle in calls to
     TextWidget() and FontHeight().

     When you are done with a font, you should free it with FreeFont().

`SetWidgetFont(widget, font)'
     This functions sets the font used by the widget `widget', to be the
     font referred to by the argument `font'.  The argument f should have
     been obtained with GetFont().

`GetWidgetFont(widget)'
     This function returns a handle to the font currently used by the
     Widget widget.  If an error occurs or there is no default font for the
     widget, a FALSE is returned.

     You should NOT call FreeFont() on any value returned by this function
     unless you are sure that you allocated the font with GetFont().

`FreeFont(font)'
     This function frees the resources associated with the font.  You
     should call this function when your application is done using a
     particular font.

     Of course you should make sure that no widget still uses the
     identified font.

`FontHeight(font)'
     This function returns an integer value that is the height in pixels of
     the specified font.   The height is defined to be the ascent of the
     characters (from the baseline to the top of a capital letter) plus the
     descent of the characters (the distance from the baseline to bottom of
     a descender character like `g' or `p').

`TextWidth(font, txt)'
     This functions returns the width in pixels used by the string pointed
     to by txt in the specifiedfont.  The entire string is used to
     determine the width.

MISCELLANEOUS
-------------

The following function allows you to specify how the display should be
layed out.  It lets you logically position the components you created with
the MakeXXX() functions.  You will use this function to layout the
arrangement of your buttons, labels and drawing area(s).

`SetWidgetPos(widget, where1, from1, where2, from2)'
     This function lets you position a Widget in your window.  The idea is
     that you specify logical placement of the Widget (i.e. place it to the
     right of this widget, and under that widget).  Many layouts are
     possible, and you can even specify that you don't care where a
     specific widget is placed.

     There are three types of placement.  You can place a widget to the
     right of another widget with $Sx::PLACE_RIGHT.  If the argument
     "where1" is $Sx::PLACE_RIGHT, then the specified widget will be placed
     to the right of the Widget "from1".  If "where1" is equal to
     $Sx::PLACE_UNDER, the widget will be placed under the widget "from1".
     The same holds true for the argument "where2" and Widget "from2".
     Having two arguments is necessary to be able to unambiguously specify
     where you want components placed in the display.  If you don't care
     about where a widget is placed, you can use $Sx::NO_CARE for the
     `where' argument and a $Sx::Nullsx value for the `from' argument.

     Generally, the first widget created need not be specified, it will
     always be in the top left corner.  Other widgets can the be placed
     relative to that widget.  For example, if you created 4 widgets
     ($w[0..4]) and wanted to arrange them in a column, you would do the
     following :

          SetWidgetPos($w[1], $Sx::PLACE_UNDER, $w[0], $Sx::NO_CARE, $Sx::Nullsx);
          SetWidgetPos($w[2], $Sx::PLACE_UNDER, $w[1], $Sx::NO_CARE, $Sx::Nullsx);
          SetWidgetPos($w[3], $Sx::PLACE_UNDER, $w[2], $Sx::NO_CARE, $Sx::Nullsx);

     Notice how the third argument changes; we are placing the next widget
     underneath the previous widget.  The zero'th widget ($w[0]) doesn't
     have to be placed because it is always in the top left corner (this
     can not be changed).

     If you wanted to arrange things in a row, you would use
     $Sx::PLACE_RIGHT instead of $Sx::PLACE_UNDER.

     As a more complicated example, supposed you want to create two rows of
     widgets, and a drawing area.  You would do the following :

          # first three across the top
          SetWidgetPos($w[1], $Sx::PLACE_RIGHT, $w[0], $Sx::NO_CARE, $Sx::Nullsx);
          SetWidgetPos($w[2], $Sx::PLACE_RIGHT, $w[1], $Sx::NO_CARE, $Sx::Nullsx);
          SetWidgetPos($w[3], $Sx::PLACE_RIGHT, $w[2], $Sx::NO_CARE, $Sx::Nullsx);

          # next three underneath the top row
          SetWidgetPos($w[4], $Sx::PLACE_UNDER, $w[0], $Sx::NO_CARE, $Sx::Nullsx);
          SetWidgetPos($w[5], $Sx::PLACE_UNDER, $w[0], $Sx::PLACE_RIGHT, $w[4]);
          SetWidgetPos($w[6], $Sx::PLACE_UNDER, $w[0], $Sx::PLACE_RIGHT, $w[5]);

          # put the drawing area under the second row
          SetWidgetPos($w[7], $Sx::PLACE_UNDER, $w[4], $Sx::NO_CARE, $Sx::Nullsx);

     It is useful to think of the window as a kind of grid in which you can
     put various pieces.  Just draw a picture of what you want and then use
     SetWidgetPos() to indicate to the system what is next to/underneath of
     what.

     Also, all imaginable layouts are not possible with SetWidgetPos().
     For example, you cannot specify specific pixel offsets for a widget,
     or that it be centered in the display, or right justified.  This
     limitaton is for the sake of simplicity.  Generally this should not be
     a problem (if it is, you are probably getting beyond the scope of what
     libsx was intended to provide, i.e. you're becoming an X hacker :).

     You can simulate more complicated layouts by cheating and creating
     label widgets whose label is just spaces and then placing other widget
     the left or underneath the label.  This works but is kind of hackish.
     See also SetWidgetInt() for another way to cheat.

`SetFgColor(widget, color)'
     This function sets the foreground color of a widget. If the widget is
     a drawing area, all future primitives are drawn with the specified
     color.  If the widget is some other type of widget, it sets the
     foreground color of the widget (such as its text) to be the specified
     color.

     The argument "color" should be an integer that was returned from the
     colormap functions (GetNamedColor(), GetRGBColor(), GetPrivateColor()
     or GetStandardColors()).

`SetBgColor(widget, color)'
     This function sets the background color of a widget.  If the specified
     widget is a drawing area, the next call to ClearDisplay() will clear
     the drawing area to the specified background color.

     The argument "color" should be an integer that was returned from the
     colormap functions (GetNamedColor(), GetRGBColor(), GetPrivateColor()
     or GetStandardColors()).

`SetBorderColor(widget, color)'
     This argument will set the border color that is drawn around a widget.
     The same effect happens for all of the different widgets - the border
     is redrawn with the new color.  This can be very useful for giving a
     nice visual offset to an important or dangerous button.  Of course you
     should avoid garish combinations of colors that are hard to look at.

`GetFgColor(widget)'
     This routine is a convience function that will return the current
     foreground color of any kind of widget.  This is mainly useful for
     drawing widgets to make sure that you draw things in the proper
     foreground color.  This can arise as a problem if you assume that
     black is going to be the default foreground color (which it normally
     is).  However, the user can change this default by using the -fg
     "color" option on the command line.  This is an X command line option,
     and can not be overriden by your program.  A real application would
     use this function to check the value and use it to draw in the user's
     preferred foreground color.  Other programs can just ignore the
     problem and still work ok as long as the user doesn't change the
     program's colors.

     This function returns the integer value of the foreground color that
     you can use in later calls to SetFgColor() or SetColor(). It returns
     -1 if you passed an invalid Widget to it.

`GetBgColor(widget)'
     This routine is a convience function that will return the current
     background color of any kind of widget.  This is mainly useful for
     drawing widgets to make sure that you draw things in the proper
     background color.  This can be a problem if you assume that white is
     going to be the default background color (which it normally is).
     However, the user can change this default by using the -bg "color"
     option on the command line.  This is an X command line option, and can
     not be overriden by your program.  A real application would use this
     function to check the value and use it to draw in the user's preferred
     background color.  Other programs can just ignore the problem and
     still work ok as long as the user doesn't change the program's colors.

     The other problem that crops up if you ignore the background color is
     that if you go to erase something by just drawing in white and white
     doesn't happen to be the actual background color, your program will
     look funny.

     This function returns the integer value of the background color that
     you can use in later calls to SetBgColor() or SetColor(). It returns
     -1 if you passed an invalid Widget to it.

`AddTimeOut(interval, func, data)'
     If you would like to animate a display or do some periodic processing
     (such as an auto-save feature for an editor), you can use time-outs.

     A time-out is a callback function that gets called when the specified
     amount of time has expired (or I should say more precisely, when at
     *least* that much time has passed, Unix a'int no real time system).

     The argument `interval' is an unsigned long and is specified in
     milliseconds. That is, a time out of 1 second would be an argument of
     1000.

     The callback should look like:

          sub  func {
          	my($data) = @_
          }

     The function is only called once, if you would like the function to be
     called repeatedly (to update an animation for example), the last thing
     the function should do is to call AddTimeOut() again.

     The value returned by AddTimeOut() can be used with RemoveTimeOut()
     to cancel that time-out.

`RemoveTimeOut(id)'
     Cancels a time-out callback which was previously registered with
     AddTimeOut().

     Argument id is an identifier returned by AddTimeOut().

`SetWidgetState(widget, state); '
     This function lets you enable or disable particular widgets in an
     interface.  If, for example, choosing one item from a menu should
     disable various other widgets, you can call this function.

     The Widget argument is the widget in question.  The state argument is
     a boolean, which indicates whether the widget should be active or not.
     A value of TRUE indicates that the widget should accept input, and a
     value of FALSE indicates that the widget should not accept input (it
     becomes greyed out).

     When you disable a widget, the user can no longer interact with that
     widget in any way (it becomes grey'ed out and just ignores all input).

`GetWidgetState(widget)'
     This function returns a boolean value indicating whether or not the
     specified widget is currently active.

     If the widget is active and accepting input, the return is TRUE, if
     the widget is inactive, the return value is FALSE.

`Beep()'
     This function is real complicated.  It beeps the workstation speaker.

`SetWidgetBitmap(widget, data, width, height)'
     This function lets you attach a bitmap to a widget instead of its
     default text.  This function only works correctly on Button, Toggle
     and Label widgets.  Using it on another type of widget yields
     undefined results.

     The widget will display the bitmap data given by the argument, data,
     whose width and height are given as the last two arguments.

     The bitmap data is only one bitplane deep, and is usually produced by
     a somewhat brain-dead X program called `bitmap'.  The output of the
     bitmap program is a file you can almost directly 'require' in your
     source code.  The contents of the file is an array of characters and
     two #defines that give the width and height of the bitmap.

     Thus, making a widget with a bitmap is a three step process.  First
     you would edit a bitmap using the `bitmap' program, then you need to
     edit the resulting file to convert it to perl syntax then you would
     do the following:

          require  'bmap.ph';

          $w = MakeButton($Sx::Nullsx, 'func', $a_value);
          SetWidgetBitmap($w, $bmap_bits,$bmap_width,$bmap_height);

     Bits which are a one in the bitmap are drawn in the widget's current
     foreground color and zero bits are drawn in the current background
     color.

ADDITION TO THE ORIGINAL LIBSX
------------------------------

All the following functions and widgets were added to libsx.

`XtDestroyWidget(widget)'
     This function calls destroys a given widget and all it's descendant.
     Care should be taken not to re-use the widget after that.

`SetWidgetInt(widget, resource, value)'
     Sets the named resource with an integer value for a given widget.

`SetWidgetDat(widget, resource, value)'
     Sets the named resource with a 'string' value for a given widget.

`GetWidgetInt(widget, resource)'
     Get the integer value of the named resource.

`GetWidgetDat(widget, resource)'
     Get the string value of the named resource.

     The following functions are intended for Text widgets.

`AppendText(widget, text)'
     Append the given text to the end of widget. widget should be a 'text
     entry' widget.

`InsertText(widget, text)'
     Insert the given text in a 'text entry' widget at the current caret
     position.

`ReplaceText(widget, text, left, right)'
     Replace the text in the widget between position left and right by the
     given text.

`GetSelection(widget,str)'
     Returns (in buf) the selected string from the given text widget.

`GetTextSelectionPos(widget,left,right)'
     Returns (in left and right) the start and the end of the selected
     area.

`SetTextSelection(widget,left,right)'
     Set the start (left) and the end (right) of the selected area.

`UnsetTextSelection(widget,left,right)'
     Unset the selection.

     Misceallaneous functions.

`XWarpPointer(widget,x,y)' Moves the pointer to the (x,y) coordinates relative to the given widget.
`RemoveTimeOut(id)' Cancels an AddTimeOut() callback; id is the value as returned by AddTimeOut().
`AddReadCallback(fd, func, data)' Adds an input callback which gets called if some data are readable for a given filedescriptor fd.
`AddWriteCallback(fd, func, data)' Like AddReadCallback() but checks for data writeable.
`RemoveReadWriteCallback(id)' Cancels an AddReadCallback() or AddWriteCallback() request; id is the value as returned by AddReadCallback() or AddWriteCallback().
`AddTranslation(widget, translation_table)'
     Add (override) a translation table for the specified widget. Each
     translation should associate an event to a perl action. This action
     will take, the widget as its first argument, then the event as packed
     datas followed by the rest of the specified arguments. Be warned that
     the arguments will be passed as strings. So if you want to pass perl
     variables, you should quote them and use eval in the callback.

     For example :

          sub pargs {
            my($w,$ev,@a) = @_;
            print "args are [@_]\n";
            SetLabel($w,join('-',@a));
          }

          @ARGV = OpenDisplay('test',@ARGV);

          $w1 = MakeButton('quit','quit',undef);

          Sx::AddTranslation($w1,
          		       '<Btn1Up>','pargs(button1,up)',
          		       '<Btn1Down>', 'pargs(button1,down)',
          		       '<Btn2Up>', 'pargs(button2,up)',
          		       '<Btn2Down>', 'pargs(button2,down)',
          		       '<Btn3Up>', 'pargs(button3,up)',
          		       '<Btn3Down>', 'pargs(button3,down)',
          		       '<Motion>', 'pargs(motion)');

          &ShowDisplay;

          &MainLoop;

AUTHOR
======

Original by Dominic Giampaolo <`dbg@sgi.com'>.

Rewritten for Sx by Frederic Chauveau <`fmc@pasteur.fr'>.


File: pm.info,  Node: Sybase/BCP,  Next: Sybase/Login,  Prev: Sx,  Up: Module List

Simple front end to the Sybase BCP API
**************************************

NAME
====

Sybase::BCP - Simple front end to the Sybase BCP API

SYNOPSIS
========

     use Sybase::BCP;

     $bcp = new Sybase::BCP ...;
     $bcp->config(...);
     $bcp->run;

DESCRIPTION
===========

The Sybase::BCP module serves as a simplified front end for Sybase's Bulk
Copy library. It is sub-classed from the `Sybase::DBlib' in this node
module, so all the features of the Sybase::DBlib module are available in
addition to the specific Sybase::BCP methods.

So how does it work?

Let's say we want to copy the contents of a file name 'foo.bcp' into the
table 'mydb.dbo.bar'. The fields in the file are separated by a '|'.

     #!/usr/local/bin/perl

     use Sybase::BCP;

     $bcp = new Sybase::BCP $user, $passwd;
     $bcp->config(INPUT => 'foo.bcp',
     		 OUTPUT => 'mydb.dbo.bar',
     		 SEPARATOR => '|');
     $bcp->run;

That's it!

Of course, there are several things you can do to cater for non-standard
input files (see Configuration Parameters, below).

Features
--------

   * Automatic conversions from non-standard date formats.

   * Automatic retries of failed batches.

     If there are errors in the input file, or if there are duplicat rows
     that are rejected, the invalid rows are stored in an error log file,
     and the batch is retried, so that only the failed rows are not
     uploaded.

   * Handles column reordering and/or skipping of unneeded data.

   * Row or column based callbacks.

     Allows vetoing of rows, or arbitrary processing of data on input.

The following methods are available:
------------------------------------

$bcp = new Sybase::BCP [$user [, $password [, $server [, $appname]]]]
     Allocate a new *BCP* handle. Opens a new connection to Sybase via the
     *Sybase::DBlib* module, and enables BCP IN on this handle.

$bcp->config([parameters])
     Sets up the Bulk Copy operation. See Configuration Parameters below
     for details.

$bcp->describe($colid, {parameters})
     Adds a specific configuration element for column $colid. Columns are
     numbered starting at 1, as is standard in the Sybase APIs.

$bcp->run
     Perform the *BCP* operation, returns the actual number of rows sent
     to the server.

Configuration Parameters
------------------------

The general form for configuration is to pass (parameter => value) pairs
via the config() or describe() methods. Some parameters take slightly more
complex arguments (see REORDER).

Paramaters for config()
-----------------------

DIRECTION
     The direction in which the bulkcopy operation is done. Can be 'IN' or
     'OUT'.  Default: 'IN' (*Note:* 'OUT' is not implemented yet.)

INPUT
     Where *BCP* should take it's input from. It's a filename for *bcp
     IN*, it's a table name for *bcp OUT*.

     For *bcp IN* INPUT can also be a reference to a perl subroutine that
     returns the array to be inserted via bcp_sendrow().

OUTPUT
     Where *BCP* should place it's output. It's a table name for *bcp IN*,
     a filename for *bcp OUT*.

ERRORS
     The file where invalid rows should be recorded. Default: bcp.err.

SEPARATOR
     The pattern that separates fields in the input file, or that should
     be used to separate fields in the output file. Default: TAB.

FIELDS
     Number of fields in the input file for *bcp IN* operations. Default:
     Number of fields found in the first line. This parameter is ignored
     for *bcp OUT*.

BATCH_SIZE
     Number of rows to be batched together before committing to the server
     for *bcp IN* operations. Defaults to 100. If there is a risk that
     retries could be requiered due to failed batches (e.g. duplicat
     rows/keys errors) then you should not use a large batch size: one
     failed row in a batch requires the entire batch to be resent.

NULL
     A pattern to be used to detect NULL values in the input file.
     Defaults to a zero length string.

DATE
     The default format for DATE fields in the input file. The parameter
     should be a symbolic value representing the format. Currently, the
     following values are recognized: CTIME (the Unix ctime(3) format), or
     the numbers 0-12, 100-112, corresponding to the conversion formats
     defined in table 2-4 of the *SQL Server Reference Manual*.

     *BCP* detects *datetime* targets by looking up the target table
     structure in the Sybase system tables.

REORDER
     The ordering of the fields in the input file does not correspond to
     the order of columns in the table, or there are columns that you wish
     to skip. The REORDER parameter takes a hash that describes the
     reordering operation:

          $bcp->config(...
          		 REORDER => { 1 => 2,
          			      3 => 1,
          			      2 => 'foobar',
          			      12 => 4},
          		 ...);

     In this example, field 1 of the input file goes in column 2 of the
     table, field 3 goes in column 1, field 2 goes in the column named
     foobar, and field 12 goes in column 4. Fields 4-11, and anything
     beyond 12 is skipped.  As you can see you can use the column *name*
     instead of its position.  The default is to not do any reordering.

CALLBACK
     The callback subroutine is called for each row (after any
     reordering), and allows the user to do global processing on the row,
     or vetoing it's processing. Example:

          $bcp->config(...
                       CALLBACK => \&row_cb,
                       ...);

          sub row_cb {
          	my $row_ref = shift;

          # Skip rows where the first field starts with FOO:
          return undef if $$row_ref[0] =~ /^FOO/;

          1;
              }

CONDITION
     A *where* clause to be used in *bcp OUT* operations. Not implemented.

Parameters for describe()
-------------------------

CALLBACK
     Specify a callback for this column. The field value is passed as the
     first parameter, and the callback should return the value that it
     wants *BCP* to use. Example:

          $dbh->describe(2, {CALLBACK, \&col_cb});

          sub col_cb {
          	my $data = shift;

          # Convert to lower case...
          $data =~ tr/A-Z/a-z/;
              }

SKIP
     If this is defined then this field is skipped. This is useful if only
     one or two fields need to be skipped and you don't want to define a
     big REORDER hash to handle the skipping.

EXAMPLES
========

     #!/usr/local/bin/perl
     
     use Sybase::BCP;
     require 'sybutil.pl';

     $bcp = new Sybase::BCP sa, undef, TROLL;

     $bcp->config(INPUT => '../../Sybperl/xab',
     	         OUTPUT => 'excalibur.dbo.t3',
        	         BATCH_SIZE => 200,
     	         FIELDS => 4,
     	         REORDER => {1 => 'account',
     			     3 => 'date',
     			     2 => 'seq_no',
     			     11 => 'broker'},
     	         SEPARATOR => '|');
     $bcp->run;

BUGS
====

The current implementation seems to run about 2.5 to 3 times slower than
plain bcp.

AUTHOR
======

Michael Peppler `<mpeppler@itf.ch>'. Contact the sybperl mailing list
`mailto:sybperl-l@trln.lib.unc.edu' if you have any questions.


File: pm.info,  Node: Sybase/Login,  Next: Symbol,  Prev: Sybase/BCP,  Up: Module List

A highly configurable Login widget for Sybperl and Perl/Tk
**********************************************************

NAME
====

Sybase::Login - A highly configurable Login widget for Sybperl and Perl/Tk

Change History
==============


     1.0 - Initial Implementation

     *1.1* - Componentized for perl5.0021bh, handlers fixed

     *1.2* - Set up for general distribution, added Version and VERSION.
     Changed funky menu generation to Optionmenus.

     *Todo:* - Subclass Optionmenu to dynamically set up the Server
     selections on post (or Buttondown?)

DESCRIPTION
===========

Login is a Widget that presents a dialog box to the user so that the user
may enter his or her login name and password, as well as select the
appropriate database and server.

USAGE
=====

One uses Login by creating a new Login widget, adding at least one
Database via the addDatabase method, configuring via the configure method,
and then getting a valid login via the getVerification method.


Sample Program
--------------


          #!/usr/local/bin/perl -w

          use Tk;
          use Sybase::DBlib;
          use Sybase::Login;
          use strict;

          my($main) = MainWindow->new;
          my($Login) = $main->Login;

          $Login->addDatabase('DB',	'SYBSRV1','SYB11');
          $Login->addDatabase('DBBACK',	'SYBSRV1','SYB11');

          $Login->configure(-User => $ENV{'USER'},
          		   -ULabel => 'User Name:',
          		   -Title => 'Please Login');

          my($msg) = $main->Message(-text => 'Ready to go')->pack;
          $main->Button(-text => 'kick me!',
          	       -command => sub {
          		 my($pwd, $usr, $db, $srv, $mDB);
          		 if ($Login->getVerification(-Force => 1)) {
          		   $pwd = $Login->cget(-Password);
          		   $usr = $Login->cget(-User);
          		   $db =  $Login->cget(-Database);
          		   $srv = $Login->cget(-Server);
          		   print "Results good:\n\tUser:\t\t$usr\n";
          		   print "\tPassword:\t$pwd\n\tDatabase:\t$db\n";
          		   print "\tServer:\t\t$srv\n";
          		   print "Verifying Login...\n";
          		   $mDB = Sybase::DBlib->dblogin("$usr","$pwd", "$srv");
          		   $mDB->dbuse($db);
          		   $mDB->dbclose;
          		   print "Login worked!!!\n";
          		 } else {
          		   print "Login cancelled at User request.\n";
          		 }
          	       })->pack;

          $main->Button(-text => 'exit',
          	       -command => sub {$main->destroy;})->pack;

          MainLoop;

          print "And I'm on my way home!\n";

          exit;


Operation
---------

The user is presented with a dialog box.  The focus is on the username
entry if no user name has been configured; otherwise, it is on the
password entry.  If multiple databases have been configured, the user may
select the appropriate database from the menu button. If multiple servers
have been configured for the selected database, the user may select the
appropriate server from the menu button.

When the user has finished entering information, she may press the OK
button to attempt to login, or the cancel button to abort the process.  If
the user presses the OK button, and the login succeeds, control returns to
the caller.  If the login fails, an error dialog box is displayed, and the
user may press retry, or may press cancel, in which case control returns
to the caller exactly as if the user had pressed cancel at the main login
screen.

When control returns to the caller, the return value will be 1 if the
login was successful, or 0 if not.

Notes
-----

A caller may define a message or error handler either before or after
calling any of the methods of this object. getCurrentVerification will
restore the handlers extant when invoked.

Methods
=======


getCurrentVerification
----------------------

*$Login-*>*getCurrentVerification;*

*(No parameters)*

return 1 if the current configuration will result in a valid login, 0
otherwise.  No GUI is ever displayed.

getVerification
---------------

*$Login-*>*getVerification(-Force =* ?);>

If the current configuration is NOT valid, activate the login frame. This
will return 1 with a valid configuration, or 0 if the user hit cancel.  If
the -Force parameter is passed as 't', 'y', or 1, the login frame will be
activated even if the current configuration is valid.

addDatabase
-----------

*$Login-*>*addDatabase(Database, Server List);*

adds a database/server set.  The first parameter is the name of the
database, the second is a list of Associated Servers.  See the code above
for examples.

Note that the first server in the list is the default server for that
database.  Further note that adding a database a second time simply alters
the servers.

clearDatabase
-------------

*$Login-*>*clearDatabase([Database[, Database,...]]);*

Clears the given Database entries, or all databases if if none are
specified.

Version
-------

*$Login-*>Version

*(No parameters)*

Returns the current version of Login

Configuration Items
===================

Any of the following configuration items may be set via the configure
method, or retrieved via the cget method.


-User
-----

Set or get the username.  The default is blank.

-Password
---------

Set or get the password.  The default is blank.

-Title
------

Set or get the Title of the Login Widget.  The default is 'Database Login'

-Database
---------

Set or get the default Database.  The default is blank.  The call will
silently fail if the database is not configured via the AddDatabase
method.  If the configured server is not a valid server for the given
database, the server will be set to the default server for the database.

-Server
-------

Set or get the default Server.  The default is blank.  The call will
silently fail if the server is not a valid server for the currently
configured database.

-OKText
-------

Set or get the text for the *OK* button.  The default is OK.

-CancelText
-----------

Set or get the text for the *Cancel* button.  The default is Cancel.

-ULabel
-------

Set or get the label for the User name entry.  The default is 'User:'.

-PLabel
-------

Set or get the label for the Password entry.  The default is 'Password:'.

-DLabel
-------

Set or get the label for the Database Menu Button.  The default is
'Database:'.

-SLabel
-------

Set or get the label for the Server Menu Button.  The default is 'Server:'.

-Labelfont
----------

Set or get the font used for the labels.  The default is
'-Adobe-Courier-Bold-R-Normal-*-120-*'.

-EDlgTitle
----------

Set or get the Title for the Error Dialog. The default is 'Database Login
Error!'.

-EDlgText
---------

Set or get the text displayed in the Error Dialog.  The default is 'Unable
to login to $db at $srv'.  $db will be interpreted as the Database name,
$srv will be interpreted as the Server name, $usr will be interpreted as
the User name, and $pwd will be interpreted as the password.

-EDlgRetry
----------

Set or get the text for the Retry button in the Error Dialog. The default
is 'Retry'.

-EDlgCancel
-----------

Set or get the text for the Cancel button in the Error Dialog. The default
is 'Cancel'.

Author
======

*Brent B. Powers, Merrill Lynch (B2Pi)*

powers@ml.com

This code may be distributed under the same conditions as perl itself.


File: pm.info,  Node: Symbol,  Next: Sys/Hostname,  Prev: Sybase/Login,  Up: Module List

manipulate Perl symbols and their names
***************************************

NAME
====

Symbol - manipulate Perl symbols and their names

SYNOPSIS
========

     use Symbol;

     $sym = gensym;
     open($sym, "filename");
     $_ = <$sym>;
     # etc.

     ungensym $sym;      # no effect

     print qualify("x"), "\n";              # "Test::x"
     print qualify("x", "FOO"), "\n"        # "FOO::x"
     print qualify("BAR::x"), "\n";         # "BAR::x"
     print qualify("BAR::x", "FOO"), "\n";  # "BAR::x"
     print qualify("STDOUT", "FOO"), "\n";  # "main::STDOUT" (global)
     print qualify(\*x), "\n";              # returns \*x
     print qualify(\*x, "FOO"), "\n";       # returns \*x

DESCRIPTION
===========

`Symbol::gensym' creates an anonymous glob and returns a reference to it.
Such a glob reference can be used as a file or directory handle.

For backward compatibility with older implementations that didn't support
anonymous globs, `Symbol::ungensym' is also provided.  But it doesn't do
anything.

`Symbol::qualify' turns unqualified symbol names into qualified variable
names (e.g. "myvar" -> "MyPackage::myvar").  If it is given a second
parameter, `qualify' uses it as the default package; otherwise, it uses
the package of its caller.  Regardless, global variable names (e.g.
"STDOUT", "ENV", "SIG") are always qualfied with "main::".

Qualification applies only to symbol names (strings).  References are left
unchanged under the assumption that they are glob references, which are
qualified by their nature.


File: pm.info,  Node: Sys/Hostname,  Next: Sys/Syslog,  Prev: Symbol,  Up: Module List

Try every conceivable way to get hostname
*****************************************

NAME
====

Sys::Hostname - Try every conceivable way to get hostname

SYNOPSIS
========

     use Sys::Hostname;
     $host = hostname;

DESCRIPTION
===========

Attempts several methods of getting the system hostname and then caches
the result.  It tries `syscall(SYS_gethostname)', ``hostname`', ``uname
-n`', and the file `/com/host'.  If all that fails it croaks.

All nulls, returns, and newlines are removed from the result.

AUTHOR
======

David Sundstrom <`sunds@asictest.sc.ti.com'>

Texas Instruments


File: pm.info,  Node: Sys/Syslog,  Next: SysV,  Prev: Sys/Hostname,  Up: Module List

Perl interface to the UNIX syslog(3) calls
******************************************

NAME
====

Sys::Syslog, openlog, closelog, setlogmask, syslog - Perl interface to the
UNIX syslog(3) calls

SYNOPSIS
========

     use Sys::Syslog;

     openlog $ident, $logopt, $facility;
     syslog $priority, $format, @args;
     $oldmask = setlogmask $mask_priority;
     closelog;

DESCRIPTION
===========

Sys::Syslog is an interface to the UNIX `syslog(3)' program.  Call
`syslog()' with a string priority and a list of `printf()' args just like
`syslog(3)'.

Syslog provides the functions:

openlog $ident, $logopt, $facility
     *$ident* is prepended to every message.  *$logopt* contains one or
     more of the words pid, *ndelay*, *cons*, *nowait*.  *$facility*
     specifies the part of the system

syslog $priority, $format, @args
     If *$priority* permits, logs *($format, @args)* printed as by
     `printf(3V)', with the addition that *%m* is replaced with `"$!"'
     (the latest error message).

setlogmask $mask_priority
     Sets log mask *$mask_priority* and returns the old mask.

closelog
     Closes the log file.

Note that openlog now takes three arguments, just like `openlog(3)'.

EXAMPLES
========

     openlog($program, 'cons,pid', 'user');
     syslog('info', 'this is another test');
     syslog('mail|warning', 'this is a better test: %d', time);
     closelog();

     syslog('debug', 'this is the last test');
     openlog("$program $$", 'ndelay', 'user');
     syslog('notice', 'fooprogram: this is really done');

     $! = 55;
     syslog('info', 'problem was %m'); # %m == $! in syslog(3)

DEPENDENCIES
============

*Sys::Syslog* needs `syslog.ph', which can be created with h2ph.

SEE ALSO
========

`syslog(3)' in this node

AUTHOR
======

Tom Christiansen <`tchrist@perl.com'> and Larry Wall <`lwall@sems.com'>


File: pm.info,  Node: SysV,  Next: SyslogScan/ByGroup,  Prev: Sys/Syslog,  Up: Module List

SYNOPSIS
========

     use IPC::SysV;

     $msgbuf = msg_type_and_string_2_msgbuf($type,$str);
     ($type,$str) = msg_msgbuf_2_type_and_string($msgbuf);
     
     $msqid_ds = pack_msqid_ds($uid, $gid, $mode, $qbytes);
     @msqid_ds = unpack_msqid_ds($msqid_ds);
     $msgbuf = msg_type_and_string_2_msgbuf($type,$msg);
     ($type,$msg) = msg_msgbuf_2_type_and_string($msgbuf);
     @filtered = msg_queue_read_ready($msgqid1,$msgqid2, ...);
     
     $msqid_ds_obj = IPC::SysV::MSQID_DS->new($msqid_ds);
     $readable = $msqid_ds_obj->mode();
     $msqid_ds = $msqid_ds_obj->repack($uid, $gid, $mode, $qbytes);
     
     msgget(IPC_PRIVATE , $mode );
     ...

DESCRIPTION
===========

This module includes a translation of the C `sys/ipc.h', `sys/msg.h',
`sys/sem.h', and `sys/shm.h' files. In additions, various structure
manipulating functions, and useful calls are defined (so far only for msg
stuff).

NOTE!!!!! The Perl functions shmctl, shmget, shmread, shmwrite, msgctl,
msgget, msgrcv, msgsnd, semctl, semget, semop are defined here exactly as
for Perl (except that I've fixed semctl). Also I've included shmat and
shmdt. Please have a look to test these.

mode_string_2_num MODE
     Takes a string representing a permission mode and returns the numeric
     value for that string. The string can be a number, in which case it
     is just returned, or it can be of the form 'RW-RW-RW-' where R is 'r'
     or '-', W is 'w' or '-' . Returns undef if the argument is neither a
     number nor a string of the appropriate type.

mode_num_2_string MODE
     Opposite of mode_string_2_num(). Returns the string representation of
     the given permission mode. MODE can be a string of type 'RW-RW-RW-'
     in which case it is just returned. Returns undef if the argument is
     neither a number nor a string of the appropriate type.

msg_type_and_string_2_msgbuf TYPE MSG
     Returns the packed msgbuf structure as wanted by msgsnd().  TYPE is a
     positive number, and MSG is the string holding the message.

msg_msgbuf_2_type_and_string MSGBUF
     Returns the two element array consisting of the type and the message
     string. MSGBUF is the structure as filled in by msgrcv()

msg_queue_read_ready LIST_OF_MSQIDs
     This takes a list of message queue id's and returns a mapped list of
     the same size with each item being a 1, 0, or -1 depending on whether
     that queue has messages on it (1), does not have any messages on it
     (0), or an error occurred trying to determine the queue status (-1).
     The error may be because the queue did not exist, or may be a
     permission error. This can be determined by examining $!. This call
     can be implemented using msgctl in perl, and has been implemented in
     C in order to allow the slight gain provided by not having to
     repeatedly call the unpack_msqid_ds() for each queue in order to
     determine its status. There is no benefit if you just need to check
     one queue.

pack_msqid_ds UID, GID, MODE, QBYTES
     Packs the four argument values into a message queue id data
     structure, and returns that as a string. These are the only values
     that can be altered by msgctl. See also the IPC::SysV::MSQID_DS
     'repack' method.

unpack_msqid_ds MSQID_DS
     Takes a string holding a message queue id data structure, and unpacks
     it to return some of the packed parts (the parts that are system
     inpdendent I hope). You are probably better off using the
     IPC::SysV::MSQID_DS 'new' method which does the same but returns an
     object which is more easily handled.

     The MSQID_DS structure can be returned by the msgctl() function This
     function returns a 12 element array of the following elements of the
     MSQID_DS:

          msqid_ds.msg_perm.uid	user id
          msqid_ds.msg_perm.gid	group id
          msqid_ds.msg_perm.cuid	creator user id
          msqid_ds.msg_perm.cgid	creator group id
          msqid_ds.msg_perm.mode	r/w permission
          msqid_ds.msg_qnum		current number of msgs on the queue
          msqid_ds.msg_qbytes		max number of bytes allowed on queue
          msqid_ds.msg_lspid		pid of last msgsnd operation
          msqid_ds.msg_lrpid		pid of last msgrcv operation
          msqid_ds.msg_stime		last msgsnd time
          msqid_ds.msg_rtime		last msgrcv time
          msqid_ds.msg_ctime		last time queue was changed

     Jack Shirazi

          This program is free software; you can redistribute it and/or
          modify it under the same terms as Perl itself.

Version 1.0
     Base version.


File: pm.info,  Node: SyslogScan/ByGroup,  Next: SyslogScan/Delivery,  Prev: SysV,  Up: Module List

Organizes a Summary of mail statistics into Groups of related e-mail users
**************************************************************************

NAME
====

SyslogScan::ByGroup - Organizes a Summary of mail statistics into Groups
of related e-mail users

SYNOPSIS
========

     # $summary is a SyslogScan::Summary object

     # default is to organize by internet host
     my $byGroup = new SyslogScan::ByGroup($summary);
     print $byGroup -> dump();

     # group by whether users use 'jupiter' or 'satellife' as
     # their machine name, and discard users who use neither

     my $pointerToGroupingRoutine = sub {
     	my $address = shift;

     return 'jupiter' if $address =~ /jupiter.healthnet.org$/;
     	return 'satellife' if $address =~ /satellife.healthnet.org$/;

     # ignore all others
     return undef;
         }

     my $groupByMachine = new SyslogScan::ByGroup($summary,
     						 $pointerToGroupingRoutine);
     print $groupByMachine -> dump();

     # Extract a SyslogScan::Group object
     my $jupiterGroup = $$groupByMachine{jupiter};
     print $jupiterGroup -> dump();

     # Extract a SyslogScan::Summary object
     my $summaryOfJupiter = $jupiterGroup{byAddress};
     print $summaryOfJupiter -> dump();
     
     # Create a summary by group, rather than a summary by address
     my $summaryByMachine = $groupByMachine -> createSummary();

DESCRIPTION
===========

A SyslogScan::ByGroup object is a hash table of SyslogScan::Group objects,
each indexed by the group name as returned by the sorting algorithm fed to
'new'.

A SyslogScan::Group is a hash table with two members: 'byAddress', which
is a SyslogScan::Summary of each address which is a member of the Group,
and 'groupUsage', which is a SyslogScan::Usage object containing the total
usage of the group.

AUTHOR and COPYRIGHT
====================

The author (Rolf Harold Nelson) can currently be e-mailed as
rolf@usa.healthnet.org.

This code is Copyright (C) SatelLife, Inc. 1996.  All rights reserved.
This code is free software; you can redistribute it and/or modify it under
the same terms as Perl itself.

In no event shall SatelLife be liable to any party for direct, indirect,
special, incidental, or consequential damages arising out of the use of
this software and its documentation (including, but not limited to, lost
profits) even if the authors have been advised of the possibility of such
damage.

SEE ALSO
========

*Note SyslogScan/Summary: SyslogScan/Summary,, *Note SyslogScan/Usage:
SyslogScan/Usage,


File: pm.info,  Node: SyslogScan/Delivery,  Next: SyslogScan/DeliveryIterator,  Prev: SyslogScan/ByGroup,  Up: Module List

encapsulates a logged, successful delivery of mail from a sender to a list of recipients.
*****************************************************************************************

NAME
====

SyslogScan::Delivery - encapsulates a logged, successful delivery of mail
from a sender to a list of recipients.

SYNOPSIS
========

see *Note SyslogScan/DeliveryIterator: SyslogScan/DeliveryIterator,

DESCRIPTION
===========

A 'Delivery' object is an indication that mail was successfully delivered
or forwarded from a sender to a list of recipients.  You can extract
Delivery objects from a syslog file by using *Note
SyslogScan/DeliveryIterator: SyslogScan/DeliveryIterator,.

Variables
---------

     my $delivery = $iter -> next();
     
     #-----------------------------------------
     #  Sender, ReceiverList, Size, and Date are the most useful
     #-----------------------------------------
     
     # e-mail address of sender, may be 'undef' if the sender
     # could not be determined from the syslog
     my $sender = $$delivery{Sender};
     
     # reference to array of e-mail addresses of recipients
     my $paReceiverList = $$delivery{ReceiverList};
     my @aReceiverList = @$paReceiverList;
     print "The recipient(s) of the message was (were) ",
         join(' ',@aReceiverList), "\n";
     
     # size of message, may be 'undef' if the size could not be
     # determined from the syslog
     my $sizeInBytes = $$delivery{Size};
     
     # date the message was succesfully delivered or forwarded
     my $date = $$delivery{Date};
     
     #-----------------------------------------
     #    Id and Instance are more advanced features
     #-----------------------------------------
     
     # 'id' in syslog, useful for cross-referencing
     my $id = $$delivery{Id};
     
     # The first delivery of any message has Instance of 1; the next
     # deliveries will have Instance > 1, specifically a number equal to
     # the number of people who the message has previously been delivered
     # to, plus 1.  This is useful for detecing mass-mailings.
     
     # Suppose I send a message to 5 people, but only three copies are
     # delivered right away, the other two are deferred.  The first
     # Delivery has instance 1; the next delivery of the same message
     # will have instance 4.
     my $instance = $$delivery{Instance};
     my @aReceiverList = @{$$delivery{ReceiverList}};
     print "This message has so far been delivered to ",
         $instance + $@aReceiverList - 1, "people so far\n";

METHODS
=======

     # Manually create a new Delivery object.
     my $delivery = new SyslogScan::Delivery (Date => time(),
     					 Size => 100,
     					 From => 'foo@bar.com',
     					 ReceiverList =>
     					   [him@baz.edu, her@baz.edu],
     					 Instance => 1,
     					 Id => 'manual' . $id++);
     
     # print out contents, either in summary or in verbose mode
     print $delivery -> summary();
     print $delivery -> dump();
     
     # save/restore delivery to/from file
     open(OUT,">save.txt");
     $delivery -> persist(\*OUT);
     close(OUT);
     undef($delivery);
     
     open(IN,"save.txt");
     $delivery = SyslogScan::Delivery -> restore(\*IN);
     # $delivery is restored to its original state

SUPPORT
=======

E-mail bugs to rolf@usa.healthnet.org.

AUTHOR and COPYRIGHT
====================

This code is Copyright (C) SatelLife, Inc. 1996.  All rights reserved.
This code is free software; you can redistribute it and/or modify it under
the same terms as Perl itself.

IN NO EVENT SHALL THE AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
THIS SOFTWARE AND ITS DOCUMENTATION (INCLUDING, BUT NOT LIMITED TO, LOST
PROFITS) EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.

SEE ALSO
========

*Note SyslogScan/DeliveryIterator: SyslogScan/DeliveryIterator,, *Note
SyslogScan/Summary: SyslogScan/Summary,


File: pm.info,  Node: SyslogScan/DeliveryIterator,  Next: SyslogScan/SendmailLine,  Prev: SyslogScan/Delivery,  Up: Module List

scans a syslog file for "deliveries", successful transfers of mail to mailboxes or to other machines.
*****************************************************************************************************

NAME
====

SyslogScan::DeliveryIterator - scans a syslog file for "deliveries",
successful transfers of mail to mailboxes or to other machines.

SYNOPSIS
========

     use SyslogScan::Delivery;
     use SyslogScan::DeliveryIterator;
     
     my $iter = new SyslogScan::DeliveryIterator(syslogList =>
     						["/var/log/syslog"]);
     
     my $delivery;
     while ($delivery = $iter -> next())
     {
         print $delivery -> summary();
     }

DESCRIPTION
===========

A DeliveryIterator goes through your sendmail logging file (which may be
/var/log/syslog, /var/adm/messages, or something completely different)
looking for successful deliveries of mail to local user-accounts or
successful transfers of mail to remote machines.

Here is an excerpt from a sample syslog:

Jun 13 01:50:16 satellife sendmail[29556]: DAA29556:
from=<shookway@fs1.ho.man.ac.uk>, size=954, class=0, pri=30954, nrcpts=1,
msgid=<5B013544E0D@fs1.ho.man.ac.uk>, proto=ESMTP,
relay=curlew.cs.man.ac.uk [130.88.13.7]

Jun 13 01:50:17 satellife sendmail[29558]: DAA29556:
to=<shoko@time.healthnet.org>, delay=00:00:05, mailer=fidogate,
stat=Deferred (Remote host is busy)

...

Jun 13 14:55:50 satellife sendmail[29558]: DAA29556:
to=<shoko@time.healthnet.org>, delay=13:00:05, mailer=fidogate, stat=Sent

The delivery is not registered until 14:55:50.  In order to figure out the
size and sender, the iterator needs to have gone over the 'from' entry
associated with message DAA29566, otherwise it will return a delivery with
'Sender' and 'Size' set to an undefined value (unless you specified
defaults when constructing your DeliveryIterator.)

METHOD 'NEW'
------------

'new' creates a new iterator.

     my $iter =
         new SyslogScan::DeliveryIterator(startDate => "06.01.96 18:00:00",
     					 endDate => "06.02.96 06:00:00",
     					 syslogList =>
     					 [/var/log/syslog.090696,
     					  /var/log/syslog.090796],
     					 unknownSender => 'antiquity',
     					 unknownSize => 0,
     					 defaultYear => 1996);

All of the above parameters are optional.

*startDate* and *endDate* define a span of time; we ignore deliveries that
fall before *startDate* or after *endDate*.  This allows you to generate
statistical reports about mail delivered over a given span of time.

*syslogList* is a list of files to search through for deliveries.  The
alternative to specifying syslogList is to supply a file-handle to a
syslog file on each call to the next() method.

*unknownSender* and *unknownSize* are what to specify as the sender and
the size if we cannot determine from the logs who sent the message and how
large the message is.

*defaultYear* is the year in which the deliveries are assumed to have
taken place (this is not specified in the syslog file.)  Default is to
guess the year that makes the delivery take place close to now.  (For
example, if 'now' is February 3rd 1996, then by default a delivery made on
December 14th is assumed to be in 1995, and a delivery made on February
4th is assumed to be in 1996.

METHOD 'NEXT'
-------------

Once an iterator is defined, the next() method will search for the next
delivery, skipping any deliveries which don't match the time constraints
of *startDate* and *endDate*.  There are two ways to call next():

     # poll syslogList members
     $delivery = $iter -> next;

     # poll filehandle
     open(LOG,"/var/log/syslog");
     $delivery = $iter -> next(\*LOG);

OTHER OPERATIONS
----------------

The 'appendSyslog' method can add a syslog filename to the list of syslog
filenames which were specified at construction time as 'syslogList'.

Setting the global variable *$::gbQuiet* to 1 will suppress some of the
error messages to STDERR.

BUGS
====

If two messages have the same message ID through a bad coincidence, a
message is produced with sender of 'duplicate' and size of '0' rather than
using the unknownSender and unknownSize parameters.

Sender and receiver address are downcased automatically.  It would
probably be better if this module downcased only the host-name part of the
address and not the user-name.

Some mailings have a 'ctladdr' field; DeliveryIterator should probably try
to parse this as a backup clue for figuring out the sender.

AUTHOR and COPYRIGHT
====================

The author (Rolf Harold Nelson) can currently be e-mailed as
rolf@usa.healthnet.org.

This code is Copyright (C) SatelLife, Inc. 1996.  All rights reserved.
This code is free software; you can redistribute it and/or modify it under
the same terms as Perl itself.

In no event shall SatelLife be liable to any party for direct, indirect,
special, incidental, or consequential damages arising out of the use of
this software and its documentation (including, but not limited to, lost
profits) even if the authors have been advised of the possibility of such
damage.

SEE ALSO
========

*Note SyslogScan/Delivery: SyslogScan/Delivery,, *Note SyslogScan/Summary:
SyslogScan/Summary,


File: pm.info,  Node: SyslogScan/SendmailLine,  Next: SyslogScan/SendmailLineFrom,  Prev: SyslogScan/DeliveryIterator,  Up: Module List

Enhances basic SyslogEntry parsing by understanding sendmail to/from message syntax.
************************************************************************************

NAME
====

SyslogScan::SendmailLine - Enhances basic SyslogEntry parsing by
understanding sendmail to/from message syntax.

DESCRIPTION
===========

Suppose I run a 'new SyslogEntry' command and read in the following line:

Jun 13 01:32:26 satellife sendmail[23498]: WAA18677:
to=bar@foo.org,baz@foo.org, delay=03:50:20, mailer=smtp,
relay=relay.ulthar.com [128.206.5.3], stat=Sent (May, have (embedded,
commas))

If I have not loaded in SendmailLine, then 'new SyslogEntry' will return
an 'UnsupportedEntry' object looking like this:

     month => Jun,
     day => 13,
     time => 01:32:26,
     machine => satellife,
     executable => sendmail,
     tag => 23498,
     content => WAA18677: to=bar@foo.org,baz@foo.org, delay=03:50:20, ...

On the other hand, if I have a 'use SyslogScan::SendmailLine' command
before my call to 'new SyslogEntry', then I will a 'SendmailLine' object
with all of the above parameters, plus the following additional parameters:

     messageID => WAA18677
     toList => ( bar@foo.org, baz@foo.org )
     attrHash => ( to => "bar@foo.org,baz@foo.org",
     	     delay => "03:50:20",
     	     mailer => "smtp",
     	     relay => "relay.ulthar.com [128.206.5.3]",
     	     stat => "Sent (May, have (embedded, commas))"
     	     )

Also well-supported is the 'From' line:

Jun 13 01:34:54 satellife sendmail[26035]: BAA26035: from=<bar!baz!foo>,
size=7000, class=0, pri=37000, nrcpts=1,
msgid=<199606130634.BAA26035@satellife.healthnet.org>, proto=SMTP,
relay=uth.bar.com [155.247.14.2]

will produce a SendmailLine object with the additional attributes of

     messageID => BAA26035
     attrHash => ( from => "<bar!baz!foo>",
     	     size => "7000",
     	     class => "0",
     	     pri => "37000"
     	     nrcpts => "1",
     	     msgid => "<199606130634.BAA26035@satellife.healthnet.org>",
     	     proto => "SMTP",
     	     relay => "uth.bar.com [155.247.14.2]"
     	     )

Other types of lines are legal, but are not currently very thorougly
parsed, and therefore return somewhat minimal SendmailLine objects.

Jun 13 13:05:35 satellife sendmail[19620]: NAA19606: NAA19620: return to
sender: unknown mailer error 2

will return a SendmailLine object with the usual SyslogEntry attributes,
plus the single additional attribute of

messageID => NAA19606

while lines like the following produce SendmailLine objects with no
additional SendmailLine-specific attributes:

Jun 13 03:00:05 satellife sendmail[26611]: alias database
/var/yp/nis.healthnet.org/mail.aliases rebuilt by root

Note this is a subclass for SyslogScan::SyslogEntry which handles certain
types of logfile lines.  See the documentation for SyslogEntry for further
details of how SyslogEntry subclassing works.

Also, see the SyslogScan::SendmailLineFrom and SyslogScan::SendmailLineTo
modules for examples of returned SendmailLine objects.

AUTHOR and COPYRIGHT
====================

The author (Rolf Harold Nelson) can currently be e-mailed as
rolf@usa.healthnet.org.

This code is Copyright (C) SatelLife, Inc. 1996.  All rights reserved.
This code is free software; you can redistribute it and/or modify it under
the same terms as Perl itself.

In no event shall SatelLife be liable to any party for direct, indirect,
special, incidental, or consequential damages arising out of the use of
this software and its documentation (including, but not limited to, lost
profits) even if the authors have been advised of the possibility of such
damage.

SEE ALSO
========

*Note SyslogScan/SyslogEntry: SyslogScan/SyslogEntry,, *Note
SyslogScan/SendmailLineFrom: SyslogScan/SendmailLineFrom,, *Note
SyslogScan/SendmailLineTo: SyslogScan/SendmailLineTo,


File: pm.info,  Node: SyslogScan/SendmailLineFrom,  Next: SyslogScan/SendmailLineTo,  Prev: SyslogScan/SendmailLine,  Up: Module List

encapsulates a 'From:' line in a syslog file
********************************************

NAME
====

SyslogScan::SendmailLineFrom - encapsulates a 'From:' line in a syslog file

DESCRIPTION
===========

Here is a sample SendmailLineFrom object.

If 'new SyslogScan::SendmailLineEntry' reads in a line like

Jun 13 02:34:54 satellife sendmail[26035]: BAA26035:
from=<HELP-NET@BAR.TEMPLE.EDU>, size=7000, class=0, pri=37000, nrcpts=1,
msgid=<199606130634.BAA26035@satellife.healthnet.org>, proto=SMTP,
relay=vm.temple.edu [155.247.14.2]

then it will return a SyslogScan::SendmailLineFrom object like this:

     # generic SyslogScan::SyslogEntry stuff
     day => 13,
     executable => 'sendmail',
     machine => 'satellife',
     month => 'Jun',
     tag => 26035,
     time => '02:34:54',
     content => 'BAA26035: from=<HELP-NET@BAR.TEMPLE.EDU>, size=7000, class=0, pri=37000, nrcpts=1, msgid=<199606130634.BAA26035@satellife.healthnet.org>, proto=SMTP, relay=vm.temple.edu [155.247.14.2]',

     # sendMailLineFrom-specific stuff
     messageID => 'BAA26035',
     attrHash => {
     	 'class' => 0,
              'from' => 'help-net@bar.temple.edu',
              'msgid' => '<199606130634.BAA26035@satellife.healthnet.org>',
              'nrcpts' => 1,
              'pri' => 37000,
              'proto' => 'SMTP',
              'relay' => 'vm.temple.edu [155.247.14.2]',
              'size' => 7000
     	 }

AUTHOR and COPYRIGHT
====================

The author (Rolf Harold Nelson) can currently be e-mailed as
rolf@usa.healthnet.org.

This code is Copyright (C) SatelLife, Inc. 1996.  All rights reserved.
This code is free software; you can redistribute it and/or modify it under
the same terms as Perl itself.

In no event shall SatelLife be liable to any party for direct, indirect,
special, incidental, or consequential damages arising out of the use of
this software and its documentation (including, but not limited to, lost
profits) even if the authors have been advised of the possibility of such
damage.

SEE ALSO
========

*Note SyslogScan/SendmailLine: SyslogScan/SendmailLine,


File: pm.info,  Node: SyslogScan/SendmailLineTo,  Next: SyslogScan/SendmailUtil,  Prev: SyslogScan/SendmailLineFrom,  Up: Module List

encapsulates a 'To:' line in a syslog file
******************************************

NAME
====

SyslogScan::SendmailLineTo - encapsulates a 'To:' line in a syslog file

DESCRIPTION
===========

Here is a sample SendmailLineTo object.

If 'new SyslogScan::SendmailLineEntry' reads in a line like

Jun 13 01:50:48 satellife sendmail[23498]: WAA18677:
to=mbe527@time.nums.nwu.edu,jsm341@anima.nums.nwu.edu, delay=03:52:42,
mailer=smtp, relay=anima.nums.nwu.edu. [165.124.50.10], stat=Sent
(AA097917369 Message accepted for delivery)

then it will return a SyslogScan::SendmailLineTo object like this:

     # generic SyslogScan::SyslogEntry stuff
     day => 13,
     executable => 'sendmail',
     machine => 'satellife',
     messageID => 'WAA18677',
     month => 'Jun',
     tag => 23498,
     content => 'WAA18677: to=mbe527@time.nums.nwu.edu,jsm341@anima.nums.nwu.edu, delay=03:52:42, mailer=smtp, relay=anima.nums.nwu.edu. [165.124.50.10], stat=Sent (AA097917369 Message accepted for delivery)',

     # sendMailLineTo-specific stuff
     messageID => 'WAA18677'
     toList => (mbe527@time.nums.nwu.edu, jsm341@anima.nums.nwu.edu)
     attrHash => (
              'delay' => '03:52:42',
              'mailer' => 'smtp',
              'relay' => 'anima.nums.nwu.edu. [165.124.50.10]',
              'stat' => 'Sent (AA097917369 Message accepted for delivery)',
              'to' => 'mbe527@time.nums.nwu.edu,jsm341@anima.nums.nwu.edu'
     	 )

AUTHOR and COPYRIGHT
====================

The author (Rolf Harold Nelson) can currently be e-mailed as
rolf@usa.healthnet.org.

This code is Copyright (C) SatelLife, Inc. 1996.  All rights reserved.
This code is free software; you can redistribute it and/or modify it under
the same terms as Perl itself.

In no event shall SatelLife be liable to any party for direct, indirect,
special, incidental, or consequential damages arising out of the use of
this software and its documentation (including, but not limited to, lost
profits) even if the authors have been advised of the possibility of such
damage.

SEE ALSO
========

*Note SyslogScan/SendmailLineTo: SyslogScan/SendmailLineTo,


File: pm.info,  Node: SyslogScan/SendmailUtil,  Next: SyslogScan/Summary,  Prev: SyslogScan/SendmailLineTo,  Up: Module List

utilities for sendmail packages.
********************************

NAME
====

SendmailUtil.pm - utilities for sendmail packages.

SYNOPSIS
========

     use SyslogScan::SendmailUtil;

     open(FH,"/var/log/syslog");
     my $transfer;
     while ($transfer = SyslogScan::SendmailUtil::getNextMailTranfer(\*FH))
     {
        # process the tranfer
     }

DESCRIPTION
===========

getNextMailTransfer queries a filehandle pointing to a syslog for the next
line which is a sendmail 'To:', 'From:', and 'Clone:' lines, and returns a
SyslogScan::SendmailLineFrom, SyslogScan::SendmailLineTo, or
SyslogScan::SendmailLineClone object.

canonAddress() routine
======================

The canonAddress() routine modifies the address of the Sendmail routines
to be all-lowercase, remove enclosing brackets, and append '@localhost' to
local addresses.  Modifying this routine will change how SyslogScan
canonicalizes.

AUTHOR and COPYRIGHT
====================

The author (Rolf Harold Nelson) can currently be e-mailed as
rolf@usa.healthnet.org.

This code is Copyright (C) SatelLife, Inc. 1996.  All rights reserved.
This code is free software; you can redistribute it and/or modify it under
the same terms as Perl itself.

In no event shall SatelLife be liable to any party for direct, indirect,
special, incidental, or consequential damages arising out of the use of
this software and its documentation (including, but not limited to, lost
profits) even if the authors have been advised of the possibility of such
damage.

SEE ALSO
========

*Note SyslogScan/SendmailLineFrom: SyslogScan/SendmailLineFrom,, *Note
SyslogScan/SendmailLineTo: SyslogScan/SendmailLineTo,, *Note
SyslogScan/SyslogEntry: SyslogScan/SyslogEntry,


File: pm.info,  Node: SyslogScan/Summary,  Next: SyslogScan/SyslogEntry,  Prev: SyslogScan/SendmailUtil,  Up: Module List

encapsulates a tally of how many bytes people have sent and received through sendmail
*************************************************************************************

NAME
====

SyslogScan::Summary - encapsulates a tally of how many bytes people have
sent and received through sendmail

SYNOPSIS
========

     Use SyslogScan::Summary;
     Use SyslogScan::DeliveryIterator;

     my $iter = new SyslogScan::DeliveryIterator(syslogList =>
     						[/var/log/syslog]);
     my $summary;
     if (defined $DOING_IT_THE_HARD_WAY_FOR_NO_PARTICULAR_REASON)
     {
     	# feed a series of SyslogScan::Delivery objects
     	$summary = new SyslogScan::Summary();
     	my $delivery;
     	while ($delivery = $iter -> next())
     	{
     	    $summary -> registerDelivery($delivery);

     # You would instead use:
     # $summary -> registerDelivery($delivery,'foo\.com\.$')
     # if you only cared to get statistics relating to how
     # much mail users at foo.com sent or received.
     	}
         }
         else
         {
     	# slurps up all deliveries in the iterator,
     	# producing the same effect as the block above
     	$summary = new SyslogScan::Summary($iter);
         }

     print $summary -> dump();

     use SyslogScan::Usage;
     my $usage = $$summary{'john_doe@foo.com'};
     if (defined $usage)
     {
     	print "Here is the usage of John Doe at foo.com:\n";
     	print $usage -> dump();
     }
     else
     {
         print "John Doe has neither sent nor received messages lately.\n";
     }

DESCRIPTION
===========

A SyslogScan::Summary object will 'register' a series of
SyslogScan::Delivery objects.  All registered deliveries are grouped by
sender and receiver e-mail addresses, and then added up.  Three sums are
kept: Total Bytes Recieved, Total Bytes Sent, and Total Bytes Broadcast.

Methods
-------

static new() method
     new takes as arguments a (possibly null) list of
     SyslogScan::DeliveryIterator objects, from which it extracts and
     registers all queued deliveries.

registerDelivery() method
     *registerDelivery* takes as its first argument a SyslogScan::Delivery
     object followed by up to two optional patterns.  If the first pattern
     is specified, only those e-mail addresses which match the pattern are
     tallied.  This enables you to create an accounting summary for only
     those users at your site.

     If the second pattern is also specified, then deliveries will only be
     registered to the person matched by the first pattern if the second
     pattern matches the address at 'the other end of the pipe'.

     Pattern-matches are case-insensitive.  Remember the '(?!regexp)'
     operation if you want only addresses which do _not_ match the pattern
     to get passed through the filter.  For example, if mail to or from
     'support' is exempt from billing charges, note that the pattern-match

     /^(?!support)/

     does _not_ match 'support@foo.com' but _does_ match
     'random_guy@foo.com'.

registerAllInIterators() method
     Takes as parameters two patterns and a list of iterators, then feeds
     deliveries in the iterators and the patterns to registerDelivery().

     For example:

          $sum -> registerAllInIterators('foo\.com$','^(?!.*bar\.com$)',@iterList)

     will bill users at foo.com for all mail extracted from @iterList which
     was sent from foo.com to somewhere besides bar.com, or sent to foo.com
     from somewhere besides bar.com.

dump() method
     dump returns a string containing address lines alternating with usage
     reports.  Usage reports are in the form:

          B#,Bb        S#,Sb        R#,Rb

     Where:

     B# is the number of messages broadcast B# is the total number of
     bytes broadcast

     S# is the number of messages sent S# is the total number of bytes sent

     R# is the number of messages received R# is the total number of bytes
     received

persist() method
     *persist* takes as its single argument an output file-handle, and
     then persists the state of the summary to the file.

static restore() method
     restore takes as its single argument an input file-handle which
     stores the results of a previous persist() command, and then returns a
     copy of the object in the state in which it was originally persisted.

addSummary() method
     *addSummary* takes as its single argument a second
     SyslogScan::Summary object, and then adds this second summary to the
     $self object.

Example of use
--------------

Suppose I have a function getTodaySummary() which gets a Summary of the
last 24 hours of sendmail logging.

     my $summary = getTodaySummary();
     open(SUMMARY1,">summary1.sav");
     $summary -> persist(\*SUMMARY1);
     close(SUMMARY1);
     exit 0;

     # wait 24 hours

     my $summary = getTodaySummary();
     open(SUMMARY2,">summary2.sav");
     $summary -> persist(\*SUMMARY2);
     close(SUMMARY2);
     exit 0;

     # some time later, you decide you want a summary of the total
     # for both days.  So, you write this program:

     open(INSUM1,"summary1.sav");
     my $sum = SyslogScan::Summary -> restore(\*INSUM1);

     open(INSUM2,"summary2.sav");
     my $sum2 = SyslogScan::Summary -> restore(\*INSUM2);

     $sum -> addSummary($sum2);
     print "Here is the grand total for both days:\n\n";
     print $sum -> dump();

Internals
---------

A SyslogScan::Summary object is a hash of SyslogScan::Usage objects, where
the key is the e-mail address of the user in question.  SyslogScan::Usage
has its own man page which describes how to extract information without
having to use the dump() method.

AUTHOR and COPYRIGHT
====================

The author (Rolf Harold Nelson) can currently be e-mailed as
rolf@usa.healthnet.org.

This code is Copyright (C) SatelLife, Inc. 1996.  All rights reserved.
This code is free software; you can redistribute it and/or modify it under
the same terms as Perl itself.

In no event shall SatelLife be liable to any party for direct, indirect,
special, incidental, or consequential damages arising out of the use of
this software and its documentation (including, but not limited to, lost
profits) even if the authors have been advised of the possibility of such
damage.

SEE ALSO
========

*Note SyslogScan/Usage: SyslogScan/Usage,, *Note
SyslogScan/DeliveryIterator: SyslogScan/DeliveryIterator,, *Note
SyslogScan/Delivery: SyslogScan/Delivery,, *Note SyslogScan/ByGroup:
SyslogScan/ByGroup,


File: pm.info,  Node: SyslogScan/SyslogEntry,  Next: SyslogScan/Usage,  Prev: SyslogScan/Summary,  Up: Module List

parses generic lines in syslog files.
*************************************

NAME
====

SyslogScan::SyslogEntry - parses generic lines in syslog files.

SYNOPSIS
========

     use SyslogScan::SyslogEntry;

     open(FH,"/var/log/syslog");

     my $entry;

     # reads from filehandle $fh and returns an object
     # of a subclass of SyslogEntry.
     while ($entry = new SyslogScan::SyslogEntry (\*FH))
     {
     	# process $entry
     }

DESCRIPTION
===========

All Syslog object share these data structures: month, day, time, machine,
executable, tag (optional), content.

For example, if a syslog line looks like:

Jun 13 02:32:27 satellife in.identd[25994]: connect from mail.missouri.edu

then the line returned by 'new SyslogEntry' will return an
SyslogEntry-derived object with at least this set of parameters:

month => Jun, day => 13, time => 02:32:27, machine => satellife,
executable => in.identd, tag => 25994, content => connect from
mail.missouri.edu

Since the executable is 'in.identd', SyslogEntry.pm will look for a class
called "SyslogScan::In_identdLine" derived from SyslogEntry, and attempt
to call that class's parseContent method.  If no such In_identdLine class
is in use, then the returned object is of the default
"SyslogScan::UnsupportedEntry" class.

If the In_identdLine class throws a die() exception, SyslogEntry.pm will
catch the die() and return a "SyslogScan::BotchedEntry" object containing
the exception in "$errorString" and the failed handler in "brokenHandler".

"new SyslogEntry" returns the undefined value if at EOF.

BUGS
====

In retrospect, this model of passing control to subclasses based on the
name of the controlling program doesn't work exceptionally elegantly in
perl.  I would probably do it more conventionally if I had it to do over
again.

AUTHOR and COPYRIGHT
====================

The author (Rolf Harold Nelson) can currently be e-mailed as
rolf@usa.healthnet.org.

This code is Copyright (C) SatelLife, Inc. 1996.  All rights reserved.
This code is free software; you can redistribute it and/or modify it under
the same terms as Perl itself.

In no event shall SatelLife be liable to any party for direct, indirect,
special, incidental, or consequential damages arising out of the use of
this software and its documentation (including, but not limited to, lost
profits) even if the authors have been advised of the possibility of such
damage.

SEE ALSO
========

*Note SyslogScan/SendmailLine: SyslogScan/SendmailLine,


File: pm.info,  Node: SyslogScan/Usage,  Next: SyslogScan/WhereIs,  Prev: SyslogScan/SyslogEntry,  Up: Module List

encapsulates the total volumes of mail broadcast, sent, and received through sendmail by a single user or group.
****************************************************************************************************************

NAME
====

SyslogScan::Usage - encapsulates the total volumes of mail broadcast,
sent, and received through sendmail by a single user or group.

SyslogScan::Volume - encapsulates a number of messages along with a total
number of bytes

SYNOPSIS
========

# $summary is a SyslogScan::Summary object

use SyslogScan::Usage; my $usage = $$summary{'john_doe@foo.com'}; $usage
-> dump();

use SyslogScan::Volume; my $broadcastVolume = $usage ->
getBroadcastVolume(); my $sendVolume = $usage -> getSendVolume(); my
$receiveVolume = $usage -> getReceiveVolume();

print "John Doe sent $$sendVolume[0] messages with $$sendVolume[1]
bytes\n";

DESCRIPTION
===========

Broadcast, Send, and Receive
----------------------------

Volume of messages received has the obvious meaning.  Volume of messages
sent and volume of messages broadcast require more explanation.

If I send out a message which has three recipients, then for the purposes
of the SyslogScan modules, I am *broadcasting* the message once, but I am
*sending* it three times.

Usage methods
-------------

new() method
     Creates a new, empty Usage object.

addUsage() method and deepCopy() method
          # $usage1 is 4 messages of 100 bytes Received
          # $usage2 is 1 message of 35 bytes Received

          my $usageTotal = $usage1 -> deepCopy();
          # $usageTotal is 4 messages of 100 bytes Received

          $usageTotal -> addUsage($usage2);
          # $usageTotal is 5 messages of 135 bytes Received

     Note that because we used deepCopy, *$usage1* is still 4 messages of
     100 bytes.

registerBroadcast, registerSend, registerReceive methods
          my $usage = new SyslogScan::Usage();
          $usage -> registerSend(512);
          $usage -> registerSend(34);
          $usage -> registerBroadcast(34);
          # $usage is now 2 messages, 546 bytes Sent,
          # and 1 message, 34 bytes Broadcast

getBroadcastVolume, getSendVolume, getReceiveVolume methods
     Returns deep copy of the applicable SyslogScan::Volume objects.

static deepCopy method
     Returns deep copy of the whole SyslogScan::Usage object.

static dump
     Returns a string containing (Message,Bytes) pairs for Broadcast, Send,
     and Receive volumes.

Volume methods
--------------

new() method
     Creates a new Volume object of 0 messages, 0 bytes.

deepCopy() method
     Creates a new Volume object with the same number of messages and bytes
     as the current Volume object.

addVolume(), addSize() methods
     addVolume() adds the volume of a second Volume object onto the volume
     of the current Volume object.

     addSize() adds on one message of the given size.

          use SyslogScan::Volume;

          my $volume1 = new SyslogScan::Volume();
          $volume1 -> addSize(512);

          my $volume2 = $volume1 -> deepCopy();
          # $volume2 is 1 message, 512 bytes

          $volume2 -> addSize(31);
          # $volume2 is 2 messages, 543 bytes

          $volume2 -> addVolume($volume1);
          # $volume2 is 3 messages, 1055 bytes

          $volume2 -> addVolume($volume2);
          # $volume2 is 6 messages, 2110 bytes

getMessageCount, getByteCount
     Gets the number of messages and the total number of bytes,
     respectively.

dump()
     Returns the string "getMessageCount(),getByteCount()"

Volume internals
----------------

A Volume is simply a two-element array of ($messages, $bytes).

$$volume[0] is the number of messages $$volume[1] is the number of bytes

AUTHOR and COPYRIGHT
====================

The author (Rolf Harold Nelson) can currently be e-mailed as
rolf@usa.healthnet.org.

This code is Copyright (C) SatelLife, Inc. 1996.  All rights reserved.
This code is free software; you can redistribute it and/or modify it under
the same terms as Perl itself.

In no event shall SatelLife be liable to any party for direct, indirect,
special, incidental, or consequential damages arising out of the use of
this software and its documentation (including, but not limited to, lost
profits) even if the authors have been advised of the possibility of such
damage.

SEE ALSO
========

*Note SyslogScan/Summary: SyslogScan/Summary,


File: pm.info,  Node: SyslogScan/WhereIs,  Next: Tcl,  Prev: SyslogScan/Usage,  Up: Module List

return full path of syslog file where mail messages are logged
**************************************************************

NAME
====

SyslogScan::WhereIs::guess - return full path of syslog file where mail
messages are logged

SYNOPSIS
========

     my $syslogPath =
         new SyslogScan::Whereis::guess("/etc/syslog.conf");

DESCRIPTION
===========

Scans a syslog configuration file to try to figure out where "mail.info"
messages are sent.  Default configuration file is "/etc/syslog.conf".

Returns undef if the syslog file cannot be determined.

BUGS
====

It might have been more elegant to return an array of syslog files; this
would, as a bonus, permit multiple syslogs to be returned if mail messages
go to more than one place.

AUTHOR and COPYRIGHT
====================

The author (Rolf Harold Nelson) can currently be e-mailed as
rolf@usa.healthnet.org.

This code is Copyright (C) SatelLife, Inc. 1996.  All rights reserved.
This code is free software; you can redistribute it and/or modify it under
the same terms as Perl itself.

In no event shall SatelLife be liable to any party for direct, indirect,
special, incidental, or consequential damages arising out of the use of
this software and its documentation (including, but not limited to, lost
profits) even if the authors have been advised of the possibility of such
damage.

SEE ALSO
========

*Note SyslogScan/DeliveryIterator: SyslogScan/DeliveryIterator,


File: pm.info,  Node: Tcl,  Next: Tcl/Tk,  Prev: SyslogScan/WhereIs,  Up: Module List

Tcl extension module for Perl
*****************************

NAME
====

Tcl - Tcl extension module for Perl

DESCRIPTION
===========

The Tcl extension module gives access to the Tcl library with
functionality and interface similar to the C functions of Tcl.  In other
words, you can

create Tcl interpreters
     The Tcl interpreters so created are Perl objects whose destructors
     delete the interpreters cleanly when appropriate.

execute Tcl code in an interpreter
     The code can come from strings, files or Perl filehandles.

bind in new Tcl procedures
     The new procedures can be either C code (with addresses presumably
     obtained using *dl_open* and *dl_find_symbol*) or Perl subroutines
     (by name, reference or as anonymous subs). The (optional) deleteProc
     callback in the latter case is another perl subroutine which is called
     when the command is explicitly deleted by name or else when the
     destructor for the interpreter object is explicitly or implicitly
     called.

Manipulate the result field of a Tcl interpreter
Set and get values of variables in a Tcl interpreter
Tie perl variables to variables in a Tcl interpreter
     The variables can be either scalars or hashes.

Methods in class Tcl
--------------------

To create a new Tcl interpreter, use

     $i = new Tcl;

The following methods and routines can then be used on the Perl object
returned (the object argument omitted in each case).

Init ()
     Invoke *Tcl_Init* on the interpeter.

Eval (STRING)
     Evaluate script STRING in the interpreter. If the script returns
     successfully (TCL_OK) then the Perl return value corresponds to
     interp->result otherwise a die exception is raised with the $@
     variable corresponding to interp->result. In each case, *corresponds*
     means that if the method is called in scalar context then the string
     interp->result is returned but if the method is called in list context
     then interp->result is split as a Tcl list and returned as a Perl
     list.

GlobalEval (STRING)
     Evalulate script STRING at global level. Otherwise, the same as
     Eval() above.

EvalFile (FILENAME)
     Evaluate the contents of the file with name FILENAME. Otherwise, the
     same as Eval() above.

EvalFileHandle (FILEHANDLE)
     Evaluate the contents of the Perl filehandle FILEHANDLE. Otherwise,
     the same as Eval() above. Useful when using the filehandle DATA to
     tack on a Tcl script following an __END__ token.

call (PROC, ARG, ...)
     Looks up procedure PROC in the interpreter and invokes it directly
     with arguments (ARG, ...) without passing through the Tcl parser. For
     example, spaces embedded in any ARG will not cause it to be split
     into two Tcl arguments before being passed to PROC.

result ()
     Returns the current interp->result field. List v. scalar context is
     handled as in Eval() above.

CreateCommand (CMDNAME, CMDPROC, CLIENTDATA, DELETEPROC)
     Binds a new procedure named CMDNAME into the interpreter. The
     CLIENTDATA and DELETEPROC arguments are optional. There are two cases:

     (1) CMDPROC is the address of a C function

     (presumably obtained using *dl_open* and *dl_find_symbol*. In this
     case CLIENTDATA and DELETEPROC are taken to be raw data of the
     ClientData and deleteProc field presumably obtained in a similar way.

     (2) CMDPROC is a Perl subroutine

     (either a sub name, a sub reference or an anonymous sub). In this case
     CLIENTDATA can be any perl scalar (e.g. a ref to some other data) and
     DELETEPROC must be a perl sub too. When CMDNAME is invoked in the Tcl
     interpeter, the arguments passed to the Perl sub CMDPROC are

          (CLIENTDATA, INTERP, LIST)

     where INTERP is a Perl object for the Tcl interpreter which called out
     and LIST is a Perl list of the arguments CMDNAME was called with.  As
     usual in Tcl, the first element of the list is CMDNAME itself.  When
     CMDNAME is deleted from the interpreter (either explicitly with
     DeleteCommand or because the destructor for the interpeter object is
     called), it is passed the single argument CLIENTDATA.

DeleteCommand (CMDNAME)
     Deletes command CMDNAME from the interpreter. If the command was
     created with a DELETEPROC (see CreateCommand above), then it is
     invoked at this point. When a Tcl interpreter object is destroyed
     either explicitly or implicitly, an implicit DeleteCommand happens on
     all its currently registered commands.

SetResult (STRING)
     Sets interp->result to STRING.

AppendResult (LIST)
     Appends each element of LIST to interp->result.

AppendElement (STRING)
     Appends STRING to interp->result as an extra Tcl list element.

ResetResult ()
     Resets interp->result.

SplitList (STRING)
     Splits STRING as a Tcl list. Returns a Perl list or the empty list if
     there was an error (i.e. STRING was not a properly formed Tcl list).
     In the latter case, the error message is left in interp->result.

SetVar (VARNAME, VALUE, FLAGS)
     The FLAGS field is optional. Sets Tcl variable VARNAME in the
     interpreter to VALUE. The FLAGS argument is the usual Tcl one and can
     be a bitwise OR of the constants $Tcl::GLOBAL_ONLY,
     $Tcl::LEAVE_ERR_MSG, $Tcl::APPEND_VALUE, $Tcl::LIST_ELEMENT.

SetVar2 (VARNAME1, VARNAME2, VALUE, FLAGS)
     Sets the element VARNAME1(VARNAME2) of a Tcl array to VALUE. The
     optional argument FLAGS behaves as in SetVar above.

GetVar (VARNAME, FLAGS)
     Returns the value of Tcl variable VARNAME. The optional argument FLAGS
     behaves as in SetVar above.

GetVar2 (VARNAME1, VARNAME2, FLAGS)
     Returns the value of the element VARNAME1(VARNAME2) of a Tcl array.
     The optional argument FLAGS behaves as in SetVar above.

UnsetVar (VARNAME, FLAGS)
     Unsets Tcl variable VARNAME. The optional argument FLAGS behaves as
     in SetVar above.

UnsetVar2 (VARNAME1, VARNAME2, FLAGS)
     Unsets the element VARNAME1(VARNAME2) of a Tcl array.  The optional
     argument FLAGS behaves as in SetVar above.

Linking Perl and Tcl variables
------------------------------

You can tie a Perl variable (scalar or hash) into class Tcl::Var so that
changes to a Tcl variable automatically "change" the value of the Perl
variable. In fact, as usual with Perl tied variables, its current value is
just fetched from the Tcl variable when needed and setting the Perl
variable triggers the setting of the Tcl variable.

To tie a Perl scalar *$scalar* to the Tcl variable *tclscalar* in
interpreter *$interp* with optional flags *$flags* (see SetVar above), use

     tie $scalar, Tcl::Var, $interp, "tclscalar", $flags;

Omit the *$flags* argument if not wanted.

To tie a Perl hash *%hash* to the Tcl array variable *array* in
interpreter *$interp* with optional flags *$flags* (see SetVar above), use

     tie %hash, Tcl::Var, $interp, "array", $flags;

Omit the *$flags* argument if not wanted. Any alteration to Perl variable
*$hash{"key"}* affects the Tcl variable *array(key)* and *vice versa*.

AUTHOR
------

Malcolm Beattie, mbeattie@sable.ox.ac.uk, 23 Oct 1994.


File: pm.info,  Node: Tcl/Tk,  Next: Term/Cap,  Prev: Tcl,  Up: Module List



Tcl::Tk - Extension module for Perl giving access to Tk via the Tcl
extension

DESCRIPTION
===========

The Tcl::Tk submodule of the Tcl module gives access to the Tk library.
It does this by creating a Tcl interpreter object (using the Tcl extension)
and binding in all of Tk into the interpreter (in the same way that *wish*
or other Tcl/Tk applications do).

Access to the Tcl and Tcl::Tk extensions
----------------------------------------

To get access to the Tcl and Tcl::Tk extensions, put the commands
require Tcl;     use Tcl::Tk;

near the top of your program. The Tcl extension does not alter your
namespace at all (hence the "require"). The Tcl::Tk extension imports the
widget and other Tk commands into your namespace (hence the "use").

Creating a Tcl interpreter for Tk
---------------------------------

To create a Tcl interpreter initialised for Tk, use     $i = new Tcl::Tk
(DISPLAY, NAME, SYNC);

All arguments are optional. This creates a Tcl interpreter object $i,
binds in all the additional Tk/Tcl commands and creates a main toplevel
window. The window is created on display DISPLAY (defaulting to the display
named in the DISPLAY environment variable) with name NAME (defaulting to
the name of the Perl program, i.e. the contents of Perl variable $0).  If
the SYNC argument is present and true then an *XSynchronize()* call is
done ensuring that X events are processed synchronously (and thus slowly).
This is there for completeness and is only very occasionally useful for
debugging errant X clients (usually at a much lower level than Tk users
will want).

Entering the main event loop
----------------------------

The Perl command     MainLoop;

enters the Tk event loop. (Notice that the name differs from the equivalent
command in TkPerl5: names of commands in the Tcl and Tcl::Tk extensions
closely follow the C interface names with leading Tcl_ or Tk_ removed.)

Creating widgets
----------------

If desired, widgets can be created and handled entirely by Tcl/Tk code
evaluated in the Tcl interpreter object $i (created above). However, there
is an additional way of creating widgets in the interpreter directly from
Perl. The names of the widgets (frame, toplevel, label etc.) are exported
as Perl commands by the Tcl::Tk extension. The initial "use Tcl::Tk;"
command imports those commands into your namespace.  The command     $l =
label(".l", -text => "Hello world);

(for example), executes the command     $i->call("label", ".l", "-text",
"Hello world);

and hence gets Tcl to create a new label widget .l in your Tcl/Tk
interpreter.  Since Tcl/Tk then creates a command ".l" in the interpreter
and creating a similarly named sub in Perl isn't a good idea, the Tcl::Tk
extension uses a kludge to give a slightly more convenient way of
manipulating the widget.  Instead of returning the name of the new widget
as a string, the above label command returns a Perl reference to the
widget's name, blessed into an almost empty class. Perl method calls on
the object are translated into commands for the Tcl/Tk interpreter in a
very simplistic fashion. For example, the Perl command
$l->configure(-background => "green");

is translated into the command     $i->call($$l, "configure",
"-background", "green");

for execution in your Tcl/Tk interpreter. Notice that it simply
dereferences the object to find the widget name. There is no automagic
conversion that happens: if you use a Tcl command which wants a widget
pathname and you only have an object returned by *label()* (or *button()*
or *entry()* or whatever) then you must dereference it yourself.

Non-widget Tk commands
----------------------

For convenience, the non-widget Tk commands (such as destroy, focus, wm,
winfo and so on) are also available as Perl commands and translate into
into their Tcl equivalents for execution in your Tk/Tcl interpreter. The
names of the Perl commands are the same as their Tcl equivalents except
for two: Tcl's pack command becomes tkpack in Perl and Tcl's bind command
becomes tkbind in Perl. The arguments you pass to any of these Perl
commands are not touched by the Tcl parser: each Perl argument is passed
as a separate argument to the Tcl command.

AUTHOR
------

Malcolm Beattie, mbeattie@sable.ox.ac.uk


File: pm.info,  Node: Term/Cap,  Next: Term/Complete,  Prev: Tcl/Tk,  Up: Module List

Perl termcap interface
**********************

NAME
====

Term::Cap - Perl termcap interface

SYNOPSIS
========

     require Term::Cap;
     $terminal = Tgetent Term::Cap { TERM => undef, OSPEED => $ospeed };
     $terminal->Trequire(qw/ce ku kd/);
     $terminal->Tgoto('cm', $col, $row, $FH);
     $terminal->Tputs('dl', $count, $FH);
     $terminal->Tpad($string, $count, $FH);

DESCRIPTION
===========

These are low-level functions to extract and use capabilities from a
terminal capability (termcap) database.

The *Tgetent* function extracts the entry of the specified terminal type
*TERM* (defaults to the environment variable *TERM*) from the database.

It will look in the environment for a *TERMCAP* variable.  If found, and
the value does not begin with a slash, and the terminal type name is the
same as the environment string *TERM*, the *TERMCAP* string is used
instead of reading a termcap file.  If it does begin with a slash, the
string is used as a path name of the termcap file to search.  If *TERMCAP*
does not begin with a slash and name is different from *TERM*, *Tgetent*
searches the files `$HOME/.termcap', `/etc/termcap', and
`/usr/share/misc/termcap', in that order, unless the environment variable
*TERMPATH* exists, in which case it specifies a list of file pathnames
(separated by spaces or colons) to be searched *instead*.  Whenever
multiple files are searched and a tc field occurs in the requested entry,
the entry it names must be found in the same file or one of the succeeding
files.  If there is a `:tc=...:' in the *TERMCAP* environment variable
string it will continue the search in the files as above.

*OSPEED* is the terminal output bit rate (often mistakenly called the baud
rate).  *OSPEED* can be specified as either a POSIX termios/SYSV termio
speeds (where 9600 equals 9600) or an old BSD-style speeds (where 13
equals 9600).

*Tgetent* returns a blessed object reference which the user can then use
to send the control strings to the terminal using *Tputs* and *Tgoto*.  It
calls croak on failure.

*Tgoto* decodes a cursor addressing string with the given parameters.

The output strings for *Tputs* are cached for counts of 1 for performance.
*Tgoto* and *Tpad* do not cache.  `$self->{_xx}' is the raw termcap data
and `$self->{xx}' is the cached version.

     print $terminal->Tpad($self->{_xx}, 1);

*Tgoto*, *Tputs*, and *Tpad* return the string and will also output the
string to $FH if specified.

The extracted termcap entry is available in the object as
`$self->{TERMCAP}'.

EXAMPLES
========

     # Get terminal output speed
     require POSIX;
     my $termios = new POSIX::Termios;
     $termios->getattr;
     my $ospeed = $termios->getospeed;

     # Old-style ioctl code to get ospeed:
     #     require 'ioctl.pl';
     #     ioctl(TTY,$TIOCGETP,$sgtty);
     #     ($ispeed,$ospeed) = unpack('cc',$sgtty);

     # allocate and initialize a terminal structure
     $terminal = Tgetent Term::Cap { TERM => undef, OSPEED => $ospeed };

     # require certain capabilities to be available
     $terminal->Trequire(qw/ce ku kd/);

     # Output Routines, if $FH is undefined these just return the string

     # Tgoto does the % expansion stuff with the given args
     $terminal->Tgoto('cm', $col, $row, $FH);

     # Tputs doesn't do any % expansion.
     $terminal->Tputs('dl', $count = 1, $FH);


File: pm.info,  Node: Term/Complete,  Next: Term/ReadKey,  Prev: Term/Cap,  Up: Module List

Perl word completion module
***************************

NAME
====

Term::Complete - Perl word completion module

SYNOPSIS
========

     $input = complete('prompt_string', \@completion_list);
     $input = complete('prompt_string', @completion_list);

DESCRIPTION
===========

This routine provides word completion on the list of words in the array
(or array ref).

The tty driver is put into raw mode using the system command `stty raw
-echo' and restored using `stty -raw echo'.

The following command characters are defined:

<tab> Attempts word completion. Cannot be changed.
^D
     Prints completion list.  Defined by *$Term::Complete::complete*.

^U
     Erases the current input.  Defined by *$Term::Complete::kill*.

<del>, <bs>
     Erases one character.  Defined by *$Term::Complete::erase1* and
     *$Term::Complete::erase2*.

DIAGNOSTICS
===========

Bell sounds when word completion fails.

BUGS
====

The completion charater <tab> cannot be changed.

AUTHOR
======

Wayne Thompson


File: pm.info,  Node: Term/ReadKey,  Next: Term/ReadLine,  Prev: Term/Complete,  Up: Module List

A perl module for simple terminal control
*****************************************

NAME
====

Term::ReadKey - A perl module for simple terminal control

DESCRIPTION
===========

Term::ReadKey is a compiled perl module dedicated to providing simple
control over terminal driver modes (cbreak, raw, cooked, etc.,) support for
non-blocking reads, if the architecture allows, and some generalized handy
functions for working with terminals. One of the main goals is to have the
functions as portable as possible, so you can just plug in "use
Term::ReadKey" on any architecture and have a good likelyhood of it
working.

ReadMode MODE [, Filehandle]
     Takes an integer argument, which can currently be one of the following
     values:

          0    Restore original settings.
          1    Change to cooked mode.
          2	 Change to cooked mode with echo off.
                (Good for passwords)
          3    Change to cbreak mode.
          4    Change to raw mode.
          5    Change to ultra-raw mode.
                (LF to CR/LF translation turned off)
          
          Or, you may use the synonyms:
          
          restore
          normal
          noecho
          cbreak
          raw
          ultra-raw

     These functions are automatically applied to the STDIN handle if no
     other handle is supplied. Modes 0 and 5 have some special properties
     worth mentioning: not only will mode 0 restore original settings, but
     it cause the next ReadMode call to save a new set of default
     settings. Mode 5 is similar to mode 4, except no CR/LF translation is
     performed, and if possible, parity will be disabled (only if not
     being used by the terminal, however.)

     If you are executing another program that may be changing the
     terminal mode, you will either want to say

          ReadMode 1
          system('someprogram');
          ReadMode 1;
          
          which resets the settings after the program has run, or:

          $somemode=1;
          ReadMode 0;
          system('someprogram');
          ReadMode 1;
          
          which records any changes the program may have made, before resetting the
          mode.

ReadKey MODE [, Filehandle]
     Takes an integer argument, which can currently be one of the following
     values:

          0    Perform a normal read using getc
          -1   Perform a non-blocked read
          >0	 Perform a timed read

     (If the filehandle is not supplied, it will default to STDIN.) If
     there is nothing waiting in the buffer during a non-blocked read,
     then undef will be returned. Note that if the OS does not provide any
     known mechanism for non-blocking reads, then a `ReadKey -1' can die
     with a fatal error. This will hopefully not be common.

     If MODE is greater then zero, then ReadKey will use it as a timeout
     value in seconds (fractional seconds are allowed), and won't return
     undef until that time expires. (Note, again, that some OS's may not
     support this timeout behaviour.) If MODE is less then zero, then this
     is treated as a timeout of zero, and thus will return immediately if
     no character is waiting. A MODE of zero, however, will act like a
     normal getc.

ReadLine MODE [, Filehandle]
     Takes an integer argument, which can currently be one of the following
     values:

          0    Perform a normal read using scalar(<FileHandle>)
          -1   Perform a non-blocked read
          >0	 Perform a timed read

     If there is nothing waiting in the buffer during a non-blocked read,
     then undef will be returned. Note that if the OS does not provide any
     known mechanism for non-blocking reads, then a `ReadLine 1' can die
     with a fatal error. This will hopefully not be common. Note that a
     non-blocking test is only performed for the first character in the
     line, not the entire line.  This call will probably *not* do what you
     assume, especially with ReadMode's higher then 1. For example,
     pressing Space and then Backspace would appear to leave you where you
     started, but any timeouts would now be suspended.

GetTerminalSize [Filehandle]
     Returns either an empty array if this operation is unsupported, or a
     four element array containing: the width of the terminal in
     characters, the height of the terminal in character, the width in
     pixels, and the height in pixels.

SetTerminalSize WIDTH,HEIGHT,XPIX,YPIX [, Filehandle]
     Return -1 on failure, 0 otherwise. Note that this terminal size is
     only for *informative* value, and changing the size via this
     mechanism will *not* change the size of the screen. For example,
     XTerm uses a call like this when it resizes the screen. If any of the
     new measurements vary from the old, the OS will probably send a
     SIGWINCH signal to anything reading that tty or pty.

GetSpeeds [, Filehandle]
     Returns either an empty array if the operation is unsupported, or a
     two value array containing the terminal in and out speeds, in
     *decimal*. E.g, an in speed of 9600 baud and an out speed of 4800
     baud would be returned as (9600,4800). Note that currently the in and
     out speeds will always be identical in some OS's.

GetControlChars [, Filehandle]
     Returns an array containing key/value pairs suitable for a hash. The
     pairs consist of a key, the name of the control character/signal, and
     the value of that character, as a single character.

     Each key will be an entry from the following list:

          DISCARD
          DSUSPEND
          EOF
          EOL
          EOL2
          ERASE
          ERASEWORD
          INTERRUPT
          KILL
          MIN
          QUIT
          QUOTENEXT
          REPRINT
          START
          STATUS
          STOP
          SUSPEND
          SWITCH
          TIME

     Thus, the following will always return the current interrupt
     character, regardless of platform.

          %keys = GetControlChars;
          $int = $keys{INTERRUPT};

SetControlChars [, Filehandle]
     Takes an array containing key/value pairs, as a hash will produce.
     The pairs should consist of a key that is the name of a legal control
     character/signal, and the value should be either a single character,
     or a number in the range 0-255. SetControlChars will die with a
     runtime error if an invalid character name is passed or there is an
     error changing the settings. The list of valid names is easily
     available via

          %cchars = GetControlChars();
          @cnames = keys %cchars;


File: pm.info,  Node: Term/ReadLine,  Next: Test/Harness,  Prev: Term/ReadKey,  Up: Module List

Perl interface to various `readline' packages. If no real package is found, substitutes stubs instead of basic functions.
*************************************************************************************************************************

NAME
====

Term::ReadLine - Perl interface to various `readline' packages. If no real
package is found, substitutes stubs instead of basic functions.

SYNOPSIS
========

     use Term::ReadLine;
     $term = new Term::ReadLine 'Simple Perl calc';
     $prompt = "Enter your arithmetic expression: ";
     $OUT = $term->OUT || STDOUT;
     while ( defined ($_ = $term->readline($prompt)) ) {
       $res = eval($_), "\n";
       warn $@ if $@;
       print $OUT $res, "\n" unless $@;
       $term->addhistory($_) if /\S/;
     }

DESCRIPTION
===========

This package is just a front end to some other packages. At the moment
this description is written, the only such package is Term-ReadLine,
available on CPAN near you. The real target of this stub package is to set
up a common interface to whatever Readline emerges with time.

Minimal set of supported functions
==================================

All the supported functions should be called as methods, i.e., either as

     $term = new Term::ReadLine 'name';

or as

     $term->addhistory('row');

where $term is a return value of Term::ReadLine->Init.

ReadLine
     returns the actual package that executes the commands. Among possible
     values are `Term::ReadLine::Gnu', `Term::ReadLine::Perl',
     `Term::ReadLine::Stub Exporter'.

new
     returns the handle for subsequent calls to following functions.
     Argument is the name of the application. Optionally can be followed
     by two arguments for IN and `OUT' filehandles. These arguments should
     be globs.

`readline'
     gets an input line, *possibly* with actual `readline' support.
     Trailing newline is removed. Returns undef on `EOF'.

`addhistory'
     adds the line to the history of input, from where it can be used if
     the actual `readline' is present.

IN, $`OUT'
     return the filehandles for input and output or undef if `readline'
     input and output cannot be used for Perl.

`MinLine'
     If argument is specified, it is an advice on minimal size of line to
     be included into history.  undef means do not include anything into
     history. Returns the old value.

`findConsole'
     returns an array with two strings that give most appropriate names for
     files for input and output using conventions `"<$in"', `">out"'.

Features
     Returns a reference to a hash with keys being features present in
     current implementation. Several optional features are used in the
     minimal interface: `appname' should be present if the first argument
     to new is recognized, and `minline' should be present if `MinLine'
     method is not dummy.  `autohistory' should be present if lines are
     put into history automatically (maybe subject to `MinLine'), and
     `addhistory' if `addhistory' method is not dummy.

Actually `Term::ReadLine' can use some other package, that will support
reacher set of commands.

EXPORTS
=======

None


File: pm.info,  Node: Test/Harness,  Next: Text/Abbrev,  Prev: Term/ReadLine,  Up: Module List

run perl standard test scripts with statistics
**********************************************

NAME
====

Test::Harness - run perl standard test scripts with statistics

SYNOPSIS
========

use Test::Harness;

runtests(@tests);

DESCRIPTION
===========

Perl test scripts print to standard output `"ok N"' for each single test,
where `N' is an increasing sequence of integers. The first line output by
a standard test script is `"1..M"' with `M' being the number of tests that
should be run within the test script. Test::Harness::runtests(@tests) runs
all the testscripts named as arguments and checks standard output for the
expected `"ok N"' strings.

After all tests have been performed, runtests() prints some performance
statistics that are computed by the Benchmark module.

The test script output
----------------------

Any output from the testscript to standard error is ignored and bypassed,
thus will be seen by the user. Lines written to standard output containing
`/^(not\s+)?ok\b/' are interpreted as feedback for runtests().  All other
lines are discarded.

It is tolerated if the test numbers after ok are omitted. In this case
Test::Harness maintains temporarily its own counter until the script
supplies test numbers again. So the following test script

     print <<END;
     1..6
     not ok
     ok
     not ok
     ok
     ok
     END

will generate

     FAILED tests 1, 3, 6
     Failed 3/6 tests, 50.00% okay

The global variable $Test::Harness::verbose is exportable and can be used
to let runtests() display the standard output of the script without
altering the behavior otherwise.

EXPORT
======

`&runtests' is exported by Test::Harness per default.

DIAGNOSTICS
===========

`All tests successful.\nFiles=%d,  Tests=%d, %s'
     If all tests are successful some statistics about the performance are
     printed.

`FAILED tests %s\n\tFailed %d/%d tests, %.2f%% okay.'
     For any single script that has failing subtests statistics like the
     above are printed.

`Test returned status %d (wstat %d)'
     Scripts that return a non-zero exit status, both `$? >> 8' and $? are
     printed in a message similar to the above.

`Failed 1 test, %.2f%% okay. %s'
`Failed %d/%d tests, %.2f%% okay. %s'
     If not all tests were successful, the script dies with one of the
     above messages.

SEE ALSO
========

See *Note Benchmark: Benchmark, for the underlying timing routines.

AUTHORS
=======

Either Tim Bunce or Andreas Koenig, we don't know. What we know for sure
is, that it was inspired by Larry Wall's TEST script that came with perl
distributions for ages. Current maintainer is Andreas Koenig.

BUGS
====

Test::Harness uses $^X to determine the perl binary to run the tests with.
Test scripts running via the shebang (`#!') line may not be portable
because $^X is not consistent for shebang scripts across platforms. This
is no problem when Test::Harness is run with an absolute path to the perl
binary or when $^X can be found in the path.


File: pm.info,  Node: Text/Abbrev,  Next: Text/English,  Prev: Test/Harness,  Up: Module List

create an abbreviation table from a list
****************************************

NAME
====

abbrev - create an abbreviation table from a list

SYNOPSIS
========

     use Text::Abbrev;
     abbrev $hashref, LIST

DESCRIPTION
===========

Stores all unambiguous truncations of each element of LIST as keys key in
the associative array referenced to by `$hashref'.  The values are the
original list elements.

EXAMPLE
=======

     $hashref = abbrev qw(list edit send abort gripe);

     %hash = abbrev qw(list edit send abort gripe);

     abbrev $hashref, qw(list edit send abort gripe);

     abbrev(*hash, qw(list edit send abort gripe));


File: pm.info,  Node: Text/English,  Next: Text/German,  Prev: Text/Abbrev,  Up: Module List

Porter's stemming algorithm
***************************

NAME
====

Text::English - Porter's stemming algorithm

SYNOPSIS
========

     use Text::English;
     @stems = Text::English::stem( @words );

DESCRIPTION
===========

This routine applies the Porter Stemming Algorithm to its parameters,
returning the stemmed words.  It is derived from the C program "stemmer.c"
as found in freewais and elsewhere, which contains these notes:

     Purpose:    Implementation of the Porter stemming algorithm documented
                 in: Porter, M.F., "An Algorithm For Suffix Stripping,"
                 Program 14 (3), July 1980, pp. 130-137.
     Provenance: Written by B. Frakes and C. Cox, 1986.

I have re-interpreted areas that use Frakes and Cox's "WordSize" function.
My version may misbehave on short words starting with "y", but I can't
think of any examples.

The step numbers correspond to Frakes and Cox, and are probably in
Porter's article (which I've not seen).  Porter's algorithm still has
rough spots (e.g current/currency, -ings words), which I've not attempted
to cure, although I have added support for the British -ise suffix.

NOTES
=====

This is version 0.1. I would welcome feedback, especially improvements to
the punctuation-stripping step.

AUTHOR
======

Ian Phillipps <ian@unipalm.pipex.com>

COPYRIGHT
=========

Copyright Public IP Exchange Ltd (PIPEX).  Available for use under the
same terms as perl.


File: pm.info,  Node: Text/German,  Next: Text/ParseWords,  Prev: Text/English,  Up: Module List

German grundform reduction
**************************

NAME
====

Text::German - German grundform reduction

SYNOPSYS
========

`use Text::German;'

`$stem = Text::German::reduce($word)'

DESCRIPTION
===========

This is a rather incomplete implementaion of work done by Gudrun
Putze-Meier `<gudrun.pm@t-online.de>'. I have to confess that I never read
her original paper. So all credit belongs to her, all bugs are mine. I
tried to get some insight from an implementation of two students of mine.
They remain anonymous because their work was the wost piece of code I ever
saw. My code behaves mostly as their implementation did except it is about
75 times faster.

AUTHOR
======

Ulrich Pfeifer `<pfeifer@ls6.informatik.uni-dortmund.de>'


File: pm.info,  Node: Text/ParseWords,  Next: Text/Soundex,  Prev: Text/German,  Up: Module List

parse text into an array of tokens
**********************************

NAME
====

Text::ParseWords - parse text into an array of tokens

SYNOPSIS
========

     use Text::ParseWords;
     @words = &quotewords($delim, $keep, @lines);
     @words = &shellwords(@lines);
     @words = &old_shellwords(@lines);

DESCRIPTION
===========

&quotewords() accepts a delimiter (which can be a regular expression) and
a list of lines and then breaks those lines up into a list of words
ignoring delimiters that appear inside quotes.

The $keep argument is a boolean flag.  If true, the quotes are kept with
each word, otherwise quotes are stripped in the splitting process.  $keep
also defines whether unprotected backslashes are retained.

A &shellwords() replacement is included to demonstrate the new package.
This version differs from the original in that it will _NOT_ default to
using $_ if no arguments are given.  I personally find the old behavior to
be a mis-feature.

&quotewords() works by simply jamming all of @lines into a single string
in $_ and then pulling off words a bit at a time until $_ is exhausted.

AUTHORS
=======

Hal Pomeranz (pomeranz@netcom.com), 23 March 1994

Basically an update and generalization of the old shellwords.pl.  Much
code shamelessly stolen from the old version (author unknown).


File: pm.info,  Node: Text/Soundex,  Next: Text/Tabs,  Prev: Text/ParseWords,  Up: Module List

Implementation of the Soundex Algorithm as Described by Knuth
*************************************************************

NAME
====

Text::Soundex - Implementation of the Soundex Algorithm as Described by
Knuth

SYNOPSIS
========

     use Text::Soundex;

     $code = soundex $string;            # get soundex code for a string
     @codes = soundex @list;             # get list of codes for list of strings

     # set value to be returned for strings without soundex code

     $soundex_nocode = 'Z000';

DESCRIPTION
===========

This module implements the soundex algorithm as described by Donald Knuth
in Volume 3 of *The Art of Computer Programming*.  The algorithm is
intended to hash words (in particular surnames) into a small space using a
simple model which approximates the sound of the word when spoken by an
English speaker.  Each word is reduced to a four character string, the
first character being an upper case letter and the remaining three being
digits.

If there is no soundex code representation for a string then the value of
`$soundex_nocode' is returned.  This is initially set to undef, but many
people seem to prefer an *unlikely* value like `Z000' (how unlikely this
is depends on the data set being dealt with.)  Any value can be assigned
to `$soundex_nocode'.

In scalar context `soundex' returns the soundex code of its first
argument, and in array context a list is returned in which each element is
the soundex code for the corresponding argument passed to `soundex' e.g.

     @codes = soundex qw(Mike Stok);

leaves `@codes' containing `('M200', 'S320')'.

EXAMPLES
========

Knuth's examples of various names and the soundex codes they map to are
listed below:

     Euler, Ellery -> E460
     Gauss, Ghosh -> G200
     Hilbert, Heilbronn -> H416
     Knuth, Kant -> K530
     Lloyd, Ladd -> L300
     Lukasiewicz, Lissajous -> L222

so:

     $code = soundex 'Knuth';              # $code contains 'K530'
     @list = soundex qw(Lloyd Gauss);	# @list contains 'L300', 'G200'

LIMITATIONS
===========

As the soundex algorithm was originally used a *long* time ago in the US
it considers only the English alphabet and pronunciation.

As it is mapping a large space (arbitrary length strings) onto a small
space (single letter plus 3 digits) no inference can be made about the
similarity of two strings which end up with the same soundex code.  For
example, both `Hilbert' and `Heilbronn' end up with a soundex code of
`H416'.

AUTHOR
======

This code was implemented by Mike Stok (`stok@cybercom.net') from the
description given by Knuth.  Ian Phillips (`ian@pipex.net') and Rich Pinder
(`rpinder@hsc.usc.edu') supplied ideas and spotted mistakes.


File: pm.info,  Node: Text/Tabs,  Next: Text/Template,  Prev: Text/Soundex,  Up: Module List

expand and unexpand tabs per the unix expand(1) and unexpand(1)
***************************************************************

NAME
====

Text::Tabs - expand and unexpand tabs per the unix expand(1) and
unexpand(1)

SYNOPSIS
========

     use Text::Tabs;

     $tabstop = 4;
     @lines_without_tabs = expand(@lines_with_tabs);
     @lines_with_tabs = unexpand(@lines_without_tabs);

DESCRIPTION
===========

Text::Tabs does about what the unix utilities expand(1) and unexpand(1)
do.  Given a line with tabs in it, expand will replace the tabs with the
appropriate number of spaces.  Given a line with or without tabs in it,
unexpand will add tabs when it can save bytes by doing so.  Invisible
compression with plain ascii!

BUGS
====

expand doesn't handle newlines very quickly - do not feed it an entire
document in one string.  Instead feed it an array of lines.

AUTHOR
======

David Muir Sharnoff <`muir@idiom.com'>


File: pm.info,  Node: Text/Template,  Next: Text/Wrap,  Prev: Text/Tabs,  Up: Module List

Expand template text with embedded Perl
***************************************

NAME
====

Text::Template - Expand template text with embedded Perl

SYNOPSIS
========

     use Text::Template;

     $template = new Text::Template ('type' => FILE, 'source' => 'f.tmpl');
       # or
     $template = new Text::Template ('type' => ARRAY,
     				 'source' => [ ... ] );
       # or
     $template = new Text::Template ('type' => FILEHANDLE,
     					'source' => $fh );

     $recipient = 'King';
     $text = $template->fill_in();
     print $text;

     $T::recipient = 'Josh';
     $text = $template->fill_in('package' => T);
     print $text;

     $text = $template->fill_in('broken' => \&callback);

     use Text::Template fill_this_in;
     $text = fill_this_in( <<EOM, 'package' => T);
     Dear {$recipient},
     Pay me at once.
            Love,
             G.V.
     EOM

     print Text::Template->Version;

OVERVIEW
========

This is a library for printing form letters!  This is a library for
playing Mad Libs!

A `template' is a piece of text that has little Perl programs embedded in
it here and there.  When you `fill in' a template, you evaluate the little
programs and replace them with their values.

This is a good way to generate many kinds of output, such as error
messages and HTML pages.  Here is one way I use it: I am a freelance
computer consultant; I write world-wide web applications.  Usually I work
with an HTML designer who designs the pages for me.

Often these pages change a lot over the life of the project: The client's
legal department takes several tries to get the disclaimer just right; the
client changes the background GIF a few times; the text moves around, and
soforth.  These are all changes that are easy to make.  Anyone proficient
with the editor can go and make them.  But if the page is embedded inside
a Perl program, I don't want the designer to change it because you never
know what they might muck up.  I'd like to put the page in an external
file instead.

The trouble with that is that parts of the page really are generated by
the program; it needs to fill in certani values in some places, maybe
conditionally include some text somewhere else.  The page can't just be a
simple static file that the program reads in and prints out.

A template has blanks, and when you print one out, the blanks are filled
in automatically, so this is no trouble.  And because the blanks are small
and easy to recognize, it's easy to tell the page designer to stay away
from them.

Here's a sample template:

     Dear {$title} {$lastname},

     It has come to our attention that you are delinquent in your
     {$last_paid_month} payment.  Please remit ${$amount} immediately,
     or your patellae may be needlessly endangered.

     Love,

     Mark "Vizopteryx" Dominus

Pretty simple, isn't it?  Items in curly braces `{' `}' get filled in;
everything else stays the same.  Anyone can understand that.  You can
totally believe that the art director isn't going to screw this up while
editing it.

You can put any perl code you want into the braces, so instead of
`{$amount}', you might want to use `{sprintf("%.2f", $amount)}', to print
the amount rounded off to the nearest cent.

This is good for generating form letters, HTML pages, error messages, and
probably a lot of other things.

Detailed documentation follows:

Constructor: new
----------------

     new Text::Template ( attribute => value, ... );

This creates a new template object.  You specify the source of the
template with a set of attribute-value pairs in the arguments.

At present, there are only two attributes.  One is type; the other is
`source'.  type can be `FILEHANDLE', FILE, or `ARRAY'.  If type is FILE,
then the `source' is interpreted as the name of a file that contains the
template to fill out.  If type is `FILEHANDLE', then the `source' is
interpreted as the name of a filehandle, which, when read, will deliver
the template to fill out.  A type of `ARRAY' means that the `source' is a
reference to an array of strings; the template is the concatentation of
these strings.

Neither type nor `source' are optional yet.

Here are some examples of how to call new:

     $template = new Text::Template
     	('type' => 'ARRAY',
     	 'source' => [ "Dear {\$recipient}\n",
     			"Up your {\$nose}.\n",
     			"Love, {\$me}.\n" ]);

     $template = new Text::Template
     	('type' => 'FILE',
     	 'source' => '/home/mjd/src/game/youlose.tmpl');

new returns a template object on success, and undef on failure.  On an
error, it puts an error message in the variable `$Text::Template::ERROR'.

`fill_in'
---------

Fills in a template.  Returns the resulting text.

Like new, `fill_in' accepts a set of attribute-value pairs.  At present,
the only attributes are package and `broken'.

Here's an example: Suppose that `$template' contains a template object
that we created with this template:

     Dear {$name},
     	You owe me ${sprintf("%.2f", $amount)}.
     	Pay or I will break your {$part}.
     			Love,
     			Uncle Dominus.

Here's how you might fill it in:

     $name = 'Donald';
     	$amount = 141.61;
     	$part = 'hyoid bone';

     $text = $template->fill_in();

Here's another example:

     Your Royal Highness,

     Enclosed please find a list of things I have gotten
     for you since 1907:

     { $list = '';
       foreach $item (@things) {
         $list .= " o \u$item\n";
       }
       $list
     }

     Signed,
     Lord High Chamberlain

We want to pass in an array which will be assigned to the array `@things'.
Here's how to do that:

     @the_things = ('ivory', 'apes', 'peacocks', );
     $template->fill_in();

This is not very safe.  The reason this isn't as safe is that if you had
any variables named `$list' or `$item' in scope in your program at the
point you called `fill_in', their values would be clobbered by the act of
filling out the template.

The next section will show how to make this safer.

package
     The value of the package attribute names a package which contains the
     variables that should be used to fill in the template.  If you omit
     the package attribute, `fill_in' uses the package that was active
     when it was called.

     Here's a safer version of the `Lord High Chamberlain' example from the
     previous section:

          @VARS::the_things = ('ivory', 'apes', 'peacocks', );
          $template->fill_in('package' => VARS);

     This call to `fill_in' clobbers `$VARS::list' and `$VARS::item'
     instead of clobbering `$list' and `$item'.  If your program didn't
     use anything in the `VARS' package, you don't have to worry that
     filling out the template is altering on your variables.

`broken'
     If you specify a value for the `broken' attribute, it should be a
     reference to a function that `fill_in' can call if one of the little
     programs fails to evaluate.

     `fill_in' will pass an associative array to the `broken' function.
     The associative array will have at least these two members:

          text => (The full text of the little program that failed)
          error => (The text of the error message (C<$@>) generated by eval)

     If the `broken' function returns a text string, `fill_in' will insert
     it into the template in place of the broken program, just as though
     the broken program had evaluated successfully and yielded that same
     string.  If the `broken' function returns undef, `fill_in' will stop
     filling in the template, and will immediately return undef itself.

     If you don't specify a `broken' function, you get a default one that
     inserts something like this:

          Warning

          This part of the template:
          	1/0

          Returned the following errors:
          	Illegal division by zero at (eval 7) line 2.

`fill_this_in'
--------------

Maybe it's not worth your trouble to put the template into a file; maybe
it's a small file, and you want to leave it inline in the code.  Maybe you
don't want to have to worry about managing template objects.  In that
case, use `fill_this_in'.  You give it the entire template as a string
argument, follow with variable substitutions just like in `fill_in', and
it gives you back the filled-in text.

An example:

     $Q::name = 'Donald';
     $Q::amount = 141.61;
     $Q::part = 'hyoid bone';

     $text = fill_this_in Text::Template ( <<EOM, 'package' => Q);
     Dear {\$name},
     You owe me {sprintf('%.2f', \$amount)}.
     Pay or I will break your {\$part}.
     	Love,
     	Grand Vizopteryx of Irkutsk.
     EOM

Version   Version Text::Template ();
====================================

Returns the current version of the `Text::Template' package.  The current
version is `'Text::Template 0.1 beta $Revision: 1.4 $ $Date: 1996/01/25
19:31:12 $''.

Template Format
===============

Here's the deal with templates: Anything in braces is a little program,
which is evaluated, and replaced with its perl value.  A backslashed
character has no special meaning, so to include a literal `{' in your
template, use `\{', and to include a literal `\', use `\\'.

A little program starts at an open brace and ends at the matching close
brace.  This means that your little programs can include braces and you
don't need to worry about it.  See the example below for an example of
braces inside a little program.

If an expression at the beginning of the template has side effects, the
side effects carry over to the subsequent expressions.  For example:

     {$x = @things; ''} The Lord High Chamberlain has gotten {$x}
     things for me this year.
     { $diff = $x - 17;
       $more = 'more'
       if ($diff == 0) {
         $diff = 'no';
       } elsif ($diff < 0) {
         $more = 'fewer';
       }
     }
     That is {$diff} {$more} than he gave me last year.

Notice that after we set $x in the first little program, its value carries
over to the second little program, and that we can set `$diff' and `$more'
on one place and use their values again later.

All variables are evaluated in the package you specify as an argument to
`fill_in'.  This means that if your templates don't do anything
egregiously stupid, you don't have to worry that evaluation of the little
programs will creep out into the rest of your program and wreck something.
On the other hand, there's really no way to protect against a template
that says

     { $Important::Secret::Security::Enable = 0;
       # Disable security checks in this program
     }

or even

     { system("rm -rf /") }

so *don't* go filling in templates unless you're sure you know what's in
them.  This package may eventually use Perl's Safe extension to fill in
templates in a safe compartment.

AUTHOR
======

Mark-Jason Dominus, Plover Systems

`mjd@pobox.com'

SUPPORT?
========

This software is version 0.1 beta.  It probably has bugs.  It is
inadequately tested.  Suggestions and bug reports are always welcome.

BUGS AND CAVEATS
================

This package is in beta testing and should not be used in critical
applications.

This package should fill in templates in a Safe compartment.

The callback function that `fill_in' calls when a template contains an
error should be eble to return an error message to the rest of the program.

my variables in `fill_in' are still susceptible to being clobbered by
template evaluation.  Perhaps it will be safer to make them local
variables.

Maybe there should be a utility method for emptying out a package?

Maybe there should be a utility function for doing `#include'.  It would
be easy.  (John Cavanaugh, `sdd@hp.com')

Maybe there should be a control item for doing #if.  Perl's `if' is
sufficient, but a little cumbersome to handle the quoting.


File: pm.info,  Node: Text/Wrap,  Next: Tie/Dir,  Prev: Text/Template,  Up: Module List

line wrapping to form simple paragraphs
***************************************

NAME
====

Text::Wrap - line wrapping to form simple paragraphs

SYNOPSIS
========

     use Text::Wrap

     print wrap($initial_tab, $subsequent_tab, @text);

     use Text::Wrap qw(wrap $columns);

     $columns = 132;

DESCRIPTION
===========

Text::Wrap is a very simple paragraph formatter.  It formats a single
paragraph at a time by breaking lines at word boundries.  Indentation is
controlled for the first line ($initial_tab) and all subsquent lines
($subsequent_tab) independently.  $Text::Wrap::columns should be set to
the full width of your output device.

EXAMPLE
=======

     print wrap("\t","","This is a bit of text that forms
     	a normal book-style paragraph");

AUTHOR
======

David Muir Sharnoff <`muir@idiom.com'>


File: pm.info,  Node: Tie/Dir,  Next: Tie/Hash,  Prev: Text/Wrap,  Up: Module List

class definition for reading directories via a tied hash
********************************************************

NAME
====

Tie::Dir - class definition for reading directories via a tied hash

SYNOPSIS
========

     use Tie::Dir qw(DIR_UNLINK);
     
     # Both of these produce identical results
     #(ie %hash is tied)
     tie %hash, Tie::Dir, ".", DIR_UNLINK;
     new Tie::Dir \%hash, ".", DIR_UNLINK;
     
     # This creates a reference to a hash, which is tied.
     $hash = new Tie::Dir ".";
     
     # All these examples assume that %hash is tied (ie one of the
     # first two tie methods was used
     
     # itterate through the directory
     foreach $file ( keys %hash ) {
     	...
     }
     
     # Set the access and modification times (touch :-)
     $hash{SomeFile} = time;
     
     # Obtain stat information of a file
     @stat = @{$hash{SomeFile}};
     
     # Check if entry exists
     if(exists $hash{SomeFile}) {
     	...
     }
     
     # Delete an entry, only if DIR_UNLINK specified
     delete $hash{SomeFile};

DESCRIPTION
===========

This module provides a method of reading directories using a hash.

The keys of the hash are the directory entries and the values are a
reference to an array which holds the result of stat being called on the
entry.

The access and modification times of an entry can be changed by assigning
to an element of the hash. If a single number is assigned then the access
and modification times will both be set to the same value, alternatively
the access and modification times may be set separetly by passing a
reference to an array with 2 entries, the first being the access time and
the second being the modification time.

new [hashref,] dirname [, options]
     This method ties the hash referenced by `hashref' to the directory
     `dirname'.  If `hashref' is omitted then new returns a reference to a
     hash which hash been tied, otherwise it returns the result of tie

     The possible options are:

    DIR_UNLINK
          Delete operations on the hash will cause unlink to be called on
          the corresponding file

AUTHOR
======

Graham Barr <bodg@tiuk.ti.com>, from a quick hack posted by Kenneth
Albanowski <kjahds@kjahds.com>  to the perl5-porters mailing list based on
a neat idea by Ilya Zakharevich.


File: pm.info,  Node: Tie/Hash,  Next: Tie/Scalar,  Prev: Tie/Dir,  Up: Module List

base class definitions for tied hashes
**************************************

NAME
====

Tie::Hash, Tie::StdHash - base class definitions for tied hashes

SYNOPSIS
========

     package NewHash;
     require Tie::Hash;
     
     @ISA = (Tie::Hash);
     
     sub DELETE { ... }		# Provides needed method
     sub CLEAR { ... }		# Overrides inherited method
     
     
     package NewStdHash;
     require Tie::Hash;
     
     @ISA = (Tie::StdHash);
     
     # All methods provided by default, define only those needing overrides
     sub DELETE { ... }
     
     
     package main;
     
     tie %new_hash, 'NewHash';
     tie %new_std_hash, 'NewStdHash';

DESCRIPTION
===========

This module provides some skeletal methods for hash-tying classes. See
*Note Perltie: (perl.info)perltie, for a list of the functions required in
order to tie a hash to a package. The basic *Tie::Hash* package provides a
new method, as well as methods TIEHASH, EXISTS and CLEAR. The
*Tie::StdHash* package provides most methods required for hashes in *Note
Perltie: (perl.info)perltie,. It inherits from *Tie::Hash*, and causes
tied hashes to behave exactly like standard hashes, allowing for selective
overloading of methods. The new method is provided as grandfathering in
the case a class forgets to include a TIEHASH method.

For developers wishing to write their own tied hashes, the required methods
are briefly defined below. See the *Note Perltie: (perl.info)perltie,
section for more detailed descriptive, as well as example code:

TIEHASH classname, LIST
     The method invoked by the command `tie %hash, classname'. Associates
     a new hash instance with the specified class. LIST would represent
     additional arguments (along the lines of *Note AnyDBM_File:
     AnyDBM_File, and compatriots) needed to complete the association.

STORE this, key, value
     Store datum value into *key* for the tied hash *this*.

FETCH this, key
     Retrieve the datum in *key* for the tied hash *this*.

FIRSTKEY this
     Return the (key, value) pair for the first key in the hash.

NEXTKEY this, lastkey
     Return the next (key, value) pair for the hash.

EXISTS this, key
     Verify that *key* exists with the tied hash *this*.

DELETE this, key
     Delete the key *key* from the tied hash *this*.

CLEAR this
     Clear all values from the tied hash *this*.

CAVEATS
=======

The *Note Perltie: (perl.info)perltie, documentation includes a method
called DESTROY as a necessary method for tied hashes. Neither *Tie::Hash*
nor *Tie::StdHash* define a default for this method. This is a standard
for class packages, but may be omitted in favor of a simple default.

MORE INFORMATION
================

The packages relating to various DBM-related implemetations (DB_File,
`NDBM_File', etc.) show examples of general tied hashes, as does the *Note
Config: Config, module. While these do not utilize *Tie::Hash*, they serve
as good working examples.


File: pm.info,  Node: Tie/Scalar,  Next: Tie/SubstrHash,  Prev: Tie/Hash,  Up: Module List

base class definitions for tied scalars
***************************************

NAME
====

Tie::Scalar, Tie::StdScalar - base class definitions for tied scalars

SYNOPSIS
========

     package NewScalar;
     require Tie::Scalar;
     
     @ISA = (Tie::Scalar);
     
     sub FETCH { ... }		# Provide a needed method
     sub TIESCALAR { ... }	# Overrides inherited method
     
     
     package NewStdScalar;
     require Tie::Scalar;
     
     @ISA = (Tie::StdScalar);
     
     # All methods provided by default, so define only what needs be overridden
     sub FETCH { ... }
     
     
     package main;
     
     tie $new_scalar, 'NewScalar';
     tie $new_std_scalar, 'NewStdScalar';

DESCRIPTION
===========

This module provides some skeletal methods for scalar-tying classes. See
*Note Perltie: (perl.info)perltie, for a list of the functions required in
tying a scalar to a package. The basic *Tie::Scalar* package provides a
new method, as well as methods TIESCALAR, FETCH and STORE. The
*Tie::StdScalar* package provides all the methods specified in  *Note
Perltie: (perl.info)perltie,. It inherits from *Tie::Scalar* and causes
scalars tied to it to behave exactly like the built-in scalars, allowing
for selective overloading of methods. The new method is provided as a
means of grandfathering, for classes that forget to provide their own
TIESCALAR method.

For developers wishing to write their own tied-scalar classes, the methods
are summarized below. The *Note Perltie: (perl.info)perltie, section not
only documents these, but has sample code as well:

TIESCALAR classname, LIST
     The method invoked by the command `tie $scalar, classname'.
     Associates a new scalar instance with the specified class. LIST would
     represent additional arguments (along the lines of *Note AnyDBM_File:
     AnyDBM_File, and compatriots) needed to complete the association.

FETCH this
     Retrieve the value of the tied scalar referenced by *this*.

STORE this, value
     Store data value in the tied scalar referenced by *this*.

DESTROY this
     Free the storage associated with the tied scalar referenced by *this*.
     This is rarely needed, as Perl manages its memory quite well. But the
     option exists, should a class wish to perform specific actions upon
     the destruction of an instance.

MORE INFORMATION
================

The *Note Perltie: (perl.info)perltie, section uses a good example of
tying scalars by associating process IDs with priority.


File: pm.info,  Node: Tie/SubstrHash,  Next: Tie/Watch,  Prev: Tie/Scalar,  Up: Module List

Fixed-table-size, fixed-key-length hashing
******************************************

NAME
====

Tie::SubstrHash - Fixed-table-size, fixed-key-length hashing

SYNOPSIS
========

     require Tie::SubstrHash;

     tie %myhash, 'Tie::SubstrHash', $key_len, $value_len, $table_size;

DESCRIPTION
===========

The *Tie::SubstrHash* package provides a hash-table-like interface to an
array of determinate size, with constant key size and record size.

Upon tying a new hash to this package, the developer must specify the size
of the keys that will be used, the size of the value fields that the keys
will index, and the size of the overall table (in terms of key-value
pairs, not size in hard memory). *These values will not change for the
duration of the tied hash*. The newly-allocated hash table may now have
data stored and retrieved. Efforts to store more than `$table_size'
elements will result in a fatal error, as will efforts to store a value
not exactly `$value_len' characters in length, or reference through a key
not exactly `$key_len' characters in length. While these constraints may
seem excessive, the result is a hash table using much less internal memory
than an equivalent freely-allocated hash table.

CAVEATS
=======

Because the current implementation uses the table and key sizes for the
hashing algorithm, there is no means by which to dynamically change the
value of any of the initialization parameters.


File: pm.info,  Node: Tie/Watch,  Next: Time/CTime,  Prev: Tie/SubstrHash,  Up: Module List

place watchpoints on Perl variables.
************************************

NAME
====

     Tie::Watch() - place watchpoints on Perl variables.

SYNOPSIS
========

     use Tie::Watch;

     $watch = Tie::Watch->new(
         -variable => \$frog,
         -debug    => 1,
         -fetch    => [\&fetch, 'arg1', 'arg2', ..., 'argn'],
         -store    => \&store,
         -destroy  => sub {print "Final value=$frog.\n"},
     %vinfo = $watch->Info;
     $args  = $watch->Args(-fetch);
     $val   = $watch->Fetch;
     print "val=", $watch->Say($val), ".\n";
     $watch->Store('Hello');
     $watch->Delete;

DESCRIPTION
===========

This class module binds subroutine(s) of your devising to a Perl variable.
All variables can have FETCH, STORE and DESTROY callbacks.  Additionally,
hashes can define CLEAR, DELETE, EXISTS, FIRSTKEY and NEXTKEY callbacks.
With Tie::Watch you can:

     . alter a variable's value
     . prevent a variable's value from being changed
     . invoke a Perl/Tk callback when a variable changes
     . trace references to a variable

Callback format is patterned after the Perl/Tk scheme:  supply either a
code reference, or, supply an array reference, and pass the callback code
reference in the first element of the array, followed by callback
arguments.  (See examples in the Synopsis, above.)

Tie::Watch provides default callbacks for any that you fail to specify.
Other than negatively impacting performance, they perform the standard
action that you'd expect, so the variable behaves "normally".

Here are two callbacks for a scalar. The fetch (read) callback does nothing
other than illustrate the fact that it returns the value to assign the
variable.  The store (write) callback uppercases the variable.

     my $fetch_scalar = sub {
         my($self) = @ARG;
         $self->Fetch;
     };

     my $store_scalar = sub {
         my($self, $new_val) = @ARG;
         $self->Store(uc $new_val);
     };

Here are fetch and store callbacks for either an array or hash.  They do
essentially the same thing as the scalar callbacks, but provide a little
more information.

     my $fetch = sub {
         my($self, $key) = @ARG;
         my $val = $self->Fetch($key);
         print "In fetch callback, key=$key, val=", $self->Say($val);
         my $args = $self->Args(-fetch);
         print ", args=('", join("', '",  @{$args}), "')" if $args;
         print ".\n";
         $val;
     };

     my $store = sub {
         my($self, $key, $new_val) = @ARG;
         my $val = $self->Fetch($key);
         $new_val = uc $new_val;
         $self->Store($key, $new_val);
         print "In store callback, key=$key, val=", $self->Say($val),
           ", new_val=", $self->Say($new_val);
         my $args = $self->Args(-store);
         print ", args=('", join("', '",  @{$args}), "')" if $args;
         print ".\n";
         $new_val;
     };

In all cases, the first parameter is a reference to the Watch object.  You
can use this to invoke useful class methods.

METHODS
=======

$watch = Tie::Watch->new(-options => values);
---------------------------------------------

-variable  = a *reference* to a scalar, array or hash variable.

-debug     = 1 to activate debug print statements internal to Tie::Watch.

Specify any of the following relevant callback parameters, in the format
described above: -fetch -store -destroy -clear -delete -exists -firstkey
and/or -nextkey.

$args = $watch->Args(-fetch);
-----------------------------

Returns a reference to a list of arguments for the specified callback, or
undef() if none.

$watch->Delete;
---------------

Stop watching the variable.

$watch->Fetch;  $watch->Fetch($key);
------------------------------------

Return a variable's current value.  $key is required for an array or hash.

%vinfo = $watch->Info;
----------------------

Returns a hash detailing the internals of the Watch object, with these
keys:

     %vinfo = {
         -variable =>  SCALAR(0x200737f8)
         -fetch    =>  ARRAY(0x200f8558)
         -store    =>  ARRAY(0x200f85a0)
         -destroy  =>  ARRAY(0x200f86cc)
         -debug    =>  '1'
         -value    =>  'HELLO SCALAR'
         -legible  =>  above data formatted as a list of string, for printing
     }

For array and hash Watch objects, the 'value' key is replaced with a 'ptr'
key which is a reference to the parallel array or hash.  Additionally, for
hashes, there are key/value pairs to the hash-specific callback options.

$watch->Say($val);
------------------

Used mainly for debugging, it returns $val in quotes if required, or
returns the string "undefined" for undefined values.

$watch->Store($new_val);  $watch->Store($key, $new_val);
--------------------------------------------------------

Store a variable's new value.  $key is required for an array or hash.

EFFICIENCY CONSIDERATIONS
=========================

If you can live using the class methods provided, please do so.  You can
meddle with the object hash directly and improved watch performance, at
the risk of your code breaking in the future.

AUTHOR
======

Stephen O. Lidie <lusol@Lehigh.EDU>

HISTORY
=======

     lusol@Lehigh.EDU, LUCC, 96/05/30
     . Original version 1.0 release, based on the Trace module from Hans Mulder,
       and ideas from Tim Bunce.

COPYRIGHT
=========

Copyright (C) 1996 - 1996 Stephen O. Lidie. All rights reserved.

This program is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.


File: pm.info,  Node: Time/CTime,  Next: Time/DaysInMonth,  Prev: Tie/Watch,  Up: Module List

format times ala POSIX asctime
******************************

NAME
====

Time::CTime - format times ala POSIX asctime

SYNOPSIS
========

     use Time::CTime
      	print ctime(time);
     print asctime(timelocal(time));
     print strftime(template, localtime(time));

strftime conversions
--------------------

     %%	PERCENT
     %a	day of the week abbr
     %A	day of the week
     %b	month abbr
     %B 	month
     %c 	ctime format: Sat Nov 19 21:05:57 1994
     %d 	numeric day of the month
     %e 	DD
     %D 	MM/DD/YY
     %h 	month abbr
     %H 	hour, 24 hour clock, leading 0's)
     %I 	hour, 12 hour clock, leading 0's)
     %j 	day of the year
     %k 	hour
     %l 	hour, 12 hour clock
     %m 	month number, starting with 1
     %M 	minute, leading 0's
     %n 	NEWLINE
     %o	ornate day of month -- "1st", "2nd", "25th", etc.
     %p 	AM or PM
     %r 	time format: 09:05:57 PM
     %R 	time format: 21:05
     %S 	seconds, leading 0's
     %t 	TAB
     %T 	time format: 21:05:57
     %U 	week number, Sunday as first day of week
     %w 	day of the week, numerically, Sunday == 0
     %W 	week number, Monday as first day of week
     %x 	date format: 11/19/94
     %X 	time format: 21:05:57
     %y	year (2 digits)
     %Y	year (4 digits)
     %Z 	timezone in ascii. eg: PST

DESCRIPTION
===========

This module provides routines to format dates.  They correspond to the
libc routines.  &strftime() supports a pretty good set of coversions -
more than most C libraries.

strftime supports a pretty good set of conversions.

The POSIX module has very similar functionality.  You should consider
using it instead if you do not have allergic reactions to system libraries.

GENESIS
=======

Written by David Muir Sharnoff <muir@idiom.com>.

Tthe starting point for this package was a posting by Paul Foley
<paul@ascent.com>


File: pm.info,  Node: Time/DaysInMonth,  Next: Time/HiRes,  Prev: Time/CTime,  Up: Module List

simply report the number of days in a month
*******************************************

NAME
====

Time::DaysInMonth - simply report the number of days in a month

SYNOPSIS 	 	use Time::DaysInMonth; 	$days = days_in($year, $month_1_to_12); 	$leapyear = is_leap($year);
========================================================================================================

DESCRIPTION
===========

DaysInMonth is simply a package to report the number of days in a month.
That's all it does.  Really!

AUTHOR
======

David Muir Sharnoff <muir@idiom.com>


File: pm.info,  Node: Time/HiRes,  Next: Time/JulianDay,  Prev: Time/DaysInMonth,  Up: Module List

Perl extension for ualarm, usleep, and gettimeofday
***************************************************

NAME
====

Time::HiRes - Perl extension for ualarm, usleep, and gettimeofday

SYNOPSIS
========

     use Time::HiRes;

     Time::HiRes::usleep ($microseconds);

     Time::HiRes::ualarm ($microseconds, $interval_microseconds);

     $t0 = [Time::HiRes::gettimeofday];
     ($seconds, $microseconds) = Time::HiRes::gettimeofday;

     $elapsed = Time::HiRes::tv_interval ( $t0, [$seconds, $microseconds]);
     $elapsed = Time::HiRes::tv_interval ( $t0, [Time::HiRes::gettimeofday]);
     $elapsed = Time::HiRes::tv_interval ( $t0 );

     $now_fractions = Time::HiRes::time;

     Time::HiRes::sleep ($floating_seconds);

     Time::HiRes::alarm ($floating_seconds);
     Time::HiRes::alarm ($floating_seconds, $floating_interval);
     
     use Time::HiRes qw ( time alarm sleep );
     $now_fractions = time;
     sleep ($floating_seconds);
     alarm ($floating_seconds);

DESCRIPTION
===========

The `Time::HiRes' package implements a Perl interface to usleep, ualarm,
and gettimeofday system calls. See the EXAMPLES section below and the test
scripts for usage; see your system documentation for the description of
the underlying gettimeofday, usleep, and ualarm calls.

gettimeofday
     Returns a 2 element array with the second and microseconds since the
     epoch.

usleep ( $useconds )
     Issues a usleep for the # of microseconds specified. See also
     Time::HiRes::sleep.

ualarm ( $useconds [, $interval_useconds ] )
     Issues a ualarm call; interval_useconds is optional and will be 0 if
     unspecified, resulting in alarm-like behaviour.

tv_interval ( $ref_to_gettimeofday [, $ref_to_later_gettimeofday] )
     Returns the floating seconds between the two times, which should have
     been returned by Time::HiRes::gettimeofday. If the second is omitted,
     then the current time is use.

time
     Returns a floating seconds since the epoch. This function can be
     exported, resulting in a nice drop-in replacement for the time
     provided with perl, see the EXAMPLES below.

sleep ( $floating_seconds )
     Converts $floating_seconds to microseconds and issues a usleep for the
     result.  This function can be exported, resulting in a nice drop-in
     replacement for the sleep provided with perl, see the EXAMPLES below.

alarm ( $floating_seconds [, $interval_floating_seconds ] )
     Converts $floating_seconds and $interval_floating_seconds and issues a
     ualarm for the results.  $interval_floating_seconds is optional and
     will be 0 if unspecified, resulting in alarm-like behaviour.  This
     function can be exported, resulting in a nice drop-in replacement for
     the alarm provided with perl, see the EXAMPLES below.

EXAMPLES
========

     use Time::HiRes;

     $microseconds = 750_000;
     Time::HiRes::usleep ($microseconds);

     # signal alarm in 2.5s & every .1 s thereafter
     Time::HiRes::ualarm (2_500_000, 100_000);

     # get seconds and microseconds since the epoch
     ($s, $usec) = Time::HiRes::gettimeofday;

     # measure elapsed time
     # (could also do by subtracting 2 Time::HiRes:gettimeofday_f return values)
     $t0 = [Time::HiRes::gettimeofday];
     # do bunch of stuff here
     $t1 = [Time::HiRes::gettimeofday];
     # do more stuff here
     $t0_t1 = Time::HiRes::tv_interval ($t0, $t1);
     
     $elapsed = Time::HiRes::tv_interval ($t0, [Time::HiRes::gettimeofday]);
     $elapsed = Time::HiRes::tv_interval ($t0);	# equivalent code

     #
     # replacements for time, alarm and sleep that know about floating seconds
     #
     use Time::HiRes;
     $now_fractions = Time::HiRes::time;
     Time::HiRes::sleep (2.5);
     Time::HiRes::alarm (10.6666666);
     
     use Time::HiRes qw ( time alarm sleep );
     $now_fractions = time;
     sleep (2.5);
     alarm (10.6666666);

AUTHOR
======

D. Wegscheid <wegscd@whirlpool.com>

REVISION
========

$Id: HiRes.pm,v 1.1 1996/10/17 20:53:31 wegscd Exp $

$Log: HiRes.pm,v $ Revision 1.1  1996/10/17 20:53:31  wegscd Fix =head1
being next to __END__ so pod2man works

Revision 1.0  1996/09/03 18:25:15  wegscd Initial revision

COPYRIGHT
=========

Copyright (c) 1996 Douglas E. Wegscheid.  All rights reserved. This
program is free software; you can redistribute it and/or modify it under
the same terms as Perl itself.


File: pm.info,  Node: Time/JulianDay,  Next: Time/Local,  Prev: Time/HiRes,  Up: Module List

Julian calendar manipulations
*****************************

NAME
====

Time::JulianDay - Julian calendar manipulations

SYNOPSIS
========

     use Time::JulianDay

     $jd = julian_day($year, $month_1_to_12, $day)
     $jd = local_julian_day($seconds_since_1970);
     $jd = gm_julian_day($seconds_since_1970);
     ($year, $month_1_to_12, $day) = inverse_julian_day($jd)
     $dow = day_of_week($jd)

     print (Sun,Mon,Tue,Wed,Thu,Fri,Sat)[$dow];

     $seconds_since_jan_1_1970 = jd_secondslocal($jd, $hour, $min, $sec)
     $seconds_since_jan_1_1970 = jd_secondsgm($jd, $hour, $min, $sec)
     $seconds_since_jan_1_1970 = jd_timelocal($sec,$min,$hours,$mday,$month_0_to_11,$year)
     $seconds_since_jan_1_1970 = jd_timegm($sec,$min,$hours,$mday,$month_0_to_11,$year)

DESCRIPTION
===========

JulianDay is a package that manipulates dates as number of days since some
time a long time ago.  It's easy to add and subtract time using julian
days...

The day_of_week returned by day_of_week() is 0 for Sunday, and 6 for
Saturday and everything else is in between.

GENESIS
=======

Written by David Muir Sharnoff <muir@idiom.com> with help from previous
work by Kurt Jaeger aka PI <zrzr0111@helpdesk.rus.uni-stuttgart.de>  	based
on postings from: Ian Miller <ian_m@cix.compulink.co.uk>; Gary Puckering
<garyp%cognos.uucp@uunet.uu.net> 	based on Collected Algorithms of the ACM
?; and the unknown-to-me author of Time::Local.


File: pm.info,  Node: Time/Local,  Next: Time/ParseDate,  Prev: Time/JulianDay,  Up: Module List

efficiently compute time from local and GMT time
************************************************

NAME
====

Time::Local - efficiently compute time from local and GMT time

SYNOPSIS
========

     $time = timelocal($sec,$min,$hours,$mday,$mon,$year);
     $time = timegm($sec,$min,$hours,$mday,$mon,$year);

DESCRIPTION
===========

These routines are quite efficient and yet are always guaranteed to agree
with localtime() and gmtime().  We manage this by caching the start times
of any months we've seen before.  If we know the start time of the month,
we can always calculate any time within the month.  The start times
themselves are guessed by successive approximation starting at the current
time, since most dates seen in practice are close to the current date.
Unlike algorithms that do a binary search (calling gmtime once for each
bit of the time value, resulting in 32 calls), this algorithm calls it at
most 6 times, and usually only once or twice.  If you hit the month cache,
of course, it doesn't call it at all.

timelocal is implemented using the same cache.  We just assume that we're
translating a GMT time, and then fudge it when we're done for the timezone
and daylight savings arguments.  The timezone is determined by examining
the result of localtime(0) when the package is initialized.  The daylight
savings offset is currently assumed to be one hour.

Both routines return -1 if the integer limit is hit. I.e. for dates after
the 1st of January, 2038 on most machines.


File: pm.info,  Node: Time/ParseDate,  Next: Time/Timezone,  Prev: Time/Local,  Up: Module List

date parsing both relative and absolute
***************************************

NAME
====

Time::ParseDate - date parsing both relative and absolute

SYNOPSIS
========

     use Time::ParseDate;
     $seconds_since_jan1_1970 = parsedate("12/11/94 2pm", NO_RELATIVE => 1)
     $seconds_since_jan1_1970 = parsedate("12/11/94 2pm", %options)

OPTIONS
=======

Date parsing can also use options.  The options are as follows:

     FUZZY	-> it's okay not to parse the entire date string
     NOW	-> the "current" time for relative times (defaults to time())
     ZONE	-> local timezone (defaults to $ENV{TZ})
     WHOLE	-> the whole input string must be parsed
     GMT	-> input time is assumed to be GMT, not localtime
     UK	-> prefer UK style dates (dd/mm over mm/dd)
     DATE_REQUIRED -> do not default the date
     TIME_REQUIRED -> do not default the time
     NO_RELATIVE -> input time is not relative to NOW
     TIMEFIRST -> try parsing time before date [not default]
     PREFER_PAST -> when year or day of week is ambigueous, assume past
     PREFER_FUTURE -> when year or day of week is ambigueous, assume future

DATE FORMATS RECOGNIZED
=======================

Absolute date formats
---------------------

     Dow, dd Mon yy
     Dow, dd Mon yyyy
     Dow, dd Mon
     dd Mon yy
     dd Mon yyyy
     Month day{st,nd,rd,th}, year
     Month day{st,nd,rd,th}
     Mon dd yyyy
     yyyy/mm/dd
     yyyy/mm
     mm/dd/yy
     mm/dd/yyyy
     mm/yy
     yy/mm      (only if year > 12, or > 31 if UK)
     yy/mm/dd   (only if year > 12 and day < 32, or year > 31 if UK)
     dd/mm/yy   (only if UK, or an invalid mm/dd/yy or yy/mm/dd)
     dd/mm/yyyy (only if UK, or an invalid mm/dd/yyyy)
     dd/mm      (only if UK, or an invalid mm/dd)

Relative date formats:
----------------------

     count "days"
     count "weeks"
     count "months"
     count "years"
     Dow "after next"
     Dow 			(requires PREFER_PAST or PREFER_FUTURE)
     "next" Dow
     "tomorrow"
     "today"
     "yesterday"
     "last" dow
     "last week"
     "now"
     "now +" count units

Absolute time formats:
----------------------

     hh:mm:ss
     hh:mm
     hh:mm[AP]M
     hh[AP]M
     hhmmss[[AP]M]
     "noon"
     "midnight"

Relative time formats:
----------------------

     count "minuts"
     count "seconds"
     count "hours"
     "+" count units
     "+" count

Timezone formats:
-----------------

     [+-]dddd
     GMT[+-]d+
     [+-]dddd (TZN)
     TZN

Special formats:
----------------

     [ d]d/Mon/yyyy:hh:mm:ss [[+-]dddd]
     yy/mm/dd.hh:mm

DESCRIPTION
===========

This module recognizes the above date/time formats.   Usually a date and a
time are specified.  There are numerous options for controlling what is
recognized and what is not.

The return code is always the time in seconds since January 1st, 1970 or
zero if it was unable to parse the time.

If a timezone is specified it must be after the time.  Year specifications
can be tacked onto the end of absolute times.

EXAMPLES
========

     $seconds = parsedate("Mon Jan  2 04:24:27 1995");
     $seconds = parsedate("Tue Apr 4 00:22:12 PDT 1995");
     $seconds = parsedate("04.04.95 00:22", ZONE => PDT);
     $seconds = parsedate("122212 950404", ZONE => PDT, TIMEFIRST => 1);
     $seconds = parsedate("+3 secs", NOW => 796978800);
     $seconds = parsedate("2 months", NOW => 796720932);
     $seconds = parsedate("last Tuesday");

AUTHOR
======

David Muir Sharnoff <muir@idiom.com>

Patch for UK-style dates: Sam Yates <syates@maths.adelaide.edu.au>


File: pm.info,  Node: Time/Timezone,  Next: Time/Zone,  Prev: Time/ParseDate,  Up: Module List

miscellaneous timezone manipulations routines
*********************************************

NAME
====

Time::Timezone - miscellaneous timezone manipulations routines

SYNOPSIS
========

     use Time::Timezone;
     print tz2zone();
     print tz2zone($ENV{'TZ'});
     print tz2zone($ENV{'TZ'}, time());
     print tz2zone($ENV{'TZ'}, undef, $isdst);
     $offset = tz_local_offset();
     $offset = tz_offset($TZ);

DESCRIPTION
===========

This is a collection of miscellaneous timezone manipulation routines.

`tz2zone()' parses the TZ environment variable and returns a timezone
string suitable for inclusion in `date' in this node-like output.  It
opionally takes a timezone string, a time, and a is-dst flag.

`tz_local_offset()' determins the offset from GMT time in seconds.  It
only does the calculation once.

`tz_offset()' determines the offset from GMT in seconds of a specified
timezone.

`tz_name()' determines the name of the timezone based on its offset

AUTHORS
=======

Graham Barr <bodg@tiuk.ti.com> David Muir Sharnoff <muir@idiom.com> Paul
Foley <paul@ascent.com>


File: pm.info,  Node: Time/Zone,  Next: Tk/FileDialog,  Prev: Time/Timezone,  Up: Module List

miscellaneous timezone manipulations routines
*********************************************

NAME
====

Time::Zone - miscellaneous timezone manipulations routines

SYNOPSIS
========

     use Time::Zone;
     print tz2zone();
     print tz2zone($ENV{'TZ'});
     print tz2zone($ENV{'TZ'}, time());
     print tz2zone($ENV{'TZ'}, undef, $isdst);
     $offset = tz_local_offset();
     $offset = tz_offset($TZ);

DESCRIPTION
===========

This is a collection of miscellaneous timezone manipulation routines.

`tz2zone()' parses the TZ environment variable and returns a timezone
string suitable for inclusion in `date' in this node-like output.  It
opionally takes a timezone string, a time, and a is-dst flag.

`tz_local_offset()' determins the offset from GMT time in seconds.  It
only does the calculation once.

`tz_offset()' determines the offset from GMT in seconds of a specified
timezone.

`tz_name()' determines the name of the timezone based on its offset

AUTHORS
=======

Graham Barr <bodg@tiuk.ti.com> David Muir Sharnoff <muir@idiom.com> Paul
Foley <paul@ascent.com>

REVISION
========

$Revision: 2.2 $


File: pm.info,  Node: Tk/FileDialog,  Next: Tk/SelFile,  Prev: Time/Zone,  Up: Module List

A highly configurable File Dialog widget for Perl/Tk.
*****************************************************

NAME
====

Tk::FileDialog - A highly configurable File Dialog widget for Perl/Tk.

DESCRIPTION
===========

The widget is composed of a number of sub-widgets, namely, a listbox for
files and (optionally) directories, an entry for filename, an (optional)
entry for pathname, an entry for a filter pattern, a 'ShowAll' checkbox
(for enabling display of .* files and directories), and three buttons,
namely OK, Rescan, and Cancel.  Note that the labels for all subwidgets
(including the text for the buttons and Checkbox) are configurable for
foreign language support.  The Listboxes will respond to characters typed
over them with scrolling to the first line that starts with the given
character (or next etc. if this character is not present).

SYNOPSIS
========

Usage Description
-----------------

To use FileDialog, simply create your FileDialog objects during
initialization (or at least before a Show).  When you wish to display the
FileDialog, invoke the 'Show' method on the FileDialog object;  The method
will return either a file name, a path name, or undef.  undef is returned
only if the user pressed the Cancel button.

Example Code
------------

The following code creates a FileDialog and calls it.  Note that
perl5.002gamma is required.


          #!/usr/local/bin/perl -w

          use Tk;
          use Tk::FileDialog;
          use strict;

          my($main) = MainWindow->new;
          my($Horiz) = 1;
          my($fname);

          my($LoadDialog) = $main->FileDialog(-Title =>'This is my title',
          				    -Create => 0);

          print "Using FileDialog Version ",$LoadDialog->Version,"\n";

          $LoadDialog->configure(-FPat => '*pl',
          		       -ShowAll => 'NO');

          $main->Entry(-textvariable => \$fname)
          	->pack(-expand => 1,
          	       -fill => 'x');

          $main->Button(-text => 'Kick me!',
          	      -command => sub {
          		  $fname = $LoadDialog->Show(-Horiz => $Horiz);
          		  if (!defined($fname)) {
          		      $fname = "Fine,Cancel, but no Chdir anymore!!!";
          		      $LoadDialog->configure(-Chdir =>'NO');
          		  }
          	      })
          	->pack(-expand => 1,
          	       -fill => 'x');

          $main->Checkbutton(-text => 'Horizontal',
          		   -variable => \$Horiz)
          	->pack(-expand => 1,
          	       -fill => 'x');

          $main->Button(-text => 'Exit',
          	      -command => sub {
          		  $main->destroy;
          	      })
          	->pack(-expand => 1,
          	       -fill => 'x');

          MainLoop;

          print "Exit Stage right!\n";

          exit;

METHODS
=======


     The following non-standard methods may be used with a FileDialog
     object


Show
----

Displays the file dialog box for the user to operate.  Additional
configuration items may be passed in at Show-time In other words, this
code snippet:

     $fd->Show(-Title => 'Ooooh, Preeeeeety!');

is the same as this code snippet:

     $fd->configure(-Title => 'Ooooh, Preeeeeety!');
     $fd->Show;


Version
-------

Returns the current Version of FileDialog

CONFIGURATION
=============

Any of the following configuration items may be set via the configure (or
Show) method, or retrieved via the cget method.

Flags
-----

Flags may be configured with either 1,'true', or 'yes' for 1, or 0,
'false', or 'no' for 0. Any portion of 'true', 'yes', 'false', or 'no' may
be used, and case does not matter.


-Chdir
------


     Enable the user to change directories. The default is 1. If disabled,
     the directory list box will not be shown.

-Create
-------


     Enable the user to specify a file that does not exist. If not
     enabled, and the user specifies a non-existent file, a dialog box
     will be shown informing the user of the error (This Dialog Box is
     configurable via the EDlg* switches, below).

     default: 1

-ShowAll
--------


     Determines whether hidden files (.*) are displayed in the File and
     Directory Listboxes.  The default is 0. The Show All Checkbox
     reflects the setting of this switch.

-DisableShowAll
---------------


     Disables the ability of the user to change the status of the ShowAll
     flag. The default is 0 (the user is by default allowed to change the
     status).

-Grab
-----


     Enables the File Dialog to do an application Grab when displayed. The
     default is 1.

-Horiz
------


     True sets the File List box to be to the right of the Directory List
     Box. If 0, the File List box will be below the Directory List box.
     The default is 1.

-SelDir
-------


     If True, enables selection of a directory rather than a file, and
     disables the actions of the File List Box. The default is 0.

Special
-------


-FPat
-----


     Sets the default file selection pattern. The default is '*'. Only
     files matching this pattern will be displayed in the File List Box.

-Geometry
---------


     Sets the geometry of the File Dialog. Setting the size is a dangerous
     thing to do.  If not configured, or set to '', the File Dialog will
     be centered.

-SelHook
--------


     SelHook is configured with a reference to a routine that will be
     called when a file is chosen. The file is called with a sole
     parameter of the full path and file name of the file chosen. If the
     Create flag is disabled (and the user is not allowed to specify new
     files), the file will be known to exist at the time that SelHook is
     called. Note that SelHook will also be called with directories if the
     SelDir Flag is enabled, and that the FileDialog box will still be
     displayed. The FileDialog box should *not* be destroyed from within
     the SelHook routine, although it may generally be configured.

     SelHook routines return 0 to reject the selection and allow the user
     to reselect, and any other value to accept the selection. If a
     SelHook routine returns non-zero, the FileDialog will immediately be
     withdrawn, and the file will be returned to the caller.

     There may be only one SelHook routine active at any time. Configuring
     the SelHook routine replaces any existing SelHook routine.
     Configuring the SelHook routine with 0 removes the SelHook routine.
     The default SelHook routine is undef.

Strings
-------

The following two switches may be used to set default variables, and to
get final values after the Show method has returned (but has not been
explicitly destroyed by the caller)


     *-File*  The file selected, or the default file. The default is ''.

     *-Path*  The path of the selected file, or the initial path. The
     default is $ENV{'HOME'}.

Labels and Captions
-------------------

For support of internationalization, the text on any of the subwidgets may
be changed.


     -Title  The Title of the dialog box. The default is 'Select File:'.

     *-DirLBCaption*  The Caption above the Directory List Box. The
     default is 'Directories'.

     *-FileLBCaption*  The Caption above the File List Box. The default is
     'Files'.

     *-FileEntryLabel*  The label to the left of the File Entry. The
     Default is 'Filename:'.

     *-PathEntryLabel*  The label to the left of the Path Entry. The
     default is 'Pathname:'.

     *-FltEntryLabel*  The label to the left of the Filter entry. The
     default is 'Filter:'.

     *-ShowAllLabel*  The text of the Show All Checkbutton. The default is
     'Show All'.

Button Text
-----------

For support of internationalization, the text on the three buttons may be
changed.


     *-OKButtonLabel*  The text for the OK button. The default is 'OK'.

     *-RescanButtonLabel*  The text for the Rescan button. The default is
     'Rescan'.

     *-CancelButtonLabel*  The text for the Cancel button. The default is
     'Cancel'.

Error Dialog Switches
---------------------

If the Create switch is set to 0, and the user specifies a file that does
not exist, a dialog box will be displayed informing the user of the error.
These switches allow some configuration of that dialog box.


-EDlgTitle
----------


     The title of the Error Dialog Box. The default is 'File does not
     exist!'.

-EDlgText
---------


     The message of the Error Dialog Box. The variables $path, $file, and
     $filename (the full path and filename of the selected file) are
     available. The default is *"You must specify an existing
     file.\n(\$filename not found)"*

Author
======

*Brent B. Powers, Merrill Lynch (B2Pi)*

powers@ml.com

This code may be distributed under the same conditions as Perl itself.


File: pm.info,  Node: Tk/SelFile,  Next: Tk/WaitBox,  Prev: Tk/FileDialog,  Up: Module List

a widget for choosing a file to read or write
*********************************************

NAME
====

     SelFile - a widget for choosing a file to read or write

SYNOPSIS
========

     use Tk;
     use Tk::SelFile;

     $mw = MainWindow->new;  # As an example.

     $start_dir = ".";       # As an example.
     $sfw = $mw->SelFile(
     		     -directory => $start_dir,
     		     -width     =>  30,
     		     -height    =>  20,
     		     -filelistlabel  => 'Files',
     		     -filter         => '*',
     		     -filelabel      => 'File',
     		     -dirlistlabel   => 'Directories',
     		     -dirlabel       => 'Filter',
     		     -readbutlabel   => 'Read',
     		     -writebutlabel  => 'Write',
     		     -cancelbutlabel => 'Cancel',
     		     );
     Please see the Populate subroutine as the configuration
     list may change.

     ($opcode, $filename) = $sfw->Show;

     $opcode will have the value -readbutlabel (e.g. 'READ'),
     -writebutlabel (e.g. 'WRITE') or -cancelbutlabel (e.g. 'CANCEL').
     An empty string for the text assigned to -readbutlabel or
     -writebutlabel will eliminate that particular button.
     $filename will be a file pathname, or in the case of CANCEL
     it will be a single space character.

     $SFref = $sfw->configure(option => value[, ...])

DESCRIPTION
===========

     This Module pops up a file selector box, with a directory entry
     with filter on top, a list of directories in the current directory,
     a list of files in the current directory, an entry for entering
     or modifying a file name, a read button, a write button, a
     cancel button, a HOME button, and a button to return to the
     starting directory (-directory).

     The button to return to the starting directory is motivated by
     the idea that an application may have a directory unrelated to
     the home directory, e.g. a library of data, that is set to be
     the starting directory.  If the user goes to the home directory,
     the user may not recall the starting directory that was set by
     the application.

     A call to SelFile few (or no options, such as shown below)
     will result in the default values shown in the example
     given in the SYNOPSIS section.  The most uptodate list of
     configuration variables and default values can be found in the
     subroutine Populate as arguments to the subroutine ConfigSpecs.

     $sfw = $mw->SelFile;

     A dialog box error message is generated if the user clicks the
     Read button for a file that does not exist.
     For Write, a dialog box that requests whether the user wishes
     to overwrite the file is generated for a file that already exists.
     Also for Write, a dialog box error message is generated is the
     file name is blank.

     This widget can be configured for requesting a file name to read,
     requesting a file name for writing, or for requesting either.
     For the initial call to SelFile that configures the widget,
     if -readbutlabel is not a member of the argument list, then
     the default value is used (i.e. Read).  If on the other hand
     it is present but specifies an empty string, as shown below
     -readbutlabel   => '',
     then the button is not created.  An analogous rule applies
     to the argument -writebutlabel.

     The file name output is a single space character rather than undef
     when CANCEL is selected so that the user can process the return values
     without checking the values, e.g. storing the result for later use.

AUTHORS
=======

Based on original FileSelect by Klaus Lichtenwalder,
Lichtenwalder@ACM.org, Datapat GmbH, Munich, April 22, 1995 adapted by
Frederick L. Wagner, derf@ti.com, Texas Instruments Incorporated, Dallas,
21Jun95 further adapted by Alan Louis Scheinine, scheinin@crs4.it, Centro
di Ricerca, Sviluppo e Studi Superiori in Sardegna (CRS4) Cagliari, 14
November 1995

HISTORY
=======

Alan Scheinine wants to thank David Greaves (davidg@oak.reading.sgi.com)
for pointing out errors and for suggesting improvements.  He also wants to
thank Nick Ing-Simmons (nik@tiuk.ti.com) for sending the soon-to-be
FileSelect for Tk-b9.  This SelFile program diverges from SelectFile with
regard to style but nonetheless has benefited from the ideas and actual
code of SelectFile.

Future history.  For Tk-b9, "show" and "subwidget" should become "Show"
and "Subwidget" Change $cw->subwidget('dialog')->show;  Tk-b8 to
$cw->Subwidget('dialog')->Show;  Tk-b9


File: pm.info,  Node: Tk/WaitBox,  Next: UNIVERSAL,  Prev: Tk/SelFile,  Up: Module List

An Object Oriented Wait Dialog for Perl/Tk, of the Please Wait variety.
***********************************************************************

NAME
====

Tk::WaitBox - An Object Oriented Wait Dialog for Perl/Tk, of the Please
Wait variety.

DESCRIPTION
===========

A WaitBox consists of a number of subwidgets:


bitmap
------

A bitmap (configurable via the *-bitmap* command, the default is an
hourglass) on the left side of the WaitBox

label
-----

A label (configurable via the *-txt1* command), with text in the upper
portion of the right hand frame

secondary label
---------------

Another label (configurable via the *-txt2* command, the default is
'Please Wait'), with text in the lower portion of the right hand frame

userframe
---------

A frame displayed, if required, between the label and the secondary label.
For details, see the example code and the Advertised Widget section

cancel button
-------------

If a cancelroutine (configured via the *-cancelroutine* command) is
defined, a frame will be packed below the labels and bitmap, with a single
button.  The text of the button will be 'Cancel' (configurable via the
*-canceltext* command), and the button will call the supplied subroutine
when pressed.

SYNOPSIS
========

Usage Description

Basic Usage
-----------

To use, create your WaitDialog objects during initialization, or at least
before a Show.  When you wish to display the WaitDialog object, invoke the
'Show' method on the WaitDialog object; when you wish to cease displaying
the WaitDialog object, invoke the 'unShow' method on the object.

Configuration
-------------

Configuration may be done at creation or via the configure method.

Example Code
------------


          #!/usr/local/bin/perl -w

          use Tk;
          use Tk::WaitBox;
          use strict;

          my($root) = MainWindow->new;
          my($utxt) = "Initializing...";

          my($wd) = $root->WaitBox(
          	-bitmap =>'questhead', # Default would be 'hourglass'
          	-txt2 => 'tick-tick-tick', #default would be 'Please Wait'
          	-title => 'Takes forever to get service around here',
          	-cancelroutine => sub {
          	    print "\nI'm canceling....\n";
          	    $wd->unShow;
          	    $utxt = undef;
          	});
          $wd->configure(-txt1 => "Hurry up and Wait, my Drill Sergeant told me");
          $wd->configure(-foreground => 'blue',-background => 'white');

          ### Do something quite boring with the user frame
          my($u) = $wd->{SubWidget}(uframe);
          $u->pack(-expand => 1, -fill => 'both');
          $u->Label(-textvariable => \$utxt)->pack(-expand => 1, -fill => 'both');

          ## It would definitely be better to do this with a canvas... this is dumb
          my($base) = $u->Frame(-background =>'gray',
          		       -relief => 'sunken',
          		       -borderwidth => 2,
          		       -height => 20)
          	 ->pack(-side => 'left', -anchor => 'w',-expand => 1,
          		-fill => 'both');
          my($bar) = $base->Frame(-borderwidth => 2,
          			 -relief => 'raised', -height => 20,
          			 -width => 0, -background => 'blue')
          	 ->pack(-fill => 'y', -side => 'left');

          $wd->configure(-canceltext => 'Halt, Cease, Desist'); # default is 'Cancel'

          $wd->Show;

          for (1..15) {
              sleep(1);
              $bar->configure(-width => int($_/15*$base->Width));
              $utxt = 100*$_/15 . "% Complete";
              $root->update;
              last if !defined($utxt);
          }

          $wd->unShow;

Advertised Subwidgets
=====================

uframe
     uframe is a frame created between the two messages.  It may be used
     for anything the user has in mind... including exciting cycle wasting
     displays of sand dropping through an hour glass, Zippy riding either
     a Gnu or a bronc, et cetera.

     Assuming that the WaitBox is referenced by $w, the uframe may be
     addressed as $w->subwidget{'uframe'}.  Having gotten the address, you
     can do anything (I think) you would like with it

Author
======

*Brent B. Powers, Merrill Lynch (B2Pi)*  powers@ml.com

This code may be distributed under the same conditions as perl itself.


File: pm.info,  Node: UNIVERSAL,  Next: URI/Escape,  Prev: Tk/WaitBox,  Up: Module List

base class for ALL classes (blessed references)
***********************************************

NAME
====

UNIVERSAL - base class for ALL classes (blessed references)

SYNOPSIS
========

     use UNIVERSAL qw(isa);

     $yes = isa($ref, "HASH");
     $io = $fd->isa("IO::Handle");
     $sub = $obj->can('print');

DESCRIPTION
===========

`UNIVERSAL' is the base class which all bless references will inherit from,
see *Note Perlobj: (perl.info)perlobj,

`UNIVERSAL' provides the following methods

isa ( TYPE )
     isa returns *true* if `REF' is blessed into package `TYPE' or
     inherits from package `TYPE'.

     isa can be called as either a static or object method call.

can ( METHOD )
     can checks if the object has a method called `METHOD'. If it does
     then a reference to the sub is returned. If it does not the undef is
     returned.

     can can be called as either a static or object method call.

VERSION ( [ REQUIRE ] )
     VERSION will return the value of the variable `$VERSION' in the
     package the object is blessed into. If `REQUIRE' is given then it
     will do a comparison and die if the package version is not greater
     than or equal to `REQUIRE'.

     VERSION can be called as either a static or object method call.

`UNIVERSAL' also optionally exports the following subroutines

isa ( REF, TYPE )
     isa returns *true* if the first argument is a reference and either of
     the following statements is true.


          `REF' is a blessed reference and is blessed into package `TYPE'
          or inherits from package `TYPE'


          `REF' is a reference to a `TYPE' of perl variable (er 'HASH')


File: pm.info,  Node: URI/Escape,  Next: URI/URL,  Prev: UNIVERSAL,  Up: Module List

Escape unsafe characters
************************

NAME
====

uri_escape - Escape unsafe characters

uri_unescape - Unescape escaped characters

SYNOPSIS
========

     use URI::Escape;
     $safe = uri_escape("10% is enough\n");
     $verysafe = uri_escape("foo", "\0-\377");
     $str  = uri_unescape($safe);

DESCRIPTION
===========

This module provide functions to escape and unescape URI strings.  Some
characters are regarded as "unsafe" and must be escaped in accordance with
RFC 1738.  Escaped characters are represented by a triplet consisting of
the character "%" followed by two hexadecimal digits.

The uri_escape() function takes an optional second argument that overrides
the set of characters that are to be escaped.  The set is specified as a
string that can be used in a regular expression character class (between [
]).  E.g.:

     \x00-\x1f\x7f-\xff          # all control and hi-bit characters
     a-z                         # all lower case characters
     ^A-Za-z                     # everything not a letter

The default set of characters to be escaped is:

     \x00-\x20"#%;<>?{}|\\\\^~`\[\]\x7F-\xFF

The module can also export the %escapes hash which contains the mapping
from all characters to the corresponding escape code.

SEE ALSO
========

*Note URI/URL: URI/URL,


File: pm.info,  Node: URI/URL,  Next: VRML,  Prev: URI/Escape,  Up: Module List

Uniform Resource Locators (absolute and relative)
*************************************************

NAME
====

URI::URL - Uniform Resource Locators (absolute and relative)

SYNOPSIS
========

     use URI::URL;

     # Constructors
     $url1 = new URI::URL 'http://www.perl.com/%7Euser/gisle.gif';
     $url2 = new URI::URL 'gisle.gif', 'http://www.com/%7Euser';
     $url3 = url 'http://www.sn.no/'; # handy constructor
     $url4 = $url2->abs;       # get absolute url using base
     $url5 = $url2->abs('http:/other/path');
     $url6 = newlocal URI::URL 'test';

     # Stringify URL
     $str1 = $url->as_string;  # complete escaped URL string
     $str2 = $url->full_path;  # escaped path+params+query
     $str3 = "$url";           # use operator overloading

     # Retrieving Generic-RL components:
     $scheme   = $url->scheme;
     $netloc   = $url->netloc; # see user,password,host,port below
     $path     = $url->path;
     $params   = $url->params;
     $query    = $url->query;
     $frag     = $url->frag;

     # Accessing elements in their escaped form
     $path     = $url->epath;
     $params   = $url->eparams;
     $query    = $url->equery;

     # Retrieving Network location (netloc) components:
     $user     = $url->user;
     $password = $url->password;
     $host     = $url->host;
     $port     = $url->port;   # returns default if not defined

     # Retrieve escaped path components as an array
     @path     = $url->path_components;

     # HTTP query-string access methods
     @keywords = $url->keywords;
     @form     = $url->query_form;

     # All methods above can set the field values, e.g:
     $url->scheme('http');
     $url->host('www.w3.org');
     $url->port($url->default_port);
     $url->base($url5);                      # use string or object
     $url->keywords(qw(dog bones));

     # File methods
     $url = new URI::URL "file:/foo/bar";
     open(F, $url->local_path) or die;

     # Compare URLs
     if ($url->eq("http://www.sn.no")) or die;

DESCRIPTION
===========

This module implements the URI::URL class representing Uniform Resource
Locators (URL). URLs provide a compact string representation for resources
available via the Internet. Both absolute (RFC 1738) and relative (RFC
1808) URLs are supported.

URI::URL objects are created by calling new(), which takes as argument a
string representation of the URL or an existing URL object reference to be
cloned. Specific individual elements can then be accessed via the
scheme(), user(), password(), host(), port(), path(), params(), query()
and frag() methods.  In addition escaped versions of the path, params and
query can be accessed with the epath(), eparams() and equery() methods.
Note that some URL schemes will support all these methods.

The object constructor new() must be able to determine the scheme for the
URL.  If a scheme is not specified in the URL itself, it will use the
scheme specified by the base URL. If no base URL scheme is defined then
new() will croak if URI::URL::strict(1) has been invoked, otherwise *http*
is silently assumed.  Once the scheme has been determined new() then uses
the implementor() function to determine which class implements that
scheme.  If no implementor class is defined for the scheme then new() will
croak if URI::URL::strict(1) has been invoked, otherwise the internal
generic URL class is assumed.

Internally defined schemes are implemented by the URI::URL::*scheme_name*
module.  The URI::URL::implementor() function can be used to explicitly
set the class used to implement a scheme if you want to override this.

HOW AND WHEN TO ESCAPE
======================

This is an edited extract from a URI specification:
     The printability requirement has been met by specifying a safe set of
     characters, and a general escaping scheme for encoding "unsafe"
     characters. This "safe" set is suitable, for example, for use in
     electronic mail.  This is the canonical form of a URI.

     There is a conflict between the need to be able to represent many
     characters including spaces within a URI directly, and the need to be
     able to use a URI in environments which have limited character sets
     or in which certain characters are prone to corruption. This conflict
     has been resolved by use of an hexadecimal escaping method which may
     be applied to any characters forbidden in a given context. When URLs
     are moved between contexts, the set of characters escaped may be
     enlarged or reduced unambiguously.  The canonical form for URIs has
     all white spaces encoded.

Notes:
     A URL string *must*, by definition, consist of escaped components.
     Complete URLs are always escaped.

     The components of a URL string must be *individually* escaped.  Each
     component of a URL may have a separate requirements regarding what
     must be escaped, and those requirements are also dependent on the URL
     scheme.

     Never escape an already escaped component string.

This implementation expects an escaped URL string to be passed to new()
and will return a fully escaped URL string from as_string() and
full_path().

Individual components can be manipulated in unescaped or escaped form. The
following methods return/accept unescaped strings:

     scheme                  path
     user                    params
     password                query
     host                    frag
     port

The following methods return/accept partial *escaped* strings:

     netloc                  eparams
     epath                   equery

*Partial escaped* means that only reserved characters (i.e. ':', '@', '/',
';', '?', '=', '&' in addition to '%', '.' and '#') needs to be escaped
when they are to be treated as normal characters.  *Fully escaped* means
that all unsafe characters are escaped. Unsafe characters are all all
control characters (%00-%1F and %7F), all 8-bit characters (%80-%FF) as
well as '{', '}', '|', '\', '^', '[', ']' '`', '"', '<' and '>'.  Note
that the character '~' is *not* considered unsafe by this library as it is
common practice to use it to reference personal home pages, but it is
still unsafe according to RFC 1738.

ADDING NEW URL SCHEMES
======================

New URL schemes or alternative implementations for existing schemes can be
added to your own code. To create a new scheme class use code like:

     package MYURL::foo;
     @ISA = (URI::URL::implementor());   # inherit from generic scheme

The 'URI::URL::implementor()' function call with no parameters returns the
name of the class which implements the generic URL scheme behaviour
(typically `URI::URL::_generic'). All hierarchical schemes should be
derived from this class.

Your class can then define overriding methods (e.g., new(), _parse() as
required).

To register your new class as the implementor for a specific scheme use
code like:

     URI::URL::implementor('x-foo', 'MYURL::foo');

Any new URL created for scheme 'x-foo' will be implemented by your
`MYURL::foo' class. Existing URLs will not be affected.

FUNCTIONS
=========

new URI::URL $url_string [, $base_url]
     This is the object constructor.  It will create a new URI::URL object,
     initialized from the URL string.  To trap bad or unknown URL schemes
     use:

          $obj = eval { new URI::URL "snews:comp.lang.perl.misc" };

     or set URI::URL::strict(0) if you do not care about bad or unknown
     schemes.

newlocal URI::URL $path;
     Returns an URL object that denotes a path within the local filesystem.
     Paths not starting with '/' are interpreted relative to the current
     working directory.  This constructor always return an absolute 'file'
     URL.

url($url_string, [, $base_url])
     Alternative constructor function.  The url() function is exported by
     the URI::URL module and is easier both to type and read than calling
     URI::URL->new directly.  Useful for constructs like this:

          $h = url($str)->host;

     This function is just a wrapper for URI::URL->new.

URI::URL::strict($bool)
     If strict is true then we croak on errors.  The function returns the
     previous value.

URI::URL::implementor([$scheme, [$class]])
     Use this function to get or set implementor class for a scheme.
     Returns '' if specified scheme is not supported.  Returns generic URL
     class if no scheme specified.

METHODS
=======

This section describes the methods available for an URI::URL object.  Note
that some URL schemes will disallow some of these methods and will croak
if they are used.  Some URL schemes add additional methods that are
described in the sections to follow.

Attribute access methods marked with (*) can take an optional argument to
set the value of the attribute, and they always return the old value.

$url->abs([$base, [$allow_scheme_in_relative_urls]])
     The abs() method attempts to return a new absolute URI::URL object
     for a given URL.  In order to convert a relative URL into an absolute
     one, a *base* URL is required. You can associate a default base with a
     URL either by passing a *base* to the new() constructor when a
     URI::URL is created or using the base() method on the object later.
     Alternatively you can specify a one-off base as a parameter to the
     abs() method.

     Some older parsers used to allow the scheme name to be present in the
     relative URL if it was the same as the base URL scheme.  RFC1808 says
     that this should be avoided, but you can enable this old behaviour by
     passing a TRUE value as the second argument to the abs() method.  The
     difference is demonstrated by the following examples:

          url("http:foo")->abs("http://host/a/b")     ==>  "http:foo"
          url("http:foo")->abs("http://host/a/b", 1)  ==>  "http:/host/a/foo"

     The rel() method will do the opposite transformation.

$url->as_string
     Returns a string representing the URL in its canonical form.  All
     unsafe characters will be escaped.  This method is overloaded as the
     perl "stringify" operator, which means that URLs can be used as
     strings in many contexts.

$url->base (*)
     Get/set the base URL associated with the current URI::URL object.  The
     base URL matters when you call the abs() method.

$url->clone
     Returns a copy of the current URI::URL object.

$url->crack
     Return a 9 element array with the following content:

          0: $url->scheme *)
          1: $url->user
          2: $url->password
          3: $url->host
          4: $url->port
          5: $url->epath
          6: $url->eparams
          7: $url->equery
          8: $url->frag

     All elements except *scheme* will be undefined if the corresponding
     URL part is not available.

     *Note:* The scheme (first element) returned by crack will aways be
     defined.  This is different from what the $url->scheme returns, since
     it will return undef for relative URLs.

$url->default_port
     Returns the default port number for the URL scheme that the URI::URL
     belongs too.

$url->eparams (*)
     Get/set the URL parameters in escaped form.

$url->epath (*)
     Get/set the URL path in escaped form.

$url->eq($other_url)
     Compare two URLs to decide if they match or not.  The rules for how
     comparison is made varies for different parts of the URLs; scheme and
     netloc comparison is case-insensitive, and escaped chars match their
     %XX encoding unless they are "reserved" or "unsafe".

$url->equery (*)
     Get/set the URL query string in escaped form.

$url->full_path
     Returns the string "/path;params?query".  This is the string that is
     passed to a remote server in order to access the document.

$url->frag (*)
     Get/set the fragment (unescaped)

$url->host (*)
     Get/set the host (unescaped)

$url->netloc (*)
     Get/set the network location in escaped form.  Setting the network
     location will affect 'user', 'password', 'host' and 'port'.

$url->params (*)
     Get/set the URL parameters (unescaped)

$url->password (*)
     Get/set the password (unescaped)

$url->path (*)
     Get/set the path (unescaped).  This method will croak if any of the
     path components in the return value contain the "/" character.  You
     should use the epath() method to be safe.

$url->path_components (*)
     Get/set the path using a list of unescaped path components.  The
     return value will loose the distinction beween '.' and '%2E'.  When
     setting a value, a '.' is converted to be a literal '.' and is
     therefore encoded as '%2E'.

$url->port (*)
     Get/set the network port (unescaped)

$url->rel([$base])
     Return a relative URL if possible.  This is the opposite of what the
     abs() method does.  For instance:

          url("http://www.math.uio.no/doc/mail/top.html",
              "http://www.math.uio.no/doc/linux/")->rel

     will return a relative URL with path set to "../mail/top.html" and
     with the same base as the original URL.

     If the original URL already is relative or the scheme or netloc does
     not match the base, then a copy of the original URL is returned.


     Prints a verbose presentation of the contents of the URL object to
     the specified file handle (default STDOUT).  Mainly useful for
     debugging.

$url->scheme (*)
     Get/set the scheme for the URL.

$url->query (*)
     Get/set the query string (unescaped).  This method will croak if the
     string returned contains both '+' and '%2B' or '=' together with '%3D'
     or '%26'.  You should use the equery() method to be safe.

$url->user (*)
     Get/set the URL user name (unescaped)

HTTP METHODS
============

For *http* URLs you may also access the query string using the keywords()
and the query_form() methods.  Both will croak if the query is not of the
correct format.  The encodings look like this:

     word1+word2+word3..        # keywords
     key1=val1&key2=val2...     # query_form

Note: These functions does not return the old value when they are used to
set a value of the query string.

$url->keywords (*)
     The keywords() method returns a list of unescaped strings.  The method
     can also be used to set the query string by passing in the keywords as
     individual arguments to the method.

$url->query_form (*)
     The query_form() method return a list of unescaped key/value pairs.
     If you assign the return value to a hash you might loose some values
     if the key is repeated (which it is allowed to do).

     This method can also be used to set the query sting of the URL like
     this:

          $url->query_form(foo => 'bar', foo => 'baz', equal => '=');

     If the value part of a key/value pair is a reference to an array, then
     it will be converted to separate key/value pairs for each value.  This
     means that these two calls are equal:

          $url->query_form(foo => 'bar', foo => 'baz');
          $url->query_form(foo => ['bar', 'baz']);

FILE METHODS
============

The *file* URLs implement the local_path() method that returns a path
suitable for access to files within the current filesystem.  These methods
can *not* be used to set the path of the URL.

$url->local_path
     This method is really just an alias for one of the methods below
     depending on what system you run on.

$url->unix_path
     Returns a path suitable for use on a Unix system.  This method will
     croak if any of the path segments contains a "/" or a NULL character.

$url->dos_path
     Returns a path suitable for use on a MS-DOS or MS-Windows system.

$url->mac_path
     Returns a path suitable for use on a Macintosh system.

$url->vms_path
     Returns a path suitable for use on a VMS system.  VMS is a trademark
     of Digital.

GOPHER METHODS
==============

The methods access the parts that are specific for the gopher URLs.  These
methods access different parts of the $url->path.

$url->gtype (*)
$url->selector (*)
$url->search (*)
$url->string (*)
NEWS METHODS
============

$url->group (*)
$url->article (*)
WAIS METHODS
============

The methods access the parts that are specific for the wais URLs.  These
methods access different parts of the $url->path.

$url->database (*)
$url->wtype (*)
$url->wpath (*)
MAILTO METHODS
==============

$url->address (*)
     The mail address can also be accessed with the netloc() method.

WHAT A URL IS NOT
=================

URL objects do not, and should not, know how to 'get' or 'put' the
resources they specify locations for, anymore than a postal address
'knows' anything about the postal system. The actual access/transfer
should be achieved by some form of transport agent class (see *Note
LWP/UserAgent: LWP/UserAgent,). The agent class can use the URL class, but
should not be a subclass of it.

COMPATIBILITY
=============

This is a listing incompatibilities with URI::URL version 3.x:

unsafe(), escape() and unescape()
     These methods not supported any more.

full_path() and as_string()
     These methods does no longer take a second argument which specify the
     set of characters to consider as unsafe.

'+' in the query-string
     The '+' character in the query part of the URL was earlier considered
     to be an encoding of a space. This was just bad influence from Mosaic.
     Space is now encoded as '%20'.

path() and query()
     This methods will croak if they loose information.  Use epath() or
     equery() instead.  The path() method will for instance loose
     information if any path segment contain an (encoded) '/' character.

     The path() now consider a leading '/' to be part of the path.  If the
     path is empty it will default to '/'.  You can get the old behaviour
     by setting $URI::URL::COMPAT_VER_3 to TRUE before accessing the path()
     method.

netloc()
     The string passed to netloc is now assumed to be escaped.  The string
     returned will also be (partially) escaped.

sub-classing
     The path, params and query is now stored internally in unescaped form.
     This might affect sub-classes of the URL scheme classes.

AUTHORS / ACKNOWLEDGMENTS
=========================

This module is (distantly) based on the `wwwurl.pl' code in the
libwww-perl distribution developed by Roy Fielding <fielding@ics.uci.edu>,
as part of the Arcadia project at the University of California, Irvine,
with contributions from Brooks Cutter.

Gisle Aas <aas@sn.no>, Tim Bunce <Tim.Bunce@ig.co.uk>, Roy Fielding
<fielding@ics.uci.edu> and Martijn Koster <m.koster@webcrawler.com> (in
English alphabetical order) have collaborated on the complete rewrite for
Perl 5, with input from other people on the libwww-perl mailing list.

If you have any suggestions, bug reports, fixes, or enhancements, send
them to the libwww-perl mailing list at <libwww-perl@ics.uci.edu>.

COPYRIGHT
=========

Copyright 1995-1996 Gisle Aas.  Copyright 1995 Martijn Koster.

This program is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.


File: pm.info,  Node: VRML,  Next: VRML/VRML1,  Prev: URI/URL,  Up: Module List

implements VRML primitives and extensions
*****************************************

NAME
====

VRML.pm - implements VRML primitives and extensions

SYNOPSIS
========

     use VRML;

     $vrml = new VRML (1.0);
     $vrml->browser('Live3D');
     $vrml->cube('5 3 1','-50 -10 0','yellow');
     $vrml->print;
     
     OR with the same result
     
     use VRML;

     VRML
     ->version(1.0)
     ->browser('Live3D')
     ->cube('5 3 1','-50 -10 0','yellow')
     ->print;

DESCRIPTION
===========

   * $VRML::content_type; # for CGI scripts only

     content_type is `'x-world/x-vrml'' for VRML 1.0 and 1.1

     or `'model/vrml'' for VRML 2.0

SEE ALSO
========

VRML::VRML1

VRML::VRML1::Standard

AUTHOR
======

Hartmut Palm `<palm@gfz-potsdam.de>'


File: pm.info,  Node: VRML/VRML1,  Next: VRML/VRML1/Standard,  Prev: VRML,  Up: Module List

implements VRML methods with the VRML 1.x standard
**************************************************

NAME
====

VRML::VRML1.pm - implements VRML methods with the VRML 1.x standard

SYNOPSIS
========

     use VRML::VRML1;

DESCRIPTION
===========

Following functions are currently implemented.

   * begin(['comment']); `  . . . '

   * end(['comment']);

   * backgroundcolor('color');

   * backgroundimage('URL');

   * info('string');

   * cameras_begin('whichCameraNumber');

   * camera_set('positionXYZ','orientationXYZ',heightAngle); // persp.
     cameras

   * camera('positionXYZ','orientationXYZ',heightAngle); // persp. camera

   * anchor_begin('URL','description','parameter');

   * spin_begin('axisXYZ','degree'); // Live3D only

   * text('string','transformation','material','size style family');

   * cube('width [height [depth]]','transformation','material');

   * cylinder('radius [height]','transformation','material');

   * tube('radius height','transformation','material');

   * disk(radius,'transformation','material');

   * cone('radius height','transformation','material');

   * sphere('radius_x [radius_y radius_z]','transformation','material');

   * line('fromXYZ','toXYZ',radius,'material','[x][y][z]');

   * transform('type=value ; ...');

     *Where type can be:*

          t = translation
          r = rotation
          c = center
          o = scaleOrientation
          f = scaleFactor

   * material('type=value1,value2 ; ...');

     *Where type can be:*

          a = ambientColor
          d = diffuseColor
          e = emissiveColor
          s = specularColor
          sh = shininess
          tr = transparency
          tex = texture filename[,wrapS[,wrapT]]

     *and color values see VRML::Color*


File: pm.info,  Node: VRML/VRML1/Standard,  Next: WWW/RobotRules,  Prev: VRML/VRML1,  Up: Module List

implements nodes the VRML 1.x standard
**************************************

NAME
====

VRML::VRML1::Standard.pm - implements nodes the VRML 1.x standard

SYNOPSIS
========

     use VRML::VRML1::Standard;

DESCRIPTION
===========

Following nodes are currently implemented.

[`Group Nodes'] [Geometry Nodes] [Property Nodes]

[Appearance Nodes] [Transform Nodes] [Common Nodes]

Group Nodes These nodes NEED End !
----------------------------------

Separator
     `Separator($comment)'

Switch
     `Switch($comment)'

Group
     `Group($comment)'

WWWAnchor
     `WWWAnchor($url, $description, $target)'

     $target works only with *Live3D*

LOD
     `LOD($range, $center)'

     $range is a string with comma separated values

     example: `LOD('1, 2, 5', '0 0 0')'

SpinGroup
     `SpinGroup($axis, $radians)' is supported only be *Live3D*

Geometry Nodes
--------------

AsciiText
     `AsciiText($string, $width, $justification, $spacing)'

     $justification is a string ('LEFT','CENTER','RIGHT')

Cone
     `Cone($radius, $height, @parts)'

     @parts is a list of strings ('SIDES', 'BOTTOM', 'ALL')

Cube
     `Cube($width, $height, $depth)'

Cylinder
     `Cylinder($height, $radius, @parts)'

     @parts is a list of strings ('SIDES', 'TOP', 'BOTTOM', 'ALL')

IndexedFaceSet
     `IndexedFaceSet($coordIndex_ref, $materialIndex_ref,
     $normalIndex_ref, $textureCoordIndex_ref)'

     $coordIndex_ref is a reference of a list of point index strings like
     `'0 1 3 2', '2 3 5 4', ...'

     $materialIndex_ref is a reference of a list of materials

     $normalIndex_ref is a reference of a list of normals

     $textureCoordIndex_ref is a reference of a list of textures

IndexedLineSet
     `IndexedLineSet($coordIndex_ref, $materialIndex_ref,
     $normalIndex_ref, $textureCoordIndex_ref)'

     $coordIndex_ref is a reference of a list of point index strings like
     `'0 1 3 2', '2 3 5 4', ...'

     $materialIndex_ref is a reference of a list of materials

     $normalIndex_ref is a reference of a list of normals

     $textureCoordIndex_ref is a reference of a list of textures

PointSet
     `PointSet($numPoints, $startIndex)'

Sphere
     `Sphere($radius)'

     $radius have to be > 0

Property Nodes
--------------

Coordinate3
     `Coordinate3(@points)'

     @points is a list of points with strings like `'1.0 0.0 0.0', '-1 2
     0''

Fontstyle
     `FontStyle($size, $style, $family)' defines the current font style
     for all subsequent AsciiText

     $style can be 'NONE','BOLD','ITALIC'

     $familiy can be 'SERIF','SANS','TYPEWRITER'

Appearance Nodes
----------------

Material
     `Material(%materials)'

MaterialBinding
     `MaterialBinding($value)'

     $value can be

          DEFAULT	Use default bindng
          OVERALL	Whole object has same material
          PER_PART	One material for each part of object
          PER_PART_INDEXED	One material for each part, indexed
          PER_FACE	One material for each face of object
          PER_FACE_INDEXED	One material for each face, indexed
          PER_VERTEX	One material for each vertex of object
          PER_VERTEX_INDEXED	One material for each vertex, indexed

Normal
     `Normal(@vector)'

     @vector is a list of vectors with strings like `'1.0 0.0 0.0', '-1 2
     0''

NormalBinding
     `NormalBinding($value)'

     $value is the same as MaterialBinding

Texture2
     `Texture2($value)'

Transform Nodes
---------------

Transform
     `Transform($translation, $rotation, $scaleFactor, $scaleOrientation,
     $center)'

     $translation is a string like "0 1 -2"

     $rotation is a string like "0 0 1 1.57"

     $scaleFactor is a string like "1 1 1"

     $scaleOrientation is a string like "0 0 1 0"

     $center is a string like "0 0 0"

Rotation
     `Rotation($rotation)'

     $rotation is a string like "0 0 1 1.57"

     This node is not supported under VRML 2.0

     use Transform

Scale
     `Scale($scaleFactor)'

     $scaleFactor is a string like "1 1 1"

     This node is not supported under VRML 2.0

     use Transform

Translation
     `Translation($translation)'

     $translation is a string like "0 1 -2"

     This node is not supported under VRML 2.0

     use Transform

Common Nodes
------------

PerspectiveCamera
     `PerspectiveCamera($position, $orientation, $heightAngle,
     $focalDistance, $nearDistance, $farDistance)'

OrthographicCamera
     `OrthographicCamera($position, $orientation, $height, $focalDistance,
     $nearDistance, $farDistance)'

DirectionalLight
     `DirectionalLight($direction, $intensity, $ambientIntensity, $color,
     $on)'

PointLight
     `PointLight($location, $intensity, $color, $on)'

SpotLight
     `SpotLight($location, $direction, $intensity, $color, $on)'

other
-----

WWWInline
     `WWWInline($name, $bboxSize, $bboxCenter)'

Info
     `Info($string, $comment)'

     $comment is optional

DEF
     `DEF($name)'

USE
     `USE($name)'

End
     `End($comment)'

     $comment is optional

AUTHOR
======

Hartmut Palm `<palm@gfz-potsdam.de>'


File: pm.info,  Node: WWW/RobotRules,  Next: WWW/RobotRules/AnyDBM_File,  Prev: VRML/VRML1/Standard,  Up: Module List

Parse robots.txt files
**********************

NAME
====

WWW::RobotsRules - Parse robots.txt files

SYNOPSIS
========

     require WWW::RobotRules;
     my $robotsrules = new WWW::RobotRules 'MOMspider/1.0';

     use LWP::Simple qw(get);

     $url = "http://some.place/robots.txt";
     my $robots_txt = get $url;
     $robotsrules->parse($url, $robots_txt);

     $url = "http://some.other.place/robots.txt";
     my $robots_txt = get $url;
     $robotsrules->parse($url, $robots_txt);

     # Now we are able to check if a URL is valid for those servers that
     # we have obtained and parsed "robots.txt" files for.
     if($robotsrules->allowed($url)) {
         $c = get $url;
         ...
     }

DESCRIPTION
===========

This module parses a `robots.txt' file as specified in "A Standard for
Robot Exclusion", described in
<URL:http://info.webcrawler.com/mak/projects/robots/norobots.html>
Webmasters can use the `robots.txt' file to disallow conforming robots
access to parts of their WWW server.

The parsed file is kept in the WWW::RobotRules object, and this object
provide methods to check if access to a given URL is prohibited.  The same
WWW::RobotRules object can parse multiple `robots.txt' files.

METHODS
=======

$rules = new WWW::RobotRules 'MOMspider/1.0'
--------------------------------------------

This is the constructor for WWW::RobotRules objects.  The first argument
given to new() is the name of the robot.

$rules->parse($url, $content, $fresh_until)
-------------------------------------------

The parse() method takes as arguments the URL that was used to retrieve
the `/robots.txt' file, and the contents of the file.

$rules->allowed($url)
---------------------

Returns TRUE if this robot is allowed to retrieve this URL.

$rules->agent([$name])
----------------------

Get/set the agent name. NOTE: Changing the agent name will clear the
robots.txt rules and expire times out of the cache.

ROBOTS.TXT
==========

The format and semantics of the "/robots.txt" file are as follows (this is
an edited abstract of
<URL:http://info.webcrawler.com/mak/projects/robots/norobots.html>):

The file consists of one or more records separated by one or more blank
lines. Each record contains lines of the form

     <field-name>: <value>

The field name is case insensitive.  Text after the '#' character on a
line is ignored during parsing.  This is used for comments.  The following
<field-names> can be used:

User-Agent
     The value of this field is the name of the robot the record is
     describing access policy for.  If more than one *User-Agent* field is
     present the record describes an identical access policy for more than
     one robot. At least one field needs to be present per record.  If the
     value is '*', the record describes the default access policy for any
     robot that has not not matched any of the other records.

Disallow
     The value of this field specifies a partial URL that is not to be
     visited. This can be a full path, or a partial path; any URL that
     starts with this value will not be retrieved

Examples
--------

The following example "/robots.txt" file specifies that no robots should
visit any URL starting with "/cyberworld/map/" or "/tmp/":

     # robots.txt for http://www.site.com/

     User-agent: *
     Disallow: /cyberworld/map/ # This is an infinite virtual URL space
     Disallow: /tmp/ # these will soon disappear

This example "/robots.txt" file specifies that no robots should visit any
URL starting with "/cyberworld/map/", except the robot called
"cybermapper":

     # robots.txt for http://www.site.com/

     User-agent: *
     Disallow: /cyberworld/map/ # This is an infinite virtual URL space

     # Cybermapper knows where to go.
     User-agent: cybermapper
     Disallow:

This example indicates that no robots should visit this site further:

     # go away
     User-agent: *
     Disallow: /

SEE ALSO
========

*Note LWP/RobotUA: LWP/RobotUA,, *Note WWW/RobotRules/AnyDBM_File:
WWW/RobotRules/AnyDBM_File,


File: pm.info,  Node: WWW/RobotRules/AnyDBM_File,  Next: WWW/Search,  Prev: WWW/RobotRules,  Up: Module List

Persistent RobotRules
*********************

NAME
====

WWW::RobotRules::AnyDBM_File - Persistent RobotRules

SYNOPSIS
========

     require WWW::RobotRules::AnyDBM_File;
     require LWP::RobotUA;

     # Create a robot useragent that uses a diskcaching RobotRules
     my $rules = new WWW::RobotRules::AnyDBM_File 'my-robot/1.0', 'cachefile';
     my $ua = new WWW::RobotUA 'my-robot/1.0', 'me@foo.com', $rules;

     # Then just use $ua as usual
     $res = $ua->request($req);

DESCRIPTION
===========

This is a subclass of *WWW::RobotRules* that uses the AnyDBM_File package
to implement persistent diskcaching of `robots.txt' and host visit
information.

The constructor (the new() method) takes an extra argument specifying the
name of the DBM file to use.  If the DBM file already exists, then you can
specify undef as agent name as the name can be obtained from the DBM
database.

SE ALSO
=======

*Note WWW/RobotRules: WWW/RobotRules,, *Note LWP/RobotUA: LWP/RobotUA,

AUTHORS
=======

Hakan Ardo <hakan@munin.ub2.lu.se>, Gisle Aas <aas@sn.no>


File: pm.info,  Node: WWW/Search,  Next: WWW/Search/AltaVista,  Prev: WWW/RobotRules/AnyDBM_File,  Up: Module List

Virtual base class for WWW searches
***********************************

NAME
====

WWW::Search - Virtual base class for WWW searches

DESCRIPTION
===========

This class is the parent for all access method supported by the
`WWW::Search' library.

Search results are limited and there is a pause between each request for
results to avoid overloading either the client or the server.

Sample program
--------------

Using the library should be straightforward: Here's a sample program:

     my($search) = new WWW::Search::AltaVista;
     $search->native_query(WWW::Search::escape_query($query));
     my($result);
     while ($result = $search->next_result()) {
     	print $result->url, "\n";
     };

Results are objects of `WWW::SearchResult' (see *Note WWW/SearchResult:
WWW/SearchResult,) .

SEE ALSO
========

For more details see *Note LWP: LWP,.

METHODS AND FUNCTIONS
=====================

new
---

To create a new WWW::Search, call     $search = new
WWW::Search::SearchEngineName(); where SearchEngineName is replaced with a
particular search engine.  For example:     $search = new
WWW::Search::AltaVista();

The next step is usually:
$search->native_query('search-engine-specific query string');

native_query
------------

Specify a query to the current search object.  The query must be escaped;
call `escape_query', *Note WWW/Search: WWW/Search, to escape a plain query.
Doesn't actually begin the search until results or next_result is called.

Example:     $search->native_query('search-engine-specific query string');

The next step is usually:

     @results = $search->results();

or

     while ($result = $search->next_result()) {
     	# do_something;
     };

results
-------

Return all the results of a query as a reference to array of SearchResult
objects.

Example:     @results = $search->results();     foreach $result (@results)
{         print $result->url(), "\n";     };

next_result
-----------

Return each result of a query as a SearchResult object.

Example:     while ($result = $search->next_result()) { 	print
$result->url(), "\n";     };

`seek_result($offset)'
----------------------

Set which result next_result should return (like lseek in Unix).  Results
are zero-indexed.

The only guaranteed valid offset is 0 which will replay the results from
the beginning.  In particular, seeking past the end of the current cached
results probably won't do what you might think it should.

Results are cached, so this doesn't re-issue the query or cause IO (unless
you go off the end of the results).  To re-do the query, create a new
search object.

Example:     $search->seek_result(0);

maximum_to_retrieve
-------------------

The maximum number of hits to return (approximately).  Queries resulting
in more than this many hits will return the first hits, up to this limit.

Defaults to 500.

Example:     $max = $seach->maximum_to_retrieve(100);

escape_query
------------

Escape a query.  Before queries are made special characters must be escaped
so that a proper URL can be formed.

This is like escaping a URL but "+" is a protected character and spaces
are converted to "+"'s.

Example:     $escaped = Search::escape_query('+lsam +replication');
(Returns "%22lsam+replication%22").

See also unescape_query.

unescape_query
--------------

Unescape a query.  See escape_query for details.

Example:     $unescaped = Search::unescape_query('%22lsam+replication%22');
(Returns "+lsam +replication").

See also unescape_query.

setup_search (PRIVATE)
----------------------

This internal routine does generic Search setup.  It calls
`native_setup_search' to do back-end specific setup.

setup_user_agent (PRIVATE, NOT A METHOD)
----------------------------------------

This internal routine does setup for a user-agent for dervived classes
that use the web.

user_agent_delay (PRIVATE)
--------------------------

Derived classes should call this between requests to remote servers to
avoid overloading them with many, fast back-to-back requests.

retrieve_some (PRIVATE)
-----------------------

An internal routine to interface with `native_retrieve_some'.  Checks for
overflow.

IMPLEMENTING NEW BACK-ENDS
==========================

`WWW::Search' supports back-ends to separate search engines.  Each
back-end is implemented as a subclass of `WWW::Search'.  *Note
WWW/Search/AltaVista: WWW/Search/AltaVista, provides a good sample
back-end.

A back-end usually has two routines, `native_retrieve_some' and
`native_setup_search'.

`native_retrieve_some' is the core of a back-end.  It will be called
periodically to fetch URLs.  Each call it should fetch a page with about
10 or so hits and add them to the cache.  It should return the number of
hits found or undef when there are no more hits.

Internally, `native_retrieve_some' typically will parse the HTML, extract
the links and descriptions, then find the ``next'' button and save the URL.
See the code for the AltaVista implementation for an example.

`native_setup_search' is invoked before the search.  It is passed a single
argument:  the escaped, native version of the query.

The front- and back-ends share a single object (a hash) The back-end can
change any hash element beginning with underscore, and `{response}' (an
`HTTP::Response' code) and `{cache}' (the array of `WWW::SearchResult'
objects caching all results).

If you implement a new back-end, please let the authors know.

AUTHOR
======

`WWW::Search' is written by John Heidemann, <johnh@isi.edu>.

COPYRIGHT
=========

Copyright (c) 1996 University of Southern California.  All rights reserved.

Redistribution and use in source and binary forms are permitted provided
that the above copyright notice and this paragraph are duplicated in all
such forms and that any documentation, advertising materials, and other
materials related to such distribution and use acknowledge that the
software was developed by the University of Southern California,
Information Sciences Institute.  The name of the University may not be
used to endorse or promote products derived from this software without
specific prior written permission.

THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.


File: pm.info,  Node: WWW/Search/AltaVista,  Next: WWW/SearchResult,  Prev: WWW/Search,  Up: Module List

class for searching Alta Vista
******************************

NAME
====

WWW::Search::AltaVista - class for searching Alta Vista

DESCRIPTION
===========

This class is an AltaVista specialization of WWW::Search.  It handles
making and interpreting AltaVista searches
`http://www.altavista.digital.com'.

This class exports no public interface; all interaction should be done
through WWW::Search objects.

SEE ALSO
========

To make new back-ends, see *Note WWW/Search: WWW/Search,.

HOW DOES IT WORK?
=================

`native_setup_search' is called before we do anything.  It initializes our
private variables (which all begin with underscores) and sets up a URL to
the first results page in `{_next_url}'.

`native_retrieve_some' is called (from `WWW::Search::retrieve_some')
whenever more hits are needed.  It calls the LWP library to fetch the page
specified by `{_next_url}'.  It parses this page, appending any search
hits it finds to `{cache}'.  If it finds a ``next'' button in the text, it
sets `{_next_url}' to point to the page for the next set of results,
otherwise it sets it to undef to indicate we're done.

AUTHOR
======

`WWW::Search' is written by John Heidemann, <johnh@isi.edu>.

COPYRIGHT
=========

Copyright (c) 1996 University of Southern California.  All rights reserved.

Redistribution and use in source and binary forms are permitted provided
that the above copyright notice and this paragraph are duplicated in all
such forms and that any documentation, advertising materials, and other
materials related to such distribution and use acknowledge that the
software was developed by the University of Southern California,
Information Sciences Institute.  The name of the University may not be
used to endorse or promote products derived from this software without
specific prior written permission.

THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.


File: pm.info,  Node: WWW/SearchResult,  Next: Xbase,  Prev: WWW/Search/AltaVista,  Up: Module List

class for results returned from WWW::Search
*******************************************

NAME
====

WWW::SearchResult - class for results returned from WWW::Search

DESCRIPTION
===========

A framework for returning the results of `WWW::Search'.

SEE ALSO
========

*Note WWW/Search: WWW/Search,

METHODS AND FUNCTIONS
=====================

new
---

To create a new WWW::SearchResult, call     $search = new
WWW::SearchResult();

url
---

Return url.  Note that there may be a list of urls, see also methods urls
and add_url.

urls
----

Return a reference to an array of urls.  There is also a distinguished URL
(url).  See also add_url.

add_url
-------

Add a URL to the list.

title, description
------------------

Set or get attributes of the result.  In the future, these attributes
might expand to include size and change-date.


File: pm.info,  Node: Xbase,  Next: diagnostics,  Prev: WWW/SearchResult,  Up: Module List

Perl Module to Read Xbase DBF Files and Foxpro IDX indexes
**********************************************************

NAME
====

Xbase - Perl Module to Read Xbase DBF Files and Foxpro IDX indexes

ABSTRACT
========

This is a perl module to access xbase files with simple IDX indexes.  At
the moment only read access to the files are provided by this package
Writing is tougher with IDX updates etc and is being worked on. Since the
read functionality is useful in itself this version is being released.

INSTALLATION
============

To install this package, change to the directory where this file is present
and type

     perl Makefile.PL
     make
     make install

This will copy Xbase.pm to the perl library directory provided you have the
permissions to do so. To use the module in your programs you will use the
line:

     use Xbase;

If you cannot install it in the system directory, put it whereever you like
and tell perl where to find it by using the following in the beginning of
your script:

     BEGIN {
     	unshift(@INC,'/usr/underprivileged/me/lib');
     }
     use Xbase;

DESCRIPTION
===========

The various methods that are supported by this module are given below.
There is a very distinct xbase like flavour to most of the commands.

CREATING A NEW XBASE OBJECT:
----------------------------

     $database = new Xbase;

This will create an object $database that will be used to interact with the
various methods the module provides.

OPENING A DATABASE
------------------

     $database->open_dbf($dbf_name, $idx_name);

Associates the DBF file and optionally the IDX file with the object. It
opens the files and if a associated MEMO file is present automatically
opens it. Only Foxpro Memo files are currently supported and assumes the
same filename as the DBF with a FPT extension.

DATABASE TYPE
-------------

     print $database->dbf_type;

Returns a string telling you if the xbase file opened is DBF3, DBF4 or FOX

LAST UPDATE DATE
----------------

     print $database->last_update;

Returns a date string telling you when the database was last updated.

LAST RECORD NUMBER
------------------

     $end=$database->lastrec;

Returns the record number of the last record in the database file.

DATABASE STATUS INFORMATION
---------------------------

     $database->dbf_stat;

This prints out on to STDOUT a display of the status/structure of the
database. It is similar to the xbase command DISPLAY STATUS. Since it
prints field names and structure it is commonly used to see if the module
is reading the database as intended and finding out the field names.

INDEX FILE STATUS INFORMATION
-----------------------------

     $database->idx_stat;

Prints on to STDOUT the status information of an open IDX file.

GO TOP
------

     $database->go_top;

Moves the record pointer to the top of the database. Physical top of
database if no index is present else first record according to index order.

GO BOTTOM
---------

     $database->go_bottom;

Moves the record pointer to the bottom of the database. Physical bottom of
database if no index is present else last record according to index order.

GO NEXT
-------

     $database->go_next;

Equivalent to the xbase command SKIP 1 which moves the record pointer to
the next record.

GO PREVIOUS
-----------

     $database->go_prev;

Equivalent to the xbase command SKIP -1 which moves the record pointer to
the previous record.

SEEK
----

     $stat=$database->seek($keyvalue);

This command positions the record pointer on the first matching record that
has the key value specified. The database should be opened with an
associated index. Seek without an available index will print an error
message and abort. The return value indicates whether the key value was
found or not.

RECORD NUMBER
-------------

     $current_rec=$database->recno;

Returns the record number that the record pointer is currently at.

BEGINNING OF FILE
-----------------

     if ($database->bof) {
     	print "At the very top of the file \n";
     }

Tells you whether you are at the beginning of the file. Like in xbase it is
not true when you are at record number one but rather it is set when you
try to $database->go_prev when you are at the top of the file.

END OF FILE   	if ($database->eof) { 		print "At the very end of the file \n"; 	}
---------------------------------------------------------------------------------

Tells you whether you are at the end of the file. Like in xbase it is not
true when you are at the last record but rather it is set when you try to
$database->go_next from the last record.

READ INDIVIDUAL FIELD VALUES
----------------------------

     print $database->get_field("NAME");

Returns as a string the contents of a field name specified from the current
record. Using the pseudo field name _DELETED will tell you if the current
record is marked for deletion.

READ FIELD VALUES INTO ARRAY
----------------------------

     @fields = $database->get_record;

Returns as an array all the fields from the current record. The fields are
in the same order as in the database.

CLOSE DATABASE
--------------

     $database->close_dbf;

This closes the database files, index files and memo files that are
associated with the $database object with $database->open_dbf

COPYRIGHT
=========

Copyright (c) 1995 Pratap Pereira. All rights reserved.  This program is
free software; you can redistribute it and/or modify it under the same
terms as Perl itself.

I request that if you use this module at a web site to make a link to

	http://eewww.eng.ohio-state.edu/~pereira/software/xbase/

This is just so that others might find it. This is however not required of
you.

AUTHOR INFORMATION
==================

Please send your comments, suggestions, gripes, bug-reports to

     Pratap Pereira
     pereira@ee.eng.ohio-state.edu

UPDATE HISTORY
==============

Original perl 4 script done in March 1994
Perl 5 module done in February 1995
RELEASE 2 was first public release now called xbase12.pm
RELEASE 3 was done 6/22/95 called xbase13.pm
          Fixed problem with GO_PREV & GO_NEXT after SEEK.
          Fixed problem with parsing headers of dbfs with
                  record length > 255.
          Added Memo file support.

RELEASE 4 was done 9/29/95
          Fixed problem with certain IDX failing completely,
                  was a stupid
          indexing mistake.

RELEASE 5 was done 11/14/95 (called xbase.pm 1.05)
          Fixed field length inconsistency errors by changing
                  way header is decoded. Should work with more xbase
                  variants. (Dick Sutton & Andrew Vasquez)

Version 1.06  was done 11/17/95
          Added binmode command to file handles to support
          Windows NT

Version 1.07 was done 01/23/96
          Made documentation in pod format, installation
                  automated. Fixed problem with deleted status being
                  improperly read (Chung Huynh). Renamed to Xbase
                  (previously xbase) to be consistent with other perl
                  modules. Released in CPAN.
          Prettied up dbf_stat output (Gilbert Ramirez).

CREDITS
=======

Thanks are due to Chung Huynh (chuynh@nero.finearts.uvic.ca), Jim Esposito
(jgespo@exis.net), Dick Sutton (suttond@federal.unisys.com), Andrew
Vasquez (praka@ophelia.fullcoll.edu), Leonard Samuelson
(lcs@synergy.smartpages.com) and Gilbert Ramirez Jr
(gram@merece.uthscsa.edu)


File: pm.info,  Node: diagnostics,  Next: gettext,  Prev: Xbase,  Up: Module List

Perl compiler pragma to force verbose warning diagnostics
*********************************************************

NAME
====

diagnostics - Perl compiler pragma to force verbose warning diagnostics

splain - standalone program to do the same thing

SYNOPSIS
========

As a pragma:

     use diagnostics;
     use diagnostics -verbose;

     enable  diagnostics;
     disable diagnostics;

Aa a program:

     perl program 2>diag.out
     splain [-v] [-p] diag.out

DESCRIPTION
===========

The diagnostics Pragma
----------------------

This module extends the terse diagnostics normally emitted by both the
perl compiler and the perl interpeter, augmenting them with the more
explicative and endearing descriptions found in *Note Perldiag:
(perl.info)perldiag,.  Like the other pragmata, it affects the compilation
phase of your program rather than merely the execution phase.

To use in your program as a pragma, merely invoke

     use diagnostics;

at the start (or near the start) of your program.  (Note that this *does*
enable perl's -w flag.)  Your whole compilation will then be subject(ed
:-) to the enhanced diagnostics.  These still go out *STDERR*.

Due to the interaction between runtime and compiletime issues, and because
it's probably not a very good idea anyway, you may not use `no
diagnostics' to turn them off at compiletime.  However, you may control
there behaviour at runtime using the disable() and enable() methods to
turn them off and on respectively.

The *-verbose* flag first prints out the *Note Perldiag:
(perl.info)perldiag, introduction before any other diagnostics.  The
$diagnostics::PRETTY variable can generate nicer escape sequences for
pagers.

The *splain* Program
--------------------

While apparently a whole nuther program, *splain* is actually nothing more
than a link to the (executable) `diagnostics.pm' module, as well as a link
to the `diagnostics.pod' documentation.  The -v flag is like the `use
diagnostics -verbose' directive.  The -p flag is like the
$diagnostics::PRETTY variable.  Since you're post-processing with
*splain*, there's no sense in being able to enable() or disable()
processing.

Output from *splain* is directed to *STDOUT*, unlike the pragma.

EXAMPLES
========

The following file is certain to trigger a few errors at both runtime and
compiletime:

     use diagnostics;
     print NOWHERE "nothing\n";
     print STDERR "\n\tThis message should be unadorned.\n";
     warn "\tThis is a user warning";
     print "\nDIAGNOSTIC TESTER: Please enter a <CR> here: ";
     my $a, $b = scalar <STDIN>;
     print "\n";
     print $x/$y;

If you prefer to run your program first and look at its problem
afterwards, do this:

     perl -w test.pl 2>test.out
     ./splain < test.out

Note that this is not in general possible in shells of more dubious
heritage, as the theoretical

     (perl -w test.pl >/dev/tty) >& test.out
     ./splain < test.out

Because you just moved the existing *stdout* to somewhere else.

If you don't want to modify your source code, but still have on-the-fly
warnings, do this:

     exec 3>&1; perl -w test.pl 2>&1 1>&3 3>&- | splain 1>&2 3>&-

Nifty, eh?

If you want to control warnings on the fly, do something like this.  Make
sure you do the use first, or you won't be able to get at the enable() or
disable() methods.

     use diagnostics; # checks entire compilation phase
     	print "\ntime for 1st bogus diags: SQUAWKINGS\n";
     	print BOGUS1 'nada';
     	print "done with 1st bogus\n";

     disable diagnostics; # only turns off runtime warnings
     	print "\ntime for 2nd bogus: (squelched)\n";
     	print BOGUS2 'nada';
     	print "done with 2nd bogus\n";

     enable diagnostics; # turns back on runtime warnings
     	print "\ntime for 3rd bogus: SQUAWKINGS\n";
     	print BOGUS3 'nada';
     	print "done with 3rd bogus\n";

     disable diagnostics;
     	print "\ntime for 4th bogus: (squelched)\n";
     	print BOGUS4 'nada';
     	print "done with 4th bogus\n";

INTERNALS
=========

Diagnostic messages derive from the `perldiag.pod' file when available at
runtime.  Otherwise, they may be embedded in the file itself when the
splain package is built.   See the `Makefile' for details.

If an extant $SIG{__WARN__} handler is discovered, it will continue to be
honored, but only after the diagnostics::splainthis() function (the
module's $SIG{__WARN__} interceptor) has had its way with your warnings.

There is a $diagnostics::DEBUG variable you may set if you're desperately
curious what sorts of things are being intercepted.

     BEGIN { $diagnostics::DEBUG = 1 }

BUGS
====

Not being able to say "no diagnostics" is annoying, but may not be
insurmountable.

The `-pretty' directive is called too late to affect matters.  You have to
to this instead, and *before* you load the module.

     BEGIN { $diagnostics::PRETTY = 1 }

I could start up faster by delaying compilation until it should be needed,
but this gets a "panic: top_level" when using the pragma form in 5.001e.

While it's true that this documentation is somewhat subserious, if you use
a program named *splain*, you should expect a bit of whimsy.

AUTHOR
======

Tom Christiansen `<tchrist@mox.perl.com>', 25 June 1995.


File: pm.info,  Node: gettext,  Next: integer,  Prev: diagnostics,  Up: Module List

message handling functions
**************************

NAME
====

gettext - message handling functions

SYNOPSIS
========

     use gettext;
     use POSIX;     # Needed for setlocale()

     setlocale(LC_MESSAGES, "");
     textdomain("my_program");

     print gettext("Welcome to my program"), "\n";
             # (printed in the local language)

DESCRIPTION
===========

The gettext module permits access from perl to the gettext() family of
functions for retrieving message strings from databases constructed to
internationalize software.

gettext(), dgettext(), and dcgettext() attempt to retrieve a string
matching their `msgid' parameter within the context of the current locale.
dcgettext() takes the message's category and the text domain as parameters
while dcgettext() defaults to the LC_MESSAGES category and gettext()
defaults to LC_MESSAGES and uses the current text domain.  If the string
is not found in the database, then `msgid' is returned.

textdomain() sets the current text domain and returns the previously
active domain.

*bindtextdomain(domain, dirname)* instructs the retrieval functions to look
for the databases belonging to domain domain in the directory `dirname'

SEE ALSO
========

gettext(3i), gettext(1), msgfmt(1)

AUTHOR
======

Phillip Vandry <vandry@Mlink.NET>


File: pm.info,  Node: integer,  Next: iodbc,  Prev: gettext,  Up: Module List

Perl pragma to compute arithmetic in integer instead of double
**************************************************************

NAME
====

integer - Perl pragma to compute arithmetic in integer instead of double

SYNOPSIS
========

     use integer;
     $x = 10/3;
     # $x is now 3, not 3.33333333333333333

DESCRIPTION
===========

This tells the compiler that it's okay to use integer operations from here
to the end of the enclosing BLOCK.  On many machines, this doesn't matter
a great deal for most computations, but on those without floating point
hardware, it can make a big difference.

See `Pragmatic Modules', *Note Perlmod: (perl.info)perlmod,.


File: pm.info,  Node: iodbc,  Next: less,  Prev: integer,  Up: Module List

Perl extension for the iODBC API
********************************

NAME
====

iodbc - Perl extension for the iODBC API

SYNOPSIS
========

This man page is not intended to be a manual on the ODBC API.  Please see
an ODBC manual for extended documentation on the usage of ODBC commands.

To use iodbc functions:

`use iodbc;'

DESCRIPTION
===========

Everything in the extension follows the ODBC core API except that all
function calls are pass by value.  The one exception is SQLBindCol which
needs to be passed a reference to a scalar.  For More information please
seek a ODBC manual and remember that this extension only works with core
implementations.

Functions
---------

The following functions are included with this iodbc extension.
Parameters marked [i] are for input into the function while parameters
marked [r] return data from a function.

   * SQLAllocEnv

    Syntax
          `SQLAllocEnv($hEnv);'

    Parameters

          $hEnv


               [o]  The environment handle.  This will be passed to other
               functions.

   * SQLAllocConnect

    Syntax
          `SQLAllocConnect($hEnv, $hDbc);'

    Parameters

          $hEnv


               [i]  The environment handle as it is returned from
               `SQLAllocEnv()'.


          $hDbc


               [o]  The connection handle.  This will be passed to other
               functions.

   * SQLConnect

    Syntax
          `SQLConnect($hDbc, $pvDsn, $ivfDsnSize, $pvUid, $ivfUidSize,
          $pvPwd, $ivfPwdSize);'

    Parameters

          $hDbc


               [i]  The connection handle as it is returned from
               `SQLAllocConnect()'.


          $pvDsn


               [i]  The data source name.  This should be a string.


          $ivfDsnSize


               [i]  The size of $pvDsn.  It should be `SQL_NTS'.  This
               stands for a null terminated string.


          $pvUid


               [i]  The user id.  This should also be a string.


          $ivfUidSize


               [i]  The size of $pvUid.  It should also be `SQL_NTS'.


          $pvPwd


               [i]  The password.  Once again it should be a string.


          $ivfPwdSize


               [i]  The size of pvPwd.  Once again it should be `SQL_NTS'

   * SQLAllocStmt

    Syntax
          `SQLAllocStmt($hDbc, $hStmt);'

    Parameters

          $hDbc


               [i]  The connection handle as it is returned from
               `SQLAllocConnect()'.


          $hStmt


               [o]  The statement handle.  This will be passed to other
               functions.

   * SQLGetCursorName

    Syntax
          `SQLGetCursorName($hStmt, $pvCursor, $ivCursorMax,
          $ivCursorSize);'

    Parameters

          $hStmt


               [i]  The statement handle as it is returned from
               `SQLAllocStmt()'.


          $pvCursor


               [o]  The cursor name associated with the $hStmt.  This will
               be returned from the function as a string of maximum length
               $ivCursorMax.


          $ivCursorMax


               [i]  The maximum size of $ivCursor.


          $ivCursorSize


               [i]  The actual size of the string available for return to
               $pvCursor.

   * SQLSetCursorName

    Syntax
          `SQLSetCursorName($hStmt, $pvCursor, $ivfCursorSize);'

    Parameters

          $hStmt


               [i]  The statement handle as it is returned from
               `SQLAllocStmt()'.


          $pvCursor


               [i]  The Cursor Name to be associated with the $hStmt.
               This should be a string.


          $ivfCursorSize


               [i]  The size of $pvCursor.  This should be `SQL_NTS'.

   * SQLPrepare

    Syntax
          `SQLPrepare($hStmt, $pvSql, $ivfSqlSize);'

    Parameters

          $hStmt


               [i]  The statement handle as it is returned from
               `SQLAllocStmt()'.


          $pvSql


               [i]  The SQL statement to be prepared.  This should be a
               string.


          $ivfSqlSize


               [i]  The size of $Sql.  This should be `SQL_NTS'.

   * SQLExecute

    Syntax
          `SQLExecute($hStmt);'

    Parameters

          $hStmt


               [i]  The statement handle as it is returned from
               `SQLAllocStmt()'.

   * SQLExecDirect

    Syntax
          `SQLExecDirect($hStmt, $pvSql, $ivfSqlSize);'

    Parameters

          $hStmt


               [i]  The statement handle as it is returned from
               `SQLAllocStmt()'.


          $pvSql


               [i]  The SQL statement to be prepared.  This should be a
               string.


          $ivfSqlSize


               [i]  The size of $pvSql.  This should be `SQL_NTS'.

   * SQLRowCount

    Syntax
          `SQLRowCount($hStmt, $ivNumRows);'

    Parameters

          $hStmt


               [i]  The statement handle as it is returned from
               `SQLAllocStmt()'.


          $ivNumCols


               [o]  The number of rows affected by the SQL statement just
               executed in $hStmt.  This works for `UPDATE', `INSERT' and
               DELETE statements.

   * SQLNumResultCols

    Syntax
          `SQLNumResultCols($hStmt, $ivNumCols);'

    Parameters

          $hStmt


               [i]  The statement handle as it is returned from
               `SQLAllocStmt()'.


          $ivNumCols


               [o]  The Number of columns returned in a result set of a
               SQL statement in $hStmt.

   * SQLDescribeCol

    Syntax
          `SQLDescribeCol($hStmt, $ivCol, $pvColName, $ivColNameMax,
          $ivColNameSize, $fSqlType, $ivPrecision, $ivScale, $fNullable);'

    Parameters

          $hStmt


               [i]  The statement handle as it is returned from
               `SQLAllocStmt()'.


          $ivCol


               [i]  The function will return a description of this column.


          $pvColName


               [o]  A string that contains the name of column $ivCol


          $ivColNameMax


               [i]  The maximum size of the column name to return to
               $pvColName


          $ivColNameSize


               [o]  The size of the column name available to return to
               $pvColName


          $fSqlType


               [o]  The type of data contained in column $ivCol.


          $ivPrecision


               [o]  The precision of column $ivCol.


          $ivScale


               [o]  The scale of column $ivCol.


          $fNullable


               [o]  Returns whether column $ivCol allows null values.

   * SQLColAttributes

    Syntax
          `SQLColAttributes($hStmt, $ivCol, $fType, $pvAttrib,
          $ivAttribMax, $ivAttribSize, $ivAttrib);'

    Parameters

          $hStmt


               [i]  The statement handle as it is returned from
               `SQLAllocStmt()'.


          $ivCol


               [i]  The function will return a attributes from column
               $ivCol.


          $fType


               [i]  The type of attribute to return.


          $pvAttrib


               [o]  The attribute.   This will be returned from the
               function as a string.


          $ivAttribMax


               [i]  The maximum size of $pvAttrib


          $ivAttribSize


               [o]  The size of the attribute string available to return
               to $pvAttrib.


          $ivAttrib


               [o]  The attribute.  This will be returned as an integer.

   * SQLBindCol

    Syntax
          `SQLBindCol($hStmt, $ivCol, $fType, $svValue, $ivValueMax,
          $ivValueSize);'

    Parameters

          $hStmt


               [i]  The statement handle as it is returned from
               `SQLAllocStmt()'.


          $ivCol


               [i]  The function will bind this column.


          $fType


               [i]  The data type to bind.


          $svValue


               [i]  A reference to a scalar that will store the data from
               a result set.


          $ivValueMax


               [i]  The maximum size allowed for the scalar referenced by
               $svValue


          $ivValueSize


               [i]  Size available to return to the scalar referenced by
               $svValue before `SQLFetch()' is called.

   * SQLFetch

    Syntax
          `SQLFetch($hStmt);'

    Parameters

          $hStmt


               [i]  The statement handle as it is returned from
               `SQLAllocStmt()'.

    Notes
          `SQLFetch()' returns data from each bound column to the scalar
          that was referenced by the $svValue parameter when the
          `SQLBindCol()' function was called.

   * SQLError

    Syntax
          `SQLError($hfEnv, $hfDbc, $hfStmt, $pvSqlState, $fNativeError,
          $pvErrorMsg, $ivErrorMsgMax, $ivErrorMsgSize);'

    Parameters

          $hfEnv


               [i]  The environment handle as it is returned from
               `SQLAllocEnv()' or SQL_NULL_HENV.


          $hfDbc


               [i]  The connection handle as it is returned from
               `SQLAllocConnect()' or SQL_NULL_HDBC.


          $hfStmt


               [i]  The statement handle as it is returned from
               `SQLAllocStmt()' or SQL_NULL_HSTMT.


          $pvSqlState


               [o]  This returns the SQLSTATE as a string.


          $fNativeError


               [o]  This returns a Native Error Code.


          $pvErrorMsg


               [o]  This returns an Error Message as a string.


          $ivErrorMsgMax


               [i]  The maximum size of $pvErrorMsg


          $ivErrorMsgSize


               [o]  The size of the string available to return to
               $pvErrorMsg

   * SQLFreeStmt

    Syntax
          `SQLFreeStmt($hStmt, $fOption);'

    Parameters

          $hStmt


               [i]  The statement handle as it is returned from
               `SQLAllocStmt()'.


          $fOption


               [i]  The action to be taken by the function.

   * SQLCancel

    Syntax
          `SQLCancel($hStmt);'

    Parameters

          $hStmt


               [i]  The statement handle as it is returned from
               `SQLAllocStmt()'.

   * SQLTransact

    Syntax
          `SQLTransact($hEnv, $hDbc, $fType);'

    Parameters

          $hEnv


               [i]  The environment handle as it is returned from
               `SQLAllocEnv()'.


          $hDbc


               [i]  The connection handle as it is returned from
               `SQLAllocConnect'.


          $fType


               [i]  The type of transaction to take

   * SQLDisconnect

    Syntax
          `SQLDisconnect($hDbc);'

    Parameters

          $hDbc


               [i]  The connection handle as it is returned from
               `SQLAllocConnect()'.

   * SQLFreeConnect

    Syntax
          `SQLFreeConnect($hDbc);'

    Parameters

          $hDbc


               [i]  The connection handle as it is returned from
               `SQLAllocConnect()'.

   * SQLFreeEnv

    Syntax
          `SQLFreeEnv($hEnv);'

    Parameters

          $hEnv


               [i]  The connection handle as it is returned from
               `SQLAllocEnv()'.

EXAMPLES
========

`use iodbc;'

#

#To start I allocate handles and connect to my favorite data source.
Notice I check every return code.

`checkretcode(&SQLAllocEnv($henv));'

`checkretcode(SQLAllocConnect($henv, $hdbc));'

`checkretcode(SQLConnect($hdbc, "favorite_datsource", SQL_NTS, "user",
SQL_NTS, "password", SQL_NTS));'

`checkretcode(SQLAllocStmt($hdbc,$hstmt));'

#

#Then I execute a simple SQL statement

`checkretcode(SQLExecDirect($hstmt, "SELECT * FROM sample_table",
SQL_NTS));'

#Bind column one to $rgbValue

`checkretcode(SQLBindCol($hstmt, 1, SQL_C_DEFAULT, \$rgbValue, 24,
SQL_NULL_DATA));'

#Fetch all the rows and print them out

`while(checkretcode(SQLFetch($hstmt))==SQL_SUCCESS){'

`    print "$rgbValue\n";'

`}'

#

#Finally close up shop by freeing statements and disconnecting.

`checkretcode(SQLFreeStmt($hstmt, SQL_DROP));'

`checkretcode(SQLDisconnect($hdbc));'

`checkretcode(SQLFreeConnect($hdbc));'

`checkretcode(SQLFreeEnv($henv));'

#

#This subroutine checks the return code to make sure that the function
executed correctly

`sub checkretcode {'

`    my $retcode = shift;'

`    if (($retcode==SQL_SUCCESS)||($retcode==SQL_NO_DATA_FOUND)) {'

`	return $retcode;'

`    } else {'

`	die "some error";'

`    }'

`}'

TO DO
=====

   * Further testing.  In particular add `SQLCancel()' and `SQLTransact()'
     to the test scripts.

   * Add ODBC 1.0 and then ODBC 2.0 support.

   * Put an DBD/DBI face on top of iODBC.

   * Improvement of the documentation.

BUGS
====

Let me know if you find any.

AUTHOR
======

J. Michael Mahan, mahanm@nextwork.rose-hulman.edu

SEE ALSO
========

perl(1).


File: pm.info,  Node: less,  Next: lib,  Prev: iodbc,  Up: Module List

perl pragma to request less of something from the compiler
**********************************************************

NAME
====

less - perl pragma to request less of something from the compiler

SYNOPSIS
========

     use less;  # unimplemented

DESCRIPTION
===========

Currently unimplemented, this may someday be a compiler directive to make
certain trade-offs, such as perhaps

     use less 'memory';
     use less 'CPU';
     use less 'fat';


File: pm.info,  Node: lib,  Next: lwpcook,  Prev: less,  Up: Module List

manipulate @INC at compile time
*******************************

NAME
====

lib - manipulate @INC at compile time

SYNOPSIS
========

     use lib LIST;

     no lib LIST;

DESCRIPTION
===========

This is a small simple module which simplifies the manipulation of @INC at
compile time.

It is typically used to add extra directories to perl's search path so
that later use or require statements will find modules which are not
located on perl's default search path.

ADDING DIRECTORIES TO @INC
--------------------------

The parameters to `use lib' are added to the start of the perl search
path. Saying

     use lib LIST;

is *almost* the same as saying

     BEGIN { unshift(@INC, LIST) }

For each directory in LIST (called $dir here) the lib module also checks
to see if a directory called $dir/$archname/auto exists.  If so the
$dir/$archname directory is assumed to be a corresponding architecture
specific directory and is added to @INC in front of $dir.

If LIST includes both $dir and $dir/$archname then $dir/$archname will be
added to @INC twice (if $dir/$archname/auto exists).

DELETING DIRECTORIES FROM @INC
------------------------------

You should normally only add directories to @INC.  If you need to delete
directories from @INC take care to only delete those which you added
yourself or which you are certain are not needed by other modules in your
script.  Other modules may have added directories which they need for
correct operation.

By default the `no lib' statement deletes the *first* instance of each
named directory from @INC.  To delete multiple instances of the same name
from @INC you can specify the name multiple times.

To delete all instances of all the specified names from @INC you can
specify ':ALL' as the first parameter of `no lib'. For example:

     no lib qw(:ALL .);

For each directory in LIST (called $dir here) the lib module also checks
to see if a directory called $dir/$archname/auto exists.  If so the
$dir/$archname directory is assumed to be a corresponding architecture
specific directory and is also deleted from @INC.

If LIST includes both $dir and $dir/$archname then $dir/$archname will be
deleted from @INC twice (if $dir/$archname/auto exists).

RESTORING ORIGINAL @INC
-----------------------

When the lib module is first loaded it records the current value of @INC
in an array `@lib::ORIG_INC'. To restore @INC to that value you can say

     @INC = @lib::ORIG_INC;

SEE ALSO
========

FindBin - optional module which deals with paths relative to the source
file.

AUTHOR
======

Tim Bunce, 2nd June 1995.


File: pm.info,  Node: lwpcook,  Next: ops,  Prev: lib,  Up: Module List

libwww-perl cookbook
********************

NAME
====

lwpcook - libwww-perl cookbook

DESCRIPTION
===========

This document contain some examples that show typical usage of the
libwww-perl library.  You should consult the documentation for the
individual modules for more detail.

All examples should be runnable programs. You can, in most cases, test the
code sections by piping the program text directly to perl.

GET
===

It is very easy to use this library to just fetch documents from the net.
The LWP::Simple module provides the get() function that return the
document specified by its URL argument:

     use LWP::Simple;
     $doc = get 'http://www.sn.no/libwww-perl/';

or, as a perl one-liner using the getprint() function:

     perl -MLWP::Simple -e 'getprint "http://www.sn.no/libwww-perl/"'

or, how about fetching the latest perl by running this:

     perl -MLWP::Simple -e '
       getstore "ftp://ftp.sunet.se/pub/lang/perl/CPAN/src/latest.tar.gz",
                "perl.tar.gz"'

You will probably first want to find a CPAN site closer to you by running
something like the following command:

     perl -MLWP::Simple -e 'getprint "http://www.perl.com/perl/CPAN/CPAN.html"'

Enough of this simple stuff!  The LWP object oriented interface gives you
more control over the request sent to the server.  Using this interface
you have full control over headers sent and how you want to handle the
response returned.

     use LWP::UserAgent;
     $ua = new LWP::UserAgent;
     $ua->agent("$0/0.1 " . $ua->agent);
     # $ua->agent("Mozilla/5.0") # pretend you are some very new Netscape browser

     $req = new HTTP::Request 'GET' => 'http://www.sn.no/libwww-perl';
     $req->header('Accept' => 'text/html');

     # send request
     $res = $ua->request($req);

     # check the outcome
     if ($res->is_success) {
        print $res->content;
     } else {
        print "Error: " . $res->code . " " . $res->message;
     }

The lwp-request program (alias GET) that is distributed with the library
can also be used to fetch documents from WWW servers.

HEAD
====

If you just want to check if a document is present (i.e. the URL is valid)
try to run code that looks like this:

     use LWP::Simple;

     if (head($url)) {
        # ok document exists
     }

The head() function really returns a list of meta-information about the
document.  The first three values of the list returned are the document
type, the size of the document, and the age of the document.

More control over the request or access to all header values returned
require that you use the object oriented interface described for GET
above.  Just s/GET/HEAD/g.

POST
====

There is no simple interface for posting data to a WWW server.  You must
use the object oriented interface for this. The most common POST operation
is to access a WWW form application:

     use LWP::UserAgent;
     $ua = new LWP::UserAgent;

     my $req = new HTTP::Request 'POST','http://www.perl.com/cgi-bin/BugGlimpse';
     $req->content_type('application/x-www-form-urlencoded');
     $req->content('match=www&errors=0');

     my $res = $ua->request($req);
     print $res->as_string;

If your application has the key/value pairs to be posted in an associative
array, then we can exploit the URI::URL module to create the content for
the POST request message (it handles all the escaping issues):

     %form = ( search => 'www', errors => 0 );

     use URI::URL;
     use LWP::UserAgent;
     $ua = new LWP::UserAgent;

     my $req = new HTTP::Request 'POST', 'http://www.perl.com/cgi-bin/BugGlimpse';
     $req->content_type('application/x-www-form-urlencoded');

     my $curl = url("http:");      # create an empty HTTP URL object
     $curl->query_form(%form);
     $req->content($curl->equery); # %form content as escaped query string

     print $ua->request($req)->as_string;

The lwp-request program (alias POST) that is distributed with the library
can also be used for posting data.

PROXIES
=======

Some sites use proxies to go through fire wall machines, or just as cache
in order to improve performance.  Proxies can also be used for accessing
resources through protocols not supported directly (or supported badly :-)
by the libwww-perl library.

You should initialize your proxy setting before you start sending requests:

     use LWP::UserAgent;
     $ua = new LWP::UserAgent;
     $ua->env_proxy; # initialize from environment variables
     # or
     $ua->proxy(ftp  => 'http://proxy.myorg.com');
     $ua->proxy(wais => 'http://proxy.myorg.com');
     $ua->no_proxy(qw(no se fi));

     my $req = new HTTP::Request 'wais://xxx.com/';
     print $ua->request($req)->as_string;

The LWP::Simple interface will call env_proxy() for you automatically.
Applications that use the $ua->env_proxy() method will normally not use
the $ua->proxy() and $ua->no_proxy() methods.

ACCESS TO PROTECTED DOCUMENTS
=============================

Documents protected by basic authorization can easily be accessed like
this:

     use LWP::UserAgent;
     $ua = new LWP::UserAgent;
     $req = new HTTP::Request GET => 'http://www.sn.no/secret/';
     $req->authorization_basic('aas', 'mypassword');
     print $ua->request($req)->as_string;

The other alternative is to provide a subclass of *LWP::UserAgent* that
overrides the get_basic_credentials() method. Study the *lwp-request*
program for an example of this.

MIRRORING
=========

If you want to mirror documents from a WWW server, then try to run code
similar to this at regular intervals:

     use LWP::Simple;

     %mirrors = (
        'http://www.sn.no/'             => 'sn.html',
        'http://www.perl.com/'          => 'perl.html',
        'http://www.sn.no/libwww-perl/' => 'lwp.html',
        'gopher://gopher.sn.no/'        => 'gopher.html',
     );

     while (($url, $localfile) = each(%mirrors)) {
        mirror($url, $localfile);
     }

Or, as a perl one-liner:

     perl -MLWP::Simple -e 'mirror("http://www.perl.com/", "perl.html")';

The document will not be transfered unless it has been updated.

LARGE DOCUMENTS
===============

If the document you want to fetch is too large to be kept in memory, then
you have two alternatives.  You can instruct the library to write the
document content to a file (second $ua->request() argument is a file name):

     use LWP::UserAgent;
     $ua = new LWP::UserAgent;

     my $req = new HTTP::Request 'GET',
                   'http://www.sn.no/~aas/perl/www/libwww-perl-5.00.tar.gz';
     $res = $ua->request($req, "libwww-perl.tar.gz");
     if ($res->is_success) {
        print "ok\n";
     }

Or you can process the document as it arrives (second $ua->request()
argument is a code reference):

     use LWP::UserAgent;
     $ua = new LWP::UserAgent;
     $URL = 'ftp://ftp.unit.no/pub/rfc/rfc-index.txt';

     my $expected_length;
     my $bytes_received = 0;
     $ua->request(HTTP::Request->new('GET', $URL),
                  sub {
                      my($chunk, $res) = @_;
                      $bytes_received += length($chunk);
     	           unless (defined $expected_length) {
     	              $expected_length = $res->content_length || 0;
                      }
     		   if ($expected_length) {
     		        printf STDERR "%d%% - ",
     	                          100 * $bytes_received / $expected_length;
                      }
     	           print STDERR "$bytes_received bytes received\n";

     # XXX Should really do something with the chunk itself
     	           # print $chunk;
                    });

HTML FORMATTING
===============

It is easy to convert HTML code to "readable" text.

     use LWP::Simple;
     use HTML::Parse;
     print parse_html(get 'http://www.sn.no/libwww-perl/')->format;

PARSE URLS
==========

To access individual elements of a URL, try this:

     use URI::URL;
     $host = url("http://www.sn.no/")->host;

or

     use URI::URL;
     $u = url("ftp://ftp.sn.no/test/aas;type=i");
     print "Protocol scheme is ", $u->scheme, "\n";
     print "Host is ", $u->host, " at port ", $u->port, "\n";

or even

     use URI::URL;
     my($host,$port) = (url("ftp://ftp.sn.no/test/aas;type=i")->crack)[3,4];

EXPAND RELATIVE URLS
====================

This code reads URLs and print expanded version.

     use URI::URL;
     $BASE = "http://www.sn.no/some/place?query";
     while (<>) {
        print url($_, $BASE)->abs->as_string, "\n";
     }

We can expand URLs in an HTML document by using the parser to build a tree
that we then traverse:

     %link_elements =
     (
      'a'    => 'href',
      'img'  => 'src',
      'form' => 'action',
      'link' => 'href',
     );

     use HTML::Parse;
     use URI::URL;

     $BASE = "http://somewhere/root/";
     $h = parse_htmlfile("xxx.html");
     $h->traverse(\&expand_urls, 1);

     print $h->as_HTML;

     sub expand_urls
     {
        my($e, $start) = @_;
        return 1 unless $start;
        my $attr = $link_elements{$e->tag};
        return 1 unless defined $attr;
        my $url = $e->attr($attr);
        return 1 unless defined $url;
        $e->attr($attr, url($url, $BASE)->abs->as_string);
     }

BASE URL
========

If you want to resolve relative links in a page you will have to determine
which base URL to use.  The HTTP::Response objects now has a base() method.

     $BASE = $res->base;


File: pm.info,  Node: ops,  Next: overload,  Prev: lwpcook,  Up: Module List

Perl pragma to restrict unsafe operations when compiling
********************************************************

NAME
====

ops - Perl pragma to restrict unsafe operations when compiling

SYNOPSIS
========

     perl -Mops=:default ...    # only allow reasonably safe operations

     perl -M-ops=system ...     # disable the 'system' opcode

DESCRIPTION
===========

Since the ops pragma currently has an irreversable global effect, it is
only of significant practical use with the -M option on the command line.

See the *Note Opcode: Opcode, module for information about opcodes,
optags, opmasks and important information about safety.

SEE ALSO
========

Opcode(3), Safe(3), perlrun(3)


File: pm.info,  Node: overload,  Next: ptkFAQ,  Prev: ops,  Up: Module List

Package for overloading perl operations
***************************************

NAME
====

overload - Package for overloading perl operations

SYNOPSIS
========

     package SomeThing;

     use overload
     	'+' => \&myadd,
     	'-' => \&mysub;
     	# etc
     ...

     package main;
     $a = new SomeThing 57;
     $b=5+$a;
     ...
     if (overload::Overloaded $b) {...}
     ...
     $strval = overload::StrVal $b;

CAVEAT SCRIPTOR
===============

Overloading of operators is a subject not to be taken lightly.  Neither
its precise implementation, syntax, nor semantics are 100% endorsed by
Larry Wall.  So any of these may be changed at some point in the future.

DESCRIPTION
===========

Declaration of overloaded functions
-----------------------------------

The compilation directive

     package Number;
     use overload
     	"+" => \&add,
     	"*=" => "muas";

declares function Number::add() for addition, and method muas() in the
"class" `Number' (or one of its base classes) for the assignment form `*='
of multiplication.

Arguments of this directive come in (key, value) pairs.  Legal values are
values legal inside a `&{ ... }' call, so the name of a subroutine, a
reference to a subroutine, or an anonymous subroutine will all work.
Legal keys are listed below.

The subroutine add will be called to execute `$a+$b' if $a is a reference
to an object blessed into the package `Number', or if $a is not an object
from a package with defined mathemagic addition, but $b is a reference to
a `Number'.  It can also be called in other situations, like `$a+=7', or
`$a++'.  See `MAGIC AUTOGENERATION' in this node.  (Mathemagical methods
refer to methods triggered by an overloaded mathematical operator.)

Calling Conventions for Binary Operations
-----------------------------------------

The functions specified in the `use overload ...' directive are called
with three (in one particular case with four, see `Last Resort' in this
node) arguments.  If the corresponding operation is binary, then the first
two arguments are the two arguments of the operation.  However, due to
general object calling conventions, the first argument should always be an
object in the package, so in the situation of `7+$a', the order of the
arguments is interchanged.  It probably does not matter when implementing
the addition method, but whether the arguments are reversed is vital to
the subtraction method.  The method can query this information by
examining the third argument, which can take three different values:

FALSE
     the order of arguments is as in the current operation.

TRUE
     the arguments are reversed.

undef
     the current operation is an assignment variant (as in `$a+=7'), but
     the usual function is called instead.  This additional information
     can be used to generate some optimizations.

Calling Conventions for Unary Operations
----------------------------------------

Unary operation are considered binary operations with the second argument
being undef.  Thus the functions that overloads `{"++"}' is called with
arguments `($a,undef,'')' when $a++ is executed.

Overloadable Operations
-----------------------

The following symbols can be specified in `use overload':

   * *Arithmetic operations*
          "+", "+=", "-", "-=", "*", "*=", "/", "/=", "%", "%=",
          "**", "**=", "<<", "<<=", ">>", ">>=", "x", "x=", ".", ".=",

     For these operations a substituted non-assignment variant can be
     called if the assignment variant is not available.  Methods for
     operations "+", "-", "`+='", and "`-='" can be called to
     automatically generate increment and decrement methods.  The
     operation "-" can be used to autogenerate missing methods for unary
     minus or abs.

   * *Comparison operations*
          "<",  "<=", ">",  ">=", "==", "!=", "<=>",
          "lt", "le", "gt", "ge", "eq", "ne", "cmp",

     If the corresponding "spaceship" variant is available, it can be used
     to substitute for the missing operation.  During sorting arrays, cmp
     is used to compare values subject to `use overload'.

   * *Bit operations*
          "&", "^", "|", "neg", "!", "~",

     "`neg'" stands for unary minus.  If the method for `neg' is not
     specified, it can be autogenerated using the method for subtraction.
     If the method for "!" is not specified, it can be autogenerated using
     the methods for "`bool'", or "`\"\"'", or "`0+'".

   * *Increment and decrement*
          "++", "--",

     If undefined, addition and subtraction methods can be used instead.
     These operations are called both in prefix and postfix form.

   * *Transcendental functions*
          "atan2", "cos", "sin", "exp", "abs", "log", "sqrt",

     If abs is unavailable, it can be autogenerated using methods for "<"
     or "<=>" combined with either unary minus or subtraction.

   * *Boolean, string and numeric conversion*
          "bool", "\"\"", "0+",

     If one or two of these operations are unavailable, the remaining ones
     can be used instead.  `bool' is used in the flow control operators
     (like `while') and for the ternary "`?:'" operation.  These functions
     can return any arbitrary Perl value.  If the corresponding operation
     for this value is overloaded too, that operation will be called again
     with this value.

   * Special
          "nomethod", "fallback", "=",

     see `SPECIAL SYMBOLS FOR `use overload'' in this node.

See `"Fallback"' in this node for an explanation of when a missing method
can be autogenerated.

SPECIAL SYMBOLS FOR `use overload'
==================================

Three keys are recognized by Perl that are not covered by the above
description.

Last Resort
-----------

`"nomethod"' should be followed by a reference to a function of four
parameters.  If defined, it is called when the overloading mechanism
cannot find a method for some operation.  The first three arguments of
this function coincide with the arguments for the corresponding method if
it were found, the fourth argument is the symbol corresponding to the
missing method.  If several methods are tried, the last one is used.  Say,
`1-$a' can be equivalent to

     &nomethodMethod($a,1,1,"-")

if the pair `"nomethod" => "nomethodMethod"' was specified in the `use
overload' directive.

If some operation cannot be resolved, and there is no function assigned to
`"nomethod"', then an exception will be raised via die()- unless
`"fallback"' was specified as a key in `use overload' directive.

Fallback
--------

The key `"fallback"' governs what to do if a method for a particular
operation is not found.  Three different cases are possible depending on
the value of `"fallback"':

   * undef

     Perl tries to use a substituted method (see `MAGIC AUTOGENERATION' in
     this node).  If this fails, it then tries to calls `"nomethod"'
     value; if missing, an exception will be raised.

   * TRUE

     The same as for the undef value, but no exception is raised.  Instead,
     it silently reverts to what it would have done were there no `use
     overload' present.

   * defined, but FALSE

     No autogeneration is tried.  Perl tries to call `"nomethod"' value,
     and if this is missing, raises an exception.

Copy Constructor
----------------

The value for `"="' is a reference to a function with three arguments,
i.e., it looks like the other values in `use overload'. However, it does
not overload the Perl assignment operator. This would go against Camel
hair.

This operation is called in the situations when a mutator is applied to a
reference that shares its object with some other reference, such as

     $a=$b;
     $a++;

To make this change $a and not change $b, a copy of `$$a' is made, and $a
is assigned a reference to this new object.  This operation is done during
execution of the `$a++', and not during the assignment, (so before the
increment `$$a' coincides with `$$b').  This is only done if `++' is
expressed via a method for `'++'' or `'+=''.  Note that if this operation
is expressed via `'+'' a nonmutator, i.e., as in

     $a=$b;
     $a=$a+1;

then `$a' does not reference a new copy of `$$a', since $$a does not
appear as lvalue when the above code is executed.

If the copy constructor is required during the execution of some mutator,
but a method for `'='' was not specified, it can be autogenerated as a
string copy if the object is a plain scalar.

Example
     The actually executed code for

          $a=$b;
                  Something else which does not modify $a or $b....
          ++$a;

     may be

          $a=$b;
                  Something else which does not modify $a or $b....
          $a = $a->clone(undef,"");
                  $a->incr(undef,"");

     if $b was mathemagical, and `'++'' was overloaded with `\&incr',
     `'='' was overloaded with `\&clone'.

MAGIC AUTOGENERATION
====================

If a method for an operation is not found, and the value for  `"fallback"'
is TRUE or undefined, Perl tries to autogenerate a substitute method for
the missing operation based on the defined operations.  Autogenerated
method substitutions are possible for the following operations:

*Assignment forms of arithmetic operations*
     `$a+=$b' can use the method for `"+"' if the method for `"+="' is not
     defined.

*Conversion operations*
     String, numeric, and boolean conversion are calculated in terms of one
     another if not all of them are defined.

*Increment and decrement*
     The `++$a' operation can be expressed in terms of `$a+=1' or `$a+1',
     and `$a--' in terms of `$a-=1' and `$a-1'.

`abs($a)'
     can be expressed in terms of `$a<0' and `-$a' (or `0-$a').

*Unary minus*
     can be expressed in terms of subtraction.

Negation
     ! and `not' can be expressed in terms of boolean conversion, or
     string or numerical conversion.

Concatenation
     can be expressed in terms of string conversion.

*Comparison operations*
     can be expressed in terms of its "spaceship" counterpart: either
     `<=>' or cmp:

          <, >, <=, >=, ==, != 	in terms of <=>
          lt, gt, le, ge, eq, ne 	in terms of cmp

*Copy operator*
     can be expressed in terms of an assignment to the dereferenced value,
     if this value is a scalar and not a reference.

WARNING
=======

The restriction for the comparison operation is that even if, for example,
`cmp' should return a blessed reference, the autogenerated ``lt'' function
will produce only a standard logical value based on the numerical value of
the result of `cmp'.  In particular, a working numeric conversion is
needed in this case (possibly expressed in terms of other conversions).

Similarly, `.='  and `x=' operators lose their mathemagical properties if
the string conversion substitution is applied.

When you chop() a mathemagical object it is promoted to a string and its
mathemagical properties are lost.  The same can happen with other
operations as well.

Run-time Overloading
====================

Since all use directives are executed at compile-time, the only way to
change overloading during run-time is to

     eval 'use overload "+" => \&addmethod';

You can also use

     eval 'no overload "+", "--", "<="';

though the use of these constructs during run-time is questionable.

Public functions
================

Package `overload.pm' provides the following public functions:

overload::StrVal(arg)
     Gives string value of `arg' as in absence of stringify overloading.

overload::Overloaded(arg)
     Returns true if `arg' is subject to overloading of some operations.

overload::Method(obj,op)
     Returns undef or a reference to the method that implements `op'.

IMPLEMENTATION
==============

What follows is subject to change RSN.

The table of methods for all operations is cached as magic in the symbol
table hash for the package.  The table is rechecked for changes due to
`use overload', `no overload', and @ISA only during blessing; so if they
are changed dynamically, you'll need an additional fake blessing to update
the table.

(Every SVish thing has a magic queue, and magic is an entry in that queue.
This is how a single variable may participate in multiple forms of magic
simultaneously.  For instance, environment variables regularly have two
forms at once: their %ENV magic and their taint magic.)

If an object belongs to a package using overload, it carries a special
flag.  Thus the only speed penalty during arithmetic operations without
overloading is the checking of this flag.

In fact, if `use overload' is not present, there is almost no overhead for
overloadable operations, so most programs should not suffer measurable
performance penalties.  A considerable effort was made to minimize the
overhead when overload is used and the current operation is overloadable
but the arguments in question do not belong to packages using overload.
When in doubt, test your speed with `use overload' and without it.  So far
there have been no reports of substantial speed degradation if Perl is
compiled with optimization turned on.

There is no size penalty for data if overload is not used.

Copying (`$a=$b') is shallow; however, a one-level-deep copying is carried
out before any operation that can imply an assignment to the object $a (or
$b) refers to, like `$a++'.  You can override this behavior by defining
your own copy constructor (see `"Copy Constructor"' in this node).

It is expected that arguments to methods that are not explicitly supposed
to be changed are constant (but this is not enforced).

AUTHOR
======

Ilya Zakharevich <`ilya@math.mps.ohio-state.edu'>.

DIAGNOSTICS
===========

When Perl is run with the *-Do* switch or its equivalent, overloading
induces diagnostic messages.

BUGS
====

Because it is used for overloading, the per-package associative array
%OVERLOAD now has a special meaning in Perl.

As shipped, mathemagical properties are not inherited via the @ISA tree.

This document is confusing.


File: pm.info,  Node: ptkFAQ,  Next: sigtrap,  Prev: overload,  Up: Module List

ptkFAQ
******

NAME
====

ptkFAQ

AUTHOR
======

Peter Prymmer pvhp@lns62.lns.cornell.edu


File: pm.info,  Node: sigtrap,  Next: strict,  Prev: ptkFAQ,  Up: Module List

Perl pragma to enable simple signal handling
********************************************

NAME
====

sigtrap - Perl pragma to enable simple signal handling

SYNOPSIS
========

     use sigtrap;
     use sigtrap qw(stack-trace old-interface-signals);	# equivalent
     use sigtrap qw(BUS SEGV PIPE ABRT);
     use sigtrap qw(die INT QUIT);
     use sigtrap qw(die normal-signals);
     use sigtrap qw(die untrapped normal-signals);
     use sigtrap qw(die untrapped normal-signals
     		    stack-trace any error-signals);
     use sigtrap 'handler' => \&my_handler, 'normal-signals';
     use sigtrap qw(handler my_handler normal-signals
     	    	    stack-trace error-signals);

DESCRIPTION
===========

The sigtrap pragma is a simple interface to installing signal handlers.
You can have it install one of two handlers supplied by sigtrap itself
(one which provides a Perl stack trace and one which simply `die()'s), or
alternately you can supply your own handler for it to install.  It can be
told only to install a handler for signals which are either untrapped or
ignored.  It has a couple of lists of signals to trap, plus you can supply
your own list of signals.

The arguments passed to the use statement which invokes sigtrap are
processed in order.  When a signal name or the name of one of sigtrap's
signal lists is encountered a handler is immediately installed, when an
option is encountered it affects subsequently installed handlers.

OPTIONS
=======

SIGNAL HANDLERS
---------------

These options affect which handler will be used for subsequently installed
signals.

*stack-trace*
     The handler used for subsequently installed signals will output a Perl
     stack trace to STDERR and then tries to dump core.  This is the
     default signal handler.

die
     The handler used for subsequently installed signals calls die
     (actually croak) with a message indicating which signal was caught.

handler *your-handler*
     *your-handler* will be used as the handler for subsequently installed
     signals.  *your-handler* can be any value which is valid as an
     assignment to an element of `%SIG'.

SIGNAL LISTS
------------

sigtrap has two built-in lists of signals to trap.  They are:

*normal-signals*
     These are the signals which a program might normally expect to
     encounter and which by default cause it to terminate.  They are HUP,
     INT, PIPE and TERM.

*error-signals*
     These signals usually indicate a serious problem with the Perl
     interpreter or with your script.  They are ABRT, BUS, EMT, FPE, ILL,
     QUIT, SEGV, SYS and TRAP.

*old-interface-signals*
     These are the signals which were trapped by default by the old
     sigtrap interface, they are ABRT, BUS, EMT, FPE, ILL, PIPE, QUIT,
     SEGV, SYS, TERM, and TRAP.  If no signals or signals lists are passed
     to sigtrap this list is used.

OTHER
-----

untrapped
     This token tells sigtrap only to install handlers for subsequently
     listed signals which aren't already trapped or ignored.

any
     This token tells sigtrap to install handlers for all subsequently
     listed signals.  This is the default behavior.

signal
     Any argument which looks like a signals name (that is,
     `/^[A-Z][A-Z0-9]*$/') is taken as a signal name and indicates that
     sigtrap should install a handler for it.

number
     Require that at least version number of sigtrap is being used.

EXAMPLES
========

Provide a stack trace for the old-interface-signals:

     use sigtrap;

Ditto:

     use sigtrap qw(stack-trace old-interface-signals);

Provide a stack trace on the 4 listed signals only:

     use sigtrap qw(BUS SEGV PIPE ABRT);

Die on INT or QUIT:

     use sigtrap qw(die INT QUIT);

Die on HUP, INT, PIPE or TERM:

     use sigtrap qw(die normal-signals);

Die on HUP, INT, PIPE or TERM, except don't change the behavior for
signals which are already trapped or ignored:

     use sigtrap qw(die untrapped normal-signals);

Die on receipt one of an of the *normal-signals* which is currently
untrapped, provide a stack trace on receipt of any of the *error-signals*:

     use sigtrap qw(die untrapped normal-signals
     		    stack-trace any error-signals);

Install my_handler() as the handler for the *normal-signals*:

     use sigtrap 'handler', \&my_handler, 'normal-signals';

Install my_handler() as the handler for the normal-signals, provide a Perl
stack trace on receipt of one of the error-signals:

     use sigtrap qw(handler my_handler normal-signals
     	    	    stack-trace error-signals);


File: pm.info,  Node: strict,  Next: subs,  Prev: sigtrap,  Up: Module List

Perl pragma to restrict unsafe constructs
*****************************************

NAME
====

strict - Perl pragma to restrict unsafe constructs

SYNOPSIS
========

     use strict;

     use strict "vars";
     use strict "refs";
     use strict "subs";
     use strict "untie";

     use strict;
     no strict "vars";

DESCRIPTION
===========

If no import list is supplied, all possible restrictions are assumed.
(This is the safest mode to operate in, but is sometimes too strict for
casual programming.)  Currently, there are four possible things to be
strict about:  "subs", "vars", "refs", and "untie".

`strict refs'
     This generates a runtime error if you use symbolic references (see
     *Note Perlref: (perl.info)perlref,).

          use strict 'refs';
          $ref = \$foo;
          print $$ref;	# ok
          $ref = "foo";
          print $$ref;	# runtime error; normally ok

`strict vars'
     This generates a compile-time error if you access a variable that
     wasn't localized via `my()' or wasn't fully qualified.  Because this
     is to avoid variable suicide problems and subtle dynamic scoping
     issues, a merely local() variable isn't good enough.  See `my', *Note
     Perlfunc: (perl.info)perlfunc, and `local', *Note Perlfunc:
     (perl.info)perlfunc,.

          use strict 'vars';
          $X::foo = 1;	 # ok, fully qualified
          my $foo = 10;	 # ok, my() var
          local $foo = 9;	 # blows up

     The local() generated a compile-time error because you just touched a
     global name without fully qualifying it.

`strict subs'
     This disables the poetry optimization, generating a compile-time
     error if you try to use a bareword identifier that's not a
     subroutine, unless it appears in curly braces or on the left hand
     side of the "=>" symbol.

          use strict 'subs';
          $SIG{PIPE} = Plumber;   	# blows up
          $SIG{PIPE} = "Plumber"; 	# just fine: bareword in curlies always ok
          $SIG{PIPE} = \&Plumber; 	# preferred form

`strict untie'
     This generates a runtime error if any references to the object
     returned by tie (or tied) still exist when untie is called. Note that
     to get this strict behaviour, the `use strict 'untie'' statement must
     be in the same scope as the untie. See `tie', *Note Perlfunc:
     (perl.info)perlfunc,, `untie', *Note Perlfunc: (perl.info)perlfunc,,
     `tied', *Note Perlfunc: (perl.info)perlfunc, and `tied', *Note
     Perltie: (perl.info)perltie,.

          use strict 'untie';
          $a = tie %a, 'SOME_PKG';
          $b = tie %b, 'SOME_PKG';
          $b = 0;
          tie %c, PKG;
          $c = tied %c;
          untie %a ;		# blows up, $a is a valid object reference.
          untie %b;		# ok, $b is not a reference to the object.
          untie %c ;		# blows up, $c is a valid object reference.

See `Pragmatic Modules', *Note Perlmod: (perl.info)perlmod,.


File: pm.info,  Node: subs,  Next: vars,  Prev: strict,  Up: Module List

Perl pragma to predeclare sub names
***********************************

NAME
====

subs - Perl pragma to predeclare sub names

SYNOPSIS
========

     use subs qw(frob);
     frob 3..10;

DESCRIPTION
===========

This will predeclare all the subroutine whose names are in the list,
allowing you to use them without parentheses even before they're declared.

See `Pragmatic Modules', *Note Perlmod: (perl.info)perlmod, and `subs',
*Note Strict: strict,.


File: pm.info,  Node: vars,  Prev: subs,  Up: Module List

Perl pragma to predeclare global variable names
***********************************************

NAME
====

vars - Perl pragma to predeclare global variable names

SYNOPSIS
========

     use vars qw($frob @mung %seen);

DESCRIPTION
===========

This will predeclare all the variables whose names are in the list,
allowing you to use them under "use strict", and disabling any typo
warnings.

Packages such as the AutoLoader and SelfLoader that delay loading of
subroutines within packages can create problems with package lexicals
defined using `my()'. While the vars pragma cannot duplicate the effect of
package lexicals (total transparency outside of the package), it can act
as an acceptable substitute by pre-declaring global symbols, ensuring
their availability to to the later-loaded routines.

See `Pragmatic Modules', *Note Perlmod: (perl.info)perlmod,.



Tag table:
Node: Module List89
Node: Agent20828
Node: Alias24422
Node: AnyDBM_File30864
Node: Apache33449
Node: Apache/AccessLimitNum46134
Node: Apache/Authen47198
Node: Apache/AuthzAge48744
Node: Apache/CGI49621
Node: Apache/Debug50397
Node: Apache/MsqlProxy50882
Node: Apache/Options52572
Node: Apache/Registry53393
Node: Apache/SSI54751
Node: Apache/TieHandle56377
Node: Archie57145
Node: AtExit59599
Node: AutoLoader67293
Node: AutoSplit71472
Node: B/Xref75190
Node: BSD/Resource78049
Node: Benchmark81776
Node: BitCount85249
Node: C/Scan86256
Node: CGI89165
Node: CGI/Base158795
Node: CGI/BasePlus168971
Node: CGI/Carp169891
Node: CGI/Fast173920
Node: CGI/Form178380
Node: CGI/Imagemap212197
Node: CGI/MiniSvr217999
Node: CGI/Out229108
Node: CGI/Request230463
Node: CGI/Response242406
Node: CGI/Switch250957
Node: CGI/Wrap251796
Node: CGI/XA253109
Node: CPAN254957
Node: Carp263827
Node: Color264562
Node: Compress/Zlib267061
Node: Config281404
Node: ConfigFile283864
Node: Convert/UU286298
Node: Crypt/DES287957
Node: Crypt/IDEA289803
Node: Cwd291621
Node: DB_File292953
Node: DCE/Login332289
Node: DCE/Registry332884
Node: DCE/Status333542
Node: DCE/UUID333901
Node: DCE/login_base334438
Node: DCE/rgybase334932
Node: Data/Dumper336544
Node: Data/Flow346068
Node: Date/DateCalc350706
Node: Date/Format376364
Node: Date/Manip379947
Node: Date/Parse405740
Node: Des407603
Node: Devel/CoreStack413597
Node: Devel/DProf414200
Node: Devel/Peek417281
Node: Devel/SelfStubber426262
Node: Devel/Symdump429209
Node: Devel/TraceFuncs432544
Node: DirHandle436226
Node: DynaLoader437024
Node: English448294
Node: Env449200
Node: EventServer450436
Node: Exporter499663
Node: ExtUtils/Embed506346
Node: ExtUtils/Install513006
Node: ExtUtils/Liblist514857
Node: ExtUtils/MM_OS2517151
Node: ExtUtils/MM_Unix517742
Node: ExtUtils/MM_VMS528929
Node: ExtUtils/MakeMaker538061
Node: ExtUtils/Manifest569415
Node: ExtUtils/Miniperl573898
Node: ExtUtils/Mkbootstrap574996
Node: ExtUtils/Mksymlists576216
Node: ExtUtils/testlib579980
Node: Fatal580511
Node: Fcntl581577
Node: File/Basename582269
Node: File/BasicFlock586398
Node: File/CheckTree586990
Node: File/Cmp588494
Node: File/Copy589253
Node: File/CounterFile593912
Node: File/Find596602
Node: File/Flock598372
Node: File/Listing599072
Node: File/Path601500
Node: File/PathConvert603776
Node: File/Recurse607423
Node: File/Slurp610675
Node: File/Tools612377
Node: FileCache613083
Node: FileHandle613766
Node: Filter/Util/Call618767
Node: Filter/Util/Exec630266
Node: Filter/cpp630797
Node: Filter/decrypt631698
Node: Filter/exec633902
Node: Filter/sh634972
Node: Filter/tee636029
Node: FindBin636817
Node: Font/AFM638653
Node: GD643124
Node: GDBM_File670572
Node: Getopt/Long671668
Node: Getopt/Mixed685630
Node: Getopt/Regex699419
Node: Getopt/Std703006
Node: HTML/AsSubs704011
Node: HTML/Element705897
Node: HTML/Entities711312
Node: HTML/FormatPS712800
Node: HTML/FormatText715094
Node: HTML/Formatter715960
Node: HTML/HeadParser716882
Node: HTML/LinkExtor719212
Node: HTML/Parse722055
Node: HTML/Parser724797
Node: HTML/QuickCheck728535
Node: HTML/Stream730948
Node: HTML/TreeBuilder743213
Node: HTTP/Daemon745092
Node: HTTP/Date749833
Node: HTTP/Headers753225
Node: HTTP/Message760556
Node: HTTP/Negotiate763066
Node: HTTP/Request771045
Node: HTTP/Response773289
Node: HTTP/Status778116
Node: HTTPD/Authen781102
Node: HTTPD/GroupAdmin786914
Node: HTTPD/UserAdmin791279
Node: I18N/Collate797839
Node: IO799526
Node: IO/File800024
Node: IO/Handle802542
Node: IO/Pipe807459
Node: IO/Seekable809683
Node: IO/Select810984
Node: IO/Socket814615
Node: IPC/Open2820112
Node: IPC/Open3821791
Node: Image/Size823036
Node: IniConf826493
Node: LWP833305
Node: LWP/Debug852698
Node: LWP/IO854766
Node: LWP/MediaTypes855485
Node: LWP/MemberMixin856995
Node: LWP/Protocol857723
Node: LWP/RobotUA861484
Node: LWP/Simple863883
Node: LWP/Socket867742
Node: LWP/TkIO871062
Node: LWP/UserAgent871644
Node: Log/Topics881695
Node: Logfile885048
Node: MD5892081
Node: MIME/Base64897516
Node: MIME/Body899285
Node: MIME/Decoder908136
Node: MIME/Entity921329
Node: MIME/Field/ConTraEnc937251
Node: MIME/Field/ContDisp938162
Node: MIME/Field/ContType938906
Node: MIME/Field/ParamVal942673
Node: MIME/Head945668
Node: MIME/IO964611
Node: MIME/Latin1969660
Node: MIME/OLD/ParserUtil971989
Node: MIME/Parser972972
Node: MIME/ParserBase982765
Node: MIME/QuotedPrint997590
Node: MIME/ToolUtils999137
Node: MLDBM1000415
Node: Mail/Address1004867
Node: Mail/Cap1006410
Node: Mail/Field1008861
Node: Mail/Folder1013079
Node: Mail/Folder/Emaul1027163
Node: Mail/Folder/Mbox1031684
Node: Mail/Header1036090
Node: Mail/Internet1038457
Node: Mail/MIME1041437
Node: Mail/Mailer1041994
Node: Mail/POP3Client1044440
Node: Mail/Send1047940
Node: Mail/Util1049096
Node: Make1050504
Node: Math/Amoeba1053062
Node: Math/Approx1056308
Node: Math/BigFloat1058028
Node: Math/BigInt1059728
Node: Math/BigInteger1061815
Node: Math/Brent1066675
Node: Math/Complex1069271
Node: Math/DVector1080250
Node: Math/Derivative1082479
Node: Math/Fortran1083455
Node: Math/Matrix1084219
Node: Math/PRSG1086310
Node: Math/Spline1087356
Node: Math/Trig1089947
Node: Math/TrulyRandom1091210
Node: Math/VecStat1092278
Node: Mmap1095004
Node: Msql/RDBMS1098151
Node: NDBM_File1100402
Node: NNML/Server1100788
Node: Net/Cmd1103591
Node: Net/Domain1108172
Node: Net/DummyInetd1109419
Node: Net/FTP1111170
Node: Net/NIS1121798
Node: Net/NISPlus/Table1126259
Node: Net/NISTable1128148
Node: Net/NNTP1132640
Node: Net/Netrc1144219
Node: Net/POP31147946
Node: Net/Ping1152108
Node: Net/SMTP1153088
Node: Net/SNPP1158202
Node: Net/SSLeay1161239
Node: Net/Socket1170684
Node: Net/Telnet1173349
Node: Net/Time1174340
Node: News/NNTPClient1175747
Node: News/Newsrc1196906
Node: ODBM_File1204847
Node: OS2/Attrib1205233
Node: OS2/SoftInstaller1207356
Node: Opcode1209045
Node: PDL1223267
Node: PGP1247415
Node: POSIX1256932
Node: Parext1290559
Node: Pari1292368
Node: Parity1300030
Node: Penguin/Easy1301797
Node: Pg1302884
Node: Pod/Parse1312683
Node: Pod/Parser1317466
Node: Pod/Select1338391
Node: Pod/Text1340711
Node: Pod/Usage1342002
Node: Pod/foo1345804
Node: Pod/newrun1367120
Node: Pod/newvar1381781
Node: Pod/newvar21401523
Node: Pod/test1421263
Node: Proc/Forkfunc1421673
Node: Proc/Simple1422220
Node: Religion1424539
Node: Remedy/Ar1430996
Node: Resources1435742
Node: SDBM_File1462622
Node: SHA1462999
Node: Safe1467336
Node: Search/Base1478899
Node: Search/Dict1497181
Node: SelectSaver1497868
Node: SelfLoader1498774
Node: Set/IntSpan1506859
Node: Shell1516364
Node: Socket1517394
Node: Sort/Versions1522394
Node: Sprite1524823
Node: Statistics/ChiSquare1539131
Node: Statistics/LTU1545193
Node: Storable1552434
Node: String/Scanf1556252
Node: Sx1560809
Node: Sybase/BCP1649975
Node: Sybase/Login1657215
Node: Symbol1664627
Node: Sys/Hostname1666264
Node: Sys/Syslog1666951
Node: SysV1668889
Node: SyslogScan/ByGroup1673550
Node: SyslogScan/Delivery1676183
Node: SyslogScan/DeliveryIterator1680307
Node: SyslogScan/SendmailLine1685599
Node: SyslogScan/SendmailLineFrom1689587
Node: SyslogScan/SendmailLineTo1691830
Node: SyslogScan/SendmailUtil1694108
Node: SyslogScan/Summary1695956
Node: SyslogScan/SyslogEntry1702557
Node: SyslogScan/Usage1705163
Node: SyslogScan/WhereIs1709674
Node: Tcl1711211
Node: Tcl/Tk1718434
Node: Term/Cap1722762
Node: Term/Complete1726218
Node: Term/ReadKey1727312
Node: Term/ReadLine1734020
Node: Test/Harness1737267
Node: Text/Abbrev1740348
Node: Text/English1741089
Node: Text/German1742621
Node: Text/ParseWords1743461
Node: Text/Soundex1744878
Node: Text/Tabs1747666
Node: Text/Template1748690
Node: Text/Wrap1760535
Node: Tie/Dir1761448
Node: Tie/Hash1763842
Node: Tie/Scalar1766880
Node: Tie/SubstrHash1769467
Node: Tie/Watch1770992
Node: Time/CTime1776566
Node: Time/DaysInMonth1778509
Node: Time/HiRes1779164
Node: Time/JulianDay1783654
Node: Time/Local1785183
Node: Time/ParseDate1786780
Node: Time/Timezone1790421
Node: Time/Zone1791607
Node: Tk/FileDialog1792821
Node: Tk/SelFile1801648
Node: Tk/WaitBox1806236
Node: UNIVERSAL1810582
Node: URI/Escape1812326
Node: URI/URL1813717
Node: VRML1832768
Node: VRML/VRML11833613
Node: VRML/VRML1/Standard1835472
Node: WWW/RobotRules1840636
Node: WWW/RobotRules/AnyDBM_File1844791
Node: WWW/Search1845960
Node: WWW/Search/AltaVista1852373
Node: WWW/SearchResult1854505
Node: Xbase1855446
Node: diagnostics1862973
Node: gettext1868283
Node: integer1869672
Node: iodbc1870412
Node: less1883364
Node: lib1883890
Node: lwpcook1886544
Node: ops1895961
Node: overload1896734
Node: ptkFAQ1910775
Node: sigtrap1910949
Node: strict1915584
Node: subs1918595
Node: vars1919126

End tag table
