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


File: pm.info,  Node: gettext,  Next: import,  Prev: genopt,  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: import,  Next: integer,  Prev: gettext,  Up: Module List

import all modules with a package prefix, aliasing it away.
***********************************************************

NAME
====

   import - import all modules with a package prefix, aliasing it away.

   'import' acts as a pragma that performs a 'use' on all modules that can
be found with the given package prefix. Any modules found have a 'use'
statement performed, and the fully qualified package name is aliased to
one without the given prefix. The functionality is similar to Java's
'import' statement.

   See import.pod for details.

HISTORY
=======

     import.pm
     v1.01 10/10/99 mak

COPYRIGHT
=========

     Copyright (C) 1999 Michael King ( mike808@mo.net )
     Saint Louis, MO USA.

   This module is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

   This module is copyright (c) 1997,1998 by Michael King ( mike808@mo.net
) and is made available to the Perl public under terms of the Artistic
License used to cover Perl itself. See the file Artistic in the
distribution  of Perl 5.002 or later for details of copy and distribution
terms.

AVAILABILITY
============

   The latest version of this module is likely to be available from:

     http://walden.mo.net/~mike808/import_pm

   The best place to discuss this code is via email with the author.


File: pm.info,  Node: integer,  Next: iodbc,  Prev: import,  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 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.

   Note that this affects the operations, not the numbers.  If you run this
code

     use integer;
     $x = 1.5;
     $y = $x + 1;
     $z = -1.5;

   you'll be left with `$x == 1.5', `$y == 2' and `$z == -1'.  The $z case
happens because unary - counts as an operation.

   Native integer arithmetic (as provided by your C compiler) is used.
This means that Perl's own semantics for arithmetic operations may not be
preserved.  One common source of trouble is the modulus of negative
numbers, which Perl does one way, but your hardware may do another.

     % perl -le 'print (4 % -3)'
     -2
     % perl -Minteger -le 'print (4 % -3)'
     1

   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: libapreq,  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.

   To avoid memory leaks, all trailing duplicate entries in @INC are
removed.

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.

   The `no lib' statement deletes all instances of each named directory
from @INC.

   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.

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: libapreq,  Next: locale,  Prev: lib,  Up: Module List

Apache Request C Library
************************

NAME
====

   libapreq - Apache Request C Library

SYNOPSIS
========

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

ApacheRequest
=============

req->parms
     This field is an Apache table that holds the parsed contents of GET
     and POST requests.  Example:

          table *data = req->parms;
          ap_table_set(data, "Key", "Value");

req->post_max
     Limit the size of POST data.  *ApacheRequest_parse* will return an
     error code if the size is exceeded:

          int status;
          ApacheRequest *req = ApacheRequest_new(r);

          req->post_max = 1204;
          if((status = ApacheRequest_parse(req)) != OK) {
              char *errmsg = ap_table_get(r->notes, "error-notes");
              ...
              return status;
          }

req->disable_uploads
     Disable file uploads.  *ApacheRequest_parse* will return an error
     code if a file upload is attempted:

          int status;
          ApacheRequest *req = ApacheRequest_new(r);

          req->disable_uploads = 1;
          if((status = ApacheRequest_parse(req)) != OK) {
              char *errmsg = ap_table_get(r->notes, "error-notes");
              ...
              return status;
          }

ApacheRequest *ApacheRequest_new (request_rec *r)
-------------------------------------------------

   This function creates a new ApacheRequest object using the given
*request_rec* structure:

     ApacheRequest *req = ApacheRequest_new(r);

int ApacheRequest_parse (ApacheRequest *req)
--------------------------------------------

   If the request method is GET or POST, the query string arguments and
the client form data will be read, parsed and saved.  In addition, if the
request method is POST and the *Content-type* is *multipart/form-data*,
the uploaded files will be written to temporary files which can be
accessed with the upload field names.  The return value is OK on success,
otherwise an error code that your handler should return.

const char *ApacheRequest_param (ApacheRequest *req, const char *key)
---------------------------------------------------------------------

   This function will return the value of the given parameter key:

     const char *value = ApacheRequest_param(req, "Key");

array_header *ApacheRequest_params (ApacheRequest *req, const char *key)
------------------------------------------------------------------------

   This function will return an *array_header* of values for the given
parameter key:

     array_header *values = ApacheRequest_params(req, "Key");

char *ApacheRequest_params_as_string (ApacheRequest *req, const char *key)
--------------------------------------------------------------------------

   This function will format multi-value parmeters into a comma delimited
string.

     char *list = ApacheRequest_params_as_string(req, "Key");

ApacheUpload *upload = ApacheRequest_upload (ApacheRequest *req)
----------------------------------------------------------------

   If the request *Content-type* was that of *multipart/form-data*, this
will return an ApacheUpload pointer containing the upload data, NULL
otherwise.  See ApacheUpload.

     ApacheUpload *upload = ApacheRequest_upload(req);

ApacheUpload
============

   The ApacheUpload structure holds all information for all uploaded files
and is accessed via the upload field of an ApacheRequest structure.

upload->name
     The name of the filefield parameter:

          char *name = upload->name;

upload->filename
     The name of the upload file:

          char *filename = upload->filename;

upload->fp
     A file pointer to the uploaded file:

          FILE *fp = upload->fp;

upload->size
     The size of the uploaded file in bytes:

          long size = upload->size;

upload->info
     The additional header information for the uploaded file:

          table *info = upload->info;
          const char *type = ap_table_get(info, "Content-type");

upload->next
     Pointer to the next ApacheUpload structure if multiple files were
     uploaded:

          ApacheUpload *uptr;
          for (uptr = ApacheRequest_upload(req); uptr; uptr = uptr->next) {
          	char *name = uptr->name;
          	FILE *fp   = uptr->fp;
          	...
          }

ApacheUpload *ApacheUpload_find (ApacheUpload *upload, char *name)
------------------------------------------------------------------

   Returns the ApacheUpload pointer associated with name or NULL if name
is not found in the list:

     ApacheUpload *upload = ApacheUpload_find(upload, name);

const char *ApacheUpload_info (ApacheUpload *upload, char *key)
---------------------------------------------------------------

   Shortcut for accessing the info table:

     const char *type = ApacheUpload_info(upload, "Content-Type");

const char *ApacheUpload_type (ApacheUpload *upload)
----------------------------------------------------

   Shortcut for accessing the uploaded file *Content-Type*:

     const char *type = ApacheUpload_type(upload);

ApacheCookie
============

ApacheCookie *ApacheCookie_new (request_rec *r, ...)
----------------------------------------------------

   This function creates a new ApacheCookie object, using the given
*request_request* and optional attribute arguments which are as follows:

-name
     Sets the name field to the given value.

-value
     Adds the value to values field.

-expires
     Sets the expires field to the calculated date string.  See
     *ApacheCookie_expires* for a listing of format options.  The default
     is NULL.

-domain
     Sets the domain field to the given value.  The default is NULL.

-path
     Sets the path field to the given value.  The default path is derived
     from the requested *uri*.

-secure
     Sets the secure field to true or false using a given string value of
     On or *Off*.  The default is *Off*.

   Example:

     ApacheCookie *c = ApacheCookie_new(r,
     			"-name",    "foo",
                            "-value",   "bar",
                            "-expires", "+3M",
                            "-domain",  ".cp.net",
                            "-path",    "/mypath/database",
                            "-secure",  "On",
                            NULL);

char *ApacheCookie_attr (ApacheCookie *c, char *key, char *val)
---------------------------------------------------------------

   This function is used to get or set a cookie attribute pair, accepting
the same attributes as the list above.  Example:

     char *name = ApacheCookie_attr(c, "-name"); /* same as c->name */
     (void *)ApacheCookie_attr(c, "-expires", "+3h");

ApacheCookieJar *ApacheCookie_parse (request_rec *r, const char *data)
----------------------------------------------------------------------

   This function parses the given data string or the incoming *Cookie*
header, returning an *ApacheCookieJar* of ApacheCookie objects.

   Example:

     int i;
     ApacheCookieJar *cookies = ApacheCookie_parse(r, NULL);
     for (i = 0; i < ApacheCookieJarItems(cookies); i++) {
         ApacheCookie *c = ApacheCookieJarFetch(cookies, i);
         int j;
         for (j = 0; j < ApacheCookieItems(c); j++) {
             char *name = c->name;
             char *value = ApacheCookieFetch(c, j);
             ...
         }
     }

int ApacheCookieItems (ApacheCookie *c)
---------------------------------------

   The number of values for the given cookie.

char *ApacheCookieFetch (ApacheCookie *c, int n)
------------------------------------------------

   The nth value for the given cookie.

void ApacheCookieAdd (ApacheCookie *c, char *value)
---------------------------------------------------

   Add a new value to the cookie.

int ApacheCookieJarItems (ApacheCookieJar *cookies)
---------------------------------------------------

   The number of cookies in the given cookie jar.

ApacheCookie *ApacheCookieJarFetch (ApacheCookieJar *cookies, int n)
--------------------------------------------------------------------

   The nth cookie in the given cookie jar.

void ApacheCookieJarAdd (ApacheCookieJar *cookies, ApacheCookie *c)
-------------------------------------------------------------------

   Add a new cookie to the cookie jar.

char *ApacheCookie_expires (ApacheCookie *c, char *time_str)
------------------------------------------------------------

   This function gets or sets the expiration date for cookie.  The
following forms are all valid for the *time_str* parmeter:

     +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-1999 00:40:33 GMT  at the indicated time & date

void ApacheCookie_bake (ApacheCookie *c)
----------------------------------------

   Put cookie in the oven to bake.  (Add a *Set-Cookie* header to the
outgoing headers table.)

     ApacheCookie_bake(c);

char *ApacheCookie_as_string (ApacheCookie *c)
----------------------------------------------

   Returns a string version of the cookie:

     ap_table_add(r->headers_out, "Set-Cookie", ApacheCookie_as_string(c));

CREDITS
=======

   This library is based on Perl modules by Lincoln Stein.

AUTHOR
======

   Doug MacEachern


File: pm.info,  Node: locale,  Next: loose,  Prev: libapreq,  Up: Module List

Perl pragma to use and avoid POSIX locales for built-in operations
******************************************************************

NAME
====

   locale - Perl pragma to use and avoid POSIX locales for built-in
operations

SYNOPSIS
========

     @x = sort @y;	# ASCII sorting order
     {
         use locale;
         @x = sort @y;   # Locale-defined sorting order
     }
     @x = sort @y;	# ASCII sorting order again

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

   This pragma tells the compiler to enable (or disable) the use of POSIX
locales for built-in operations (LC_CTYPE for regular expressions, and
LC_COLLATE for string comparison).  Each "use locale" or "no locale"
affects statements to the end of the enclosing BLOCK.

   See *Note Perllocale: (perl.info)perllocale, for more detailed
information on how Perl supports locales.


File: pm.info,  Node: loose,  Next: lwpcook,  Prev: locale,  Up: Module List

Perl pragma to allow unsafe constructs
**************************************

NAME
====

   loose - Perl pragma to allow unsafe constructs

SYNOPSIS
========

     use loose;

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

   loose.pm provides you with a slack, casual environment in which to
write your Perl code.  It doesn't get hung up on little things like
warnings and die() calls, it just lets them slide.

   Use loose.pm to help relieve stress at the work place.  loose helps to
make your error logs shorter by getting right of all those wordly warning
messages.

BUGS
====

   Yeah, probably.  Who cares?

AUTHOR
======

   Michael G Schwern <schwern@pobox.com>


File: pm.info,  Node: lwpcook,  Next: mods,  Prev: loose,  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 command:

     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 = LWP::UserAgent->new;
     $ua->agent("$0/0.1 " . $ua->agent);
     # $ua->agent("Mozilla/8.0") # pretend we are very capable browser

     $req = HTTP::Request->new(GET => 'http://www.linpro.no/lwp');
     $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->status_line . "\n";
     }

   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 procedural 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 = LWP::UserAgent->new;

     my $req = HTTP::Request->new(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;

   Lazy people use the HTTP::Request::Common module to set up a suitable
POST request message (it handles all the escaping issues) and has a
suitable default for the content_type:

     use HTTP::Request::Common qw(POST);
     use LWP::UserAgent;
     $ua = LWP::UserAgent->new;

     my $req = POST 'http://www.perl.com/cgi-bin/BugGlimpse',
                   [ search => 'www', errors => 0 ];

     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 = LWP::UserAgent->new;
     $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 = HTTP::Request->new(GET => '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.

   Some proxies also require that you send it a username/password in order
to let requests through.  You should be able to add the required header,
with something like this:

     use LWP::UserAgent;

     $ua = LWP::UserAgent->new;
     $ua->proxy(['http', 'ftp'] => 'http://proxy.myorg.com');

     $req = HTTP::Request->new('GET',"http://www.perl.com");
     $req->proxy_authorization_basic("proxy_user", "proxy_password");

     $res = $ua->request($req);
     print $res->content if $res->is_success;

   Replace `proxy.myorg.com', `proxy_user' and `proxy_password' with
something suitable for your site.

ACCESS TO PROTECTED DOCUMENTS
=============================

   Documents protected by basic authorization can easily be accessed like
this:

     use LWP::UserAgent;
     $ua = LWP::UserAgent->new;
     $req = HTTP::Request->new(GET => 'http://www.linpro.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.

COOKIES
=======

   Some sites like to play games with cookies.  By default LWP ignores
cookies provided by the servers it visits.  LWP will collect cookies and
respond to cookie requests if you set up a cookie jar.

     use LWP::UserAgent;
     use HTTP::Cookies;

     $ua = LWP::UserAgent->new;
     $ua->cookie_jar(HTTP::Cookies->new(file => "lwpcookies.txt",
     				     autosave => 1));

     # and then send requests just as you used to do
     $res = $ua->request(HTTP::Request->new(GET => "http://www.yahoo.no"));
     print $res->status_line, "\n";

   As you visit sites that send you cookies to keep, then the file
`lwpcookies.txt"' will grow.

HTTPS
=====

   URLs with https scheme are accessed in exactly the same way as with
http scheme, provided that an SSL interface module for LWP has been
properly installed (see the `README.SSL' file found in the libwww-perl
distribution for more details).  If no SSL interface is installed for LWP
to use, then you will get "501 Protocol scheme 'https' is not supported"
errors when accessing such URLs.

   Here's an example of fetching and printing a WWW page using SSL:

     use LWP::UserAgent;

     my $ua = LWP::UserAgent->new;
     my $req = HTTP::Request->new(GET => 'https://www.helsinki.fi/');
     my $res = $ua->request($req);
     if ($res->is_success) {
         print $res->as_string;
     } else {
         print "Failed: ", $res->status_line, "\n";
     }

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 = LWP::UserAgent->new;

     my $req = HTTP::Request->new(GET =>
                   'http://www.linpro.no/lwp/libwww-perl-5.46.tar.gz');
     $res = $ua->request($req, "libwww-perl.tar.gz");
     if ($res->is_success) {
        print "ok\n";
     }
     else {
        print $res->status_line, "\n";
     }

   Or you can process the document as it arrives (second $ua->request()
argument is a code reference):

     use LWP::UserAgent;
     $ua = LWP::UserAgent->new;
     $URL = 'ftp://ftp.unit.no/pub/rfc/rfc-index.txt';

     my $expected_length;
     my $bytes_received = 0;
     my $res =
        $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;
                    });
        print $res->status_line, "\n";

COPYRIGHT
=========

   Copyright 1996-2000, 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: mods,  Next: open,  Prev: lwpcook,  Up: Module List

easy one-stop module shopping
*****************************

NAME
====

   *mods* - easy one-stop module shopping

SYNOPSIS
========

     use mods;   # Various defaults.

     use mods qw(SomePkg Other::Pkg(somefunc, $somevar));
     somefunc($somevar);

     use mods qw(foo bar());    # No imports from bar.pm; default from foo.pm.

   More options:

     use mods q{
       diagnostics,     # Integral comments! Commas optional.
       Foo (bar, baz)   # Whitespace ignored.
       Quux   Jolt();   # As you think.
       vars (	    # Multilines fine.
     	 $foo, $bar, $baz
     	)
       !strict(refs)    # Unimport.
       $foo, $bar;      # Alternate declaration of vars.
       {$bar=7}	    # Compile-time code.
       <this, $that, @theother!> # Export; &this and $that optional.
       [Foo, Bar::Baz]  # Inherit from these.
     };

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

   This pragmatic module is intended as a way to reduce clutter in the
prologue of a typical OO module, which often contains a large number of
repetitive directives. Encouraging a clean programming style is the intent.

   Each import-syntax item in the argument corresponds to a module to be
imported. Usage is very similar to normal use statements: no extra
arguments runs a default importation; empty parens bypass importation; and
arguments within parens, assumed to be literal and separated by commas
and/or whitespace, imports those items. An exclamation point before the
statement does an unimportation, like the no keyword. Note that both
standard modules and compiler pragmas are supported.

   Code inside braces is evaluated at compile time, as if it were inside a
BEGIN block.

   Words inside angle brackets are taken to be things to be exported with
the Exporter module (which is loaded for you, and your *@ISA*
appropriately extended). They are placed in *@EXPORT_OK*, or *@EXPORT* if
you append an exclamation point. If variables (vs. functions), they are
declared as globals for you.

   Words inside square brackets declare superclasses: they append to
*@ISA*.

   Variable names (scalar, array or hash) alone predeclare the variable,
as with vars.

   "#" introduces comments until end-of-line. If multiple arguments are
received, they are first joined together as you would expect.

DEFAULTS
========

   Without you needing to specify it, *mods* automatically:

   * Uses strict.

   * Uses integer.

   * Declares some common package variables for you (with vars): *@ISA*,
     *@EXPORT*, *@EXPORT_OK*, *%EXPORT_TAGS*, *@EXPORT_FAIL*, $AUTOLOAD,
     and $VERSION.

   If any of these defaults causes a problem in your module which cannot
be trivially reversed, precede all other directives by a tilde (`~') to
suppress them.

BUGS
====

   Implementation of *sim_use* workhorse function is incomprehensible to
the author.

AUTHORS
=======

   Jesse Glick, *jglick@sig.bsh.com*

REVISION
========

   X<$Format: "`$Source$' last modified $Date$ release $modsRelease$.
$Copyright$"$> `mods/lib/mods.pm' last modified Fri, 12 Sep 1997 23:21:20
-0400 release 0.004. Copyright (c) 1997 Strategic Interactive Group. 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: open,  Next: ops,  Prev: mods,  Up: Module List

perl pragma to set default disciplines for input and output
***********************************************************

NAME
====

   open - perl pragma to set default disciplines for input and output

SYNOPSIS
========

     use open IN => ":crlf", OUT => ":raw";

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

   The open pragma is used to declare one or more default disciplines for
I/O operations.  Any open() and readpipe() (aka qx//) operators found
within the lexical scope of this pragma will use the declared defaults.
Neither open() with an explicit set of disciplines, nor sysopen() are
influenced by this pragma.

   Only the two pseudo-disciplines ":raw" and ":crlf" are currently
available.

   The ":raw" discipline corresponds to "binary mode" and the ":crlf"
discipline corresponds to "text mode" on platforms that distinguish
between the two modes when opening files (which is many DOS-like
platforms, including Windows).  These two disciplines are currently no-ops
on platforms where binmode() is a no-op, but will be supported everywhere
in future.

UNIMPLEMENTED FUNCTIONALITY
===========================

   Full-fledged support for I/O disciplines is currently unimplemented.
When they are eventually supported, this pragma will serve as one of the
interfaces to declare default disciplines for all I/O.

   In future, any default disciplines declared by this pragma will be
available by the special discipline name ":DEFAULT", and could be used
within handle constructors that allow disciplines to be specified.  This
would make it possible to stack new disciplines over the default ones.

     open FH, "<:para :DEFAULT", $file or die "can't open $file: $!";

   Socket and directory handles will also support disciplines in future.

   Full support for I/O disciplines will enable all of the supported
disciplines to work on all platforms.

SEE ALSO
========

   `"binmode"', *Note Perlfunc: (perl.info)perlfunc,, `"open"', *Note
Perlfunc: (perl.info)perlfunc,, `"open"', *Note Perlunicode:
(perl.info)perlunicode,


File: pm.info,  Node: ops,  Next: overload,  Prev: open,  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 irreversible 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: perlrpcgen/Fstream,  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;

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.  Note
that values specified as strings are interpreted as methods, not
subroutines.  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.)

   Since overloading respects inheritance via the @ISA hierarchy, the
above declaration would also trigger overloading of + and `*=' in all the
packages which inherit from Number.

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.  Compare `Calling
     Conventions for Mutators' in this node.

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.

Calling Conventions for Mutators
--------------------------------

   Two types of mutators have different calling conventions:

`++' and -
     The routines which implement these operators are expected to actually
     mutate their arguments.  So, assuming that $obj is a reference to a
     number,

          sub incr { my $n = $ {$_[0]}; ++$n; $_[0] = bless \$n}

     is an appropriate implementation of overloaded `++'.  Note that

          sub incr { ++$ {$_[0]} ; shift }

     is OK if used with preincrement and with postincrement. (In the case
     of postincrement a copying will be performed, see `Copy Constructor'
     in this node.)

`x=' and other assignment versions
     There is nothing special about these methods.  They may change the
     value of their arguments, and may leave it as is.  The result is going
     to be assigned to the value in the left-hand-side if different from
     this value.

     This allows for the same method to be used as overloaded `+=' and +.
     Note that this is allowed, but not recommended, since by the semantic
     of `"Fallback"' in this node Perl will call the method for + anyway,
     if `+=' is not overloaded.

   *Warning.*  Due to the presense of assignment versions of operations,
routines which may be called in assignment context may create
self-referential structures.  Currently Perl will not free self-referential
structures until cycles are `explicitly' broken.  You may get problems
when traversing your structures too.

   Say,

     use overload '+' => sub { bless [ \$_[0], \$_[1] ] };

   is asking for trouble, since for code `$obj += $foo' the subroutine is
called as `$obj = add($obj, $foo, undef)', or `$obj = [\$obj, \$foo]'.  If
using such a subroutine is an important optimization, one can overload
`+=' explicitly by a non-"optimized" version, or switch to non-optimized
version if `not defined $_[2]' (see `Calling Conventions for Binary
Operations' in this node).

   Even if no explicit assignment-variants of operators are present in the
script, they may be generated by the optimizer.  Say, `",$obj,"' or `',' .
$obj . ','' may be both optimized to

     my $tmp = ',' . $obj;    $tmp .= ',';

Overloadable Operations
-----------------------

   The following symbols can be specified in `use overload' directive:

   * *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.

     See `"MAGIC AUTOGENERATION"' in this node, `"Calling Conventions for
     Mutators"' in this node and `"Calling Conventions for Binary
     Operations"' in this node) for details of these substitutions.

   * *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 not overloaded, 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.

   * *Iteration*
          "<>"

     If not overloaded, the argument will be converted to a filehandle or
     glob (which may require a stringification).  The same overloading
     happens both for the *read-filehandle* syntax `<$var>' and *globbing*
     syntax `<${var}>'.

   * Dereferencing
          '${}', '@{}', '%{}', '&{}', '*{}'.

     If not overloaded, the argument will be dereferenced *as is*, thus
     should be of correct type.  These functions should return a reference
     of correct type, or another object with overloaded dereferencing.

   * 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.

   A computer-readable form of the above table is available in the hash
%overload::ops, with values being space-separated lists of names:

     with_assign	  => '+ - * / % ** << >> x .',
     assign		  => '+= -= *= /= %= **= <<= >>= x= .=',
     num_comparison	  => '< <= > >= == !=',
     '3way_comparison'=> '<=> cmp',
     str_comparison	  => 'lt le gt ge eq ne',
     binary		  => '& | ^',
     unary		  => 'neg ! ~',
     mutators	  => '++ --',
     func		  => 'atan2 cos sin exp abs log sqrt',
     conversion	  => 'bool "" 0+',
     iterators	  => '<>',
     dereferencing	  => '${} @{} %{} &{} *{}',
     special	  => 'nomethod fallback ='

Inheritance and overloading
---------------------------

   Inheritance interacts with overloading in two ways.

Strings as values of `use overload' directive
     If value in

          use overload key => value;

     is a string, it is interpreted as a method name.

Overloading of an operation is inherited by derived classes
     Any class derived from an overloaded class is also overloaded.  The
     set of overloaded methods is the union of overloaded methods of all
     the ancestors. If some method is overloaded in several ancestor, then
     which description will be used is decided by the usual inheritance
     rules:

     If A inherits from B and C (in this order), B overloads + with
     `\&D::plus_sub', and C overloads + by `"plus_meth"', then the
     subroutine `D::plus_sub' will be called to implement operation + for
     an object in package A.

   Note that since the value of the `fallback' key is not a subroutine,
its inheritance is not governed by the above rules.  In the current
implementation, the value of `fallback' in the first overloaded ancestor
is used, but this is accidental and subject to change.

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.

   *Note.* `"fallback"' inheritance via @ISA is not carved in stone yet,
see `"Inheritance and overloading"' in this node.

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 `'+='' (or `nomethod').  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'.

   Same behaviour is triggered by `$b = $a++', which is consider a synonym
for `$b = $a; ++$a'.

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

Iterator
          <>				in terms of builtin operations

Dereferencing
          ${} @{} %{} &{} *{}		in terms of builtin operations

*Copy operator*
     can be expressed in terms of an assignment to the dereferenced value,
     if this value is a scalar and not a reference.

Losing overloading
==================

   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.

Overloading constants
=====================

   For some application Perl parser mangles constants too much.  It is
possible to hook into this process via overload::constant() and
overload::remove_constant() functions.

   These functions take a hash as an argument.  The recognized keys of
this hash are

integer
     to overload integer constants,

float
     to overload floating point constants,

binary
     to overload octal and hexadecimal constants,

q
     to overload q-quoted strings, constant pieces of qq- and `qx'-quoted
     strings and here-documents,

qr
     to overload constant pieces of regular expressions.

   The corresponding values are references to functions which take three
arguments: the first one is the *initial* string form of the constant, the
second one is how Perl interprets this constant, the third one is how the
constant is used.  Note that the initial string form does not contain
string delimiters, and has backslashes in backslash-delimiter combinations
stripped (thus the value of delimiter is not relevant for processing of
this string).  The return value of this function is how this constant is
going to be interpreted by Perl.  The third argument is undefined unless
for overloaded q- and qr- constants, it is q in single-quote context
(comes from strings, regular expressions, and single-quote HERE
documents), it is tr for arguments of tr/y operators, it is s for
right-hand side of s-operator, and it is qq otherwise.

   Since an expression `"ab$cd,,"' is just a shortcut for `'ab' . $cd .
',,'', it is expected that overloaded constant strings are equipped with
reasonable overloaded catenation operator, otherwise absurd results will
result.  Similarly, negative numbers are considered as negations of
positive constants.

   Note that it is probably meaningless to call the functions
overload::constant() and overload::remove_constant() from anywhere but
import() and unimport() methods.  From these methods they may be called as

     sub import {
       shift;
       return unless @_;
       die "unknown import: @_" unless @_ == 1 and $_[0] eq ':constant';
       overload::constant integer => sub {Math::BigInt->new(shift)};
     }

   BUGS Currently overloaded-ness of constants does not propagate into
`eval '...''.

IMPLEMENTATION
==============

   What follows is subject to change RSN.

   The table of methods for all operations is cached in magic for the
symbol table hash for the package.  The cache is invalidated during
processing of `use overload', `no overload', new function definitions, and
changes in @ISA. However, this invalidation remains unprocessed until the
next blessing into the package. Hence if you want to change overloading
structure 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. However, the
magic which implements overloading is applied to the stashes, which are
rarely used directly, thus should not slow down Perl.)

   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 in some package, 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. The only
size penalty if overload is used in some package is that all the packages
acquire a magic during the next blessing into the package. This magic is
three-words-long for packages without overloading, and carries the cache
table if the package is overloaded.

   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).

Metaphor clash
==============

   One may wonder why the semantic of overloaded = is so counter intuitive.
If it *looks* counter intuitive to you, you are subject to a metaphor
clash.

   Here is a Perl object metaphor:

   *  object is a reference to blessed data*

   and an arithmetic metaphor:

   *  object is a thing by itself*.

   The main problem of overloading = is the fact that these metaphors
imply different actions on the assignment `$a = $b' if $a and $b are
objects.  Perl-think implies that $a becomes a reference to whatever $b
was referencing.  Arithmetic-think implies that the value of "object" $a
is changed to become the value of the object $b, preserving the fact that
$a and $b are separate entities.

   The difference is not relevant in the absence of mutators.  After a
Perl-way assignment an operation which mutates the data referenced by $a
would change the data referenced by $b too.  Effectively, after `$a = $b'
values of $a and $b become *indistinguishable*.

   On the other hand, anyone who has used algebraic notation knows the
expressive power of the arithmetic metaphor.  Overloading works hard to
enable this metaphor while preserving the Perlian way as far as possible.
Since it is not not possible to freely mix two contradicting metaphors,
overloading allows the arithmetic way to write things *as far as all the
mutators are called via overloaded access only*.  The way it is done is
described in `Copy Constructor' in this node.

   If some mutator methods are directly applied to the overloaded values,
one may need to *explicitly unlink* other values which references the same
value:

     $a = new Data 23;
     ...
     $b = $a;		# $b is "linked" to $a
     ...
     $a = $a->clone;	# Unlink $b from $a
     $a->increment_by(4);

   Note that overloaded access makes this transparent:

     $a = new Data 23;
     $b = $a;		# $b is "linked" to $a
     $a += 4;		# would unlink $b automagically

   However, it would not make

     $a = new Data 23;
     $a = 4;		# Now $a is a plain 4, not 'Data'

   preserve "objectness" of $a.  But Perl *has* a way to make assignments
to an object do whatever you want.  It is just not the overload, but
tie()ing interface (see `tie', *Note Perlfunc: (perl.info)perlfunc,).
Adding a FETCH() method which returns the object itself, and STORE()
method which changes the value of the object, one can reproduce the
arithmetic metaphor in its completeness, at least for variables which were
tie()d from the start.

   (Note that a workaround for a bug may be needed, see `"BUGS"' in this
node.)

Cookbook
========

   Please add examples to what follows!

Two-face scalars
----------------

   Put this in `two_face.pm' in your Perl library directory:

     package two_face;		# Scalars with separate string and
                                   # numeric values.
     sub new { my $p = shift; bless [@_], $p }
     use overload '""' => \&str, '0+' => \&num, fallback => 1;
     sub num {shift->[1]}
     sub str {shift->[0]}

   Use it as follows:

     require two_face;
     my $seven = new two_face ("vii", 7);
     printf "seven=$seven, seven=%d, eight=%d\n", $seven, $seven+1;
     print "seven contains `i'\n" if $seven =~ /i/;

   (The second line creates a scalar which has both a string value, and a
numeric value.)  This prints:

     seven=vii, seven=7, eight=8
     seven contains `i'

Two-face references
-------------------

   Suppose you want to create an object which is accessible as both an
array reference, and a hash reference, similar to the builtin
`array-accessible-as-a-hash|perlref' in this node builtin Perl type.  Let
us make it better than the builtin type, there will be no restriction that
you cannot use the index 0 of your array.

     package two_refs;
     use overload '%{}' => \&gethash, '@{}' => sub { $ {shift()} };
     sub new {
       my $p = shift;
       bless \ [@_], $p;
     }
     sub gethash {
       my %h;
       my $self = shift;
       tie %h, ref $self, $self;
       \%h;
     }

     sub TIEHASH { my $p = shift; bless \ shift, $p }
     my %fields;
     my $i = 0;
     $fields{$_} = $i++ foreach qw{zero one two three};
     sub STORE {
       my $self = ${shift()};
       my $key = $fields{shift()};
       defined $key or die "Out of band access";
       $$self->[$key] = shift;
     }
     sub FETCH {
       my $self = ${shift()};
       my $key = $fields{shift()};
       defined $key or die "Out of band access";
       $$self->[$key];
     }

   Now one can access an object using both the array and hash syntax:

     my $bar = new two_refs 3,4,5,6;
     $bar->[2] = 11;
     $bar->{two} == 11 or die 'bad hash fetch';

   Note several important features of this example.  First of all, the
*actual* type of $bar is a scalar reference, and we do not overload the
scalar dereference.  Thus we can get the *actual* non-overloaded contents
of $bar by just using `$$bar' (what we do in functions which overload
dereference).  Similarly, the object returned by the TIEHASH() method is a
scalar reference.

   Second, we create a new tied hash each time the hash syntax is used.
This allows us not to worry about a possibility of a reference loop, would
would lead to a memory leak.

   Both these problems can be cured.  Say, if we want to overload hash
dereference on a reference to an object which is *implemented* as a hash
itself, the only problem one has to circumvent is how to access this
*actual* hash (as opposed to the *virtual* exhibited by overloaded
dereference operator).  Here is one possible fetching routine:

     sub access_hash {
       my ($self, $key) = (shift, shift);
       my $class = ref $self;
       bless $self, 'overload::dummy'; # Disable overloading of %{}
       my $out = $self->{$key};
       bless $self, $class;	# Restore overloading
       $out;
     }

   To move creation of the tied hash on each access, one may an extra
level of indirection which allows a non-circular structure of references:

     package two_refs1;
     use overload '%{}' => sub { ${shift()}->[1] },
                  '@{}' => sub { ${shift()}->[0] };
     sub new {
       my $p = shift;
       my $a = [@_];
       my %h;
       tie %h, $p, $a;
       bless \ [$a, \%h], $p;
     }
     sub gethash {
       my %h;
       my $self = shift;
       tie %h, ref $self, $self;
       \%h;
     }

     sub TIEHASH { my $p = shift; bless \ shift, $p }
     my %fields;
     my $i = 0;
     $fields{$_} = $i++ foreach qw{zero one two three};
     sub STORE {
       my $a = ${shift()};
       my $key = $fields{shift()};
       defined $key or die "Out of band access";
       $a->[$key] = shift;
     }
     sub FETCH {
       my $a = ${shift()};
       my $key = $fields{shift()};
       defined $key or die "Out of band access";
       $a->[$key];
     }

   Now if $baz is overloaded like this, then `$bar' is a reference to a
reference to the intermediate array, which keeps a reference to an actual
array, and the access hash.  The tie()ing object for the access hash is
also a reference to a reference to the actual array, so

   * There are no loops of references.

   * Both "objects" which are blessed into the class `two_refs1' are
     references to a reference to an array, thus references to a scalar.
     Thus the accessor expression `$$foo->[$ind]' involves no overloaded
     operations.

Symbolic calculator
-------------------

   Put this in `symbolic.pm' in your Perl library directory:

     package symbolic;		# Primitive symbolic calculator
     use overload nomethod => \&wrap;

     sub new { shift; bless ['n', @_] }
     sub wrap {
       my ($obj, $other, $inv, $meth) = @_;
       ($obj, $other) = ($other, $obj) if $inv;
       bless [$meth, $obj, $other];
     }

   This module is very unusual as overloaded modules go: it does not
provide any usual overloaded operators, instead it provides the `Last
Resort' in this node operator `nomethod'.  In this example the
corresponding subroutine returns an object which encapsulates operations
done over the objects: `new symbolic 3' contains `['n', 3]', `2 + new
symbolic 3' contains `['+', 2, ['n', 3]]'.

   Here is an example of the script which "calculates" the side of
circumscribed octagon using the above package:

     require symbolic;
     my $iter = 1;			# 2**($iter+2) = 8
     my $side = new symbolic 1;
     my $cnt = $iter;

     while ($cnt--) {
       $side = (sqrt(1 + $side**2) - 1)/$side;
     }
     print "OK\n";

   The value of $side is

     ['/', ['-', ['sqrt', ['+', 1, ['**', ['n', 1], 2]],
     	               undef], 1], ['n', 1]]

   Note that while we obtained this value using a nice little script,
there is no simple way to use this value.  In fact this value may be
inspected in debugger (see *Note Perldebug: (perl.info)perldebug,), but
ony if bareStringify Option is set, and not via p command.

   If one attempts to print this value, then the overloaded operator ""
will be called, which will call `nomethod' operator.  The result of this
operator will be stringified again, but this result is again of type
`symbolic', which will lead to an infinite loop.

   Add a pretty-printer method to the module `symbolic.pm':

     sub pretty {
       my ($meth, $a, $b) = @{+shift};
       $a = 'u' unless defined $a;
       $b = 'u' unless defined $b;
       $a = $a->pretty if ref $a;
       $b = $b->pretty if ref $b;
       "[$meth $a $b]";
     }

   Now one can finish the script by

     print "side = ", $side->pretty, "\n";

   The method pretty is doing object-to-string conversion, so it is
natural to overload the operator "" using this method.  However, inside
such a method it is not necessary to pretty-print the components $a and $b
of an object.  In the above subroutine `"[$meth $a $b]"' is a catenation
of some strings and components $a and $b.  If these components use
overloading, the catenation operator will look for an overloaded operator
., if not present, it will look for an overloaded operator "".  Thus it is
enough to use

     use overload nomethod => \&wrap, '""' => \&str;
     sub str {
       my ($meth, $a, $b) = @{+shift};
       $a = 'u' unless defined $a;
       $b = 'u' unless defined $b;
       "[$meth $a $b]";
     }

   Now one can change the last line of the script to

     print "side = $side\n";

   which outputs

     side = [/ [- [sqrt [+ 1 [** [n 1 u] 2]] u] 1] [n 1 u]]

   and one can inspect the value in debugger using all the possible
methods.

   Something is is still amiss: consider the loop variable $cnt of the
script.  It was a number, not an object.  We cannot make this value of
type `symbolic', since then the loop will not terminate.

   Indeed, to terminate the cycle, the $cnt should become false.  However,
the operator `bool' for checking falsity is overloaded (this time via
overloaded ""), and returns a long string, thus any object of type
`symbolic' is true.  To overcome this, we need a way to compare an object
to 0.  In fact, it is easier to write a numeric conversion routine.

   Here is the text of `symbolic.pm' with such a routine added (and
slightly modified str()):

     package symbolic;		# Primitive symbolic calculator
     use overload
       nomethod => \&wrap, '""' => \&str, '0+' => \&num;

     sub new { shift; bless ['n', @_] }
     sub wrap {
       my ($obj, $other, $inv, $meth) = @_;
       ($obj, $other) = ($other, $obj) if $inv;
       bless [$meth, $obj, $other];
     }
     sub str {
       my ($meth, $a, $b) = @{+shift};
       $a = 'u' unless defined $a;
       if (defined $b) {
         "[$meth $a $b]";
       } else {
         "[$meth $a]";
       }
     }
     my %subr = ( n => sub {$_[0]},
     	       sqrt => sub {sqrt $_[0]},
     	       '-' => sub {shift() - shift()},
     	       '+' => sub {shift() + shift()},
     	       '/' => sub {shift() / shift()},
     	       '*' => sub {shift() * shift()},
     	       '**' => sub {shift() ** shift()},
     	     );
     sub num {
       my ($meth, $a, $b) = @{+shift};
       my $subr = $subr{$meth}
         or die "Do not know how to ($meth) in symbolic";
       $a = $a->num if ref $a eq __PACKAGE__;
       $b = $b->num if ref $b eq __PACKAGE__;
       $subr->($a,$b);
     }

   All the work of numeric conversion is done in %subr and num().  Of
course, %subr is not complete, it contains only operators used in the
example below.  Here is the extra-credit question: why do we need an
explicit recursion in num()?  (Answer is at the end of this section.)

   Use this module like this:

     require symbolic;
     my $iter = new symbolic 2;	# 16-gon
     my $side = new symbolic 1;
     my $cnt = $iter;

     while ($cnt) {
       $cnt = $cnt - 1;		# Mutator `--' not implemented
       $side = (sqrt(1 + $side**2) - 1)/$side;
     }
     printf "%s=%f\n", $side, $side;
     printf "pi=%f\n", $side*(2**($iter+2));

   It prints (without so many line breaks)

     [/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1]
     			  [n 1]] 2]]] 1]
        [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]=0.198912
     pi=3.182598

   The above module is very primitive.  It does not implement mutator
methods (`++', `-=' and so on), does not do deep copying (not required
without mutators!), and implements only those arithmetic operations which
are used in the example.

   To implement most arithmetic operations is easy, one should just use
the tables of operations, and change the code which fills %subr to

     my %subr = ( 'n' => sub {$_[0]} );
     foreach my $op (split " ", $overload::ops{with_assign}) {
       $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
     }
     my @bins = qw(binary 3way_comparison num_comparison str_comparison);
     foreach my $op (split " ", "@overload::ops{ @bins }") {
       $subr{$op} = eval "sub {shift() $op shift()}";
     }
     foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
       print "defining `$op'\n";
       $subr{$op} = eval "sub {$op shift()}";
     }

   Due to `Calling Conventions for Mutators' in this node, we do not need
anything special to make `+=' and friends work, except filling `+=' entry
of %subr, and defining a copy constructor (needed since Perl has no way to
know that the implementation of `'+='' does not mutate the argument,
compare `Copy Constructor' in this node).

   To implement a copy constructor, add `'=' =' \&cpy> to `use overload'
line, and code (this code assumes that mutators change things one level
deep only, so recursive copying is not needed):

     sub cpy {
       my $self = shift;
       bless [@$self], ref $self;
     }

   To make `++' and - work, we need to implement actual mutators, either
directly, or in `nomethod'.  We continue to do things inside `nomethod',
thus add

     if ($meth eq '++' or $meth eq '--') {
       @$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference
       return $obj;
     }

   after the first line of wrap().  This is not a most effective
implementation, one may consider

     sub inc { $_[0] = bless ['++', shift, 1]; }

   instead.

   As a final remark, note that one can fill %subr by

     my %subr = ( 'n' => sub {$_[0]} );
     foreach my $op (split " ", $overload::ops{with_assign}) {
       $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
     }
     my @bins = qw(binary 3way_comparison num_comparison str_comparison);
     foreach my $op (split " ", "@overload::ops{ @bins }") {
       $subr{$op} = eval "sub {shift() $op shift()}";
     }
     foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
       $subr{$op} = eval "sub {$op shift()}";
     }
     $subr{'++'} = $subr{'+'};
     $subr{'--'} = $subr{'-'};

   This finishes implementation of a primitive symbolic calculator in 50
lines of Perl code.  Since the numeric values of subexpressions are not
cached, the calculator is very slow.

   Here is the answer for the exercise: In the case of str(), we need no
explicit recursion since the overloaded .-operator will fall back to an
existing overloaded operator "".  Overloaded arithmetic operators *do not*
fall back to numeric conversion if `fallback' is not explicitly requested.
Thus without an explicit recursion num() would convert `['+', $a, $b]' to
`$a + $b', which would just rebuild the argument of num().

   If you wonder why defaults for conversion are different for str() and
num(), note how easy it was to write the symbolic calculator.  This
simplicity is due to an appropriate choice of defaults.  One extra note:
due to the explicit recursion num() is more fragile than sym(): we need to
explicitly check for the type of $a and $b.  If components $a and $b
happen to be of some related type, this may lead to problems.

Really symbolic calculator
--------------------------

   One may wonder why we call the above calculator symbolic.  The reason
is that the actual calculation of the value of expression is postponed
until the value is used.

   To see it in action, add a method

     sub STORE {
       my $obj = shift;
       $#$obj = 1;
       @$obj->[0,1] = ('=', shift);
     }

   to the package `symbolic'.  After this change one can do

     my $a = new symbolic 3;
     my $b = new symbolic 4;
     my $c = sqrt($a**2 + $b**2);

   and the numeric value of $c becomes 5.  However, after calling

     $a->STORE(12);  $b->STORE(5);

   the numeric value of $c becomes 13.  There is no doubt now that the
module symbolic provides a *symbolic* calculator indeed.

   To hide the rough edges under the hood, provide a tie()d interface to
the package `symbolic' (compare with `Metaphor clash' in this node).  Add
methods

     sub TIESCALAR { my $pack = shift; $pack->new(@_) }
     sub FETCH { shift }
     sub nop {  }		# Around a bug

   (the bug is described in `"BUGS"' in this node).  One can use this new
interface as

     tie $a, 'symbolic', 3;
     tie $b, 'symbolic', 4;
     $a->nop;  $b->nop;	# Around a bug

     my $c = sqrt($a**2 + $b**2);

   Now numeric value of $c is 5.  After `$a = 12; $b = 5' the numeric value
of $c becomes 13.  To insulate the user of the module add a method

     sub vars { my $p = shift; tie($_, $p), $_->nop foreach @_; }

   Now

     my ($a, $b);
     symbolic->vars($a, $b);
     my $c = sqrt($a**2 + $b**2);

     $a = 3; $b = 4;
     printf "c5  %s=%f\n", $c, $c;

     $a = 12; $b = 5;
     printf "c13  %s=%f\n", $c, $c;

   shows that the numeric value of $c follows changes to the values of $a
and $b.

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.

   Using the m command of Perl debugger (see *Note Perldebug:
(perl.info)perldebug,) one can deduce which operations are overloaded (and
which ancestor triggers this overloading). Say, if eq is overloaded, then
the method `(eq' is shown by debugger. The method `()' corresponds to the
`fallback' key (in fact a presence of this method shows that this package
has overloading enabled, and it is what is used by the `Overloaded'
function of module overload).

BUGS
====

   Because it is used for overloading, the per-package hash %OVERLOAD now
has a special meaning in Perl. The symbol table is filled with names
looking like line-noise.

   For the purpose of inheritance every overloaded package behaves as if
`fallback' is present (possibly undefined). This may create interesting
effects if some package is not overloaded, but inherits from two
overloaded packages.

   Relation between overloading and tie()ing is broken.  Overloading is
triggered or not basing on the previous class of tie()d value.

   This happens because the presence of overloading is checked too early,
before any tie()d access is attempted.  If the FETCH()ed class of the
tie()d value does not change, a simple workaround is to access the value
immediately after tie()ing, so that after this call the previous class
coincides with the current one.

   *Needed:* a way to fix this without a speed penalty.

   Barewords are not covered by overloaded string constants.

   This document is confusing.  There are grammos and misleading language
used in places.  It would seem a total rewrite is needed.


