Plan 9 from Bell Labs’s /usr/web/sources/contrib/gabidiaz/root/sys/man/1perl/perlguts

Copyright © 2021 Plan 9 Foundation.
Distributed under the MIT License.
Download the Plan 9 distribution.


.\" Automatically generated by Pod::Man v1.34, Pod::Parser v1.13
.\"
.\" Standard preamble:
.\" ========================================================================
.de Sh \" Subsection heading
.br
.if t .Sp
.ne 5
.PP
\fB\\$1\fR
.PP
..
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Vb \" Begin verbatim text
.ft CW
.nf
.ne \\$1
..
.de Ve \" End verbatim text
.ft R
.fi
..
.\" Set up some character translations and predefined strings.  \*(-- will
.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
.\" double quote, and \*(R" will give a right double quote.  | will give a
.\" real vertical bar.  \*(C+ will give a nicer C++.  Capital omega is used to
.\" do unbreakable dashes and therefore won't be available.  \*(C` and \*(C'
.\" expand to `' in nroff, nothing in troff, for use with C<>.
.tr \(*W-|\(bv\*(Tr
.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
.ie n \{\
.    ds -- \(*W-
.    ds PI pi
.    if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
.    if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\"  diablo 12 pitch
.    ds L" ""
.    ds R" ""
.    ds C` ""
.    ds C' ""
'br\}
.el\{\
.    ds -- \|\(em\|
.    ds PI \(*p
.    ds L" ``
.    ds R" ''
'br\}
.\"
.\" If the F register is turned on, we'll generate index entries on stderr for
.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
.\" entries marked with X<> in POD.  Of course, you'll have to process the
.\" output yourself in some meaningful fashion.
.if \nF \{\
.    de IX
.    tm Index:\\$1\t\\n%\t"\\$2"
..
.    nr % 0
.    rr F
.\}
.\"
.\" For nroff, turn off justification.  Always turn off hyphenation; it makes
.\" way too many mistakes in technical documents.
.hy 0
.if n .na
.\"
.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
.\" Fear.  Run.  Save yourself.  No user-serviceable parts.
.    \" fudge factors for nroff and troff
.if n \{\
.    ds #H 0
.    ds #V .8m
.    ds #F .3m
.    ds #[ \f1
.    ds #] \fP
.\}
.if t \{\
.    ds #H ((1u-(\\\\n(.fu%2u))*.13m)
.    ds #V .6m
.    ds #F 0
.    ds #[ \&
.    ds #] \&
.\}
.    \" simple accents for nroff and troff
.if n \{\
.    ds ' \&
.    ds ` \&
.    ds ^ \&
.    ds , \&
.    ds ~ ~
.    ds /
.\}
.if t \{\
.    ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
.    ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
.    ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
.    ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
.    ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
.    ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
.\}
.    \" troff and (daisy-wheel) nroff accents
.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
.ds ae a\h'-(\w'a'u*4/10)'e
.ds Ae A\h'-(\w'A'u*4/10)'E
.    \" corrections for vroff
.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
.    \" for low resolution devices (crt and lpr)
.if \n(.H>23 .if \n(.V>19 \
\{\
.    ds : e
.    ds 8 ss
.    ds o a
.    ds d- d\h'-1'\(ga
.    ds D- D\h'-1'\(hy
.    ds th \o'bp'
.    ds Th \o'LP'
.    ds ae ae
.    ds Ae AE
.\}
.rm #[ #] #H #V #F C
.\" ========================================================================
.\"
.IX Title "PERLGUTS 1"
.TH PERLGUTS 1 "2002-11-24" "perl v5.8.0" "Perl Programmers Reference Guide"
.SH "NAME"
perlguts \- Introduction to the Perl API
.SH "DESCRIPTION"
.IX Header "DESCRIPTION"
This document attempts to describe how to use the Perl \s-1API\s0, as well as
containing some info on the basic workings of the Perl core. It is far
from complete and probably contains many errors. Please refer any
questions or comments to the author below.
.SH "Variables"
.IX Header "Variables"
.Sh "Datatypes"
.IX Subsection "Datatypes"
Perl has three typedefs that handle Perl's three main data types:
.PP
.Vb 3
\&    SV  Scalar Value
\&    AV  Array Value
\&    HV  Hash Value
.Ve
.PP
Each typedef has specific routines that manipulate the various data types.
.ie n .Sh "What is an ""\s-1IV\s0""?"
.el .Sh "What is an ``\s-1IV\s0''?"
.IX Subsection "What is an IV?"
Perl uses a special typedef \s-1IV\s0 which is a simple signed integer type that is
guaranteed to be large enough to hold a pointer (as well as an integer).
Additionally, there is the \s-1UV\s0, which is simply an unsigned \s-1IV\s0.
.PP
Perl also uses two special typedefs, I32 and I16, which will always be at
least 32\-bits and 16\-bits long, respectively. (Again, there are U32 and U16,
as well.)  They will usually be exactly 32 and 16 bits long, but on Crays
they will both be 64 bits.
.Sh "Working with SVs"
.IX Subsection "Working with SVs"
An \s-1SV\s0 can be created and loaded with one command.  There are five types of
values that can be loaded: an integer value (\s-1IV\s0), an unsigned integer
value (\s-1UV\s0), a double (\s-1NV\s0), a string (\s-1PV\s0), and another scalar (\s-1SV\s0).
.PP
The seven routines are:
.PP
.Vb 7
\&    SV*  newSViv(IV);
\&    SV*  newSVuv(UV);
\&    SV*  newSVnv(double);
\&    SV*  newSVpv(const char*, int);
\&    SV*  newSVpvn(const char*, int);
\&    SV*  newSVpvf(const char*, ...);
\&    SV*  newSVsv(SV*);
.Ve
.PP
If you require more complex initialisation you can create an empty \s-1SV\s0 with
newSV(len).  If \f(CW\*(C`len\*(C'\fR is 0 an empty \s-1SV\s0 of type \s-1NULL\s0 is returned, else an
\&\s-1SV\s0 of type \s-1PV\s0 is returned with len + 1 (for the \s-1NUL\s0) bytes of storage
allocated, accessible via SvPVX.  In both cases the \s-1SV\s0 has value undef.
.PP
.Vb 2
\&    SV*  newSV(0);   /* no storage allocated  */
\&    SV*  newSV(10);  /* 10 (+1) bytes of uninitialised storage allocated  */
.Ve
.PP
To change the value of an *already\-existing* \s-1SV\s0, there are eight routines:
.PP
.Vb 8
\&    void  sv_setiv(SV*, IV);
\&    void  sv_setuv(SV*, UV);
\&    void  sv_setnv(SV*, double);
\&    void  sv_setpv(SV*, const char*);
\&    void  sv_setpvn(SV*, const char*, int)
\&    void  sv_setpvf(SV*, const char*, ...);
\&    void  sv_vsetpvfn(SV*, const char*, STRLEN, va_list *, SV **, I32, bool *);
\&    void  sv_setsv(SV*, SV*);
.Ve
.PP
Notice that you can choose to specify the length of the string to be
assigned by using \f(CW\*(C`sv_setpvn\*(C'\fR, \f(CW\*(C`newSVpvn\*(C'\fR, or \f(CW\*(C`newSVpv\*(C'\fR, or you may
allow Perl to calculate the length by using \f(CW\*(C`sv_setpv\*(C'\fR or by specifying
0 as the second argument to \f(CW\*(C`newSVpv\*(C'\fR.  Be warned, though, that Perl will
determine the string's length by using \f(CW\*(C`strlen\*(C'\fR, which depends on the
string terminating with a \s-1NUL\s0 character.
.PP
The arguments of \f(CW\*(C`sv_setpvf\*(C'\fR are processed like \f(CW\*(C`sprintf\*(C'\fR, and the
formatted output becomes the value.
.PP
\&\f(CW\*(C`sv_vsetpvfn\*(C'\fR is an analogue of \f(CW\*(C`vsprintf\*(C'\fR, but it allows you to specify
either a pointer to a variable argument list or the address and length of
an array of SVs.  The last argument points to a boolean; on return, if that
boolean is true, then locale-specific information has been used to format
the string, and the string's contents are therefore untrustworthy (see
perlsec).  This pointer may be \s-1NULL\s0 if that information is not
important.  Note that this function requires you to specify the length of
the format.
.PP
\&\s-1STRLEN\s0 is an integer type (Size_t, usually defined as size_t in
config.h) guaranteed to be large enough to represent the size of
any string that perl can handle.
.PP
The \f(CW\*(C`sv_set*()\*(C'\fR functions are not generic enough to operate on values
that have \*(L"magic\*(R".  See \*(L"Magic Virtual Tables\*(R" later in this document.
.PP
All SVs that contain strings should be terminated with a \s-1NUL\s0 character.
If it is not NUL-terminated there is a risk of
core dumps and corruptions from code which passes the string to C
functions or system calls which expect a NUL-terminated string.
Perl's own functions typically add a trailing \s-1NUL\s0 for this reason.
Nevertheless, you should be very careful when you pass a string stored
in an \s-1SV\s0 to a C function or system call.
.PP
To access the actual value that an \s-1SV\s0 points to, you can use the macros:
.PP
.Vb 5
\&    SvIV(SV*)
\&    SvUV(SV*)
\&    SvNV(SV*)
\&    SvPV(SV*, STRLEN len)
\&    SvPV_nolen(SV*)
.Ve
.PP
which will automatically coerce the actual scalar type into an \s-1IV\s0, \s-1UV\s0, double,
or string.
.PP
In the \f(CW\*(C`SvPV\*(C'\fR macro, the length of the string returned is placed into the
variable \f(CW\*(C`len\*(C'\fR (this is a macro, so you do \fInot\fR use \f(CW&len\fR).  If you do
not care what the length of the data is, use the \f(CW\*(C`SvPV_nolen\*(C'\fR macro.
Historically the \f(CW\*(C`SvPV\*(C'\fR macro with the global variable \f(CW\*(C`PL_na\*(C'\fR has been
used in this case.  But that can be quite inefficient because \f(CW\*(C`PL_na\*(C'\fR must
be accessed in thread-local storage in threaded Perl.  In any case, remember
that Perl allows arbitrary strings of data that may both contain NULs and
might not be terminated by a \s-1NUL\s0.
.PP
Also remember that C doesn't allow you to safely say \f(CW\*(C`foo(SvPV(s, len),
len);\*(C'\fR. It might work with your compiler, but it won't work for everyone.
Break this sort of statement up into separate assignments:
.PP
.Vb 5
\&        SV *s;
\&        STRLEN len;
\&        char * ptr;
\&        ptr = SvPV(s, len);
\&        foo(ptr, len);
.Ve
.PP
If you want to know if the scalar value is \s-1TRUE\s0, you can use:
.PP
.Vb 1
\&    SvTRUE(SV*)
.Ve
.PP
Although Perl will automatically grow strings for you, if you need to force
Perl to allocate more memory for your \s-1SV\s0, you can use the macro
.PP
.Vb 1
\&    SvGROW(SV*, STRLEN newlen)
.Ve
.PP
which will determine if more memory needs to be allocated.  If so, it will
call the function \f(CW\*(C`sv_grow\*(C'\fR.  Note that \f(CW\*(C`SvGROW\*(C'\fR can only increase, not
decrease, the allocated memory of an \s-1SV\s0 and that it does not automatically
add a byte for the a trailing \s-1NUL\s0 (perl's own string functions typically do
\&\f(CW\*(C`SvGROW(sv, len + 1)\*(C'\fR).
.PP
If you have an \s-1SV\s0 and want to know what kind of data Perl thinks is stored
in it, you can use the following macros to check the type of \s-1SV\s0 you have.
.PP
.Vb 3
\&    SvIOK(SV*)
\&    SvNOK(SV*)
\&    SvPOK(SV*)
.Ve
.PP
You can get and set the current length of the string stored in an \s-1SV\s0 with
the following macros:
.PP
.Vb 2
\&    SvCUR(SV*)
\&    SvCUR_set(SV*, I32 val)
.Ve
.PP
You can also get a pointer to the end of the string stored in the \s-1SV\s0
with the macro:
.PP
.Vb 1
\&    SvEND(SV*)
.Ve
.PP
But note that these last three macros are valid only if \f(CW\*(C`SvPOK()\*(C'\fR is true.
.PP
If you want to append something to the end of string stored in an \f(CW\*(C`SV*\*(C'\fR,
you can use the following functions:
.PP
.Vb 5
\&    void  sv_catpv(SV*, const char*);
\&    void  sv_catpvn(SV*, const char*, STRLEN);
\&    void  sv_catpvf(SV*, const char*, ...);
\&    void  sv_vcatpvfn(SV*, const char*, STRLEN, va_list *, SV **, I32, bool);
\&    void  sv_catsv(SV*, SV*);
.Ve
.PP
The first function calculates the length of the string to be appended by
using \f(CW\*(C`strlen\*(C'\fR.  In the second, you specify the length of the string
yourself.  The third function processes its arguments like \f(CW\*(C`sprintf\*(C'\fR and
appends the formatted output.  The fourth function works like \f(CW\*(C`vsprintf\*(C'\fR.
You can specify the address and length of an array of SVs instead of the
va_list argument. The fifth function extends the string stored in the first
\&\s-1SV\s0 with the string stored in the second \s-1SV\s0.  It also forces the second \s-1SV\s0
to be interpreted as a string.
.PP
The \f(CW\*(C`sv_cat*()\*(C'\fR functions are not generic enough to operate on values that
have \*(L"magic\*(R".  See \*(L"Magic Virtual Tables\*(R" later in this document.
.PP
If you know the name of a scalar variable, you can get a pointer to its \s-1SV\s0
by using the following:
.PP
.Vb 1
\&    SV*  get_sv("package::varname", FALSE);
.Ve
.PP
This returns \s-1NULL\s0 if the variable does not exist.
.PP
If you want to know if this variable (or any other \s-1SV\s0) is actually \f(CW\*(C`defined\*(C'\fR,
you can call:
.PP
.Vb 1
\&    SvOK(SV*)
.Ve
.PP
The scalar \f(CW\*(C`undef\*(C'\fR value is stored in an \s-1SV\s0 instance called \f(CW\*(C`PL_sv_undef\*(C'\fR.  Its
address can be used whenever an \f(CW\*(C`SV*\*(C'\fR is needed.
.PP
There are also the two values \f(CW\*(C`PL_sv_yes\*(C'\fR and \f(CW\*(C`PL_sv_no\*(C'\fR, which contain Boolean
\&\s-1TRUE\s0 and \s-1FALSE\s0 values, respectively.  Like \f(CW\*(C`PL_sv_undef\*(C'\fR, their addresses can
be used whenever an \f(CW\*(C`SV*\*(C'\fR is needed.
.PP
Do not be fooled into thinking that \f(CW\*(C`(SV *) 0\*(C'\fR is the same as \f(CW&PL_sv_undef\fR.
Take this code:
.PP
.Vb 5
\&    SV* sv = (SV*) 0;
\&    if (I-am-to-return-a-real-value) {
\&            sv = sv_2mortal(newSViv(42));
\&    }
\&    sv_setsv(ST(0), sv);
.Ve
.PP
This code tries to return a new \s-1SV\s0 (which contains the value 42) if it should
return a real value, or undef otherwise.  Instead it has returned a \s-1NULL\s0
pointer which, somewhere down the line, will cause a segmentation violation,
bus error, or just weird results.  Change the zero to \f(CW&PL_sv_undef\fR in the first
line and all will be well.
.PP
To free an \s-1SV\s0 that you've created, call \f(CW\*(C`SvREFCNT_dec(SV*)\*(C'\fR.  Normally this
call is not necessary (see \*(L"Reference Counts and Mortality\*(R").
.Sh "Offsets"
.IX Subsection "Offsets"
Perl provides the function \f(CW\*(C`sv_chop\*(C'\fR to efficiently remove characters
from the beginning of a string; you give it an \s-1SV\s0 and a pointer to
somewhere inside the \s-1PV\s0, and it discards everything before the
pointer. The efficiency comes by means of a little hack: instead of
actually removing the characters, \f(CW\*(C`sv_chop\*(C'\fR sets the flag \f(CW\*(C`OOK\*(C'\fR
(offset \s-1OK\s0) to signal to other functions that the offset hack is in
effect, and it puts the number of bytes chopped off into the \s-1IV\s0 field
of the \s-1SV\s0. It then moves the \s-1PV\s0 pointer (called \f(CW\*(C`SvPVX\*(C'\fR) forward that
many bytes, and adjusts \f(CW\*(C`SvCUR\*(C'\fR and \f(CW\*(C`SvLEN\*(C'\fR.
.PP
Hence, at this point, the start of the buffer that we allocated lives
at \f(CW\*(C`SvPVX(sv) \- SvIV(sv)\*(C'\fR in memory and the \s-1PV\s0 pointer is pointing
into the middle of this allocated storage.
.PP
This is best demonstrated by example:
.PP
.Vb 8
\&  % ./perl -Ilib -MDevel::Peek -le '$a="12345"; $a=~s/.//; Dump($a)'
\&  SV = PVIV(0x8128450) at 0x81340f0
\&    REFCNT = 1
\&    FLAGS = (POK,OOK,pPOK)
\&    IV = 1  (OFFSET)
\&    PV = 0x8135781 ( "1" . ) "2345"\e0
\&    CUR = 4
\&    LEN = 5
.Ve
.PP
Here the number of bytes chopped off (1) is put into \s-1IV\s0, and
\&\f(CW\*(C`Devel::Peek::Dump\*(C'\fR helpfully reminds us that this is an offset. The
portion of the string between the \*(L"real\*(R" and the \*(L"fake\*(R" beginnings is
shown in parentheses, and the values of \f(CW\*(C`SvCUR\*(C'\fR and \f(CW\*(C`SvLEN\*(C'\fR reflect
the fake beginning, not the real one.
.PP
Something similar to the offset hack is performed on AVs to enable
efficient shifting and splicing off the beginning of the array; while
\&\f(CW\*(C`AvARRAY\*(C'\fR points to the first element in the array that is visible from
Perl, \f(CW\*(C`AvALLOC\*(C'\fR points to the real start of the C array. These are
usually the same, but a \f(CW\*(C`shift\*(C'\fR operation can be carried out by
increasing \f(CW\*(C`AvARRAY\*(C'\fR by one and decreasing \f(CW\*(C`AvFILL\*(C'\fR and \f(CW\*(C`AvLEN\*(C'\fR.
Again, the location of the real start of the C array only comes into
play when freeing the array. See \f(CW\*(C`av_shift\*(C'\fR in \fIav.c\fR.
.Sh "What's Really Stored in an \s-1SV\s0?"
.IX Subsection "What's Really Stored in an SV?"
Recall that the usual method of determining the type of scalar you have is
to use \f(CW\*(C`Sv*OK\*(C'\fR macros.  Because a scalar can be both a number and a string,
usually these macros will always return \s-1TRUE\s0 and calling the \f(CW\*(C`Sv*V\*(C'\fR
macros will do the appropriate conversion of string to integer/double or
integer/double to string.
.PP
If you \fIreally\fR need to know if you have an integer, double, or string
pointer in an \s-1SV\s0, you can use the following three macros instead:
.PP
.Vb 3
\&    SvIOKp(SV*)
\&    SvNOKp(SV*)
\&    SvPOKp(SV*)
.Ve
.PP
These will tell you if you truly have an integer, double, or string pointer
stored in your \s-1SV\s0.  The \*(L"p\*(R" stands for private.
.PP
The are various ways in which the private and public flags may differ.
For example, a tied \s-1SV\s0 may have a valid underlying value in the \s-1IV\s0 slot
(so SvIOKp is true), but the data should be accessed via the \s-1FETCH\s0
routine rather than directly, so SvIOK is false. Another is when
numeric conversion has occured and precision has been lost: only the
private flag is set on 'lossy' values. So when an \s-1NV\s0 is converted to an
\&\s-1IV\s0 with loss, SvIOKp, SvNOKp and SvNOK will be set, while SvIOK wont be.
.PP
In general, though, it's best to use the \f(CW\*(C`Sv*V\*(C'\fR macros.
.Sh "Working with AVs"
.IX Subsection "Working with AVs"
There are two ways to create and load an \s-1AV\s0.  The first method creates an
empty \s-1AV:\s0
.PP
.Vb 1
\&    AV*  newAV();
.Ve
.PP
The second method both creates the \s-1AV\s0 and initially populates it with SVs:
.PP
.Vb 1
\&    AV*  av_make(I32 num, SV **ptr);
.Ve
.PP
The second argument points to an array containing \f(CW\*(C`num\*(C'\fR \f(CW\*(C`SV*\*(C'\fR's.  Once the
\&\s-1AV\s0 has been created, the SVs can be destroyed, if so desired.
.PP
Once the \s-1AV\s0 has been created, the following operations are possible on AVs:
.PP
.Vb 4
\&    void  av_push(AV*, SV*);
\&    SV*   av_pop(AV*);
\&    SV*   av_shift(AV*);
\&    void  av_unshift(AV*, I32 num);
.Ve
.PP
These should be familiar operations, with the exception of \f(CW\*(C`av_unshift\*(C'\fR.
This routine adds \f(CW\*(C`num\*(C'\fR elements at the front of the array with the \f(CW\*(C`undef\*(C'\fR
value.  You must then use \f(CW\*(C`av_store\*(C'\fR (described below) to assign values
to these new elements.
.PP
Here are some other functions:
.PP
.Vb 3
\&    I32   av_len(AV*);
\&    SV**  av_fetch(AV*, I32 key, I32 lval);
\&    SV**  av_store(AV*, I32 key, SV* val);
.Ve
.PP
The \f(CW\*(C`av_len\*(C'\fR function returns the highest index value in array (just
like $#array in Perl).  If the array is empty, \-1 is returned.  The
\&\f(CW\*(C`av_fetch\*(C'\fR function returns the value at index \f(CW\*(C`key\*(C'\fR, but if \f(CW\*(C`lval\*(C'\fR
is non\-zero, then \f(CW\*(C`av_fetch\*(C'\fR will store an undef value at that index.
The \f(CW\*(C`av_store\*(C'\fR function stores the value \f(CW\*(C`val\*(C'\fR at index \f(CW\*(C`key\*(C'\fR, and does
not increment the reference count of \f(CW\*(C`val\*(C'\fR.  Thus the caller is responsible
for taking care of that, and if \f(CW\*(C`av_store\*(C'\fR returns \s-1NULL\s0, the caller will
have to decrement the reference count to avoid a memory leak.  Note that
\&\f(CW\*(C`av_fetch\*(C'\fR and \f(CW\*(C`av_store\*(C'\fR both return \f(CW\*(C`SV**\*(C'\fR's, not \f(CW\*(C`SV*\*(C'\fR's as their
return value.
.PP
.Vb 3
\&    void  av_clear(AV*);
\&    void  av_undef(AV*);
\&    void  av_extend(AV*, I32 key);
.Ve
.PP
The \f(CW\*(C`av_clear\*(C'\fR function deletes all the elements in the AV* array, but
does not actually delete the array itself.  The \f(CW\*(C`av_undef\*(C'\fR function will
delete all the elements in the array plus the array itself.  The
\&\f(CW\*(C`av_extend\*(C'\fR function extends the array so that it contains at least \f(CW\*(C`key+1\*(C'\fR
elements.  If \f(CW\*(C`key+1\*(C'\fR is less than the currently allocated length of the array,
then nothing is done.
.PP
If you know the name of an array variable, you can get a pointer to its \s-1AV\s0
by using the following:
.PP
.Vb 1
\&    AV*  get_av("package::varname", FALSE);
.Ve
.PP
This returns \s-1NULL\s0 if the variable does not exist.
.PP
See \*(L"Understanding the Magic of Tied Hashes and Arrays\*(R" for more
information on how to use the array access functions on tied arrays.
.Sh "Working with HVs"
.IX Subsection "Working with HVs"
To create an \s-1HV\s0, you use the following routine:
.PP
.Vb 1
\&    HV*  newHV();
.Ve
.PP
Once the \s-1HV\s0 has been created, the following operations are possible on HVs:
.PP
.Vb 2
\&    SV**  hv_store(HV*, const char* key, U32 klen, SV* val, U32 hash);
\&    SV**  hv_fetch(HV*, const char* key, U32 klen, I32 lval);
.Ve
.PP
The \f(CW\*(C`klen\*(C'\fR parameter is the length of the key being passed in (Note that
you cannot pass 0 in as a value of \f(CW\*(C`klen\*(C'\fR to tell Perl to measure the
length of the key).  The \f(CW\*(C`val\*(C'\fR argument contains the \s-1SV\s0 pointer to the
scalar being stored, and \f(CW\*(C`hash\*(C'\fR is the precomputed hash value (zero if
you want \f(CW\*(C`hv_store\*(C'\fR to calculate it for you).  The \f(CW\*(C`lval\*(C'\fR parameter
indicates whether this fetch is actually a part of a store operation, in
which case a new undefined value will be added to the \s-1HV\s0 with the supplied
key and \f(CW\*(C`hv_fetch\*(C'\fR will return as if the value had already existed.
.PP
Remember that \f(CW\*(C`hv_store\*(C'\fR and \f(CW\*(C`hv_fetch\*(C'\fR return \f(CW\*(C`SV**\*(C'\fR's and not just
\&\f(CW\*(C`SV*\*(C'\fR.  To access the scalar value, you must first dereference the return
value.  However, you should check to make sure that the return value is
not \s-1NULL\s0 before dereferencing it.
.PP
These two functions check if a hash table entry exists, and deletes it.
.PP
.Vb 2
\&    bool  hv_exists(HV*, const char* key, U32 klen);
\&    SV*   hv_delete(HV*, const char* key, U32 klen, I32 flags);
.Ve
.PP
If \f(CW\*(C`flags\*(C'\fR does not include the \f(CW\*(C`G_DISCARD\*(C'\fR flag then \f(CW\*(C`hv_delete\*(C'\fR will
create and return a mortal copy of the deleted value.
.PP
And more miscellaneous functions:
.PP
.Vb 2
\&    void   hv_clear(HV*);
\&    void   hv_undef(HV*);
.Ve
.PP
Like their \s-1AV\s0 counterparts, \f(CW\*(C`hv_clear\*(C'\fR deletes all the entries in the hash
table but does not actually delete the hash table.  The \f(CW\*(C`hv_undef\*(C'\fR deletes
both the entries and the hash table itself.
.PP
Perl keeps the actual data in linked list of structures with a typedef of \s-1HE\s0.
These contain the actual key and value pointers (plus extra administrative
overhead).  The key is a string pointer; the value is an \f(CW\*(C`SV*\*(C'\fR.  However,
once you have an \f(CW\*(C`HE*\*(C'\fR, to get the actual key and value, use the routines
specified below.
.PP
.Vb 16
\&    I32    hv_iterinit(HV*);
\&            /* Prepares starting point to traverse hash table */
\&    HE*    hv_iternext(HV*);
\&            /* Get the next entry, and return a pointer to a
\&               structure that has both the key and value */
\&    char*  hv_iterkey(HE* entry, I32* retlen);
\&            /* Get the key from an HE structure and also return
\&               the length of the key string */
\&    SV*    hv_iterval(HV*, HE* entry);
\&            /* Return an SV pointer to the value of the HE
\&               structure */
\&    SV*    hv_iternextsv(HV*, char** key, I32* retlen);
\&            /* This convenience routine combines hv_iternext,
\&               hv_iterkey, and hv_iterval.  The key and retlen
\&               arguments are return values for the key and its
\&               length.  The value is returned in the SV* argument */
.Ve
.PP
If you know the name of a hash variable, you can get a pointer to its \s-1HV\s0
by using the following:
.PP
.Vb 1
\&    HV*  get_hv("package::varname", FALSE);
.Ve
.PP
This returns \s-1NULL\s0 if the variable does not exist.
.PP
The hash algorithm is defined in the \f(CW\*(C`PERL_HASH(hash, key, klen)\*(C'\fR macro:
.PP
.Vb 4
\&    hash = 0;
\&    while (klen--)
\&        hash = (hash * 33) + *key++;
\&    hash = hash + (hash >> 5);                  /* after 5.6 */
.Ve
.PP
The last step was added in version 5.6 to improve distribution of
lower bits in the resulting hash value.
.PP
See \*(L"Understanding the Magic of Tied Hashes and Arrays\*(R" for more
information on how to use the hash access functions on tied hashes.
.Sh "Hash \s-1API\s0 Extensions"
.IX Subsection "Hash API Extensions"
Beginning with version 5.004, the following functions are also supported:
.PP
.Vb 2
\&    HE*     hv_fetch_ent  (HV* tb, SV* key, I32 lval, U32 hash);
\&    HE*     hv_store_ent  (HV* tb, SV* key, SV* val, U32 hash);
.Ve
.PP
.Vb 2
\&    bool    hv_exists_ent (HV* tb, SV* key, U32 hash);
\&    SV*     hv_delete_ent (HV* tb, SV* key, I32 flags, U32 hash);
.Ve
.PP
.Vb 1
\&    SV*     hv_iterkeysv  (HE* entry);
.Ve
.PP
Note that these functions take \f(CW\*(C`SV*\*(C'\fR keys, which simplifies writing
of extension code that deals with hash structures.  These functions
also allow passing of \f(CW\*(C`SV*\*(C'\fR keys to \f(CW\*(C`tie\*(C'\fR functions without forcing
you to stringify the keys (unlike the previous set of functions).
.PP
They also return and accept whole hash entries (\f(CW\*(C`HE*\*(C'\fR), making their
use more efficient (since the hash number for a particular string
doesn't have to be recomputed every time).  See perlapi for detailed
descriptions.
.PP
The following macros must always be used to access the contents of hash
entries.  Note that the arguments to these macros must be simple
variables, since they may get evaluated more than once.  See
perlapi for detailed descriptions of these macros.
.PP
.Vb 6
\&    HePV(HE* he, STRLEN len)
\&    HeVAL(HE* he)
\&    HeHASH(HE* he)
\&    HeSVKEY(HE* he)
\&    HeSVKEY_force(HE* he)
\&    HeSVKEY_set(HE* he, SV* sv)
.Ve
.PP
These two lower level macros are defined, but must only be used when
dealing with keys that are not \f(CW\*(C`SV*\*(C'\fRs:
.PP
.Vb 2
\&    HeKEY(HE* he)
\&    HeKLEN(HE* he)
.Ve
.PP
Note that both \f(CW\*(C`hv_store\*(C'\fR and \f(CW\*(C`hv_store_ent\*(C'\fR do not increment the
reference count of the stored \f(CW\*(C`val\*(C'\fR, which is the caller's responsibility.
If these functions return a \s-1NULL\s0 value, the caller will usually have to
decrement the reference count of \f(CW\*(C`val\*(C'\fR to avoid a memory leak.
.Sh "References"
.IX Subsection "References"
References are a special type of scalar that point to other data types
(including references).
.PP
To create a reference, use either of the following functions:
.PP
.Vb 2
\&    SV* newRV_inc((SV*) thing);
\&    SV* newRV_noinc((SV*) thing);
.Ve
.PP
The \f(CW\*(C`thing\*(C'\fR argument can be any of an \f(CW\*(C`SV*\*(C'\fR, \f(CW\*(C`AV*\*(C'\fR, or \f(CW\*(C`HV*\*(C'\fR.  The
functions are identical except that \f(CW\*(C`newRV_inc\*(C'\fR increments the reference
count of the \f(CW\*(C`thing\*(C'\fR, while \f(CW\*(C`newRV_noinc\*(C'\fR does not.  For historical
reasons, \f(CW\*(C`newRV\*(C'\fR is a synonym for \f(CW\*(C`newRV_inc\*(C'\fR.
.PP
Once you have a reference, you can use the following macro to dereference
the reference:
.PP
.Vb 1
\&    SvRV(SV*)
.Ve
.PP
then call the appropriate routines, casting the returned \f(CW\*(C`SV*\*(C'\fR to either an
\&\f(CW\*(C`AV*\*(C'\fR or \f(CW\*(C`HV*\*(C'\fR, if required.
.PP
To determine if an \s-1SV\s0 is a reference, you can use the following macro:
.PP
.Vb 1
\&    SvROK(SV*)
.Ve
.PP
To discover what type of value the reference refers to, use the following
macro and then check the return value.
.PP
.Vb 1
\&    SvTYPE(SvRV(SV*))
.Ve
.PP
The most useful types that will be returned are:
.PP
.Vb 9
\&    SVt_IV    Scalar
\&    SVt_NV    Scalar
\&    SVt_PV    Scalar
\&    SVt_RV    Scalar
\&    SVt_PVAV  Array
\&    SVt_PVHV  Hash
\&    SVt_PVCV  Code
\&    SVt_PVGV  Glob (possible a file handle)
\&    SVt_PVMG  Blessed or Magical Scalar
.Ve
.PP
.Vb 1
\&    See the sv.h header file for more details.
.Ve
.Sh "Blessed References and Class Objects"
.IX Subsection "Blessed References and Class Objects"
References are also used to support object-oriented programming.  In the
\&\s-1OO\s0 lexicon, an object is simply a reference that has been blessed into a
package (or class).  Once blessed, the programmer may now use the reference
to access the various methods in the class.
.PP
A reference can be blessed into a package with the following function:
.PP
.Vb 1
\&    SV* sv_bless(SV* sv, HV* stash);
.Ve
.PP
The \f(CW\*(C`sv\*(C'\fR argument must be a reference.  The \f(CW\*(C`stash\*(C'\fR argument specifies
which class the reference will belong to.  See
\&\*(L"Stashes and Globs\*(R" for information on converting class names into stashes.
.PP
/* Still under construction */
.PP
Upgrades rv to reference if not already one.  Creates new \s-1SV\s0 for rv to
point to.  If \f(CW\*(C`classname\*(C'\fR is non\-null, the \s-1SV\s0 is blessed into the specified
class.  \s-1SV\s0 is returned.
.PP
.Vb 1
\&        SV* newSVrv(SV* rv, const char* classname);
.Ve
.PP
Copies integer, unsigned integer or double into an \s-1SV\s0 whose reference is \f(CW\*(C`rv\*(C'\fR.  \s-1SV\s0 is blessed
if \f(CW\*(C`classname\*(C'\fR is non\-null.
.PP
.Vb 3
\&        SV* sv_setref_iv(SV* rv, const char* classname, IV iv);
\&        SV* sv_setref_uv(SV* rv, const char* classname, UV uv);
\&        SV* sv_setref_nv(SV* rv, const char* classname, NV iv);
.Ve
.PP
Copies the pointer value (\fIthe address, not the string!\fR) into an \s-1SV\s0 whose
reference is rv.  \s-1SV\s0 is blessed if \f(CW\*(C`classname\*(C'\fR is non\-null.
.PP
.Vb 1
\&        SV* sv_setref_pv(SV* rv, const char* classname, PV iv);
.Ve
.PP
Copies string into an \s-1SV\s0 whose reference is \f(CW\*(C`rv\*(C'\fR.  Set length to 0 to let
Perl calculate the string length.  \s-1SV\s0 is blessed if \f(CW\*(C`classname\*(C'\fR is non\-null.
.PP
.Vb 1
\&        SV* sv_setref_pvn(SV* rv, const char* classname, PV iv, STRLEN length);
.Ve
.PP
Tests whether the \s-1SV\s0 is blessed into the specified class.  It does not
check inheritance relationships.
.PP
.Vb 1
\&        int  sv_isa(SV* sv, const char* name);
.Ve
.PP
Tests whether the \s-1SV\s0 is a reference to a blessed object.
.PP
.Vb 1
\&        int  sv_isobject(SV* sv);
.Ve
.PP
Tests whether the \s-1SV\s0 is derived from the specified class. \s-1SV\s0 can be either
a reference to a blessed object or a string containing a class name. This
is the function implementing the \f(CW\*(C`UNIVERSAL::isa\*(C'\fR functionality.
.PP
.Vb 1
\&        bool sv_derived_from(SV* sv, const char* name);
.Ve
.PP
To check if you've got an object derived from a specific class you have
to write:
.PP
.Vb 1
\&        if (sv_isobject(sv) && sv_derived_from(sv, class)) { ... }
.Ve
.Sh "Creating New Variables"
.IX Subsection "Creating New Variables"
To create a new Perl variable with an undef value which can be accessed from
your Perl script, use the following routines, depending on the variable type.
.PP
.Vb 3
\&    SV*  get_sv("package::varname", TRUE);
\&    AV*  get_av("package::varname", TRUE);
\&    HV*  get_hv("package::varname", TRUE);
.Ve
.PP
Notice the use of \s-1TRUE\s0 as the second parameter.  The new variable can now
be set, using the routines appropriate to the data type.
.PP
There are additional macros whose values may be bitwise \s-1OR\s0'ed with the
\&\f(CW\*(C`TRUE\*(C'\fR argument to enable certain extra features.  Those bits are:
.IP "\s-1GV_ADDMULTI\s0" 4
.IX Item "GV_ADDMULTI"
Marks the variable as multiply defined, thus preventing the:
.Sp
.Vb 1
\&  Name <varname> used only once: possible typo
.Ve
.Sp
warning.
.IP "\s-1GV_ADDWARN\s0" 4
.IX Item "GV_ADDWARN"
Issues the warning:
.Sp
.Vb 1
\&  Had to create <varname> unexpectedly
.Ve
.Sp
if the variable did not exist before the function was called.
.PP
If you do not specify a package name, the variable is created in the current
package.
.Sh "Reference Counts and Mortality"
.IX Subsection "Reference Counts and Mortality"
Perl uses a reference count-driven garbage collection mechanism. SVs,
AVs, or HVs (xV for short in the following) start their life with a
reference count of 1.  If the reference count of an xV ever drops to 0,
then it will be destroyed and its memory made available for reuse.
.PP
This normally doesn't happen at the Perl level unless a variable is
undef'ed or the last variable holding a reference to it is changed or
overwritten.  At the internal level, however, reference counts can be
manipulated with the following macros:
.PP
.Vb 3
\&    int SvREFCNT(SV* sv);
\&    SV* SvREFCNT_inc(SV* sv);
\&    void SvREFCNT_dec(SV* sv);
.Ve
.PP
However, there is one other function which manipulates the reference
count of its argument.  The \f(CW\*(C`newRV_inc\*(C'\fR function, you will recall,
creates a reference to the specified argument.  As a side effect,
it increments the argument's reference count.  If this is not what
you want, use \f(CW\*(C`newRV_noinc\*(C'\fR instead.
.PP
For example, imagine you want to return a reference from an \s-1XSUB\s0 function.
Inside the \s-1XSUB\s0 routine, you create an \s-1SV\s0 which initially has a reference
count of one.  Then you call \f(CW\*(C`newRV_inc\*(C'\fR, passing it the just-created \s-1SV\s0.
This returns the reference as a new \s-1SV\s0, but the reference count of the
\&\s-1SV\s0 you passed to \f(CW\*(C`newRV_inc\*(C'\fR has been incremented to two.  Now you
return the reference from the \s-1XSUB\s0 routine and forget about the \s-1SV\s0.
But Perl hasn't!  Whenever the returned reference is destroyed, the
reference count of the original \s-1SV\s0 is decreased to one and nothing happens.
The \s-1SV\s0 will hang around without any way to access it until Perl itself
terminates.  This is a memory leak.
.PP
The correct procedure, then, is to use \f(CW\*(C`newRV_noinc\*(C'\fR instead of
\&\f(CW\*(C`newRV_inc\*(C'\fR.  Then, if and when the last reference is destroyed,
the reference count of the \s-1SV\s0 will go to zero and it will be destroyed,
stopping any memory leak.
.PP
There are some convenience functions available that can help with the
destruction of xVs.  These functions introduce the concept of \*(L"mortality\*(R".
An xV that is mortal has had its reference count marked to be decremented,
but not actually decremented, until \*(L"a short time later\*(R".  Generally the
term \*(L"short time later\*(R" means a single Perl statement, such as a call to
an \s-1XSUB\s0 function.  The actual determinant for when mortal xVs have their
reference count decremented depends on two macros, \s-1SAVETMPS\s0 and \s-1FREETMPS\s0.
See perlcall and perlxs for more details on these macros.
.PP
\&\*(L"Mortalization\*(R" then is at its simplest a deferred \f(CW\*(C`SvREFCNT_dec\*(C'\fR.
However, if you mortalize a variable twice, the reference count will
later be decremented twice.
.PP
\&\*(L"Mortal\*(R" SVs are mainly used for SVs that are placed on perl's stack.
For example an \s-1SV\s0 which is created just to pass a number to a called sub
is made mortal to have it cleaned up automatically when stack is popped.
Similarly results returned by XSUBs (which go in the stack) are often
made mortal.
.PP
To create a mortal variable, use the functions:
.PP
.Vb 3
\&    SV*  sv_newmortal()
\&    SV*  sv_2mortal(SV*)
\&    SV*  sv_mortalcopy(SV*)
.Ve
.PP
The first call creates a mortal \s-1SV\s0 (with no value), the second converts an existing
\&\s-1SV\s0 to a mortal \s-1SV\s0 (and thus defers a call to \f(CW\*(C`SvREFCNT_dec\*(C'\fR), and the
third creates a mortal copy of an existing \s-1SV\s0.
Because \f(CW\*(C`sv_newmortal\*(C'\fR gives the new \s-1SV\s0 no value,it must normally be given one
via \f(CW\*(C`sv_setpv\*(C'\fR, \f(CW\*(C`sv_setiv\*(C'\fR, etc. :
.PP
.Vb 2
\&    SV *tmp = sv_newmortal();
\&    sv_setiv(tmp, an_integer);
.Ve
.PP
As that is multiple C statements it is quite common so see this idiom instead:
.PP
.Vb 1
\&    SV *tmp = sv_2mortal(newSViv(an_integer));
.Ve
.PP
You should be careful about creating mortal variables.  Strange things
can happen if you make the same value mortal within multiple contexts,
or if you make a variable mortal multiple times. Thinking of \*(L"Mortalization\*(R"
as deferred \f(CW\*(C`SvREFCNT_dec\*(C'\fR should help to minimize such problems.
For example if you are passing an \s-1SV\s0 which you \fIknow\fR has high enough \s-1REFCNT\s0
to survive its use on the stack you need not do any mortalization.
If you are not sure then doing an \f(CW\*(C`SvREFCNT_inc\*(C'\fR and \f(CW\*(C`sv_2mortal\*(C'\fR, or
making a \f(CW\*(C`sv_mortalcopy\*(C'\fR is safer.
.PP
The mortal routines are not just for SVs \*(-- AVs and HVs can be
made mortal by passing their address (type\-casted to \f(CW\*(C`SV*\*(C'\fR) to the
\&\f(CW\*(C`sv_2mortal\*(C'\fR or \f(CW\*(C`sv_mortalcopy\*(C'\fR routines.
.Sh "Stashes and Globs"
.IX Subsection "Stashes and Globs"
A \*(L"stash\*(R" is a hash that contains all of the different objects that
are contained within a package.  Each key of the stash is a symbol
name (shared by all the different types of objects that have the same
name), and each value in the hash table is a \s-1GV\s0 (Glob Value).  This \s-1GV\s0
in turn contains references to the various objects of that name,
including (but not limited to) the following:
.PP
.Vb 6
\&    Scalar Value
\&    Array Value
\&    Hash Value
\&    I/O Handle
\&    Format
\&    Subroutine
.Ve
.PP
There is a single stash called \*(L"PL_defstash\*(R" that holds the items that exist
in the \*(L"main\*(R" package.  To get at the items in other packages, append the
string \*(L"::\*(R" to the package name.  The items in the \*(L"Foo\*(R" package are in
the stash \*(L"Foo::\*(R" in PL_defstash.  The items in the \*(L"Bar::Baz\*(R" package are
in the stash \*(L"Baz::\*(R" in \*(L"Bar::\*(R"'s stash.
.PP
To get the stash pointer for a particular package, use the function:
.PP
.Vb 2
\&    HV*  gv_stashpv(const char* name, I32 create)
\&    HV*  gv_stashsv(SV*, I32 create)
.Ve
.PP
The first function takes a literal string, the second uses the string stored
in the \s-1SV\s0.  Remember that a stash is just a hash table, so you get back an
\&\f(CW\*(C`HV*\*(C'\fR.  The \f(CW\*(C`create\*(C'\fR flag will create a new package if it is set.
.PP
The name that \f(CW\*(C`gv_stash*v\*(C'\fR wants is the name of the package whose symbol table
you want.  The default package is called \f(CW\*(C`main\*(C'\fR.  If you have multiply nested
packages, pass their names to \f(CW\*(C`gv_stash*v\*(C'\fR, separated by \f(CW\*(C`::\*(C'\fR as in the Perl
language itself.
.PP
Alternately, if you have an \s-1SV\s0 that is a blessed reference, you can find
out the stash pointer by using:
.PP
.Vb 1
\&    HV*  SvSTASH(SvRV(SV*));
.Ve
.PP
then use the following to get the package name itself:
.PP
.Vb 1
\&    char*  HvNAME(HV* stash);
.Ve
.PP
If you need to bless or re-bless an object you can use the following
function:
.PP
.Vb 1
\&    SV*  sv_bless(SV*, HV* stash)
.Ve
.PP
where the first argument, an \f(CW\*(C`SV*\*(C'\fR, must be a reference, and the second
argument is a stash.  The returned \f(CW\*(C`SV*\*(C'\fR can now be used in the same way
as any other \s-1SV\s0.
.PP
For more information on references and blessings, consult perlref.
.Sh "Double-Typed SVs"
.IX Subsection "Double-Typed SVs"
Scalar variables normally contain only one type of value, an integer,
double, pointer, or reference.  Perl will automatically convert the
actual scalar data from the stored type into the requested type.
.PP
Some scalar variables contain more than one type of scalar data.  For
example, the variable \f(CW$!\fR contains either the numeric value of \f(CW\*(C`errno\*(C'\fR
or its string equivalent from either \f(CW\*(C`strerror\*(C'\fR or \f(CW\*(C`sys_errlist[]\*(C'\fR.
.PP
To force multiple data values into an \s-1SV\s0, you must do two things: use the
\&\f(CW\*(C`sv_set*v\*(C'\fR routines to add the additional scalar type, then set a flag
so that Perl will believe it contains more than one type of data.  The
four macros to set the flags are:
.PP
.Vb 4
\&        SvIOK_on
\&        SvNOK_on
\&        SvPOK_on
\&        SvROK_on
.Ve
.PP
The particular macro you must use depends on which \f(CW\*(C`sv_set*v\*(C'\fR routine
you called first.  This is because every \f(CW\*(C`sv_set*v\*(C'\fR routine turns on
only the bit for the particular type of data being set, and turns off
all the rest.
.PP
For example, to create a new Perl variable called \*(L"dberror\*(R" that contains
both the numeric and descriptive string error values, you could use the
following code:
.PP
.Vb 2
\&    extern int  dberror;
\&    extern char *dberror_list;
.Ve
.PP
.Vb 4
\&    SV* sv = get_sv("dberror", TRUE);
\&    sv_setiv(sv, (IV) dberror);
\&    sv_setpv(sv, dberror_list[dberror]);
\&    SvIOK_on(sv);
.Ve
.PP
If the order of \f(CW\*(C`sv_setiv\*(C'\fR and \f(CW\*(C`sv_setpv\*(C'\fR had been reversed, then the
macro \f(CW\*(C`SvPOK_on\*(C'\fR would need to be called instead of \f(CW\*(C`SvIOK_on\*(C'\fR.
.Sh "Magic Variables"
.IX Subsection "Magic Variables"
[This section still under construction.  Ignore everything here.  Post no
bills.  Everything not permitted is forbidden.]
.PP
Any \s-1SV\s0 may be magical, that is, it has special features that a normal
\&\s-1SV\s0 does not have.  These features are stored in the \s-1SV\s0 structure in a
linked list of \f(CW\*(C`struct magic\*(C'\fR's, typedef'ed to \f(CW\*(C`MAGIC\*(C'\fR.
.PP
.Vb 10
\&    struct magic {
\&        MAGIC*      mg_moremagic;
\&        MGVTBL*     mg_virtual;
\&        U16         mg_private;
\&        char        mg_type;
\&        U8          mg_flags;
\&        SV*         mg_obj;
\&        char*       mg_ptr;
\&        I32         mg_len;
\&    };
.Ve
.PP
Note this is current as of patchlevel 0, and could change at any time.
.Sh "Assigning Magic"
.IX Subsection "Assigning Magic"
Perl adds magic to an \s-1SV\s0 using the sv_magic function:
.PP
.Vb 1
\&    void sv_magic(SV* sv, SV* obj, int how, const char* name, I32 namlen);
.Ve
.PP
The \f(CW\*(C`sv\*(C'\fR argument is a pointer to the \s-1SV\s0 that is to acquire a new magical
feature.
.PP
If \f(CW\*(C`sv\*(C'\fR is not already magical, Perl uses the \f(CW\*(C`SvUPGRADE\*(C'\fR macro to
convert \f(CW\*(C`sv\*(C'\fR to type \f(CW\*(C`SVt_PVMG\*(C'\fR. Perl then continues by adding new magic
to the beginning of the linked list of magical features.  Any prior entry
of the same type of magic is deleted.  Note that this can be overridden,
and multiple instances of the same type of magic can be associated with an
\&\s-1SV\s0.
.PP
The \f(CW\*(C`name\*(C'\fR and \f(CW\*(C`namlen\*(C'\fR arguments are used to associate a string with
the magic, typically the name of a variable. \f(CW\*(C`namlen\*(C'\fR is stored in the
\&\f(CW\*(C`mg_len\*(C'\fR field and if \f(CW\*(C`name\*(C'\fR is non-null and \f(CW\*(C`namlen\*(C'\fR >= 0 a malloc'd
copy of the name is stored in \f(CW\*(C`mg_ptr\*(C'\fR field.
.PP
The sv_magic function uses \f(CW\*(C`how\*(C'\fR to determine which, if any, predefined
\&\*(L"Magic Virtual Table\*(R" should be assigned to the \f(CW\*(C`mg_virtual\*(C'\fR field.
See the \*(L"Magic Virtual Table\*(R" section below.  The \f(CW\*(C`how\*(C'\fR argument is also
stored in the \f(CW\*(C`mg_type\*(C'\fR field. The value of \f(CW\*(C`how\*(C'\fR should be chosen
from the set of macros \f(CW\*(C`PERL_MAGIC_foo\*(C'\fR found perl.h. Note that before
these macros were added, Perl internals used to directly use character
literals, so you may occasionally come across old code or documentation
referring to 'U' magic rather than \f(CW\*(C`PERL_MAGIC_uvar\*(C'\fR for example.
.PP
The \f(CW\*(C`obj\*(C'\fR argument is stored in the \f(CW\*(C`mg_obj\*(C'\fR field of the \f(CW\*(C`MAGIC\*(C'\fR
structure.  If it is not the same as the \f(CW\*(C`sv\*(C'\fR argument, the reference
count of the \f(CW\*(C`obj\*(C'\fR object is incremented.  If it is the same, or if
the \f(CW\*(C`how\*(C'\fR argument is \f(CW\*(C`PERL_MAGIC_arylen\*(C'\fR, or if it is a \s-1NULL\s0 pointer,
then \f(CW\*(C`obj\*(C'\fR is merely stored, without the reference count being incremented.
.PP
There is also a function to add magic to an \f(CW\*(C`HV\*(C'\fR:
.PP
.Vb 1
\&    void hv_magic(HV *hv, GV *gv, int how);
.Ve
.PP
This simply calls \f(CW\*(C`sv_magic\*(C'\fR and coerces the \f(CW\*(C`gv\*(C'\fR argument into an \f(CW\*(C`SV\*(C'\fR.
.PP
To remove the magic from an \s-1SV\s0, call the function sv_unmagic:
.PP
.Vb 1
\&    void sv_unmagic(SV *sv, int type);
.Ve
.PP
The \f(CW\*(C`type\*(C'\fR argument should be equal to the \f(CW\*(C`how\*(C'\fR value when the \f(CW\*(C`SV\*(C'\fR
was initially made magical.
.Sh "Magic Virtual Tables"
.IX Subsection "Magic Virtual Tables"
The \f(CW\*(C`mg_virtual\*(C'\fR field in the \f(CW\*(C`MAGIC\*(C'\fR structure is a pointer to an
\&\f(CW\*(C`MGVTBL\*(C'\fR, which is a structure of function pointers and stands for
\&\*(L"Magic Virtual Table\*(R" to handle the various operations that might be
applied to that variable.
.PP
The \f(CW\*(C`MGVTBL\*(C'\fR has five pointers to the following routine types:
.PP
.Vb 5
\&    int  (*svt_get)(SV* sv, MAGIC* mg);
\&    int  (*svt_set)(SV* sv, MAGIC* mg);
\&    U32  (*svt_len)(SV* sv, MAGIC* mg);
\&    int  (*svt_clear)(SV* sv, MAGIC* mg);
\&    int  (*svt_free)(SV* sv, MAGIC* mg);
.Ve
.PP
This \s-1MGVTBL\s0 structure is set at compile-time in \f(CW\*(C`perl.h\*(C'\fR and there are
currently 19 types (or 21 with overloading turned on).  These different
structures contain pointers to various routines that perform additional
actions depending on which function is being called.
.PP
.Vb 7
\&    Function pointer    Action taken
\&    ----------------    ------------
\&    svt_get             Do something before the value of the SV is retrieved.
\&    svt_set             Do something after the SV is assigned a value.
\&    svt_len             Report on the SV's length.
\&    svt_clear           Clear something the SV represents.
\&    svt_free            Free any extra storage associated with the SV.
.Ve
.PP
For instance, the \s-1MGVTBL\s0 structure called \f(CW\*(C`vtbl_sv\*(C'\fR (which corresponds
to an \f(CW\*(C`mg_type\*(C'\fR of \f(CW\*(C`PERL_MAGIC_sv\*(C'\fR) contains:
.PP
.Vb 1
\&    { magic_get, magic_set, magic_len, 0, 0 }
.Ve
.PP
Thus, when an \s-1SV\s0 is determined to be magical and of type \f(CW\*(C`PERL_MAGIC_sv\*(C'\fR,
if a get operation is being performed, the routine \f(CW\*(C`magic_get\*(C'\fR is
called.  All the various routines for the various magical types begin
with \f(CW\*(C`magic_\*(C'\fR.  \s-1NOTE:\s0 the magic routines are not considered part of
the Perl \s-1API\s0, and may not be exported by the Perl library.
.PP
The current kinds of Magic Virtual Tables are:
.PP
.Vb 42
\&    mg_type
\&    (old-style char and macro)   MGVTBL         Type of magic
\&    --------------------------   ------         ----------------------------
\&    \e0 PERL_MAGIC_sv             vtbl_sv        Special scalar variable
\&    A  PERL_MAGIC_overload       vtbl_amagic    %OVERLOAD hash
\&    a  PERL_MAGIC_overload_elem  vtbl_amagicelem %OVERLOAD hash element
\&    c  PERL_MAGIC_overload_table (none)         Holds overload table (AMT)
\&                                                on stash
\&    B  PERL_MAGIC_bm             vtbl_bm        Boyer-Moore (fast string search)
\&    D  PERL_MAGIC_regdata        vtbl_regdata   Regex match position data
\&                                                (@+ and @- vars)
\&    d  PERL_MAGIC_regdatum       vtbl_regdatum  Regex match position data
\&                                                element
\&    E  PERL_MAGIC_env            vtbl_env       %ENV hash
\&    e  PERL_MAGIC_envelem        vtbl_envelem   %ENV hash element
\&    f  PERL_MAGIC_fm             vtbl_fm        Formline ('compiled' format)
\&    g  PERL_MAGIC_regex_global   vtbl_mglob     m//g target / study()ed string
\&    I  PERL_MAGIC_isa            vtbl_isa       @ISA array
\&    i  PERL_MAGIC_isaelem        vtbl_isaelem   @ISA array element
\&    k  PERL_MAGIC_nkeys          vtbl_nkeys     scalar(keys()) lvalue
\&    L  PERL_MAGIC_dbfile         (none)         Debugger %_<filename
\&    l  PERL_MAGIC_dbline         vtbl_dbline    Debugger %_<filename element
\&    m  PERL_MAGIC_mutex          vtbl_mutex     ???
\&    o  PERL_MAGIC_collxfrm       vtbl_collxfrm  Locale collate transformation
\&    P  PERL_MAGIC_tied           vtbl_pack      Tied array or hash
\&    p  PERL_MAGIC_tiedelem       vtbl_packelem  Tied array or hash element
\&    q  PERL_MAGIC_tiedscalar     vtbl_packelem  Tied scalar or handle
\&    r  PERL_MAGIC_qr             vtbl_qr        precompiled qr// regex
\&    S  PERL_MAGIC_sig            vtbl_sig       %SIG hash
\&    s  PERL_MAGIC_sigelem        vtbl_sigelem   %SIG hash element
\&    t  PERL_MAGIC_taint          vtbl_taint     Taintedness
\&    U  PERL_MAGIC_uvar           vtbl_uvar      Available for use by extensions
\&    v  PERL_MAGIC_vec            vtbl_vec       vec() lvalue
\&    x  PERL_MAGIC_substr         vtbl_substr    substr() lvalue
\&    y  PERL_MAGIC_defelem        vtbl_defelem   Shadow "foreach" iterator
\&                                                variable / smart parameter
\&                                                vivification
\&    *  PERL_MAGIC_glob           vtbl_glob      GV (typeglob)
\&    #  PERL_MAGIC_arylen         vtbl_arylen    Array length ($#ary)
\&    .  PERL_MAGIC_pos            vtbl_pos       pos() lvalue
\&    <  PERL_MAGIC_backref        vtbl_backref   ???
\&    ~  PERL_MAGIC_ext            (none)         Available for use by extensions
.Ve
.PP
When an uppercase and lowercase letter both exist in the table, then the
uppercase letter is used to represent some kind of composite type (a list
or a hash), and the lowercase letter is used to represent an element of
that composite type. Some internals code makes use of this case
relationship.
.PP
The \f(CW\*(C`PERL_MAGIC_ext\*(C'\fR and \f(CW\*(C`PERL_MAGIC_uvar\*(C'\fR magic types are defined
specifically for use by extensions and will not be used by perl itself.
Extensions can use \f(CW\*(C`PERL_MAGIC_ext\*(C'\fR magic to 'attach' private information
to variables (typically objects).  This is especially useful because
there is no way for normal perl code to corrupt this private information
(unlike using extra elements of a hash object).
.PP
Similarly, \f(CW\*(C`PERL_MAGIC_uvar\*(C'\fR magic can be used much like \fItie()\fR to call a
C function any time a scalar's value is used or changed.  The \f(CW\*(C`MAGIC\*(C'\fR's
\&\f(CW\*(C`mg_ptr\*(C'\fR field points to a \f(CW\*(C`ufuncs\*(C'\fR structure:
.PP
.Vb 5
\&    struct ufuncs {
\&        I32 (*uf_val)(pTHX_ IV, SV*);
\&        I32 (*uf_set)(pTHX_ IV, SV*);
\&        IV uf_index;
\&    };
.Ve
.PP
When the \s-1SV\s0 is read from or written to, the \f(CW\*(C`uf_val\*(C'\fR or \f(CW\*(C`uf_set\*(C'\fR
function will be called with \f(CW\*(C`uf_index\*(C'\fR as the first arg and a pointer to
the \s-1SV\s0 as the second.  A simple example of how to add \f(CW\*(C`PERL_MAGIC_uvar\*(C'\fR
magic is shown below.  Note that the ufuncs structure is copied by
sv_magic, so you can safely allocate it on the stack.
.PP
.Vb 10
\&    void
\&    Umagic(sv)
\&        SV *sv;
\&    PREINIT:
\&        struct ufuncs uf;
\&    CODE:
\&        uf.uf_val   = &my_get_fn;
\&        uf.uf_set   = &my_set_fn;
\&        uf.uf_index = 0;
\&        sv_magic(sv, 0, PERL_MAGIC_uvar, (char*)&uf, sizeof(uf));
.Ve
.PP
Note that because multiple extensions may be using \f(CW\*(C`PERL_MAGIC_ext\*(C'\fR
or \f(CW\*(C`PERL_MAGIC_uvar\*(C'\fR magic, it is important for extensions to take
extra care to avoid conflict.  Typically only using the magic on
objects blessed into the same class as the extension is sufficient.
For \f(CW\*(C`PERL_MAGIC_ext\*(C'\fR magic, it may also be appropriate to add an I32
\&'signature' at the top of the private data area and check that.
.PP
Also note that the \f(CW\*(C`sv_set*()\*(C'\fR and \f(CW\*(C`sv_cat*()\*(C'\fR functions described
earlier do \fBnot\fR invoke 'set' magic on their targets.  This must
be done by the user either by calling the \f(CW\*(C`SvSETMAGIC()\*(C'\fR macro after
calling these functions, or by using one of the \f(CW\*(C`sv_set*_mg()\*(C'\fR or
\&\f(CW\*(C`sv_cat*_mg()\*(C'\fR functions.  Similarly, generic C code must call the
\&\f(CW\*(C`SvGETMAGIC()\*(C'\fR macro to invoke any 'get' magic if they use an \s-1SV\s0
obtained from external sources in functions that don't handle magic.
See perlapi for a description of these functions.
For example, calls to the \f(CW\*(C`sv_cat*()\*(C'\fR functions typically need to be
followed by \f(CW\*(C`SvSETMAGIC()\*(C'\fR, but they don't need a prior \f(CW\*(C`SvGETMAGIC()\*(C'\fR
since their implementation handles 'get' magic.
.Sh "Finding Magic"
.IX Subsection "Finding Magic"
.Vb 1
\&    MAGIC* mg_find(SV*, int type); /* Finds the magic pointer of that type */
.Ve
.PP
This routine returns a pointer to the \f(CW\*(C`MAGIC\*(C'\fR structure stored in the \s-1SV\s0.
If the \s-1SV\s0 does not have that magical feature, \f(CW\*(C`NULL\*(C'\fR is returned.  Also,
if the \s-1SV\s0 is not of type SVt_PVMG, Perl may core dump.
.PP
.Vb 1
\&    int mg_copy(SV* sv, SV* nsv, const char* key, STRLEN klen);
.Ve
.PP
This routine checks to see what types of magic \f(CW\*(C`sv\*(C'\fR has.  If the mg_type
field is an uppercase letter, then the mg_obj is copied to \f(CW\*(C`nsv\*(C'\fR, but
the mg_type field is changed to be the lowercase letter.
.Sh "Understanding the Magic of Tied Hashes and Arrays"
.IX Subsection "Understanding the Magic of Tied Hashes and Arrays"
Tied hashes and arrays are magical beasts of the \f(CW\*(C`PERL_MAGIC_tied\*(C'\fR
magic type.
.PP
\&\s-1WARNING:\s0 As of the 5.004 release, proper usage of the array and hash
access functions requires understanding a few caveats.  Some
of these caveats are actually considered bugs in the \s-1API\s0, to be fixed
in later releases, and are bracketed with [\s-1MAYCHANGE\s0] below. If
you find yourself actually applying such information in this section, be
aware that the behavior may change in the future, umm, without warning.
.PP
The perl tie function associates a variable with an object that implements
the various \s-1GET\s0, \s-1SET\s0, etc methods.  To perform the equivalent of the perl
tie function from an \s-1XSUB\s0, you must mimic this behaviour.  The code below
carries out the necessary steps \- firstly it creates a new hash, and then
creates a second hash which it blesses into the class which will implement
the tie methods. Lastly it ties the two hashes together, and returns a
reference to the new tied hash.  Note that the code below does \s-1NOT\s0 call the
\&\s-1TIEHASH\s0 method in the MyTie class \-
see \*(L"Calling Perl Routines from within C Programs\*(R" for details on how
to do this.
.PP
.Vb 15
\&    SV*
\&    mytie()
\&    PREINIT:
\&        HV *hash;
\&        HV *stash;
\&        SV *tie;
\&    CODE:
\&        hash = newHV();
\&        tie = newRV_noinc((SV*)newHV());
\&        stash = gv_stashpv("MyTie", TRUE);
\&        sv_bless(tie, stash);
\&        hv_magic(hash, (GV*)tie, PERL_MAGIC_tied);
\&        RETVAL = newRV_noinc(hash);
\&    OUTPUT:
\&        RETVAL
.Ve
.PP
The \f(CW\*(C`av_store\*(C'\fR function, when given a tied array argument, merely
copies the magic of the array onto the value to be \*(L"stored\*(R", using
\&\f(CW\*(C`mg_copy\*(C'\fR.  It may also return \s-1NULL\s0, indicating that the value did not
actually need to be stored in the array.  [\s-1MAYCHANGE\s0] After a call to
\&\f(CW\*(C`av_store\*(C'\fR on a tied array, the caller will usually need to call
\&\f(CW\*(C`mg_set(val)\*(C'\fR to actually invoke the perl level \*(L"\s-1STORE\s0\*(R" method on the
\&\s-1TIEARRAY\s0 object.  If \f(CW\*(C`av_store\*(C'\fR did return \s-1NULL\s0, a call to
\&\f(CW\*(C`SvREFCNT_dec(val)\*(C'\fR will also be usually necessary to avoid a memory
leak. [/MAYCHANGE]
.PP
The previous paragraph is applicable verbatim to tied hash access using the
\&\f(CW\*(C`hv_store\*(C'\fR and \f(CW\*(C`hv_store_ent\*(C'\fR functions as well.
.PP
\&\f(CW\*(C`av_fetch\*(C'\fR and the corresponding hash functions \f(CW\*(C`hv_fetch\*(C'\fR and
\&\f(CW\*(C`hv_fetch_ent\*(C'\fR actually return an undefined mortal value whose magic
has been initialized using \f(CW\*(C`mg_copy\*(C'\fR.  Note the value so returned does not
need to be deallocated, as it is already mortal.  [\s-1MAYCHANGE\s0] But you will
need to call \f(CW\*(C`mg_get()\*(C'\fR on the returned value in order to actually invoke
the perl level \*(L"\s-1FETCH\s0\*(R" method on the underlying \s-1TIE\s0 object.  Similarly,
you may also call \f(CW\*(C`mg_set()\*(C'\fR on the return value after possibly assigning
a suitable value to it using \f(CW\*(C`sv_setsv\*(C'\fR,  which will invoke the \*(L"\s-1STORE\s0\*(R"
method on the \s-1TIE\s0 object. [/MAYCHANGE]
.PP
[\s-1MAYCHANGE\s0]
In other words, the array or hash fetch/store functions don't really
fetch and store actual values in the case of tied arrays and hashes.  They
merely call \f(CW\*(C`mg_copy\*(C'\fR to attach magic to the values that were meant to be
\&\*(L"stored\*(R" or \*(L"fetched\*(R".  Later calls to \f(CW\*(C`mg_get\*(C'\fR and \f(CW\*(C`mg_set\*(C'\fR actually
do the job of invoking the \s-1TIE\s0 methods on the underlying objects.  Thus
the magic mechanism currently implements a kind of lazy access to arrays
and hashes.
.PP
Currently (as of perl version 5.004), use of the hash and array access
functions requires the user to be aware of whether they are operating on
\&\*(L"normal\*(R" hashes and arrays, or on their tied variants.  The \s-1API\s0 may be
changed to provide more transparent access to both tied and normal data
types in future versions.
[/MAYCHANGE]
.PP
You would do well to understand that the \s-1TIEARRAY\s0 and \s-1TIEHASH\s0 interfaces
are mere sugar to invoke some perl method calls while using the uniform hash
and array syntax.  The use of this sugar imposes some overhead (typically
about two to four extra opcodes per \s-1FETCH/STORE\s0 operation, in addition to
the creation of all the mortal variables required to invoke the methods).
This overhead will be comparatively small if the \s-1TIE\s0 methods are themselves
substantial, but if they are only a few statements long, the overhead
will not be insignificant.
.Sh "Localizing changes"
.IX Subsection "Localizing changes"
Perl has a very handy construction
.PP
.Vb 4
\&  {
\&    local $var = 2;
\&    ...
\&  }
.Ve
.PP
This construction is \fIapproximately\fR equivalent to
.PP
.Vb 6
\&  {
\&    my $oldvar = $var;
\&    $var = 2;
\&    ...
\&    $var = $oldvar;
\&  }
.Ve
.PP
The biggest difference is that the first construction would
reinstate the initial value of \f(CW$var\fR, irrespective of how control exits
the block: \f(CW\*(C`goto\*(C'\fR, \f(CW\*(C`return\*(C'\fR, \f(CW\*(C`die\*(C'\fR/\f(CW\*(C`eval\*(C'\fR, etc. It is a little bit
more efficient as well.
.PP
There is a way to achieve a similar task from C via Perl \s-1API:\s0 create a
\&\fIpseudo-block\fR, and arrange for some changes to be automatically
undone at the end of it, either explicit, or via a non-local exit (via
\&\fIdie()\fR). A \fIblock\fR\-like construct is created by a pair of
\&\f(CW\*(C`ENTER\*(C'\fR/\f(CW\*(C`LEAVE\*(C'\fR macros (see \*(L"Returning a Scalar\*(R" in perlcall).
Such a construct may be created specially for some important localized
task, or an existing one (like boundaries of enclosing Perl
subroutine/block, or an existing pair for freeing TMPs) may be
used. (In the second case the overhead of additional localization must
be almost negligible.) Note that any \s-1XSUB\s0 is automatically enclosed in
an \f(CW\*(C`ENTER\*(C'\fR/\f(CW\*(C`LEAVE\*(C'\fR pair.
.PP
Inside such a \fIpseudo-block\fR the following service is available:
.ie n .IP """SAVEINT(int i)""" 4
.el .IP "\f(CWSAVEINT(int i)\fR" 4
.IX Item "SAVEINT(int i)"
.PD 0
.ie n .IP """SAVEIV(IV i)""" 4
.el .IP "\f(CWSAVEIV(IV i)\fR" 4
.IX Item "SAVEIV(IV i)"
.ie n .IP """SAVEI32(I32 i)""" 4
.el .IP "\f(CWSAVEI32(I32 i)\fR" 4
.IX Item "SAVEI32(I32 i)"
.ie n .IP """SAVELONG(long i)""" 4
.el .IP "\f(CWSAVELONG(long i)\fR" 4
.IX Item "SAVELONG(long i)"
.PD
These macros arrange things to restore the value of integer variable
\&\f(CW\*(C`i\*(C'\fR at the end of enclosing \fIpseudo-block\fR.
.ie n .IP "SAVESPTR(s)" 4
.el .IP "\f(CWSAVESPTR(s)\fR" 4
.IX Item "SAVESPTR(s)"
.PD 0
.ie n .IP "SAVEPPTR(p)" 4
.el .IP "\f(CWSAVEPPTR(p)\fR" 4
.IX Item "SAVEPPTR(p)"
.PD
These macros arrange things to restore the value of pointers \f(CW\*(C`s\*(C'\fR and
\&\f(CW\*(C`p\*(C'\fR. \f(CW\*(C`s\*(C'\fR must be a pointer of a type which survives conversion to
\&\f(CW\*(C`SV*\*(C'\fR and back, \f(CW\*(C`p\*(C'\fR should be able to survive conversion to \f(CW\*(C`char*\*(C'\fR
and back.
.ie n .IP """SAVEFREESV(SV *sv)""" 4
.el .IP "\f(CWSAVEFREESV(SV *sv)\fR" 4
.IX Item "SAVEFREESV(SV *sv)"
The refcount of \f(CW\*(C`sv\*(C'\fR would be decremented at the end of
\&\fIpseudo-block\fR.  This is similar to \f(CW\*(C`sv_2mortal\*(C'\fR in that it is also a
mechanism for doing a delayed \f(CW\*(C`SvREFCNT_dec\*(C'\fR.  However, while \f(CW\*(C`sv_2mortal\*(C'\fR
extends the lifetime of \f(CW\*(C`sv\*(C'\fR until the beginning of the next statement,
\&\f(CW\*(C`SAVEFREESV\*(C'\fR extends it until the end of the enclosing scope.  These
lifetimes can be wildly different.
.Sp
Also compare \f(CW\*(C`SAVEMORTALIZESV\*(C'\fR.
.ie n .IP """SAVEMORTALIZESV(SV *sv)""" 4
.el .IP "\f(CWSAVEMORTALIZESV(SV *sv)\fR" 4
.IX Item "SAVEMORTALIZESV(SV *sv)"
Just like \f(CW\*(C`SAVEFREESV\*(C'\fR, but mortalizes \f(CW\*(C`sv\*(C'\fR at the end of the current
scope instead of decrementing its reference count.  This usually has the
effect of keeping \f(CW\*(C`sv\*(C'\fR alive until the statement that called the currently
live scope has finished executing.
.ie n .IP """SAVEFREEOP(OP *op)""" 4
.el .IP "\f(CWSAVEFREEOP(OP *op)\fR" 4
.IX Item "SAVEFREEOP(OP *op)"
The \f(CW\*(C`OP *\*(C'\fR is \fIop_free()\fRed at the end of \fIpseudo-block\fR.
.ie n .IP "SAVEFREEPV(p)" 4
.el .IP "\f(CWSAVEFREEPV(p)\fR" 4
.IX Item "SAVEFREEPV(p)"
The chunk of memory which is pointed to by \f(CW\*(C`p\*(C'\fR is \fISafefree()\fRed at the
end of \fIpseudo-block\fR.
.ie n .IP """SAVECLEARSV(SV *sv)""" 4
.el .IP "\f(CWSAVECLEARSV(SV *sv)\fR" 4
.IX Item "SAVECLEARSV(SV *sv)"
Clears a slot in the current scratchpad which corresponds to \f(CW\*(C`sv\*(C'\fR at
the end of \fIpseudo-block\fR.
.ie n .IP """SAVEDELETE(HV *hv, char *key, I32 length)""" 4
.el .IP "\f(CWSAVEDELETE(HV *hv, char *key, I32 length)\fR" 4
.IX Item "SAVEDELETE(HV *hv, char *key, I32 length)"
The key \f(CW\*(C`key\*(C'\fR of \f(CW\*(C`hv\*(C'\fR is deleted at the end of \fIpseudo-block\fR. The
string pointed to by \f(CW\*(C`key\*(C'\fR is \fISafefree()\fRed.  If one has a \fIkey\fR in
short-lived storage, the corresponding string may be reallocated like
this:
.Sp
.Vb 1
\&  SAVEDELETE(PL_defstash, savepv(tmpbuf), strlen(tmpbuf));
.Ve
.ie n .IP """SAVEDESTRUCTOR(DESTRUCTORFUNC_NOCONTEXT_t f, void *p)""" 4
.el .IP "\f(CWSAVEDESTRUCTOR(DESTRUCTORFUNC_NOCONTEXT_t f, void *p)\fR" 4
.IX Item "SAVEDESTRUCTOR(DESTRUCTORFUNC_NOCONTEXT_t f, void *p)"
At the end of \fIpseudo-block\fR the function \f(CW\*(C`f\*(C'\fR is called with the
only argument \f(CW\*(C`p\*(C'\fR.
.ie n .IP """SAVEDESTRUCTOR_X(DESTRUCTORFUNC_t f, void *p)""" 4
.el .IP "\f(CWSAVEDESTRUCTOR_X(DESTRUCTORFUNC_t f, void *p)\fR" 4
.IX Item "SAVEDESTRUCTOR_X(DESTRUCTORFUNC_t f, void *p)"
At the end of \fIpseudo-block\fR the function \f(CW\*(C`f\*(C'\fR is called with the
implicit context argument (if any), and \f(CW\*(C`p\*(C'\fR.
.ie n .IP """SAVESTACK_POS()""" 4
.el .IP "\f(CWSAVESTACK_POS()\fR" 4
.IX Item "SAVESTACK_POS()"
The current offset on the Perl internal stack (cf. \f(CW\*(C`SP\*(C'\fR) is restored
at the end of \fIpseudo-block\fR.
.PP
The following \s-1API\s0 list contains functions, thus one needs to
provide pointers to the modifiable data explicitly (either C pointers,
or Perlish \f(CW\*(C`GV *\*(C'\fRs).  Where the above macros take \f(CW\*(C`int\*(C'\fR, a similar
function takes \f(CW\*(C`int *\*(C'\fR.
.ie n .IP """SV* save_scalar(GV *gv)""" 4
.el .IP "\f(CWSV* save_scalar(GV *gv)\fR" 4
.IX Item "SV* save_scalar(GV *gv)"
Equivalent to Perl code \f(CW\*(C`local $gv\*(C'\fR.
.ie n .IP """AV* save_ary(GV *gv)""" 4
.el .IP "\f(CWAV* save_ary(GV *gv)\fR" 4
.IX Item "AV* save_ary(GV *gv)"
.PD 0
.ie n .IP """HV* save_hash(GV *gv)""" 4
.el .IP "\f(CWHV* save_hash(GV *gv)\fR" 4
.IX Item "HV* save_hash(GV *gv)"
.PD
Similar to \f(CW\*(C`save_scalar\*(C'\fR, but localize \f(CW@gv\fR and \f(CW%gv\fR.
.ie n .IP """void save_item(SV *item)""" 4
.el .IP "\f(CWvoid save_item(SV *item)\fR" 4
.IX Item "void save_item(SV *item)"
Duplicates the current value of \f(CW\*(C`SV\*(C'\fR, on the exit from the current
\&\f(CW\*(C`ENTER\*(C'\fR/\f(CW\*(C`LEAVE\*(C'\fR \fIpseudo-block\fR will restore the value of \f(CW\*(C`SV\*(C'\fR
using the stored value.
.ie n .IP """void save_list(SV **sarg, I32 maxsarg)""" 4
.el .IP "\f(CWvoid save_list(SV **sarg, I32 maxsarg)\fR" 4
.IX Item "void save_list(SV **sarg, I32 maxsarg)"
A variant of \f(CW\*(C`save_item\*(C'\fR which takes multiple arguments via an array
\&\f(CW\*(C`sarg\*(C'\fR of \f(CW\*(C`SV*\*(C'\fR of length \f(CW\*(C`maxsarg\*(C'\fR.
.ie n .IP """SV* save_svref(SV **sptr)""" 4
.el .IP "\f(CWSV* save_svref(SV **sptr)\fR" 4
.IX Item "SV* save_svref(SV **sptr)"
Similar to \f(CW\*(C`save_scalar\*(C'\fR, but will reinstate an \f(CW\*(C`SV *\*(C'\fR.
.ie n .IP """void save_aptr(AV **aptr)""" 4
.el .IP "\f(CWvoid save_aptr(AV **aptr)\fR" 4
.IX Item "void save_aptr(AV **aptr)"
.PD 0
.ie n .IP """void save_hptr(HV **hptr)""" 4
.el .IP "\f(CWvoid save_hptr(HV **hptr)\fR" 4
.IX Item "void save_hptr(HV **hptr)"
.PD
Similar to \f(CW\*(C`save_svref\*(C'\fR, but localize \f(CW\*(C`AV *\*(C'\fR and \f(CW\*(C`HV *\*(C'\fR.
.PP
The \f(CW\*(C`Alias\*(C'\fR module implements localization of the basic types within the
\&\fIcaller's scope\fR.  People who are interested in how to localize things in
the containing scope should take a look there too.
.SH "Subroutines"
.IX Header "Subroutines"
.Sh "XSUBs and the Argument Stack"
.IX Subsection "XSUBs and the Argument Stack"
The \s-1XSUB\s0 mechanism is a simple way for Perl programs to access C subroutines.
An \s-1XSUB\s0 routine will have a stack that contains the arguments from the Perl
program, and a way to map from the Perl data structures to a C equivalent.
.PP
The stack arguments are accessible through the \f(CWST(n)\fR macro, which returns
the \f(CW\*(C`n\*(C'\fR'th stack argument.  Argument 0 is the first argument passed in the
Perl subroutine call.  These arguments are \f(CW\*(C`SV*\*(C'\fR, and can be used anywhere
an \f(CW\*(C`SV*\*(C'\fR is used.
.PP
Most of the time, output from the C routine can be handled through use of
the \s-1RETVAL\s0 and \s-1OUTPUT\s0 directives.  However, there are some cases where the
argument stack is not already long enough to handle all the return values.
An example is the \s-1POSIX\s0 \fItzname()\fR call, which takes no arguments, but returns
two, the local time zone's standard and summer time abbreviations.
.PP
To handle this situation, the \s-1PPCODE\s0 directive is used and the stack is
extended using the macro:
.PP
.Vb 1
\&    EXTEND(SP, num);
.Ve
.PP
where \f(CW\*(C`SP\*(C'\fR is the macro that represents the local copy of the stack pointer,
and \f(CW\*(C`num\*(C'\fR is the number of elements the stack should be extended by.
.PP
Now that there is room on the stack, values can be pushed on it using \f(CW\*(C`PUSHs\*(C'\fR
macro. The values pushed will often need to be \*(L"mortal\*(R" (See \*(L"Reference Counts and Mortality\*(R").
.PP
.Vb 3
\&    PUSHs(sv_2mortal(newSViv(an_integer)))
\&    PUSHs(sv_2mortal(newSVpv("Some String",0)))
\&    PUSHs(sv_2mortal(newSVnv(3.141592)))
.Ve
.PP
And now the Perl program calling \f(CW\*(C`tzname\*(C'\fR, the two values will be assigned
as in:
.PP
.Vb 1
\&    ($standard_abbrev, $summer_abbrev) = POSIX::tzname;
.Ve
.PP
An alternate (and possibly simpler) method to pushing values on the stack is
to use the macro:
.PP
.Vb 1
\&    XPUSHs(SV*)
.Ve
.PP
This macro automatically adjust the stack for you, if needed.  Thus, you
do not need to call \f(CW\*(C`EXTEND\*(C'\fR to extend the stack.
.PP
Despite their suggestions in earlier versions of this document the macros
\&\f(CW\*(C`PUSHi\*(C'\fR, \f(CW\*(C`PUSHn\*(C'\fR and \f(CW\*(C`PUSHp\*(C'\fR are \fInot\fR suited to XSUBs which return
multiple results, see \*(L"Putting a C value on Perl stack\*(R".
.PP
For more information, consult perlxs and perlxstut.
.Sh "Calling Perl Routines from within C Programs"
.IX Subsection "Calling Perl Routines from within C Programs"
There are four routines that can be used to call a Perl subroutine from
within a C program.  These four are:
.PP
.Vb 4
\&    I32  call_sv(SV*, I32);
\&    I32  call_pv(const char*, I32);
\&    I32  call_method(const char*, I32);
\&    I32  call_argv(const char*, I32, register char**);
.Ve
.PP
The routine most often used is \f(CW\*(C`call_sv\*(C'\fR.  The \f(CW\*(C`SV*\*(C'\fR argument
contains either the name of the Perl subroutine to be called, or a
reference to the subroutine.  The second argument consists of flags
that control the context in which the subroutine is called, whether
or not the subroutine is being passed arguments, how errors should be
trapped, and how to treat return values.
.PP
All four routines return the number of arguments that the subroutine returned
on the Perl stack.
.PP
These routines used to be called \f(CW\*(C`perl_call_sv\*(C'\fR, etc., before Perl v5.6.0,
but those names are now deprecated; macros of the same name are provided for
compatibility.
.PP
When using any of these routines (except \f(CW\*(C`call_argv\*(C'\fR), the programmer
must manipulate the Perl stack.  These include the following macros and
functions:
.PP
.Vb 11
\&    dSP
\&    SP
\&    PUSHMARK()
\&    PUTBACK
\&    SPAGAIN
\&    ENTER
\&    SAVETMPS
\&    FREETMPS
\&    LEAVE
\&    XPUSH*()
\&    POP*()
.Ve
.PP
For a detailed description of calling conventions from C to Perl,
consult perlcall.
.Sh "Memory Allocation"
.IX Subsection "Memory Allocation"
All memory meant to be used with the Perl \s-1API\s0 functions should be manipulated
using the macros described in this section.  The macros provide the necessary
transparency between differences in the actual malloc implementation that is
used within perl.
.PP
It is suggested that you enable the version of malloc that is distributed
with Perl.  It keeps pools of various sizes of unallocated memory in
order to satisfy allocation requests more quickly.  However, on some
platforms, it may cause spurious malloc or free errors.
.PP
.Vb 3
\&    New(x, pointer, number, type);
\&    Newc(x, pointer, number, type, cast);
\&    Newz(x, pointer, number, type);
.Ve
.PP
These three macros are used to initially allocate memory.
.PP
The first argument \f(CW\*(C`x\*(C'\fR was a \*(L"magic cookie\*(R" that was used to keep track
of who called the macro, to help when debugging memory problems.  However,
the current code makes no use of this feature (most Perl developers now
use run-time memory checkers), so this argument can be any number.
.PP
The second argument \f(CW\*(C`pointer\*(C'\fR should be the name of a variable that will
point to the newly allocated memory.
.PP
The third and fourth arguments \f(CW\*(C`number\*(C'\fR and \f(CW\*(C`type\*(C'\fR specify how many of
the specified type of data structure should be allocated.  The argument
\&\f(CW\*(C`type\*(C'\fR is passed to \f(CW\*(C`sizeof\*(C'\fR.  The final argument to \f(CW\*(C`Newc\*(C'\fR, \f(CW\*(C`cast\*(C'\fR,
should be used if the \f(CW\*(C`pointer\*(C'\fR argument is different from the \f(CW\*(C`type\*(C'\fR
argument.
.PP
Unlike the \f(CW\*(C`New\*(C'\fR and \f(CW\*(C`Newc\*(C'\fR macros, the \f(CW\*(C`Newz\*(C'\fR macro calls \f(CW\*(C`memzero\*(C'\fR
to zero out all the newly allocated memory.
.PP
.Vb 3
\&    Renew(pointer, number, type);
\&    Renewc(pointer, number, type, cast);
\&    Safefree(pointer)
.Ve
.PP
These three macros are used to change a memory buffer size or to free a
piece of memory no longer needed.  The arguments to \f(CW\*(C`Renew\*(C'\fR and \f(CW\*(C`Renewc\*(C'\fR
match those of \f(CW\*(C`New\*(C'\fR and \f(CW\*(C`Newc\*(C'\fR with the exception of not needing the
\&\*(L"magic cookie\*(R" argument.
.PP
.Vb 3
\&    Move(source, dest, number, type);
\&    Copy(source, dest, number, type);
\&    Zero(dest, number, type);
.Ve
.PP
These three macros are used to move, copy, or zero out previously allocated
memory.  The \f(CW\*(C`source\*(C'\fR and \f(CW\*(C`dest\*(C'\fR arguments point to the source and
destination starting points.  Perl will move, copy, or zero out \f(CW\*(C`number\*(C'\fR
instances of the size of the \f(CW\*(C`type\*(C'\fR data structure (using the \f(CW\*(C`sizeof\*(C'\fR
function).
.Sh "PerlIO"
.IX Subsection "PerlIO"
The most recent development releases of Perl has been experimenting with
removing Perl's dependency on the \*(L"normal\*(R" standard I/O suite and allowing
other stdio implementations to be used.  This involves creating a new
abstraction layer that then calls whichever implementation of stdio Perl
was compiled with.  All XSUBs should now use the functions in the PerlIO
abstraction layer and not make any assumptions about what kind of stdio
is being used.
.PP
For a complete description of the PerlIO abstraction, consult perlapio.
.Sh "Putting a C value on Perl stack"
.IX Subsection "Putting a C value on Perl stack"
A lot of opcodes (this is an elementary operation in the internal perl
stack machine) put an SV* on the stack. However, as an optimization
the corresponding \s-1SV\s0 is (usually) not recreated each time. The opcodes
reuse specially assigned SVs (\fItarget\fRs) which are (as a corollary)
not constantly freed/created.
.PP
Each of the targets is created only once (but see
\&\*(L"Scratchpads and recursion\*(R" below), and when an opcode needs to put
an integer, a double, or a string on stack, it just sets the
corresponding parts of its \fItarget\fR and puts the \fItarget\fR on stack.
.PP
The macro to put this target on stack is \f(CW\*(C`PUSHTARG\*(C'\fR, and it is
directly used in some opcodes, as well as indirectly in zillions of
others, which use it via \f(CW\*(C`(X)PUSH[pni]\*(C'\fR.
.PP
Because the target is reused, you must be careful when pushing multiple
values on the stack. The following code will not do what you think:
.PP
.Vb 2
\&    XPUSHi(10);
\&    XPUSHi(20);
.Ve
.PP
This translates as "set \f(CW\*(C`TARG\*(C'\fR to 10, push a pointer to \f(CW\*(C`TARG\*(C'\fR onto
the stack; set \f(CW\*(C`TARG\*(C'\fR to 20, push a pointer to \f(CW\*(C`TARG\*(C'\fR onto the stack".
At the end of the operation, the stack does not contain the values 10
and 20, but actually contains two pointers to \f(CW\*(C`TARG\*(C'\fR, which we have set
to 20. If you need to push multiple different values, use \f(CW\*(C`XPUSHs\*(C'\fR,
which bypasses \f(CW\*(C`TARG\*(C'\fR.
.PP
On a related note, if you do use \f(CW\*(C`(X)PUSH[npi]\*(C'\fR, then you're going to
need a \f(CW\*(C`dTARG\*(C'\fR in your variable declarations so that the \f(CW\*(C`*PUSH*\*(C'\fR
macros can make use of the local variable \f(CW\*(C`TARG\*(C'\fR.
.Sh "Scratchpads"
.IX Subsection "Scratchpads"
The question remains on when the SVs which are \fItarget\fRs for opcodes
are created. The answer is that they are created when the current unit \*(--
a subroutine or a file (for opcodes for statements outside of
subroutines) \*(-- is compiled. During this time a special anonymous Perl
array is created, which is called a scratchpad for the current
unit.
.PP
A scratchpad keeps SVs which are lexicals for the current unit and are
targets for opcodes. One can deduce that an \s-1SV\s0 lives on a scratchpad
by looking on its flags: lexicals have \f(CW\*(C`SVs_PADMY\*(C'\fR set, and
\&\fItarget\fRs have \f(CW\*(C`SVs_PADTMP\*(C'\fR set.
.PP
The correspondence between OPs and \fItarget\fRs is not 1\-to\-1. Different
OPs in the compile tree of the unit can use the same target, if this
would not conflict with the expected life of the temporary.
.Sh "Scratchpads and recursion"
.IX Subsection "Scratchpads and recursion"
In fact it is not 100% true that a compiled unit contains a pointer to
the scratchpad \s-1AV\s0. In fact it contains a pointer to an \s-1AV\s0 of
(initially) one element, and this element is the scratchpad \s-1AV\s0. Why do
we need an extra level of indirection?
.PP
The answer is \fBrecursion\fR, and maybe \fBthreads\fR. Both
these can create several execution pointers going into the same
subroutine. For the subroutine-child not write over the temporaries
for the subroutine-parent (lifespan of which covers the call to the
child), the parent and the child should have different
scratchpads. (\fIAnd\fR the lexicals should be separate anyway!)
.PP
So each subroutine is born with an array of scratchpads (of length 1).
On each entry to the subroutine it is checked that the current
depth of the recursion is not more than the length of this array, and
if it is, new scratchpad is created and pushed into the array.
.PP
The \fItarget\fRs on this scratchpad are \f(CW\*(C`undef\*(C'\fRs, but they are already
marked with correct flags.
.SH "Compiled code"
.IX Header "Compiled code"
.Sh "Code tree"
.IX Subsection "Code tree"
Here we describe the internal form your code is converted to by
Perl. Start with a simple example:
.PP
.Vb 1
\&  $a = $b + $c;
.Ve
.PP
This is converted to a tree similar to this one:
.PP
.Vb 5
\&             assign-to
\&           /           \e
\&          +             $a
\&        /   \e
\&      $b     $c
.Ve
.PP
(but slightly more complicated).  This tree reflects the way Perl
parsed your code, but has nothing to do with the execution order.
There is an additional \*(L"thread\*(R" going through the nodes of the tree
which shows the order of execution of the nodes.  In our simplified
example above it looks like:
.PP
.Vb 1
\&     $b ---> $c ---> + ---> $a ---> assign-to
.Ve
.PP
But with the actual compile tree for \f(CW\*(C`$a = $b + $c\*(C'\fR it is different:
some nodes \fIoptimized away\fR.  As a corollary, though the actual tree
contains more nodes than our simplified example, the execution order
is the same as in our example.
.Sh "Examining the tree"
.IX Subsection "Examining the tree"
If you have your perl compiled for debugging (usually done with \f(CW\*(C`\-D
optimize=\-g\*(C'\fR on \f(CW\*(C`Configure\*(C'\fR command line), you may examine the
compiled tree by specifying \f(CW\*(C`\-Dx\*(C'\fR on the Perl command line.  The
output takes several lines per node, and for \f(CW\*(C`$b+$c\*(C'\fR it looks like
this:
.PP
.Vb 23
\&    5           TYPE = add  ===> 6
\&                TARG = 1
\&                FLAGS = (SCALAR,KIDS)
\&                {
\&                    TYPE = null  ===> (4)
\&                      (was rv2sv)
\&                    FLAGS = (SCALAR,KIDS)
\&                    {
\&    3                   TYPE = gvsv  ===> 4
\&                        FLAGS = (SCALAR)
\&                        GV = main::b
\&                    }
\&                }
\&                {
\&                    TYPE = null  ===> (5)
\&                      (was rv2sv)
\&                    FLAGS = (SCALAR,KIDS)
\&                    {
\&    4                   TYPE = gvsv  ===> 5
\&                        FLAGS = (SCALAR)
\&                        GV = main::c
\&                    }
\&                }
.Ve
.PP
This tree has 5 nodes (one per \f(CW\*(C`TYPE\*(C'\fR specifier), only 3 of them are
not optimized away (one per number in the left column).  The immediate
children of the given node correspond to \f(CW\*(C`{}\*(C'\fR pairs on the same level
of indentation, thus this listing corresponds to the tree:
.PP
.Vb 5
\&                   add
\&                 /     \e
\&               null    null
\&                |       |
\&               gvsv    gvsv
.Ve
.PP
The execution order is indicated by \f(CW\*(C`===>\*(C'\fR marks, thus it is \f(CW\*(C`3
4 5 6\*(C'\fR (node \f(CW6\fR is not included into above listing), i.e.,
\&\f(CW\*(C`gvsv gvsv add whatever\*(C'\fR.
.PP
Each of these nodes represents an op, a fundamental operation inside the
Perl core. The code which implements each operation can be found in the
\&\fIpp*.c\fR files; the function which implements the op with type \f(CW\*(C`gvsv\*(C'\fR
is \f(CW\*(C`pp_gvsv\*(C'\fR, and so on. As the tree above shows, different ops have
different numbers of children: \f(CW\*(C`add\*(C'\fR is a binary operator, as one would
expect, and so has two children. To accommodate the various different
numbers of children, there are various types of op data structure, and
they link together in different ways.
.PP
The simplest type of op structure is \f(CW\*(C`OP\*(C'\fR: this has no children. Unary
operators, \f(CW\*(C`UNOP\*(C'\fRs, have one child, and this is pointed to by the
\&\f(CW\*(C`op_first\*(C'\fR field. Binary operators (\f(CW\*(C`BINOP\*(C'\fRs) have not only an
\&\f(CW\*(C`op_first\*(C'\fR field but also an \f(CW\*(C`op_last\*(C'\fR field. The most complex type of
op is a \f(CW\*(C`LISTOP\*(C'\fR, which has any number of children. In this case, the
first child is pointed to by \f(CW\*(C`op_first\*(C'\fR and the last child by
\&\f(CW\*(C`op_last\*(C'\fR. The children in between can be found by iteratively
following the \f(CW\*(C`op_sibling\*(C'\fR pointer from the first child to the last.
.PP
There are also two other op types: a \f(CW\*(C`PMOP\*(C'\fR holds a regular expression,
and has no children, and a \f(CW\*(C`LOOP\*(C'\fR may or may not have children. If the
\&\f(CW\*(C`op_children\*(C'\fR field is non\-zero, it behaves like a \f(CW\*(C`LISTOP\*(C'\fR. To
complicate matters, if a \f(CW\*(C`UNOP\*(C'\fR is actually a \f(CW\*(C`null\*(C'\fR op after
optimization (see \*(L"Compile pass 2: context propagation\*(R") it will still
have children in accordance with its former type.
.Sh "Compile pass 1: check routines"
.IX Subsection "Compile pass 1: check routines"
The tree is created by the compiler while \fIyacc\fR code feeds it
the constructions it recognizes. Since \fIyacc\fR works bottom\-up, so does
the first pass of perl compilation.
.PP
What makes this pass interesting for perl developers is that some
optimization may be performed on this pass.  This is optimization by
so-called \*(L"check routines\*(R".  The correspondence between node names
and corresponding check routines is described in \fIopcode.pl\fR (do not
forget to run \f(CW\*(C`make regen_headers\*(C'\fR if you modify this file).
.PP
A check routine is called when the node is fully constructed except
for the execution-order thread.  Since at this time there are no
back-links to the currently constructed node, one can do most any
operation to the top-level node, including freeing it and/or creating
new nodes above/below it.
.PP
The check routine returns the node which should be inserted into the
tree (if the top-level node was not modified, check routine returns
its argument).
.PP
By convention, check routines have names \f(CW\*(C`ck_*\*(C'\fR. They are usually
called from \f(CW\*(C`new*OP\*(C'\fR subroutines (or \f(CW\*(C`convert\*(C'\fR) (which in turn are
called from \fIperly.y\fR).
.Sh "Compile pass 1a: constant folding"
.IX Subsection "Compile pass 1a: constant folding"
Immediately after the check routine is called the returned node is
checked for being compile-time executable.  If it is (the value is
judged to be constant) it is immediately executed, and a \fIconstant\fR
node with the \*(L"return value\*(R" of the corresponding subtree is
substituted instead.  The subtree is deleted.
.PP
If constant folding was not performed, the execution-order thread is
created.
.Sh "Compile pass 2: context propagation"
.IX Subsection "Compile pass 2: context propagation"
When a context for a part of compile tree is known, it is propagated
down through the tree.  At this time the context can have 5 values
(instead of 2 for runtime context): void, boolean, scalar, list, and
lvalue.  In contrast with the pass 1 this pass is processed from top
to bottom: a node's context determines the context for its children.
.PP
Additional context-dependent optimizations are performed at this time.
Since at this moment the compile tree contains back-references (via
\&\*(L"thread\*(R" pointers), nodes cannot be \fIfree()\fRd now.  To allow
optimized-away nodes at this stage, such nodes are \fInull()\fRified instead
of \fIfree()\fRing (i.e. their type is changed to \s-1OP_NULL\s0).
.Sh "Compile pass 3: peephole optimization"
.IX Subsection "Compile pass 3: peephole optimization"
After the compile tree for a subroutine (or for an \f(CW\*(C`eval\*(C'\fR or a file)
is created, an additional pass over the code is performed. This pass
is neither top-down or bottom\-up, but in the execution order (with
additional complications for conditionals).  These optimizations are
done in the subroutine \fIpeep()\fR.  Optimizations performed at this stage
are subject to the same restrictions as in the pass 2.
.Sh "Pluggable runops"
.IX Subsection "Pluggable runops"
The compile tree is executed in a runops function.  There are two runops
functions in \fIrun.c\fR.  \f(CW\*(C`Perl_runops_debug\*(C'\fR is used with \s-1DEBUGGING\s0 and
\&\f(CW\*(C`Perl_runops_standard\*(C'\fR is used otherwise.  For fine control over the
execution of the compile tree it is possible to provide your own runops
function.
.PP
It's probably best to copy one of the existing runops functions and
change it to suit your needs.  Then, in the \s-1BOOT\s0 section of your \s-1XS\s0
file, add the line:
.PP
.Vb 1
\&  PL_runops = my_runops;
.Ve
.PP
This function should be as efficient as possible to keep your programs
running as fast as possible.
.ie n .SH "Examining internal data structures with the ""dump"" functions"
.el .SH "Examining internal data structures with the \f(CWdump\fP functions"
.IX Header "Examining internal data structures with the dump functions"
To aid debugging, the source file \fIdump.c\fR contains a number of
functions which produce formatted output of internal data structures.
.PP
The most commonly used of these functions is \f(CW\*(C`Perl_sv_dump\*(C'\fR; it's used
for dumping SVs, AVs, HVs, and CVs. The \f(CW\*(C`Devel::Peek\*(C'\fR module calls
\&\f(CW\*(C`sv_dump\*(C'\fR to produce debugging output from Perl\-space, so users of that
module should already be familiar with its format.
.PP
\&\f(CW\*(C`Perl_op_dump\*(C'\fR can be used to dump an \f(CW\*(C`OP\*(C'\fR structure or any of its
derivatives, and produces output similar to \f(CW\*(C`perl \-Dx\*(C'\fR; in fact,
\&\f(CW\*(C`Perl_dump_eval\*(C'\fR will dump the main root of the code being evaluated,
exactly like \f(CW\*(C`\-Dx\*(C'\fR.
.PP
Other useful functions are \f(CW\*(C`Perl_dump_sub\*(C'\fR, which turns a \f(CW\*(C`GV\*(C'\fR into an
op tree, \f(CW\*(C`Perl_dump_packsubs\*(C'\fR which calls \f(CW\*(C`Perl_dump_sub\*(C'\fR on all the
subroutines in a package like so: (Thankfully, these are all xsubs, so
there is no op tree)
.PP
.Vb 1
\&    (gdb) print Perl_dump_packsubs(PL_defstash)
.Ve
.PP
.Vb 1
\&    SUB attributes::bootstrap = (xsub 0x811fedc 0)
.Ve
.PP
.Vb 1
\&    SUB UNIVERSAL::can = (xsub 0x811f50c 0)
.Ve
.PP
.Vb 1
\&    SUB UNIVERSAL::isa = (xsub 0x811f304 0)
.Ve
.PP
.Vb 1
\&    SUB UNIVERSAL::VERSION = (xsub 0x811f7ac 0)
.Ve
.PP
.Vb 1
\&    SUB DynaLoader::boot_DynaLoader = (xsub 0x805b188 0)
.Ve
.PP
and \f(CW\*(C`Perl_dump_all\*(C'\fR, which dumps all the subroutines in the stash and
the op tree of the main root.
.SH "How multiple interpreters and concurrency are supported"
.IX Header "How multiple interpreters and concurrency are supported"
.Sh "Background and \s-1PERL_IMPLICIT_CONTEXT\s0"
.IX Subsection "Background and PERL_IMPLICIT_CONTEXT"
The Perl interpreter can be regarded as a closed box: it has an \s-1API\s0
for feeding it code or otherwise making it do things, but it also has
functions for its own use.  This smells a lot like an object, and
there are ways for you to build Perl so that you can have multiple
interpreters, with one interpreter represented either as a C structure,
or inside a thread-specific structure.  These structures contain all
the context, the state of that interpreter.
.PP
Two macros control the major Perl build flavors: \s-1MULTIPLICITY\s0 and
\&\s-1USE_5005THREADS\s0.  The \s-1MULTIPLICITY\s0 build has a C structure
that packages all the interpreter state, and there is a similar thread-specific
data structure under \s-1USE_5005THREADS\s0.  In both cases,
\&\s-1PERL_IMPLICIT_CONTEXT\s0 is also normally defined, and enables the
support for passing in a \*(L"hidden\*(R" first argument that represents all three
data structures.
.PP
All this obviously requires a way for the Perl internal functions to be
either subroutines taking some kind of structure as the first
argument, or subroutines taking nothing as the first argument.  To
enable these two very different ways of building the interpreter,
the Perl source (as it does in so many other situations) makes heavy
use of macros and subroutine naming conventions.
.PP
First problem: deciding which functions will be public \s-1API\s0 functions and
which will be private.  All functions whose names begin \f(CW\*(C`S_\*(C'\fR are private
(think \*(L"S\*(R" for \*(L"secret\*(R" or \*(L"static\*(R").  All other functions begin with
\&\*(L"Perl_\*(R", but just because a function begins with \*(L"Perl_\*(R" does not mean it is
part of the \s-1API\s0. (See \*(L"Internal Functions\*(R".) The easiest way to be \fBsure\fR a
function is part of the \s-1API\s0 is to find its entry in perlapi.
If it exists in perlapi, it's part of the \s-1API\s0.  If it doesn't, and you
think it should be (i.e., you need it for your extension), send mail via
perlbug explaining why you think it should be.
.PP
Second problem: there must be a syntax so that the same subroutine
declarations and calls can pass a structure as their first argument,
or pass nothing.  To solve this, the subroutines are named and
declared in a particular way.  Here's a typical start of a static
function used within the Perl guts:
.PP
.Vb 2
\&  STATIC void
\&  S_incline(pTHX_ char *s)
.Ve
.PP
\&\s-1STATIC\s0 becomes \*(L"static\*(R" in C, and may be #define'd to nothing in some
configurations in future.
.PP
A public function (i.e. part of the internal \s-1API\s0, but not necessarily
sanctioned for use in extensions) begins like this:
.PP
.Vb 2
\&  void
\&  Perl_sv_setsv(pTHX_ SV* dsv, SV* ssv)
.Ve
.PP
\&\f(CW\*(C`pTHX_\*(C'\fR is one of a number of macros (in perl.h) that hide the
details of the interpreter's context.  \s-1THX\s0 stands for \*(L"thread\*(R", \*(L"this\*(R",
or \*(L"thingy\*(R", as the case may be.  (And no, George Lucas is not involved. :\-)
The first character could be 'p' for a \fBp\fRrototype, 'a' for \fBa\fRrgument,
or 'd' for \fBd\fReclaration, so we have \f(CW\*(C`pTHX\*(C'\fR, \f(CW\*(C`aTHX\*(C'\fR and \f(CW\*(C`dTHX\*(C'\fR, and
their variants.
.PP
When Perl is built without options that set \s-1PERL_IMPLICIT_CONTEXT\s0, there is no
first argument containing the interpreter's context.  The trailing underscore
in the pTHX_ macro indicates that the macro expansion needs a comma
after the context argument because other arguments follow it.  If
\&\s-1PERL_IMPLICIT_CONTEXT\s0 is not defined, pTHX_ will be ignored, and the
subroutine is not prototyped to take the extra argument.  The form of the
macro without the trailing underscore is used when there are no additional
explicit arguments.
.PP
When a core function calls another, it must pass the context.  This
is normally hidden via macros.  Consider \f(CW\*(C`sv_setsv\*(C'\fR.  It expands into
something like this:
.PP
.Vb 6
\&    ifdef PERL_IMPLICIT_CONTEXT
\&      define sv_setsv(a,b)      Perl_sv_setsv(aTHX_ a, b)
\&      /* can't do this for vararg functions, see below */
\&    else
\&      define sv_setsv           Perl_sv_setsv
\&    endif
.Ve
.PP
This works well, and means that \s-1XS\s0 authors can gleefully write:
.PP
.Vb 1
\&    sv_setsv(foo, bar);
.Ve
.PP
and still have it work under all the modes Perl could have been
compiled with.
.PP
This doesn't work so cleanly for varargs functions, though, as macros
imply that the number of arguments is known in advance.  Instead we
either need to spell them out fully, passing \f(CW\*(C`aTHX_\*(C'\fR as the first
argument (the Perl core tends to do this with functions like
Perl_warner), or use a context-free version.
.PP
The context-free version of Perl_warner is called
Perl_warner_nocontext, and does not take the extra argument.  Instead
it does dTHX; to get the context from thread-local storage.  We
\&\f(CW\*(C`#define warner Perl_warner_nocontext\*(C'\fR so that extensions get source
compatibility at the expense of performance.  (Passing an arg is
cheaper than grabbing it from thread-local storage.)
.PP
You can ignore [pad]THXx when browsing the Perl headers/sources.
Those are strictly for use within the core.  Extensions and embedders
need only be aware of [pad]THX.
.Sh "So what happened to dTHR?"
.IX Subsection "So what happened to dTHR?"
\&\f(CW\*(C`dTHR\*(C'\fR was introduced in perl 5.005 to support the older thread model.
The older thread model now uses the \f(CW\*(C`THX\*(C'\fR mechanism to pass context
pointers around, so \f(CW\*(C`dTHR\*(C'\fR is not useful any more.  Perl 5.6.0 and
later still have it for backward source compatibility, but it is defined
to be a no\-op.
.Sh "How do I use all this in extensions?"
.IX Subsection "How do I use all this in extensions?"
When Perl is built with \s-1PERL_IMPLICIT_CONTEXT\s0, extensions that call
any functions in the Perl \s-1API\s0 will need to pass the initial context
argument somehow.  The kicker is that you will need to write it in
such a way that the extension still compiles when Perl hasn't been
built with \s-1PERL_IMPLICIT_CONTEXT\s0 enabled.
.PP
There are three ways to do this.  First, the easy but inefficient way,
which is also the default, in order to maintain source compatibility
with extensions: whenever \s-1XSUB\s0.h is #included, it redefines the aTHX
and aTHX_ macros to call a function that will return the context.
Thus, something like:
.PP
.Vb 1
\&        sv_setsv(asv, bsv);
.Ve
.PP
in your extension will translate to this when \s-1PERL_IMPLICIT_CONTEXT\s0 is
in effect:
.PP
.Vb 1
\&        Perl_sv_setsv(Perl_get_context(), asv, bsv);
.Ve
.PP
or to this otherwise:
.PP
.Vb 1
\&        Perl_sv_setsv(asv, bsv);
.Ve
.PP
You have to do nothing new in your extension to get this; since
the Perl library provides \fIPerl_get_context()\fR, it will all just
work.
.PP
The second, more efficient way is to use the following template for
your Foo.xs:
.PP
.Vb 4
\&        #define PERL_NO_GET_CONTEXT     /* we want efficiency */
\&        #include "EXTERN.h"
\&        #include "perl.h"
\&        #include "XSUB.h"
.Ve
.PP
.Vb 1
\&        static my_private_function(int arg1, int arg2);
.Ve
.PP
.Vb 6
\&        static SV *
\&        my_private_function(int arg1, int arg2)
\&        {
\&            dTHX;       /* fetch context */
\&            ... call many Perl API functions ...
\&        }
.Ve
.PP
.Vb 1
\&        [... etc ...]
.Ve
.PP
.Vb 1
\&        MODULE = Foo            PACKAGE = Foo
.Ve
.PP
.Vb 1
\&        /* typical XSUB */
.Ve
.PP
.Vb 5
\&        void
\&        my_xsub(arg)
\&                int arg
\&            CODE:
\&                my_private_function(arg, 10);
.Ve
.PP
Note that the only two changes from the normal way of writing an
extension is the addition of a \f(CW\*(C`#define PERL_NO_GET_CONTEXT\*(C'\fR before
including the Perl headers, followed by a \f(CW\*(C`dTHX;\*(C'\fR declaration at
the start of every function that will call the Perl \s-1API\s0.  (You'll
know which functions need this, because the C compiler will complain
that there's an undeclared identifier in those functions.)  No changes
are needed for the XSUBs themselves, because the \s-1\fIXS\s0()\fR macro is
correctly defined to pass in the implicit context if needed.
.PP
The third, even more efficient way is to ape how it is done within
the Perl guts:
.PP
.Vb 4
\&        #define PERL_NO_GET_CONTEXT     /* we want efficiency */
\&        #include "EXTERN.h"
\&        #include "perl.h"
\&        #include "XSUB.h"
.Ve
.PP
.Vb 2
\&        /* pTHX_ only needed for functions that call Perl API */
\&        static my_private_function(pTHX_ int arg1, int arg2);
.Ve
.PP
.Vb 6
\&        static SV *
\&        my_private_function(pTHX_ int arg1, int arg2)
\&        {
\&            /* dTHX; not needed here, because THX is an argument */
\&            ... call Perl API functions ...
\&        }
.Ve
.PP
.Vb 1
\&        [... etc ...]
.Ve
.PP
.Vb 1
\&        MODULE = Foo            PACKAGE = Foo
.Ve
.PP
.Vb 1
\&        /* typical XSUB */
.Ve
.PP
.Vb 5
\&        void
\&        my_xsub(arg)
\&                int arg
\&            CODE:
\&                my_private_function(aTHX_ arg, 10);
.Ve
.PP
This implementation never has to fetch the context using a function
call, since it is always passed as an extra argument.  Depending on
your needs for simplicity or efficiency, you may mix the previous
two approaches freely.
.PP
Never add a comma after \f(CW\*(C`pTHX\*(C'\fR yourself\*(--always use the form of the
macro with the underscore for functions that take explicit arguments,
or the form without the argument for functions with no explicit arguments.
.Sh "Should I do anything special if I call perl from multiple threads?"
.IX Subsection "Should I do anything special if I call perl from multiple threads?"
If you create interpreters in one thread and then proceed to call them in
another, you need to make sure perl's own Thread Local Storage (\s-1TLS\s0) slot is
initialized correctly in each of those threads.
.PP
The \f(CW\*(C`perl_alloc\*(C'\fR and \f(CW\*(C`perl_clone\*(C'\fR \s-1API\s0 functions will automatically set
the \s-1TLS\s0 slot to the interpreter they created, so that there is no need to do
anything special if the interpreter is always accessed in the same thread that
created it, and that thread did not create or call any other interpreters
afterwards.  If that is not the case, you have to set the \s-1TLS\s0 slot of the
thread before calling any functions in the Perl \s-1API\s0 on that particular
interpreter.  This is done by calling the \f(CW\*(C`PERL_SET_CONTEXT\*(C'\fR macro in that
thread as the first thing you do:
.PP
.Vb 2
\&        /* do this before doing anything else with some_perl */
\&        PERL_SET_CONTEXT(some_perl);
.Ve
.PP
.Vb 1
\&        ... other Perl API calls on some_perl go here ...
.Ve
.Sh "Future Plans and \s-1PERL_IMPLICIT_SYS\s0"
.IX Subsection "Future Plans and PERL_IMPLICIT_SYS"
Just as \s-1PERL_IMPLICIT_CONTEXT\s0 provides a way to bundle up everything
that the interpreter knows about itself and pass it around, so too are
there plans to allow the interpreter to bundle up everything it knows
about the environment it's running on.  This is enabled with the
\&\s-1PERL_IMPLICIT_SYS\s0 macro.  Currently it only works with \s-1USE_ITHREADS\s0
and \s-1USE_5005THREADS\s0 on Windows (see inside iperlsys.h).
.PP
This allows the ability to provide an extra pointer (called the \*(L"host\*(R"
environment) for all the system calls.  This makes it possible for
all the system stuff to maintain their own state, broken down into
seven C structures.  These are thin wrappers around the usual system
calls (see win32/perllib.c) for the default perl executable, but for a
more ambitious host (like the one that would do \fIfork()\fR emulation) all
the extra work needed to pretend that different interpreters are
actually different \*(L"processes\*(R", would be done here.
.PP
The Perl engine/interpreter and the host are orthogonal entities.
There could be one or more interpreters in a process, and one or
more \*(L"hosts\*(R", with free association between them.
.SH "Internal Functions"
.IX Header "Internal Functions"
All of Perl's internal functions which will be exposed to the outside
world are be prefixed by \f(CW\*(C`Perl_\*(C'\fR so that they will not conflict with \s-1XS\s0
functions or functions used in a program in which Perl is embedded.
Similarly, all global variables begin with \f(CW\*(C`PL_\*(C'\fR. (By convention,
static functions start with \f(CW\*(C`S_\*(C'\fR)
.PP
Inside the Perl core, you can get at the functions either with or
without the \f(CW\*(C`Perl_\*(C'\fR prefix, thanks to a bunch of defines that live in
\&\fIembed.h\fR. This header file is generated automatically from
\&\fIembed.pl\fR. \fIembed.pl\fR also creates the prototyping header files for
the internal functions, generates the documentation and a lot of other
bits and pieces. It's important that when you add a new function to the
core or change an existing one, you change the data in the table at the
end of \fIembed.pl\fR as well. Here's a sample entry from that table:
.PP
.Vb 1
\&    Apd |SV**   |av_fetch   |AV* ar|I32 key|I32 lval
.Ve
.PP
The second column is the return type, the third column the name. Columns
after that are the arguments. The first column is a set of flags:
.IP "A" 3
.IX Item "A"
This function is a part of the public \s-1API\s0.
.IP "p" 3
.IX Item "p"
This function has a \f(CW\*(C`Perl_\*(C'\fR prefix; ie, it is defined as \f(CW\*(C`Perl_av_fetch\*(C'\fR
.IP "d" 3
.IX Item "d"
This function has documentation using the \f(CW\*(C`apidoc\*(C'\fR feature which we'll
look at in a second.
.PP
Other available flags are:
.IP "s" 3
.IX Item "s"
This is a static function and is defined as \f(CW\*(C`S_whatever\*(C'\fR, and usually
called within the sources as \f(CW\*(C`whatever(...)\*(C'\fR.
.IP "n" 3
.IX Item "n"
This does not use \f(CW\*(C`aTHX_\*(C'\fR and \f(CW\*(C`pTHX\*(C'\fR to pass interpreter context. (See
\&\*(L"Background and \s-1PERL_IMPLICIT_CONTEXT\s0\*(R" in perlguts.)
.IP "r" 3
.IX Item "r"
This function never returns; \f(CW\*(C`croak\*(C'\fR, \f(CW\*(C`exit\*(C'\fR and friends.
.IP "f" 3
.IX Item "f"
This function takes a variable number of arguments, \f(CW\*(C`printf\*(C'\fR style.
The argument list should end with \f(CW\*(C`...\*(C'\fR, like this:
.Sp
.Vb 1
\&    Afprd   |void   |croak          |const char* pat|...
.Ve
.IP "M" 3
.IX Item "M"
This function is part of the experimental development \s-1API\s0, and may change
or disappear without notice.
.IP "o" 3
This function should not have a compatibility macro to define, say,
\&\f(CW\*(C`Perl_parse\*(C'\fR to \f(CW\*(C`parse\*(C'\fR. It must be called as \f(CW\*(C`Perl_parse\*(C'\fR.
.IP "j" 3
.IX Item "j"
This function is not a member of \f(CW\*(C`CPerlObj\*(C'\fR. If you don't know
what this means, don't use it.
.IP "x" 3
.IX Item "x"
This function isn't exported out of the Perl core.
.PP
If you edit \fIembed.pl\fR, you will need to run \f(CW\*(C`make regen_headers\*(C'\fR to
force a rebuild of \fIembed.h\fR and other auto-generated files.
.Sh "Formatted Printing of IVs, UVs, and NVs"
.IX Subsection "Formatted Printing of IVs, UVs, and NVs"
If you are printing IVs, UVs, or \s-1NVS\s0 instead of the \fIstdio\fR\|(3) style
formatting codes like \f(CW%d\fR, \f(CW%ld\fR, \f(CW%f\fR, you should use the
following macros for portability
.PP
.Vb 7
\&        IVdf            IV in decimal
\&        UVuf            UV in decimal
\&        UVof            UV in octal
\&        UVxf            UV in hexadecimal
\&        NVef            NV %e-like
\&        NVff            NV %f-like
\&        NVgf            NV %g-like
.Ve
.PP
These will take care of 64\-bit integers and long doubles.
For example:
.PP
.Vb 1
\&        printf("IV is %"IVdf"\en", iv);
.Ve
.PP
The IVdf will expand to whatever is the correct format for the IVs.
.PP
If you are printing addresses of pointers, use UVxf combined
with \s-1\fIPTR2UV\s0()\fR, do not use \f(CW%lx\fR or \f(CW%p\fR.
.Sh "Pointer-To-Integer and Integer-To-Pointer"
.IX Subsection "Pointer-To-Integer and Integer-To-Pointer"
Because pointer size does not necessarily equal integer size,
use the follow macros to do it right.
.PP
.Vb 4
\&        PTR2UV(pointer)
\&        PTR2IV(pointer)
\&        PTR2NV(pointer)
\&        INT2PTR(pointertotype, integer)
.Ve
.PP
For example:
.PP
.Vb 2
\&        IV  iv = ...;
\&        SV *sv = INT2PTR(SV*, iv);
.Ve
.PP
and
.PP
.Vb 2
\&        AV *av = ...;
\&        UV  uv = PTR2UV(av);
.Ve
.Sh "Source Documentation"
.IX Subsection "Source Documentation"
There's an effort going on to document the internal functions and
automatically produce reference manuals from them \- perlapi is one
such manual which details all the functions which are available to \s-1XS\s0
writers. perlintern is the autogenerated manual for the functions
which are not part of the \s-1API\s0 and are supposedly for internal use only.
.PP
Source documentation is created by putting \s-1POD\s0 comments into the C
source, like this:
.PP
.Vb 2
\& /*
\& =for apidoc sv_setiv
.Ve
.PP
.Vb 2
\& Copies an integer into the given SV.  Does not handle 'set' magic.  See
\& C<sv_setiv_mg>.
.Ve
.PP
.Vb 2
\& =cut
\& */
.Ve
.PP
Please try and supply some documentation if you add functions to the
Perl core.
.SH "Unicode Support"
.IX Header "Unicode Support"
Perl 5.6.0 introduced Unicode support. It's important for porters and \s-1XS\s0
writers to understand this support and make sure that the code they
write does not corrupt Unicode data.
.Sh "What \fBis\fP Unicode, anyway?"
.IX Subsection "What is Unicode, anyway?"
In the olden, less enlightened times, we all used to use \s-1ASCII\s0. Most of
us did, anyway. The big problem with \s-1ASCII\s0 is that it's American. Well,
no, that's not actually the problem; the problem is that it's not
particularly useful for people who don't use the Roman alphabet. What
used to happen was that particular languages would stick their own
alphabet in the upper range of the sequence, between 128 and 255. Of
course, we then ended up with plenty of variants that weren't quite
\&\s-1ASCII\s0, and the whole point of it being a standard was lost.
.PP
Worse still, if you've got a language like Chinese or
Japanese that has hundreds or thousands of characters, then you really
can't fit them into a mere 256, so they had to forget about \s-1ASCII\s0
altogether, and build their own systems using pairs of numbers to refer
to one character.
.PP
To fix this, some people formed Unicode, Inc. and
produced a new character set containing all the characters you can
possibly think of and more. There are several ways of representing these
characters, and the one Perl uses is called \s-1UTF8\s0. \s-1UTF8\s0 uses
a variable number of bytes to represent a character, instead of just
one. You can learn more about Unicode at http://www.unicode.org/
.Sh "How can I recognise a \s-1UTF8\s0 string?"
.IX Subsection "How can I recognise a UTF8 string?"
You can't. This is because \s-1UTF8\s0 data is stored in bytes just like
non\-UTF8 data. The Unicode character 200, (\f(CW0xC8\fR for you hex types)
capital E with a grave accent, is represented by the two bytes
\&\f(CW\*(C`v196.172\*(C'\fR. Unfortunately, the non-Unicode string \f(CW\*(C`chr(196).chr(172)\*(C'\fR
has that byte sequence as well. So you can't tell just by looking \- this
is what makes Unicode input an interesting problem.
.PP
The \s-1API\s0 function \f(CW\*(C`is_utf8_string\*(C'\fR can help; it'll tell you if a string
contains only valid \s-1UTF8\s0 characters. However, it can't do the work for
you. On a character-by-character basis, \f(CW\*(C`is_utf8_char\*(C'\fR will tell you
whether the current character in a string is valid \s-1UTF8\s0.
.Sh "How does \s-1UTF8\s0 represent Unicode characters?"
.IX Subsection "How does UTF8 represent Unicode characters?"
As mentioned above, \s-1UTF8\s0 uses a variable number of bytes to store a
character. Characters with values 1...128 are stored in one byte, just
like good ol' \s-1ASCII\s0. Character 129 is stored as \f(CW\*(C`v194.129\*(C'\fR; this
continues up to character 191, which is \f(CW\*(C`v194.191\*(C'\fR. Now we've run out of
bits (191 is binary \f(CW10111111\fR) so we move on; 192 is \f(CW\*(C`v195.128\*(C'\fR. And
so it goes on, moving to three bytes at character 2048.
.PP
Assuming you know you're dealing with a \s-1UTF8\s0 string, you can find out
how long the first character in it is with the \f(CW\*(C`UTF8SKIP\*(C'\fR macro:
.PP
.Vb 2
\&    char *utf = "\e305\e233\e340\e240\e201";
\&    I32 len;
.Ve
.PP
.Vb 3
\&    len = UTF8SKIP(utf); /* len is 2 here */
\&    utf += len;
\&    len = UTF8SKIP(utf); /* len is 3 here */
.Ve
.PP
Another way to skip over characters in a \s-1UTF8\s0 string is to use
\&\f(CW\*(C`utf8_hop\*(C'\fR, which takes a string and a number of characters to skip
over. You're on your own about bounds checking, though, so don't use it
lightly.
.PP
All bytes in a multi-byte \s-1UTF8\s0 character will have the high bit set, so
you can test if you need to do something special with this character
like this:
.PP
.Vb 1
\&    UV uv;
.Ve
.PP
.Vb 6
\&    if (utf & 0x80)
\&        /* Must treat this as UTF8 */
\&        uv = utf8_to_uv(utf);
\&    else
\&        /* OK to treat this character as a byte */
\&        uv = *utf;
.Ve
.PP
You can also see in that example that we use \f(CW\*(C`utf8_to_uv\*(C'\fR to get the
value of the character; the inverse function \f(CW\*(C`uv_to_utf8\*(C'\fR is available
for putting a \s-1UV\s0 into \s-1UTF8:\s0
.PP
.Vb 6
\&    if (uv > 0x80)
\&        /* Must treat this as UTF8 */
\&        utf8 = uv_to_utf8(utf8, uv);
\&    else
\&        /* OK to treat this character as a byte */
\&        *utf8++ = uv;
.Ve
.PP
You \fBmust\fR convert characters to UVs using the above functions if
you're ever in a situation where you have to match \s-1UTF8\s0 and non\-UTF8
characters. You may not skip over \s-1UTF8\s0 characters in this case. If you
do this, you'll lose the ability to match hi-bit non\-UTF8 characters;
for instance, if your \s-1UTF8\s0 string contains \f(CW\*(C`v196.172\*(C'\fR, and you skip
that character, you can never match a \f(CW\*(C`chr(200)\*(C'\fR in a non\-UTF8 string.
So don't do that!
.Sh "How does Perl store \s-1UTF8\s0 strings?"
.IX Subsection "How does Perl store UTF8 strings?"
Currently, Perl deals with Unicode strings and non-Unicode strings
slightly differently. If a string has been identified as being \s-1UTF\-8\s0
encoded, Perl will set a flag in the \s-1SV\s0, \f(CW\*(C`SVf_UTF8\*(C'\fR. You can check and
manipulate this flag with the following macros:
.PP
.Vb 3
\&    SvUTF8(sv)
\&    SvUTF8_on(sv)
\&    SvUTF8_off(sv)
.Ve
.PP
This flag has an important effect on Perl's treatment of the string: if
Unicode data is not properly distinguished, regular expressions,
\&\f(CW\*(C`length\*(C'\fR, \f(CW\*(C`substr\*(C'\fR and other string handling operations will have
undesirable results.
.PP
The problem comes when you have, for instance, a string that isn't
flagged is \s-1UTF8\s0, and contains a byte sequence that could be \s-1UTF8\s0 \-
especially when combining non\-UTF8 and \s-1UTF8\s0 strings.
.PP
Never forget that the \f(CW\*(C`SVf_UTF8\*(C'\fR flag is separate to the \s-1PV\s0 value; you
need be sure you don't accidentally knock it off while you're
manipulating SVs. More specifically, you cannot expect to do this:
.PP
.Vb 4
\&    SV *sv;
\&    SV *nsv;
\&    STRLEN len;
\&    char *p;
.Ve
.PP
.Vb 3
\&    p = SvPV(sv, len);
\&    frobnicate(p);
\&    nsv = newSVpvn(p, len);
.Ve
.PP
The \f(CW\*(C`char*\*(C'\fR string does not tell you the whole story, and you can't
copy or reconstruct an \s-1SV\s0 just by copying the string value. Check if the
old \s-1SV\s0 has the \s-1UTF8\s0 flag set, and act accordingly:
.PP
.Vb 5
\&    p = SvPV(sv, len);
\&    frobnicate(p);
\&    nsv = newSVpvn(p, len);
\&    if (SvUTF8(sv))
\&        SvUTF8_on(nsv);
.Ve
.PP
In fact, your \f(CW\*(C`frobnicate\*(C'\fR function should be made aware of whether or
not it's dealing with \s-1UTF8\s0 data, so that it can handle the string
appropriately.
.Sh "How do I convert a string to \s-1UTF8\s0?"
.IX Subsection "How do I convert a string to UTF8?"
If you're mixing \s-1UTF8\s0 and non\-UTF8 strings, you might find it necessary
to upgrade one of the strings to \s-1UTF8\s0. If you've got an \s-1SV\s0, the easiest
way to do this is:
.PP
.Vb 1
\&    sv_utf8_upgrade(sv);
.Ve
.PP
However, you must not do this, for example:
.PP
.Vb 2
\&    if (!SvUTF8(left))
\&        sv_utf8_upgrade(left);
.Ve
.PP
If you do this in a binary operator, you will actually change one of the
strings that came into the operator, and, while it shouldn't be noticeable
by the end user, it can cause problems.
.PP
Instead, \f(CW\*(C`bytes_to_utf8\*(C'\fR will give you a UTF8\-encoded \fBcopy\fR of its
string argument. This is useful for having the data available for
comparisons and so on, without harming the original \s-1SV\s0. There's also
\&\f(CW\*(C`utf8_to_bytes\*(C'\fR to go the other way, but naturally, this will fail if
the string contains any characters above 255 that can't be represented
in a single byte.
.Sh "Is there anything else I need to know?"
.IX Subsection "Is there anything else I need to know?"
Not really. Just remember these things:
.IP "\(bu" 3
There's no way to tell if a string is \s-1UTF8\s0 or not. You can tell if an \s-1SV\s0
is \s-1UTF8\s0 by looking at is \f(CW\*(C`SvUTF8\*(C'\fR flag. Don't forget to set the flag if
something should be \s-1UTF8\s0. Treat the flag as part of the \s-1PV\s0, even though
it's not \- if you pass on the \s-1PV\s0 to somewhere, pass on the flag too.
.IP "\(bu" 3
If a string is \s-1UTF8\s0, \fBalways\fR use \f(CW\*(C`utf8_to_uv\*(C'\fR to get at the value,
unless \f(CW\*(C`!(*s & 0x80)\*(C'\fR in which case you can use \f(CW*s\fR.
.IP "\(bu" 3
When writing to a \s-1UTF8\s0 string, \fBalways\fR use \f(CW\*(C`uv_to_utf8\*(C'\fR, unless
\&\f(CW\*(C`uv < 0x80\*(C'\fR in which case you can use \f(CW\*(C`*s = uv\*(C'\fR.
.IP "\(bu" 3
Mixing \s-1UTF8\s0 and non\-UTF8 strings is tricky. Use \f(CW\*(C`bytes_to_utf8\*(C'\fR to get
a new string which is \s-1UTF8\s0 encoded. There are tricks you can use to
delay deciding whether you need to use a \s-1UTF8\s0 string until you get to a
high character \- \f(CW\*(C`HALF_UPGRADE\*(C'\fR is one of those.
.SH "Custom Operators"
.IX Header "Custom Operators"
Custom operator support is a new experimental feature that allows you to
define your own ops. This is primarily to allow the building of
interpreters for other languages in the Perl core, but it also allows
optimizations through the creation of \*(L"macro\-ops\*(R" (ops which perform the
functions of multiple ops which are usually executed together, such as
\&\f(CW\*(C`gvsv, gvsv, add\*(C'\fR.) 
.PP
This feature is implemented as a new op type, \f(CW\*(C`OP_CUSTOM\*(C'\fR. The Perl
core does not \*(L"know\*(R" anything special about this op type, and so it will
not be involved in any optimizations. This also means that you can
define your custom ops to be any op structure \- unary, binary, list and
so on \- you like.
.PP
It's important to know what custom operators won't do for you. They
won't let you add new syntax to Perl, directly. They won't even let you
add new keywords, directly. In fact, they won't change the way Perl
compiles a program at all. You have to do those changes yourself, after
Perl has compiled the program. You do this either by manipulating the op
tree using a \f(CW\*(C`CHECK\*(C'\fR block and the \f(CW\*(C`B::Generate\*(C'\fR module, or by adding
a custom peephole optimizer with the \f(CW\*(C`optimize\*(C'\fR module.
.PP
When you do this, you replace ordinary Perl ops with custom ops by
creating ops with the type \f(CW\*(C`OP_CUSTOM\*(C'\fR and the \f(CW\*(C`pp_addr\*(C'\fR of your own
\&\s-1PP\s0 function. This should be defined in \s-1XS\s0 code, and should look like
the \s-1PP\s0 ops in \f(CW\*(C`pp_*.c\*(C'\fR. You are responsible for ensuring that your op
takes the appropriate number of values from the stack, and you are
responsible for adding stack marks if necessary.
.PP
You should also \*(L"register\*(R" your op with the Perl interpreter so that it
can produce sensible error and warning messages. Since it is possible to
have multiple custom ops within the one \*(L"logical\*(R" op type \f(CW\*(C`OP_CUSTOM\*(C'\fR,
Perl uses the value of \f(CW\*(C`o\->op_ppaddr\*(C'\fR as a key into the
\&\f(CW\*(C`PL_custom_op_descs\*(C'\fR and \f(CW\*(C`PL_custom_op_names\*(C'\fR hashes. This means you
need to enter a name and description for your op at the appropriate
place in the \f(CW\*(C`PL_custom_op_names\*(C'\fR and \f(CW\*(C`PL_custom_op_descs\*(C'\fR hashes.
.PP
Forthcoming versions of \f(CW\*(C`B::Generate\*(C'\fR (version 1.0 and above) should
directly support the creation of custom ops by name; \f(CW\*(C`Opcodes::Custom\*(C'\fR 
will provide functions which make it trivial to \*(L"register\*(R" custom ops to
the Perl interpreter.
.SH "AUTHORS"
.IX Header "AUTHORS"
Until May 1997, this document was maintained by Jeff Okamoto
<okamoto@corp.hp.com>.  It is now maintained as part of Perl
itself by the Perl 5 Porters <perl5\-porters@perl.org>.
.PP
With lots of help and suggestions from Dean Roehrich, Malcolm Beattie,
Andreas Koenig, Paul Hudson, Ilya Zakharevich, Paul Marquess, Neil
Bowers, Matthew Green, Tim Bunce, Spider Boardman, Ulrich Pfeifer,
Stephen McCamant, and Gurusamy Sarathy.
.PP
\&\s-1API\s0 Listing originally by Dean Roehrich <roehrich@cray.com>.
.PP
Modifications to autogenerate the \s-1API\s0 listing (perlapi) by Benjamin
Stuhl.
.SH "SEE ALSO"
.IX Header "SEE ALSO"
\&\fIperlapi\fR\|(1), \fIperlintern\fR\|(1), \fIperlxs\fR\|(1), \fIperlembed\fR\|(1)

Bell Labs OSI certified Powered by Plan 9

(Return to Plan 9 Home Page)

Copyright © 2021 Plan 9 Foundation. All Rights Reserved.
Comments to webmaster@9p.io.