PageRenderTime 211ms CodeModel.GetById 47ms app.highlight 146ms RepoModel.GetById 1ms app.codeStats 1ms

/IronPython_Main/Runtime/Tests/LinqDlrTests/testenv/perl/lib/pod/perlguts.pod

#
Unknown | 2318 lines | 1722 code | 596 blank | 0 comment | 0 complexity | fc01ac7c98729bd3b2f13f0038743c8c MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1=head1 NAME
   2
   3perlguts - Introduction to the Perl API
   4
   5=head1 DESCRIPTION
   6
   7This document attempts to describe how to use the Perl API, as well as
   8containing some info on the basic workings of the Perl core. It is far
   9from complete and probably contains many errors. Please refer any
  10questions or comments to the author below.
  11
  12=head1 Variables
  13
  14=head2 Datatypes
  15
  16Perl has three typedefs that handle Perl's three main data types:
  17
  18    SV  Scalar Value
  19    AV  Array Value
  20    HV  Hash Value
  21
  22Each typedef has specific routines that manipulate the various data types.
  23
  24=head2 What is an "IV"?
  25
  26Perl uses a special typedef IV which is a simple signed integer type that is
  27guaranteed to be large enough to hold a pointer (as well as an integer).
  28Additionally, there is the UV, which is simply an unsigned IV.
  29
  30Perl also uses two special typedefs, I32 and I16, which will always be at
  31least 32-bits and 16-bits long, respectively. (Again, there are U32 and U16,
  32as well.)
  33
  34=head2 Working with SVs
  35
  36An SV can be created and loaded with one command.  There are four types of
  37values that can be loaded: an integer value (IV), a double (NV),
  38a string (PV), and another scalar (SV).
  39
  40The six routines are:
  41
  42    SV*  newSViv(IV);
  43    SV*  newSVnv(double);
  44    SV*  newSVpv(const char*, int);
  45    SV*  newSVpvn(const char*, int);
  46    SV*  newSVpvf(const char*, ...);
  47    SV*  newSVsv(SV*);
  48
  49To change the value of an *already-existing* SV, there are seven routines:
  50
  51    void  sv_setiv(SV*, IV);
  52    void  sv_setuv(SV*, UV);
  53    void  sv_setnv(SV*, double);
  54    void  sv_setpv(SV*, const char*);
  55    void  sv_setpvn(SV*, const char*, int)
  56    void  sv_setpvf(SV*, const char*, ...);
  57    void  sv_setpvfn(SV*, const char*, STRLEN, va_list *, SV **, I32, bool);
  58    void  sv_setsv(SV*, SV*);
  59
  60Notice that you can choose to specify the length of the string to be
  61assigned by using C<sv_setpvn>, C<newSVpvn>, or C<newSVpv>, or you may
  62allow Perl to calculate the length by using C<sv_setpv> or by specifying
  630 as the second argument to C<newSVpv>.  Be warned, though, that Perl will
  64determine the string's length by using C<strlen>, which depends on the
  65string terminating with a NUL character.
  66
  67The arguments of C<sv_setpvf> are processed like C<sprintf>, and the
  68formatted output becomes the value.
  69
  70C<sv_setpvfn> is an analogue of C<vsprintf>, but it allows you to specify
  71either a pointer to a variable argument list or the address and length of
  72an array of SVs.  The last argument points to a boolean; on return, if that
  73boolean is true, then locale-specific information has been used to format
  74the string, and the string's contents are therefore untrustworthy (see
  75L<perlsec>).  This pointer may be NULL if that information is not
  76important.  Note that this function requires you to specify the length of
  77the format.
  78
  79STRLEN is an integer type (Size_t, usually defined as size_t in
  80config.h) guaranteed to be large enough to represent the size of 
  81any string that perl can handle.
  82
  83The C<sv_set*()> functions are not generic enough to operate on values
  84that have "magic".  See L<Magic Virtual Tables> later in this document.
  85
  86All SVs that contain strings should be terminated with a NUL character.
  87If it is not NUL-terminated there is a risk of
  88core dumps and corruptions from code which passes the string to C
  89functions or system calls which expect a NUL-terminated string.
  90Perl's own functions typically add a trailing NUL for this reason.
  91Nevertheless, you should be very careful when you pass a string stored
  92in an SV to a C function or system call.
  93
  94To access the actual value that an SV points to, you can use the macros:
  95
  96    SvIV(SV*)
  97    SvUV(SV*)
  98    SvNV(SV*)
  99    SvPV(SV*, STRLEN len)
 100    SvPV_nolen(SV*)
 101
 102which will automatically coerce the actual scalar type into an IV, UV, double,
 103or string.
 104
 105In the C<SvPV> macro, the length of the string returned is placed into the
 106variable C<len> (this is a macro, so you do I<not> use C<&len>).  If you do
 107not care what the length of the data is, use the C<SvPV_nolen> macro.
 108Historically the C<SvPV> macro with the global variable C<PL_na> has been
 109used in this case.  But that can be quite inefficient because C<PL_na> must
 110be accessed in thread-local storage in threaded Perl.  In any case, remember
 111that Perl allows arbitrary strings of data that may both contain NULs and
 112might not be terminated by a NUL.
 113
 114Also remember that C doesn't allow you to safely say C<foo(SvPV(s, len),
 115len);>. It might work with your compiler, but it won't work for everyone.
 116Break this sort of statement up into separate assignments:
 117
 118	SV *s;
 119	STRLEN len;
 120	char * ptr;
 121	ptr = SvPV(s, len);
 122	foo(ptr, len);
 123
 124If you want to know if the scalar value is TRUE, you can use:
 125
 126    SvTRUE(SV*)
 127
 128Although Perl will automatically grow strings for you, if you need to force
 129Perl to allocate more memory for your SV, you can use the macro
 130
 131    SvGROW(SV*, STRLEN newlen)
 132
 133which will determine if more memory needs to be allocated.  If so, it will
 134call the function C<sv_grow>.  Note that C<SvGROW> can only increase, not
 135decrease, the allocated memory of an SV and that it does not automatically
 136add a byte for the a trailing NUL (perl's own string functions typically do
 137C<SvGROW(sv, len + 1)>).
 138
 139If you have an SV and want to know what kind of data Perl thinks is stored
 140in it, you can use the following macros to check the type of SV you have.
 141
 142    SvIOK(SV*)
 143    SvNOK(SV*)
 144    SvPOK(SV*)
 145
 146You can get and set the current length of the string stored in an SV with
 147the following macros:
 148
 149    SvCUR(SV*)
 150    SvCUR_set(SV*, I32 val)
 151
 152You can also get a pointer to the end of the string stored in the SV
 153with the macro:
 154
 155    SvEND(SV*)
 156
 157But note that these last three macros are valid only if C<SvPOK()> is true.
 158
 159If you want to append something to the end of string stored in an C<SV*>,
 160you can use the following functions:
 161
 162    void  sv_catpv(SV*, const char*);
 163    void  sv_catpvn(SV*, const char*, STRLEN);
 164    void  sv_catpvf(SV*, const char*, ...);
 165    void  sv_catpvfn(SV*, const char*, STRLEN, va_list *, SV **, I32, bool);
 166    void  sv_catsv(SV*, SV*);
 167
 168The first function calculates the length of the string to be appended by
 169using C<strlen>.  In the second, you specify the length of the string
 170yourself.  The third function processes its arguments like C<sprintf> and
 171appends the formatted output.  The fourth function works like C<vsprintf>.
 172You can specify the address and length of an array of SVs instead of the
 173va_list argument. The fifth function extends the string stored in the first
 174SV with the string stored in the second SV.  It also forces the second SV
 175to be interpreted as a string.
 176
 177The C<sv_cat*()> functions are not generic enough to operate on values that
 178have "magic".  See L<Magic Virtual Tables> later in this document.
 179
 180If you know the name of a scalar variable, you can get a pointer to its SV
 181by using the following:
 182
 183    SV*  get_sv("package::varname", FALSE);
 184
 185This returns NULL if the variable does not exist.
 186
 187If you want to know if this variable (or any other SV) is actually C<defined>,
 188you can call:
 189
 190    SvOK(SV*)
 191
 192The scalar C<undef> value is stored in an SV instance called C<PL_sv_undef>.  Its
 193address can be used whenever an C<SV*> is needed.
 194
 195There are also the two values C<PL_sv_yes> and C<PL_sv_no>, which contain Boolean
 196TRUE and FALSE values, respectively.  Like C<PL_sv_undef>, their addresses can
 197be used whenever an C<SV*> is needed.
 198
 199Do not be fooled into thinking that C<(SV *) 0> is the same as C<&PL_sv_undef>.
 200Take this code:
 201
 202    SV* sv = (SV*) 0;
 203    if (I-am-to-return-a-real-value) {
 204            sv = sv_2mortal(newSViv(42));
 205    }
 206    sv_setsv(ST(0), sv);
 207
 208This code tries to return a new SV (which contains the value 42) if it should
 209return a real value, or undef otherwise.  Instead it has returned a NULL
 210pointer which, somewhere down the line, will cause a segmentation violation,
 211bus error, or just weird results.  Change the zero to C<&PL_sv_undef> in the first
 212line and all will be well.
 213
 214To free an SV that you've created, call C<SvREFCNT_dec(SV*)>.  Normally this
 215call is not necessary (see L<Reference Counts and Mortality>).
 216
 217=head2 Offsets
 218
 219Perl provides the function C<sv_chop> to efficiently remove characters
 220from the beginning of a string; you give it an SV and a pointer to
 221somewhere inside the the PV, and it discards everything before the
 222pointer. The efficiency comes by means of a little hack: instead of
 223actually removing the characters, C<sv_chop> sets the flag C<OOK>
 224(offset OK) to signal to other functions that the offset hack is in
 225effect, and it puts the number of bytes chopped off into the IV field
 226of the SV. It then moves the PV pointer (called C<SvPVX>) forward that
 227many bytes, and adjusts C<SvCUR> and C<SvLEN>. 
 228
 229Hence, at this point, the start of the buffer that we allocated lives
 230at C<SvPVX(sv) - SvIV(sv)> in memory and the PV pointer is pointing
 231into the middle of this allocated storage.
 232
 233This is best demonstrated by example:
 234
 235  % ./perl -Ilib -MDevel::Peek -le '$a="12345"; $a=~s/.//; Dump($a)'
 236  SV = PVIV(0x8128450) at 0x81340f0
 237    REFCNT = 1
 238    FLAGS = (POK,OOK,pPOK)
 239    IV = 1  (OFFSET)
 240    PV = 0x8135781 ( "1" . ) "2345"\0
 241    CUR = 4
 242    LEN = 5
 243
 244Here the number of bytes chopped off (1) is put into IV, and
 245C<Devel::Peek::Dump> helpfully reminds us that this is an offset. The
 246portion of the string between the "real" and the "fake" beginnings is
 247shown in parentheses, and the values of C<SvCUR> and C<SvLEN> reflect
 248the fake beginning, not the real one.
 249
 250Something similar to the offset hack is perfomed on AVs to enable
 251efficient shifting and splicing off the beginning of the array; while
 252C<AvARRAY> points to the first element in the array that is visible from
 253Perl, C<AvALLOC> points to the real start of the C array. These are
 254usually the same, but a C<shift> operation can be carried out by
 255increasing C<AvARRAY> by one and decreasing C<AvFILL> and C<AvLEN>.
 256Again, the location of the real start of the C array only comes into
 257play when freeing the array. See C<av_shift> in F<av.c>.
 258
 259=head2 What's Really Stored in an SV?
 260
 261Recall that the usual method of determining the type of scalar you have is
 262to use C<Sv*OK> macros.  Because a scalar can be both a number and a string,
 263usually these macros will always return TRUE and calling the C<Sv*V>
 264macros will do the appropriate conversion of string to integer/double or
 265integer/double to string.
 266
 267If you I<really> need to know if you have an integer, double, or string
 268pointer in an SV, you can use the following three macros instead:
 269
 270    SvIOKp(SV*)
 271    SvNOKp(SV*)
 272    SvPOKp(SV*)
 273
 274These will tell you if you truly have an integer, double, or string pointer
 275stored in your SV.  The "p" stands for private.
 276
 277In general, though, it's best to use the C<Sv*V> macros.
 278
 279=head2 Working with AVs
 280
 281There are two ways to create and load an AV.  The first method creates an
 282empty AV:
 283
 284    AV*  newAV();
 285
 286The second method both creates the AV and initially populates it with SVs:
 287
 288    AV*  av_make(I32 num, SV **ptr);
 289
 290The second argument points to an array containing C<num> C<SV*>'s.  Once the
 291AV has been created, the SVs can be destroyed, if so desired.
 292
 293Once the AV has been created, the following operations are possible on AVs:
 294
 295    void  av_push(AV*, SV*);
 296    SV*   av_pop(AV*);
 297    SV*   av_shift(AV*);
 298    void  av_unshift(AV*, I32 num);
 299
 300These should be familiar operations, with the exception of C<av_unshift>.
 301This routine adds C<num> elements at the front of the array with the C<undef>
 302value.  You must then use C<av_store> (described below) to assign values
 303to these new elements.
 304
 305Here are some other functions:
 306
 307    I32   av_len(AV*);
 308    SV**  av_fetch(AV*, I32 key, I32 lval);
 309    SV**  av_store(AV*, I32 key, SV* val);
 310
 311The C<av_len> function returns the highest index value in array (just
 312like $#array in Perl).  If the array is empty, -1 is returned.  The
 313C<av_fetch> function returns the value at index C<key>, but if C<lval>
 314is non-zero, then C<av_fetch> will store an undef value at that index.
 315The C<av_store> function stores the value C<val> at index C<key>, and does
 316not increment the reference count of C<val>.  Thus the caller is responsible
 317for taking care of that, and if C<av_store> returns NULL, the caller will
 318have to decrement the reference count to avoid a memory leak.  Note that
 319C<av_fetch> and C<av_store> both return C<SV**>'s, not C<SV*>'s as their
 320return value.
 321
 322    void  av_clear(AV*);
 323    void  av_undef(AV*);
 324    void  av_extend(AV*, I32 key);
 325
 326The C<av_clear> function deletes all the elements in the AV* array, but
 327does not actually delete the array itself.  The C<av_undef> function will
 328delete all the elements in the array plus the array itself.  The
 329C<av_extend> function extends the array so that it contains at least C<key+1>
 330elements.  If C<key+1> is less than the currently allocated length of the array,
 331then nothing is done.
 332
 333If you know the name of an array variable, you can get a pointer to its AV
 334by using the following:
 335
 336    AV*  get_av("package::varname", FALSE);
 337
 338This returns NULL if the variable does not exist.
 339
 340See L<Understanding the Magic of Tied Hashes and Arrays> for more
 341information on how to use the array access functions on tied arrays.
 342
 343=head2 Working with HVs
 344
 345To create an HV, you use the following routine:
 346
 347    HV*  newHV();
 348
 349Once the HV has been created, the following operations are possible on HVs:
 350
 351    SV**  hv_store(HV*, const char* key, U32 klen, SV* val, U32 hash);
 352    SV**  hv_fetch(HV*, const char* key, U32 klen, I32 lval);
 353
 354The C<klen> parameter is the length of the key being passed in (Note that
 355you cannot pass 0 in as a value of C<klen> to tell Perl to measure the
 356length of the key).  The C<val> argument contains the SV pointer to the
 357scalar being stored, and C<hash> is the precomputed hash value (zero if
 358you want C<hv_store> to calculate it for you).  The C<lval> parameter
 359indicates whether this fetch is actually a part of a store operation, in
 360which case a new undefined value will be added to the HV with the supplied
 361key and C<hv_fetch> will return as if the value had already existed.
 362
 363Remember that C<hv_store> and C<hv_fetch> return C<SV**>'s and not just
 364C<SV*>.  To access the scalar value, you must first dereference the return
 365value.  However, you should check to make sure that the return value is
 366not NULL before dereferencing it.
 367
 368These two functions check if a hash table entry exists, and deletes it.
 369
 370    bool  hv_exists(HV*, const char* key, U32 klen);
 371    SV*   hv_delete(HV*, const char* key, U32 klen, I32 flags);
 372
 373If C<flags> does not include the C<G_DISCARD> flag then C<hv_delete> will
 374create and return a mortal copy of the deleted value.
 375
 376And more miscellaneous functions:
 377
 378    void   hv_clear(HV*);
 379    void   hv_undef(HV*);
 380
 381Like their AV counterparts, C<hv_clear> deletes all the entries in the hash
 382table but does not actually delete the hash table.  The C<hv_undef> deletes
 383both the entries and the hash table itself.
 384
 385Perl keeps the actual data in linked list of structures with a typedef of HE.
 386These contain the actual key and value pointers (plus extra administrative
 387overhead).  The key is a string pointer; the value is an C<SV*>.  However,
 388once you have an C<HE*>, to get the actual key and value, use the routines
 389specified below.
 390
 391    I32    hv_iterinit(HV*);
 392            /* Prepares starting point to traverse hash table */
 393    HE*    hv_iternext(HV*);
 394            /* Get the next entry, and return a pointer to a
 395               structure that has both the key and value */
 396    char*  hv_iterkey(HE* entry, I32* retlen);
 397            /* Get the key from an HE structure and also return
 398               the length of the key string */
 399    SV*    hv_iterval(HV*, HE* entry);
 400            /* Return a SV pointer to the value of the HE
 401               structure */
 402    SV*    hv_iternextsv(HV*, char** key, I32* retlen);
 403            /* This convenience routine combines hv_iternext,
 404	       hv_iterkey, and hv_iterval.  The key and retlen
 405	       arguments are return values for the key and its
 406	       length.  The value is returned in the SV* argument */
 407
 408If you know the name of a hash variable, you can get a pointer to its HV
 409by using the following:
 410
 411    HV*  get_hv("package::varname", FALSE);
 412
 413This returns NULL if the variable does not exist.
 414
 415The hash algorithm is defined in the C<PERL_HASH(hash, key, klen)> macro:
 416
 417    hash = 0;
 418    while (klen--)
 419	hash = (hash * 33) + *key++;
 420    hash = hash + (hash >> 5);			/* after 5.6 */
 421
 422The last step was added in version 5.6 to improve distribution of
 423lower bits in the resulting hash value.
 424
 425See L<Understanding the Magic of Tied Hashes and Arrays> for more
 426information on how to use the hash access functions on tied hashes.
 427
 428=head2 Hash API Extensions
 429
 430Beginning with version 5.004, the following functions are also supported:
 431
 432    HE*     hv_fetch_ent  (HV* tb, SV* key, I32 lval, U32 hash);
 433    HE*     hv_store_ent  (HV* tb, SV* key, SV* val, U32 hash);
 434
 435    bool    hv_exists_ent (HV* tb, SV* key, U32 hash);
 436    SV*     hv_delete_ent (HV* tb, SV* key, I32 flags, U32 hash);
 437
 438    SV*     hv_iterkeysv  (HE* entry);
 439
 440Note that these functions take C<SV*> keys, which simplifies writing
 441of extension code that deals with hash structures.  These functions
 442also allow passing of C<SV*> keys to C<tie> functions without forcing
 443you to stringify the keys (unlike the previous set of functions).
 444
 445They also return and accept whole hash entries (C<HE*>), making their
 446use more efficient (since the hash number for a particular string
 447doesn't have to be recomputed every time).  See L<perlapi> for detailed
 448descriptions.
 449
 450The following macros must always be used to access the contents of hash
 451entries.  Note that the arguments to these macros must be simple
 452variables, since they may get evaluated more than once.  See
 453L<perlapi> for detailed descriptions of these macros.
 454
 455    HePV(HE* he, STRLEN len)
 456    HeVAL(HE* he)
 457    HeHASH(HE* he)
 458    HeSVKEY(HE* he)
 459    HeSVKEY_force(HE* he)
 460    HeSVKEY_set(HE* he, SV* sv)
 461
 462These two lower level macros are defined, but must only be used when
 463dealing with keys that are not C<SV*>s:
 464
 465    HeKEY(HE* he)
 466    HeKLEN(HE* he)
 467
 468Note that both C<hv_store> and C<hv_store_ent> do not increment the
 469reference count of the stored C<val>, which is the caller's responsibility.
 470If these functions return a NULL value, the caller will usually have to
 471decrement the reference count of C<val> to avoid a memory leak.
 472
 473=head2 References
 474
 475References are a special type of scalar that point to other data types
 476(including references).
 477
 478To create a reference, use either of the following functions:
 479
 480    SV* newRV_inc((SV*) thing);
 481    SV* newRV_noinc((SV*) thing);
 482
 483The C<thing> argument can be any of an C<SV*>, C<AV*>, or C<HV*>.  The
 484functions are identical except that C<newRV_inc> increments the reference
 485count of the C<thing>, while C<newRV_noinc> does not.  For historical
 486reasons, C<newRV> is a synonym for C<newRV_inc>.
 487
 488Once you have a reference, you can use the following macro to dereference
 489the reference:
 490
 491    SvRV(SV*)
 492
 493then call the appropriate routines, casting the returned C<SV*> to either an
 494C<AV*> or C<HV*>, if required.
 495
 496To determine if an SV is a reference, you can use the following macro:
 497
 498    SvROK(SV*)
 499
 500To discover what type of value the reference refers to, use the following
 501macro and then check the return value.
 502
 503    SvTYPE(SvRV(SV*))
 504
 505The most useful types that will be returned are:
 506
 507    SVt_IV    Scalar
 508    SVt_NV    Scalar
 509    SVt_PV    Scalar
 510    SVt_RV    Scalar
 511    SVt_PVAV  Array
 512    SVt_PVHV  Hash
 513    SVt_PVCV  Code
 514    SVt_PVGV  Glob (possible a file handle)
 515    SVt_PVMG  Blessed or Magical Scalar
 516
 517    See the sv.h header file for more details.
 518
 519=head2 Blessed References and Class Objects
 520
 521References are also used to support object-oriented programming.  In the
 522OO lexicon, an object is simply a reference that has been blessed into a
 523package (or class).  Once blessed, the programmer may now use the reference
 524to access the various methods in the class.
 525
 526A reference can be blessed into a package with the following function:
 527
 528    SV* sv_bless(SV* sv, HV* stash);
 529
 530The C<sv> argument must be a reference.  The C<stash> argument specifies
 531which class the reference will belong to.  See
 532L<Stashes and Globs> for information on converting class names into stashes.
 533
 534/* Still under construction */
 535
 536Upgrades rv to reference if not already one.  Creates new SV for rv to
 537point to.  If C<classname> is non-null, the SV is blessed into the specified
 538class.  SV is returned.
 539
 540	SV* newSVrv(SV* rv, const char* classname);
 541
 542Copies integer or double into an SV whose reference is C<rv>.  SV is blessed
 543if C<classname> is non-null.
 544
 545	SV* sv_setref_iv(SV* rv, const char* classname, IV iv);
 546	SV* sv_setref_nv(SV* rv, const char* classname, NV iv);
 547
 548Copies the pointer value (I<the address, not the string!>) into an SV whose
 549reference is rv.  SV is blessed if C<classname> is non-null.
 550
 551	SV* sv_setref_pv(SV* rv, const char* classname, PV iv);
 552
 553Copies string into an SV whose reference is C<rv>.  Set length to 0 to let
 554Perl calculate the string length.  SV is blessed if C<classname> is non-null.
 555
 556	SV* sv_setref_pvn(SV* rv, const char* classname, PV iv, STRLEN length);
 557
 558Tests whether the SV is blessed into the specified class.  It does not
 559check inheritance relationships.
 560
 561	int  sv_isa(SV* sv, const char* name);
 562
 563Tests whether the SV is a reference to a blessed object.
 564
 565	int  sv_isobject(SV* sv);
 566
 567Tests whether the SV is derived from the specified class. SV can be either
 568a reference to a blessed object or a string containing a class name. This
 569is the function implementing the C<UNIVERSAL::isa> functionality.
 570
 571	bool sv_derived_from(SV* sv, const char* name);
 572
 573To check if you've got an object derived from a specific class you have 
 574to write:
 575
 576	if (sv_isobject(sv) && sv_derived_from(sv, class)) { ... }
 577
 578=head2 Creating New Variables
 579
 580To create a new Perl variable with an undef value which can be accessed from
 581your Perl script, use the following routines, depending on the variable type.
 582
 583    SV*  get_sv("package::varname", TRUE);
 584    AV*  get_av("package::varname", TRUE);
 585    HV*  get_hv("package::varname", TRUE);
 586
 587Notice the use of TRUE as the second parameter.  The new variable can now
 588be set, using the routines appropriate to the data type.
 589
 590There are additional macros whose values may be bitwise OR'ed with the
 591C<TRUE> argument to enable certain extra features.  Those bits are:
 592
 593    GV_ADDMULTI	Marks the variable as multiply defined, thus preventing the
 594		"Name <varname> used only once: possible typo" warning.
 595    GV_ADDWARN	Issues the warning "Had to create <varname> unexpectedly" if
 596		the variable did not exist before the function was called.
 597
 598If you do not specify a package name, the variable is created in the current
 599package.
 600
 601=head2 Reference Counts and Mortality
 602
 603Perl uses an reference count-driven garbage collection mechanism. SVs,
 604AVs, or HVs (xV for short in the following) start their life with a
 605reference count of 1.  If the reference count of an xV ever drops to 0,
 606then it will be destroyed and its memory made available for reuse.
 607
 608This normally doesn't happen at the Perl level unless a variable is
 609undef'ed or the last variable holding a reference to it is changed or
 610overwritten.  At the internal level, however, reference counts can be
 611manipulated with the following macros:
 612
 613    int SvREFCNT(SV* sv);
 614    SV* SvREFCNT_inc(SV* sv);
 615    void SvREFCNT_dec(SV* sv);
 616
 617However, there is one other function which manipulates the reference
 618count of its argument.  The C<newRV_inc> function, you will recall,
 619creates a reference to the specified argument.  As a side effect,
 620it increments the argument's reference count.  If this is not what
 621you want, use C<newRV_noinc> instead.
 622
 623For example, imagine you want to return a reference from an XSUB function.
 624Inside the XSUB routine, you create an SV which initially has a reference
 625count of one.  Then you call C<newRV_inc>, passing it the just-created SV.
 626This returns the reference as a new SV, but the reference count of the
 627SV you passed to C<newRV_inc> has been incremented to two.  Now you
 628return the reference from the XSUB routine and forget about the SV.
 629But Perl hasn't!  Whenever the returned reference is destroyed, the
 630reference count of the original SV is decreased to one and nothing happens.
 631The SV will hang around without any way to access it until Perl itself
 632terminates.  This is a memory leak.
 633
 634The correct procedure, then, is to use C<newRV_noinc> instead of
 635C<newRV_inc>.  Then, if and when the last reference is destroyed,
 636the reference count of the SV will go to zero and it will be destroyed,
 637stopping any memory leak.
 638
 639There are some convenience functions available that can help with the
 640destruction of xVs.  These functions introduce the concept of "mortality".
 641An xV that is mortal has had its reference count marked to be decremented,
 642but not actually decremented, until "a short time later".  Generally the
 643term "short time later" means a single Perl statement, such as a call to
 644an XSUB function.  The actual determinant for when mortal xVs have their
 645reference count decremented depends on two macros, SAVETMPS and FREETMPS.
 646See L<perlcall> and L<perlxs> for more details on these macros.
 647
 648"Mortalization" then is at its simplest a deferred C<SvREFCNT_dec>.
 649However, if you mortalize a variable twice, the reference count will
 650later be decremented twice.
 651
 652You should be careful about creating mortal variables.  Strange things
 653can happen if you make the same value mortal within multiple contexts,
 654or if you make a variable mortal multiple times.
 655
 656To create a mortal variable, use the functions:
 657
 658    SV*  sv_newmortal()
 659    SV*  sv_2mortal(SV*)
 660    SV*  sv_mortalcopy(SV*)
 661
 662The first call creates a mortal SV, the second converts an existing
 663SV to a mortal SV (and thus defers a call to C<SvREFCNT_dec>), and the
 664third creates a mortal copy of an existing SV.
 665
 666The mortal routines are not just for SVs -- AVs and HVs can be
 667made mortal by passing their address (type-casted to C<SV*>) to the
 668C<sv_2mortal> or C<sv_mortalcopy> routines.
 669
 670=head2 Stashes and Globs
 671
 672A "stash" is a hash that contains all of the different objects that
 673are contained within a package.  Each key of the stash is a symbol
 674name (shared by all the different types of objects that have the same
 675name), and each value in the hash table is a GV (Glob Value).  This GV
 676in turn contains references to the various objects of that name,
 677including (but not limited to) the following:
 678
 679    Scalar Value
 680    Array Value
 681    Hash Value
 682    I/O Handle
 683    Format
 684    Subroutine
 685
 686There is a single stash called "PL_defstash" that holds the items that exist
 687in the "main" package.  To get at the items in other packages, append the
 688string "::" to the package name.  The items in the "Foo" package are in
 689the stash "Foo::" in PL_defstash.  The items in the "Bar::Baz" package are
 690in the stash "Baz::" in "Bar::"'s stash.
 691
 692To get the stash pointer for a particular package, use the function:
 693
 694    HV*  gv_stashpv(const char* name, I32 create)
 695    HV*  gv_stashsv(SV*, I32 create)
 696
 697The first function takes a literal string, the second uses the string stored
 698in the SV.  Remember that a stash is just a hash table, so you get back an
 699C<HV*>.  The C<create> flag will create a new package if it is set.
 700
 701The name that C<gv_stash*v> wants is the name of the package whose symbol table
 702you want.  The default package is called C<main>.  If you have multiply nested
 703packages, pass their names to C<gv_stash*v>, separated by C<::> as in the Perl
 704language itself.
 705
 706Alternately, if you have an SV that is a blessed reference, you can find
 707out the stash pointer by using:
 708
 709    HV*  SvSTASH(SvRV(SV*));
 710
 711then use the following to get the package name itself:
 712
 713    char*  HvNAME(HV* stash);
 714
 715If you need to bless or re-bless an object you can use the following
 716function:
 717
 718    SV*  sv_bless(SV*, HV* stash)
 719
 720where the first argument, an C<SV*>, must be a reference, and the second
 721argument is a stash.  The returned C<SV*> can now be used in the same way
 722as any other SV.
 723
 724For more information on references and blessings, consult L<perlref>.
 725
 726=head2 Double-Typed SVs
 727
 728Scalar variables normally contain only one type of value, an integer,
 729double, pointer, or reference.  Perl will automatically convert the
 730actual scalar data from the stored type into the requested type.
 731
 732Some scalar variables contain more than one type of scalar data.  For
 733example, the variable C<$!> contains either the numeric value of C<errno>
 734or its string equivalent from either C<strerror> or C<sys_errlist[]>.
 735
 736To force multiple data values into an SV, you must do two things: use the
 737C<sv_set*v> routines to add the additional scalar type, then set a flag
 738so that Perl will believe it contains more than one type of data.  The
 739four macros to set the flags are:
 740
 741	SvIOK_on
 742	SvNOK_on
 743	SvPOK_on
 744	SvROK_on
 745
 746The particular macro you must use depends on which C<sv_set*v> routine
 747you called first.  This is because every C<sv_set*v> routine turns on
 748only the bit for the particular type of data being set, and turns off
 749all the rest.
 750
 751For example, to create a new Perl variable called "dberror" that contains
 752both the numeric and descriptive string error values, you could use the
 753following code:
 754
 755    extern int  dberror;
 756    extern char *dberror_list;
 757
 758    SV* sv = get_sv("dberror", TRUE);
 759    sv_setiv(sv, (IV) dberror);
 760    sv_setpv(sv, dberror_list[dberror]);
 761    SvIOK_on(sv);
 762
 763If the order of C<sv_setiv> and C<sv_setpv> had been reversed, then the
 764macro C<SvPOK_on> would need to be called instead of C<SvIOK_on>.
 765
 766=head2 Magic Variables
 767
 768[This section still under construction.  Ignore everything here.  Post no
 769bills.  Everything not permitted is forbidden.]
 770
 771Any SV may be magical, that is, it has special features that a normal
 772SV does not have.  These features are stored in the SV structure in a
 773linked list of C<struct magic>'s, typedef'ed to C<MAGIC>.
 774
 775    struct magic {
 776        MAGIC*      mg_moremagic;
 777        MGVTBL*     mg_virtual;
 778        U16         mg_private;
 779        char        mg_type;
 780        U8          mg_flags;
 781        SV*         mg_obj;
 782        char*       mg_ptr;
 783        I32         mg_len;
 784    };
 785
 786Note this is current as of patchlevel 0, and could change at any time.
 787
 788=head2 Assigning Magic
 789
 790Perl adds magic to an SV using the sv_magic function:
 791
 792    void sv_magic(SV* sv, SV* obj, int how, const char* name, I32 namlen);
 793
 794The C<sv> argument is a pointer to the SV that is to acquire a new magical
 795feature.
 796
 797If C<sv> is not already magical, Perl uses the C<SvUPGRADE> macro to
 798set the C<SVt_PVMG> flag for the C<sv>.  Perl then continues by adding
 799it to the beginning of the linked list of magical features.  Any prior
 800entry of the same type of magic is deleted.  Note that this can be
 801overridden, and multiple instances of the same type of magic can be
 802associated with an SV.
 803
 804The C<name> and C<namlen> arguments are used to associate a string with
 805the magic, typically the name of a variable. C<namlen> is stored in the
 806C<mg_len> field and if C<name> is non-null and C<namlen> >= 0 a malloc'd
 807copy of the name is stored in C<mg_ptr> field.
 808
 809The sv_magic function uses C<how> to determine which, if any, predefined
 810"Magic Virtual Table" should be assigned to the C<mg_virtual> field.
 811See the "Magic Virtual Table" section below.  The C<how> argument is also
 812stored in the C<mg_type> field.
 813
 814The C<obj> argument is stored in the C<mg_obj> field of the C<MAGIC>
 815structure.  If it is not the same as the C<sv> argument, the reference
 816count of the C<obj> object is incremented.  If it is the same, or if
 817the C<how> argument is "#", or if it is a NULL pointer, then C<obj> is
 818merely stored, without the reference count being incremented.
 819
 820There is also a function to add magic to an C<HV>:
 821
 822    void hv_magic(HV *hv, GV *gv, int how);
 823
 824This simply calls C<sv_magic> and coerces the C<gv> argument into an C<SV>.
 825
 826To remove the magic from an SV, call the function sv_unmagic:
 827
 828    void sv_unmagic(SV *sv, int type);
 829
 830The C<type> argument should be equal to the C<how> value when the C<SV>
 831was initially made magical.
 832
 833=head2 Magic Virtual Tables
 834
 835The C<mg_virtual> field in the C<MAGIC> structure is a pointer to a
 836C<MGVTBL>, which is a structure of function pointers and stands for
 837"Magic Virtual Table" to handle the various operations that might be
 838applied to that variable.
 839
 840The C<MGVTBL> has five pointers to the following routine types:
 841
 842    int  (*svt_get)(SV* sv, MAGIC* mg);
 843    int  (*svt_set)(SV* sv, MAGIC* mg);
 844    U32  (*svt_len)(SV* sv, MAGIC* mg);
 845    int  (*svt_clear)(SV* sv, MAGIC* mg);
 846    int  (*svt_free)(SV* sv, MAGIC* mg);
 847
 848This MGVTBL structure is set at compile-time in C<perl.h> and there are
 849currently 19 types (or 21 with overloading turned on).  These different
 850structures contain pointers to various routines that perform additional
 851actions depending on which function is being called.
 852
 853    Function pointer    Action taken
 854    ----------------    ------------
 855    svt_get             Do something after the value of the SV is retrieved.
 856    svt_set             Do something after the SV is assigned a value.
 857    svt_len             Report on the SV's length.
 858    svt_clear		Clear something the SV represents.
 859    svt_free            Free any extra storage associated with the SV.
 860
 861For instance, the MGVTBL structure called C<vtbl_sv> (which corresponds
 862to an C<mg_type> of '\0') contains:
 863
 864    { magic_get, magic_set, magic_len, 0, 0 }
 865
 866Thus, when an SV is determined to be magical and of type '\0', if a get
 867operation is being performed, the routine C<magic_get> is called.  All
 868the various routines for the various magical types begin with C<magic_>.
 869NOTE: the magic routines are not considered part of the Perl API, and may
 870not be exported by the Perl library.
 871
 872The current kinds of Magic Virtual Tables are:
 873
 874    mg_type  MGVTBL              Type of magic
 875    -------  ------              ----------------------------
 876    \0       vtbl_sv             Special scalar variable
 877    A        vtbl_amagic         %OVERLOAD hash
 878    a        vtbl_amagicelem     %OVERLOAD hash element
 879    c        (none)              Holds overload table (AMT) on stash
 880    B        vtbl_bm             Boyer-Moore (fast string search)
 881    D        vtbl_regdata        Regex match position data (@+ and @- vars)
 882    d        vtbl_regdatum       Regex match position data element
 883    E        vtbl_env            %ENV hash
 884    e        vtbl_envelem        %ENV hash element
 885    f        vtbl_fm             Formline ('compiled' format)
 886    g        vtbl_mglob          m//g target / study()ed string
 887    I        vtbl_isa            @ISA array
 888    i        vtbl_isaelem        @ISA array element
 889    k        vtbl_nkeys          scalar(keys()) lvalue
 890    L        (none)              Debugger %_<filename 
 891    l        vtbl_dbline         Debugger %_<filename element
 892    o        vtbl_collxfrm       Locale transformation
 893    P        vtbl_pack           Tied array or hash
 894    p        vtbl_packelem       Tied array or hash element
 895    q        vtbl_packelem       Tied scalar or handle
 896    S        vtbl_sig            %SIG hash
 897    s        vtbl_sigelem        %SIG hash element
 898    t        vtbl_taint          Taintedness
 899    U        vtbl_uvar           Available for use by extensions
 900    v        vtbl_vec            vec() lvalue
 901    x        vtbl_substr         substr() lvalue
 902    y        vtbl_defelem        Shadow "foreach" iterator variable /
 903                                  smart parameter vivification
 904    *        vtbl_glob           GV (typeglob)
 905    #        vtbl_arylen         Array length ($#ary)
 906    .        vtbl_pos            pos() lvalue
 907    ~        (none)              Available for use by extensions
 908
 909When an uppercase and lowercase letter both exist in the table, then the
 910uppercase letter is used to represent some kind of composite type (a list
 911or a hash), and the lowercase letter is used to represent an element of
 912that composite type.
 913
 914The '~' and 'U' magic types are defined specifically for use by
 915extensions and will not be used by perl itself.  Extensions can use
 916'~' magic to 'attach' private information to variables (typically
 917objects).  This is especially useful because there is no way for
 918normal perl code to corrupt this private information (unlike using
 919extra elements of a hash object).
 920
 921Similarly, 'U' magic can be used much like tie() to call a C function
 922any time a scalar's value is used or changed.  The C<MAGIC>'s
 923C<mg_ptr> field points to a C<ufuncs> structure:
 924
 925    struct ufuncs {
 926        I32 (*uf_val)(IV, SV*);
 927        I32 (*uf_set)(IV, SV*);
 928        IV uf_index;
 929    };
 930
 931When the SV is read from or written to, the C<uf_val> or C<uf_set>
 932function will be called with C<uf_index> as the first arg and a
 933pointer to the SV as the second.  A simple example of how to add 'U'
 934magic is shown below.  Note that the ufuncs structure is copied by
 935sv_magic, so you can safely allocate it on the stack.
 936
 937    void
 938    Umagic(sv)
 939        SV *sv;
 940    PREINIT:
 941        struct ufuncs uf;
 942    CODE:
 943        uf.uf_val   = &my_get_fn;
 944        uf.uf_set   = &my_set_fn;
 945        uf.uf_index = 0;
 946        sv_magic(sv, 0, 'U', (char*)&uf, sizeof(uf));
 947
 948Note that because multiple extensions may be using '~' or 'U' magic,
 949it is important for extensions to take extra care to avoid conflict.
 950Typically only using the magic on objects blessed into the same class
 951as the extension is sufficient.  For '~' magic, it may also be
 952appropriate to add an I32 'signature' at the top of the private data
 953area and check that.
 954
 955Also note that the C<sv_set*()> and C<sv_cat*()> functions described
 956earlier do B<not> invoke 'set' magic on their targets.  This must
 957be done by the user either by calling the C<SvSETMAGIC()> macro after
 958calling these functions, or by using one of the C<sv_set*_mg()> or
 959C<sv_cat*_mg()> functions.  Similarly, generic C code must call the
 960C<SvGETMAGIC()> macro to invoke any 'get' magic if they use an SV
 961obtained from external sources in functions that don't handle magic.
 962See L<perlapi> for a description of these functions.
 963For example, calls to the C<sv_cat*()> functions typically need to be
 964followed by C<SvSETMAGIC()>, but they don't need a prior C<SvGETMAGIC()>
 965since their implementation handles 'get' magic.
 966
 967=head2 Finding Magic
 968
 969    MAGIC* mg_find(SV*, int type); /* Finds the magic pointer of that type */
 970
 971This routine returns a pointer to the C<MAGIC> structure stored in the SV.
 972If the SV does not have that magical feature, C<NULL> is returned.  Also,
 973if the SV is not of type SVt_PVMG, Perl may core dump.
 974
 975    int mg_copy(SV* sv, SV* nsv, const char* key, STRLEN klen);
 976
 977This routine checks to see what types of magic C<sv> has.  If the mg_type
 978field is an uppercase letter, then the mg_obj is copied to C<nsv>, but
 979the mg_type field is changed to be the lowercase letter.
 980
 981=head2 Understanding the Magic of Tied Hashes and Arrays
 982
 983Tied hashes and arrays are magical beasts of the 'P' magic type.
 984
 985WARNING: As of the 5.004 release, proper usage of the array and hash
 986access functions requires understanding a few caveats.  Some
 987of these caveats are actually considered bugs in the API, to be fixed
 988in later releases, and are bracketed with [MAYCHANGE] below. If
 989you find yourself actually applying such information in this section, be
 990aware that the behavior may change in the future, umm, without warning.
 991
 992The perl tie function associates a variable with an object that implements
 993the various GET, SET etc methods.  To perform the equivalent of the perl
 994tie function from an XSUB, you must mimic this behaviour.  The code below
 995carries out the necessary steps - firstly it creates a new hash, and then
 996creates a second hash which it blesses into the class which will implement
 997the tie methods. Lastly it ties the two hashes together, and returns a
 998reference to the new tied hash.  Note that the code below does NOT call the
 999TIEHASH method in the MyTie class -
1000see L<Calling Perl Routines from within C Programs> for details on how
1001to do this.
1002
1003    SV*
1004    mytie()
1005    PREINIT:
1006        HV *hash;
1007        HV *stash;
1008        SV *tie;
1009    CODE:
1010        hash = newHV();
1011        tie = newRV_noinc((SV*)newHV());
1012        stash = gv_stashpv("MyTie", TRUE);
1013        sv_bless(tie, stash);
1014        hv_magic(hash, tie, 'P');
1015        RETVAL = newRV_noinc(hash);
1016    OUTPUT:
1017        RETVAL
1018
1019The C<av_store> function, when given a tied array argument, merely
1020copies the magic of the array onto the value to be "stored", using
1021C<mg_copy>.  It may also return NULL, indicating that the value did not
1022actually need to be stored in the array.  [MAYCHANGE] After a call to
1023C<av_store> on a tied array, the caller will usually need to call
1024C<mg_set(val)> to actually invoke the perl level "STORE" method on the
1025TIEARRAY object.  If C<av_store> did return NULL, a call to
1026C<SvREFCNT_dec(val)> will also be usually necessary to avoid a memory
1027leak. [/MAYCHANGE]
1028
1029The previous paragraph is applicable verbatim to tied hash access using the
1030C<hv_store> and C<hv_store_ent> functions as well.
1031
1032C<av_fetch> and the corresponding hash functions C<hv_fetch> and
1033C<hv_fetch_ent> actually return an undefined mortal value whose magic
1034has been initialized using C<mg_copy>.  Note the value so returned does not
1035need to be deallocated, as it is already mortal.  [MAYCHANGE] But you will
1036need to call C<mg_get()> on the returned value in order to actually invoke
1037the perl level "FETCH" method on the underlying TIE object.  Similarly,
1038you may also call C<mg_set()> on the return value after possibly assigning
1039a suitable value to it using C<sv_setsv>,  which will invoke the "STORE"
1040method on the TIE object. [/MAYCHANGE]
1041
1042[MAYCHANGE]
1043In other words, the array or hash fetch/store functions don't really
1044fetch and store actual values in the case of tied arrays and hashes.  They
1045merely call C<mg_copy> to attach magic to the values that were meant to be
1046"stored" or "fetched".  Later calls to C<mg_get> and C<mg_set> actually
1047do the job of invoking the TIE methods on the underlying objects.  Thus
1048the magic mechanism currently implements a kind of lazy access to arrays
1049and hashes.
1050
1051Currently (as of perl version 5.004), use of the hash and array access
1052functions requires the user to be aware of whether they are operating on
1053"normal" hashes and arrays, or on their tied variants.  The API may be
1054changed to provide more transparent access to both tied and normal data
1055types in future versions.
1056[/MAYCHANGE]
1057
1058You would do well to understand that the TIEARRAY and TIEHASH interfaces
1059are mere sugar to invoke some perl method calls while using the uniform hash
1060and array syntax.  The use of this sugar imposes some overhead (typically
1061about two to four extra opcodes per FETCH/STORE operation, in addition to
1062the creation of all the mortal variables required to invoke the methods).
1063This overhead will be comparatively small if the TIE methods are themselves
1064substantial, but if they are only a few statements long, the overhead
1065will not be insignificant.
1066
1067=head2 Localizing changes
1068
1069Perl has a very handy construction
1070
1071  {
1072    local $var = 2;
1073    ...
1074  }
1075
1076This construction is I<approximately> equivalent to
1077
1078  {
1079    my $oldvar = $var;
1080    $var = 2;
1081    ...
1082    $var = $oldvar;
1083  }
1084
1085The biggest difference is that the first construction would
1086reinstate the initial value of $var, irrespective of how control exits
1087the block: C<goto>, C<return>, C<die>/C<eval> etc. It is a little bit
1088more efficient as well.
1089
1090There is a way to achieve a similar task from C via Perl API: create a
1091I<pseudo-block>, and arrange for some changes to be automatically
1092undone at the end of it, either explicit, or via a non-local exit (via
1093die()). A I<block>-like construct is created by a pair of
1094C<ENTER>/C<LEAVE> macros (see L<perlcall/"Returning a Scalar">).
1095Such a construct may be created specially for some important localized
1096task, or an existing one (like boundaries of enclosing Perl
1097subroutine/block, or an existing pair for freeing TMPs) may be
1098used. (In the second case the overhead of additional localization must
1099be almost negligible.) Note that any XSUB is automatically enclosed in
1100an C<ENTER>/C<LEAVE> pair.
1101
1102Inside such a I<pseudo-block> the following service is available:
1103
1104=over 4
1105
1106=item C<SAVEINT(int i)>
1107
1108=item C<SAVEIV(IV i)>
1109
1110=item C<SAVEI32(I32 i)>
1111
1112=item C<SAVELONG(long i)>
1113
1114These macros arrange things to restore the value of integer variable
1115C<i> at the end of enclosing I<pseudo-block>.
1116
1117=item C<SAVESPTR(s)>
1118
1119=item C<SAVEPPTR(p)>
1120
1121These macros arrange things to restore the value of pointers C<s> and
1122C<p>. C<s> must be a pointer of a type which survives conversion to
1123C<SV*> and back, C<p> should be able to survive conversion to C<char*>
1124and back.
1125
1126=item C<SAVEFREESV(SV *sv)>
1127
1128The refcount of C<sv> would be decremented at the end of
1129I<pseudo-block>.  This is similar to C<sv_2mortal> in that it is also a
1130mechanism for doing a delayed C<SvREFCNT_dec>.  However, while C<sv_2mortal>
1131extends the lifetime of C<sv> until the beginning of the next statement,
1132C<SAVEFREESV> extends it until the end of the enclosing scope.  These
1133lifetimes can be wildly different.
1134
1135Also compare C<SAVEMORTALIZESV>.
1136
1137=item C<SAVEMORTALIZESV(SV *sv)>
1138
1139Just like C<SAVEFREESV>, but mortalizes C<sv> at the end of the current
1140scope instead of decrementing its reference count.  This usually has the
1141effect of keeping C<sv> alive until the statement that called the currently
1142live scope has finished executing.
1143
1144=item C<SAVEFREEOP(OP *op)>
1145
1146The C<OP *> is op_free()ed at the end of I<pseudo-block>.
1147
1148=item C<SAVEFREEPV(p)>
1149
1150The chunk of memory which is pointed to by C<p> is Safefree()ed at the
1151end of I<pseudo-block>.
1152
1153=item C<SAVECLEARSV(SV *sv)>
1154
1155Clears a slot in the current scratchpad which corresponds to C<sv> at
1156the end of I<pseudo-block>.
1157
1158=item C<SAVEDELETE(HV *hv, char *key, I32 length)>
1159
1160The key C<key> of C<hv> is deleted at the end of I<pseudo-block>. The
1161string pointed to by C<key> is Safefree()ed.  If one has a I<key> in
1162short-lived storage, the corresponding string may be reallocated like
1163this:
1164
1165  SAVEDELETE(PL_defstash, savepv(tmpbuf), strlen(tmpbuf));
1166
1167=item C<SAVEDESTRUCTOR(DESTRUCTORFUNC_NOCONTEXT_t f, void *p)>
1168
1169At the end of I<pseudo-block> the function C<f> is called with the
1170only argument C<p>.
1171
1172=item C<SAVEDESTRUCTOR_X(DESTRUCTORFUNC_t f, void *p)>
1173
1174At the end of I<pseudo-block> the function C<f> is called with the
1175implicit context argument (if any), and C<p>.
1176
1177=item C<SAVESTACK_POS()>
1178
1179The current offset on the Perl internal stack (cf. C<SP>) is restored
1180at the end of I<pseudo-block>.
1181
1182=back
1183
1184The following API list contains functions, thus one needs to
1185provide pointers to the modifiable data explicitly (either C pointers,
1186or Perlish C<GV *>s).  Where the above macros take C<int>, a similar 
1187function takes C<int *>.
1188
1189=over 4
1190
1191=item C<SV* save_scalar(GV *gv)>
1192
1193Equivalent to Perl code C<local $gv>.
1194
1195=item C<AV* save_ary(GV *gv)>
1196
1197=item C<HV* save_hash(GV *gv)>
1198
1199Similar to C<save_scalar>, but localize C<@gv> and C<%gv>.
1200
1201=item C<void save_item(SV *item)>
1202
1203Duplicates the current value of C<SV>, on the exit from the current
1204C<ENTER>/C<LEAVE> I<pseudo-block> will restore the value of C<SV>
1205using the stored value.
1206
1207=item C<void save_list(SV **sarg, I32 maxsarg)>
1208
1209A variant of C<save_item> which takes multiple arguments via an array
1210C<sarg> of C<SV*> of length C<maxsarg>.
1211
1212=item C<SV* save_svref(SV **sptr)>
1213
1214Similar to C<save_scalar>, but will reinstate a C<SV *>.
1215
1216=item C<void save_aptr(AV **aptr)>
1217
1218=item C<void save_hptr(HV **hptr)>
1219
1220Similar to C<save_svref>, but localize C<AV *> and C<HV *>.
1221
1222=back
1223
1224The C<Alias> module implements localization of the basic types within the
1225I<caller's scope>.  People who are interested in how to localize things in
1226the containing scope should take a look there too.
1227
1228=head1 Subroutines
1229
1230=head2 XSUBs and the Argument Stack
1231
1232The XSUB mechanism is a simple way for Perl programs to access C subroutines.
1233An XSUB routine will have a stack that contains the arguments from the Perl
1234program, and a way to map from the Perl data structures to a C equivalent.
1235
1236The stack arguments are accessible through the C<ST(n)> macro, which returns
1237the C<n>'th stack argument.  Argument 0 is the first argument passed in the
1238Perl subroutine call.  These arguments are C<SV*>, and can be used anywhere
1239an C<SV*> is used.
1240
1241Most of the time, output from the C routine can be handled through use of
1242the RETVAL and OUTPUT directives.  However, there are some cases where the
1243argument stack is not already long enough to handle all the return values.
1244An example is the POSIX tzname() call, which takes no arguments, but returns
1245two, the local time zone's standard and summer time abbreviations.
1246
1247To handle this 

Large files files are truncated, but you can click here to view the full file