source: trunk/essentials/dev-lang/perl/pod/perlguts.pod@ 3184

Last change on this file since 3184 was 3181, checked in by bird, 19 years ago

perl 5.8.8

File size: 98.0 KB
Line 
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
8to provide 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.) They will usually be exactly 32 and 16 bits long, but on Crays
33they will both be 64 bits.
34
35=head2 Working with SVs
36
37An SV can be created and loaded with one command. There are five types of
38values that can be loaded: an integer value (IV), an unsigned integer
39value (UV), a double (NV), a string (PV), and another scalar (SV).
40
41The seven routines are:
42
43 SV* newSViv(IV);
44 SV* newSVuv(UV);
45 SV* newSVnv(double);
46 SV* newSVpv(const char*, STRLEN);
47 SV* newSVpvn(const char*, STRLEN);
48 SV* newSVpvf(const char*, ...);
49 SV* newSVsv(SV*);
50
51C<STRLEN> is an integer type (Size_t, usually defined as size_t in
52F<config.h>) guaranteed to be large enough to represent the size of
53any string that perl can handle.
54
55In the unlikely case of a SV requiring more complex initialisation, you
56can create an empty SV with newSV(len). If C<len> is 0 an empty SV of
57type NULL is returned, else an SV of type PV is returned with len + 1 (for
58the NUL) bytes of storage allocated, accessible via SvPVX. In both cases
59the SV has value undef.
60
61 SV *sv = newSV(0); /* no storage allocated */
62 SV *sv = newSV(10); /* 10 (+1) bytes of uninitialised storage allocated */
63
64To change the value of an I<already-existing> SV, there are eight routines:
65
66 void sv_setiv(SV*, IV);
67 void sv_setuv(SV*, UV);
68 void sv_setnv(SV*, double);
69 void sv_setpv(SV*, const char*);
70 void sv_setpvn(SV*, const char*, STRLEN)
71 void sv_setpvf(SV*, const char*, ...);
72 void sv_vsetpvfn(SV*, const char*, STRLEN, va_list *, SV **, I32, bool *);
73 void sv_setsv(SV*, SV*);
74
75Notice that you can choose to specify the length of the string to be
76assigned by using C<sv_setpvn>, C<newSVpvn>, or C<newSVpv>, or you may
77allow Perl to calculate the length by using C<sv_setpv> or by specifying
780 as the second argument to C<newSVpv>. Be warned, though, that Perl will
79determine the string's length by using C<strlen>, which depends on the
80string terminating with a NUL character.
81
82The arguments of C<sv_setpvf> are processed like C<sprintf>, and the
83formatted output becomes the value.
84
85C<sv_vsetpvfn> is an analogue of C<vsprintf>, but it allows you to specify
86either a pointer to a variable argument list or the address and length of
87an array of SVs. The last argument points to a boolean; on return, if that
88boolean is true, then locale-specific information has been used to format
89the string, and the string's contents are therefore untrustworthy (see
90L<perlsec>). This pointer may be NULL if that information is not
91important. Note that this function requires you to specify the length of
92the format.
93
94The C<sv_set*()> functions are not generic enough to operate on values
95that have "magic". See L<Magic Virtual Tables> later in this document.
96
97All SVs that contain strings should be terminated with a NUL character.
98If it is not NUL-terminated there is a risk of
99core dumps and corruptions from code which passes the string to C
100functions or system calls which expect a NUL-terminated string.
101Perl's own functions typically add a trailing NUL for this reason.
102Nevertheless, you should be very careful when you pass a string stored
103in an SV to a C function or system call.
104
105To access the actual value that an SV points to, you can use the macros:
106
107 SvIV(SV*)
108 SvUV(SV*)
109 SvNV(SV*)
110 SvPV(SV*, STRLEN len)
111 SvPV_nolen(SV*)
112
113which will automatically coerce the actual scalar type into an IV, UV, double,
114or string.
115
116In the C<SvPV> macro, the length of the string returned is placed into the
117variable C<len> (this is a macro, so you do I<not> use C<&len>). If you do
118not care what the length of the data is, use the C<SvPV_nolen> macro.
119Historically the C<SvPV> macro with the global variable C<PL_na> has been
120used in this case. But that can be quite inefficient because C<PL_na> must
121be accessed in thread-local storage in threaded Perl. In any case, remember
122that Perl allows arbitrary strings of data that may both contain NULs and
123might not be terminated by a NUL.
124
125Also remember that C doesn't allow you to safely say C<foo(SvPV(s, len),
126len);>. It might work with your compiler, but it won't work for everyone.
127Break this sort of statement up into separate assignments:
128
129 SV *s;
130 STRLEN len;
131 char * ptr;
132 ptr = SvPV(s, len);
133 foo(ptr, len);
134
135If you want to know if the scalar value is TRUE, you can use:
136
137 SvTRUE(SV*)
138
139Although Perl will automatically grow strings for you, if you need to force
140Perl to allocate more memory for your SV, you can use the macro
141
142 SvGROW(SV*, STRLEN newlen)
143
144which will determine if more memory needs to be allocated. If so, it will
145call the function C<sv_grow>. Note that C<SvGROW> can only increase, not
146decrease, the allocated memory of an SV and that it does not automatically
147add a byte for the a trailing NUL (perl's own string functions typically do
148C<SvGROW(sv, len + 1)>).
149
150If you have an SV and want to know what kind of data Perl thinks is stored
151in it, you can use the following macros to check the type of SV you have.
152
153 SvIOK(SV*)
154 SvNOK(SV*)
155 SvPOK(SV*)
156
157You can get and set the current length of the string stored in an SV with
158the following macros:
159
160 SvCUR(SV*)
161 SvCUR_set(SV*, I32 val)
162
163You can also get a pointer to the end of the string stored in the SV
164with the macro:
165
166 SvEND(SV*)
167
168But note that these last three macros are valid only if C<SvPOK()> is true.
169
170If you want to append something to the end of string stored in an C<SV*>,
171you can use the following functions:
172
173 void sv_catpv(SV*, const char*);
174 void sv_catpvn(SV*, const char*, STRLEN);
175 void sv_catpvf(SV*, const char*, ...);
176 void sv_vcatpvfn(SV*, const char*, STRLEN, va_list *, SV **, I32, bool);
177 void sv_catsv(SV*, SV*);
178
179The first function calculates the length of the string to be appended by
180using C<strlen>. In the second, you specify the length of the string
181yourself. The third function processes its arguments like C<sprintf> and
182appends the formatted output. The fourth function works like C<vsprintf>.
183You can specify the address and length of an array of SVs instead of the
184va_list argument. The fifth function extends the string stored in the first
185SV with the string stored in the second SV. It also forces the second SV
186to be interpreted as a string.
187
188The C<sv_cat*()> functions are not generic enough to operate on values that
189have "magic". See L<Magic Virtual Tables> later in this document.
190
191If you know the name of a scalar variable, you can get a pointer to its SV
192by using the following:
193
194 SV* get_sv("package::varname", FALSE);
195
196This returns NULL if the variable does not exist.
197
198If you want to know if this variable (or any other SV) is actually C<defined>,
199you can call:
200
201 SvOK(SV*)
202
203The scalar C<undef> value is stored in an SV instance called C<PL_sv_undef>.
204
205Its address can be used whenever an C<SV*> is needed. Make sure that
206you don't try to compare a random sv with C<&PL_sv_undef>. For example
207when interfacing Perl code, it'll work correctly for:
208
209 foo(undef);
210
211But won't work when called as:
212
213 $x = undef;
214 foo($x);
215
216So to repeat always use SvOK() to check whether an sv is defined.
217
218Also you have to be careful when using C<&PL_sv_undef> as a value in
219AVs or HVs (see L<AVs, HVs and undefined values>).
220
221There are also the two values C<PL_sv_yes> and C<PL_sv_no>, which contain
222boolean TRUE and FALSE values, respectively. Like C<PL_sv_undef>, their
223addresses can be used whenever an C<SV*> is needed.
224
225Do not be fooled into thinking that C<(SV *) 0> is the same as C<&PL_sv_undef>.
226Take this code:
227
228 SV* sv = (SV*) 0;
229 if (I-am-to-return-a-real-value) {
230 sv = sv_2mortal(newSViv(42));
231 }
232 sv_setsv(ST(0), sv);
233
234This code tries to return a new SV (which contains the value 42) if it should
235return a real value, or undef otherwise. Instead it has returned a NULL
236pointer which, somewhere down the line, will cause a segmentation violation,
237bus error, or just weird results. Change the zero to C<&PL_sv_undef> in the
238first line and all will be well.
239
240To free an SV that you've created, call C<SvREFCNT_dec(SV*)>. Normally this
241call is not necessary (see L<Reference Counts and Mortality>).
242
243=head2 Offsets
244
245Perl provides the function C<sv_chop> to efficiently remove characters
246from the beginning of a string; you give it an SV and a pointer to
247somewhere inside the PV, and it discards everything before the
248pointer. The efficiency comes by means of a little hack: instead of
249actually removing the characters, C<sv_chop> sets the flag C<OOK>
250(offset OK) to signal to other functions that the offset hack is in
251effect, and it puts the number of bytes chopped off into the IV field
252of the SV. It then moves the PV pointer (called C<SvPVX>) forward that
253many bytes, and adjusts C<SvCUR> and C<SvLEN>.
254
255Hence, at this point, the start of the buffer that we allocated lives
256at C<SvPVX(sv) - SvIV(sv)> in memory and the PV pointer is pointing
257into the middle of this allocated storage.
258
259This is best demonstrated by example:
260
261 % ./perl -Ilib -MDevel::Peek -le '$a="12345"; $a=~s/.//; Dump($a)'
262 SV = PVIV(0x8128450) at 0x81340f0
263 REFCNT = 1
264 FLAGS = (POK,OOK,pPOK)
265 IV = 1 (OFFSET)
266 PV = 0x8135781 ( "1" . ) "2345"\0
267 CUR = 4
268 LEN = 5
269
270Here the number of bytes chopped off (1) is put into IV, and
271C<Devel::Peek::Dump> helpfully reminds us that this is an offset. The
272portion of the string between the "real" and the "fake" beginnings is
273shown in parentheses, and the values of C<SvCUR> and C<SvLEN> reflect
274the fake beginning, not the real one.
275
276Something similar to the offset hack is performed on AVs to enable
277efficient shifting and splicing off the beginning of the array; while
278C<AvARRAY> points to the first element in the array that is visible from
279Perl, C<AvALLOC> points to the real start of the C array. These are
280usually the same, but a C<shift> operation can be carried out by
281increasing C<AvARRAY> by one and decreasing C<AvFILL> and C<AvLEN>.
282Again, the location of the real start of the C array only comes into
283play when freeing the array. See C<av_shift> in F<av.c>.
284
285=head2 What's Really Stored in an SV?
286
287Recall that the usual method of determining the type of scalar you have is
288to use C<Sv*OK> macros. Because a scalar can be both a number and a string,
289usually these macros will always return TRUE and calling the C<Sv*V>
290macros will do the appropriate conversion of string to integer/double or
291integer/double to string.
292
293If you I<really> need to know if you have an integer, double, or string
294pointer in an SV, you can use the following three macros instead:
295
296 SvIOKp(SV*)
297 SvNOKp(SV*)
298 SvPOKp(SV*)
299
300These will tell you if you truly have an integer, double, or string pointer
301stored in your SV. The "p" stands for private.
302
303The are various ways in which the private and public flags may differ.
304For example, a tied SV may have a valid underlying value in the IV slot
305(so SvIOKp is true), but the data should be accessed via the FETCH
306routine rather than directly, so SvIOK is false. Another is when
307numeric conversion has occurred and precision has been lost: only the
308private flag is set on 'lossy' values. So when an NV is converted to an
309IV with loss, SvIOKp, SvNOKp and SvNOK will be set, while SvIOK wont be.
310
311In general, though, it's best to use the C<Sv*V> macros.
312
313=head2 Working with AVs
314
315There are two ways to create and load an AV. The first method creates an
316empty AV:
317
318 AV* newAV();
319
320The second method both creates the AV and initially populates it with SVs:
321
322 AV* av_make(I32 num, SV **ptr);
323
324The second argument points to an array containing C<num> C<SV*>'s. Once the
325AV has been created, the SVs can be destroyed, if so desired.
326
327Once the AV has been created, the following operations are possible on AVs:
328
329 void av_push(AV*, SV*);
330 SV* av_pop(AV*);
331 SV* av_shift(AV*);
332 void av_unshift(AV*, I32 num);
333
334These should be familiar operations, with the exception of C<av_unshift>.
335This routine adds C<num> elements at the front of the array with the C<undef>
336value. You must then use C<av_store> (described below) to assign values
337to these new elements.
338
339Here are some other functions:
340
341 I32 av_len(AV*);
342 SV** av_fetch(AV*, I32 key, I32 lval);
343 SV** av_store(AV*, I32 key, SV* val);
344
345The C<av_len> function returns the highest index value in array (just
346like $#array in Perl). If the array is empty, -1 is returned. The
347C<av_fetch> function returns the value at index C<key>, but if C<lval>
348is non-zero, then C<av_fetch> will store an undef value at that index.
349The C<av_store> function stores the value C<val> at index C<key>, and does
350not increment the reference count of C<val>. Thus the caller is responsible
351for taking care of that, and if C<av_store> returns NULL, the caller will
352have to decrement the reference count to avoid a memory leak. Note that
353C<av_fetch> and C<av_store> both return C<SV**>'s, not C<SV*>'s as their
354return value.
355
356 void av_clear(AV*);
357 void av_undef(AV*);
358 void av_extend(AV*, I32 key);
359
360The C<av_clear> function deletes all the elements in the AV* array, but
361does not actually delete the array itself. The C<av_undef> function will
362delete all the elements in the array plus the array itself. The
363C<av_extend> function extends the array so that it contains at least C<key+1>
364elements. If C<key+1> is less than the currently allocated length of the array,
365then nothing is done.
366
367If you know the name of an array variable, you can get a pointer to its AV
368by using the following:
369
370 AV* get_av("package::varname", FALSE);
371
372This returns NULL if the variable does not exist.
373
374See L<Understanding the Magic of Tied Hashes and Arrays> for more
375information on how to use the array access functions on tied arrays.
376
377=head2 Working with HVs
378
379To create an HV, you use the following routine:
380
381 HV* newHV();
382
383Once the HV has been created, the following operations are possible on HVs:
384
385 SV** hv_store(HV*, const char* key, U32 klen, SV* val, U32 hash);
386 SV** hv_fetch(HV*, const char* key, U32 klen, I32 lval);
387
388The C<klen> parameter is the length of the key being passed in (Note that
389you cannot pass 0 in as a value of C<klen> to tell Perl to measure the
390length of the key). The C<val> argument contains the SV pointer to the
391scalar being stored, and C<hash> is the precomputed hash value (zero if
392you want C<hv_store> to calculate it for you). The C<lval> parameter
393indicates whether this fetch is actually a part of a store operation, in
394which case a new undefined value will be added to the HV with the supplied
395key and C<hv_fetch> will return as if the value had already existed.
396
397Remember that C<hv_store> and C<hv_fetch> return C<SV**>'s and not just
398C<SV*>. To access the scalar value, you must first dereference the return
399value. However, you should check to make sure that the return value is
400not NULL before dereferencing it.
401
402These two functions check if a hash table entry exists, and deletes it.
403
404 bool hv_exists(HV*, const char* key, U32 klen);
405 SV* hv_delete(HV*, const char* key, U32 klen, I32 flags);
406
407If C<flags> does not include the C<G_DISCARD> flag then C<hv_delete> will
408create and return a mortal copy of the deleted value.
409
410And more miscellaneous functions:
411
412 void hv_clear(HV*);
413 void hv_undef(HV*);
414
415Like their AV counterparts, C<hv_clear> deletes all the entries in the hash
416table but does not actually delete the hash table. The C<hv_undef> deletes
417both the entries and the hash table itself.
418
419Perl keeps the actual data in linked list of structures with a typedef of HE.
420These contain the actual key and value pointers (plus extra administrative
421overhead). The key is a string pointer; the value is an C<SV*>. However,
422once you have an C<HE*>, to get the actual key and value, use the routines
423specified below.
424
425 I32 hv_iterinit(HV*);
426 /* Prepares starting point to traverse hash table */
427 HE* hv_iternext(HV*);
428 /* Get the next entry, and return a pointer to a
429 structure that has both the key and value */
430 char* hv_iterkey(HE* entry, I32* retlen);
431 /* Get the key from an HE structure and also return
432 the length of the key string */
433 SV* hv_iterval(HV*, HE* entry);
434 /* Return an SV pointer to the value of the HE
435 structure */
436 SV* hv_iternextsv(HV*, char** key, I32* retlen);
437 /* This convenience routine combines hv_iternext,
438 hv_iterkey, and hv_iterval. The key and retlen
439 arguments are return values for the key and its
440 length. The value is returned in the SV* argument */
441
442If you know the name of a hash variable, you can get a pointer to its HV
443by using the following:
444
445 HV* get_hv("package::varname", FALSE);
446
447This returns NULL if the variable does not exist.
448
449The hash algorithm is defined in the C<PERL_HASH(hash, key, klen)> macro:
450
451 hash = 0;
452 while (klen--)
453 hash = (hash * 33) + *key++;
454 hash = hash + (hash >> 5); /* after 5.6 */
455
456The last step was added in version 5.6 to improve distribution of
457lower bits in the resulting hash value.
458
459See L<Understanding the Magic of Tied Hashes and Arrays> for more
460information on how to use the hash access functions on tied hashes.
461
462=head2 Hash API Extensions
463
464Beginning with version 5.004, the following functions are also supported:
465
466 HE* hv_fetch_ent (HV* tb, SV* key, I32 lval, U32 hash);
467 HE* hv_store_ent (HV* tb, SV* key, SV* val, U32 hash);
468
469 bool hv_exists_ent (HV* tb, SV* key, U32 hash);
470 SV* hv_delete_ent (HV* tb, SV* key, I32 flags, U32 hash);
471
472 SV* hv_iterkeysv (HE* entry);
473
474Note that these functions take C<SV*> keys, which simplifies writing
475of extension code that deals with hash structures. These functions
476also allow passing of C<SV*> keys to C<tie> functions without forcing
477you to stringify the keys (unlike the previous set of functions).
478
479They also return and accept whole hash entries (C<HE*>), making their
480use more efficient (since the hash number for a particular string
481doesn't have to be recomputed every time). See L<perlapi> for detailed
482descriptions.
483
484The following macros must always be used to access the contents of hash
485entries. Note that the arguments to these macros must be simple
486variables, since they may get evaluated more than once. See
487L<perlapi> for detailed descriptions of these macros.
488
489 HePV(HE* he, STRLEN len)
490 HeVAL(HE* he)
491 HeHASH(HE* he)
492 HeSVKEY(HE* he)
493 HeSVKEY_force(HE* he)
494 HeSVKEY_set(HE* he, SV* sv)
495
496These two lower level macros are defined, but must only be used when
497dealing with keys that are not C<SV*>s:
498
499 HeKEY(HE* he)
500 HeKLEN(HE* he)
501
502Note that both C<hv_store> and C<hv_store_ent> do not increment the
503reference count of the stored C<val>, which is the caller's responsibility.
504If these functions return a NULL value, the caller will usually have to
505decrement the reference count of C<val> to avoid a memory leak.
506
507=head2 AVs, HVs and undefined values
508
509Sometimes you have to store undefined values in AVs or HVs. Although
510this may be a rare case, it can be tricky. That's because you're
511used to using C<&PL_sv_undef> if you need an undefined SV.
512
513For example, intuition tells you that this XS code:
514
515 AV *av = newAV();
516 av_store( av, 0, &PL_sv_undef );
517
518is equivalent to this Perl code:
519
520 my @av;
521 $av[0] = undef;
522
523Unfortunately, this isn't true. AVs use C<&PL_sv_undef> as a marker
524for indicating that an array element has not yet been initialized.
525Thus, C<exists $av[0]> would be true for the above Perl code, but
526false for the array generated by the XS code.
527
528Other problems can occur when storing C<&PL_sv_undef> in HVs:
529
530 hv_store( hv, "key", 3, &PL_sv_undef, 0 );
531
532This will indeed make the value C<undef>, but if you try to modify
533the value of C<key>, you'll get the following error:
534
535 Modification of non-creatable hash value attempted
536
537In perl 5.8.0, C<&PL_sv_undef> was also used to mark placeholders
538in restricted hashes. This caused such hash entries not to appear
539when iterating over the hash or when checking for the keys
540with the C<hv_exists> function.
541
542You can run into similar problems when you store C<&PL_sv_true> or
543C<&PL_sv_false> into AVs or HVs. Trying to modify such elements
544will give you the following error:
545
546 Modification of a read-only value attempted
547
548To make a long story short, you can use the special variables
549C<&PL_sv_undef>, C<&PL_sv_true> and C<&PL_sv_false> with AVs and
550HVs, but you have to make sure you know what you're doing.
551
552Generally, if you want to store an undefined value in an AV
553or HV, you should not use C<&PL_sv_undef>, but rather create a
554new undefined value using the C<newSV> function, for example:
555
556 av_store( av, 42, newSV(0) );
557 hv_store( hv, "foo", 3, newSV(0), 0 );
558
559=head2 References
560
561References are a special type of scalar that point to other data types
562(including references).
563
564To create a reference, use either of the following functions:
565
566 SV* newRV_inc((SV*) thing);
567 SV* newRV_noinc((SV*) thing);
568
569The C<thing> argument can be any of an C<SV*>, C<AV*>, or C<HV*>. The
570functions are identical except that C<newRV_inc> increments the reference
571count of the C<thing>, while C<newRV_noinc> does not. For historical
572reasons, C<newRV> is a synonym for C<newRV_inc>.
573
574Once you have a reference, you can use the following macro to dereference
575the reference:
576
577 SvRV(SV*)
578
579then call the appropriate routines, casting the returned C<SV*> to either an
580C<AV*> or C<HV*>, if required.
581
582To determine if an SV is a reference, you can use the following macro:
583
584 SvROK(SV*)
585
586To discover what type of value the reference refers to, use the following
587macro and then check the return value.
588
589 SvTYPE(SvRV(SV*))
590
591The most useful types that will be returned are:
592
593 SVt_IV Scalar
594 SVt_NV Scalar
595 SVt_PV Scalar
596 SVt_RV Scalar
597 SVt_PVAV Array
598 SVt_PVHV Hash
599 SVt_PVCV Code
600 SVt_PVGV Glob (possible a file handle)
601 SVt_PVMG Blessed or Magical Scalar
602
603 See the sv.h header file for more details.
604
605=head2 Blessed References and Class Objects
606
607References are also used to support object-oriented programming. In perl's
608OO lexicon, an object is simply a reference that has been blessed into a
609package (or class). Once blessed, the programmer may now use the reference
610to access the various methods in the class.
611
612A reference can be blessed into a package with the following function:
613
614 SV* sv_bless(SV* sv, HV* stash);
615
616The C<sv> argument must be a reference value. The C<stash> argument
617specifies which class the reference will belong to. See
618L<Stashes and Globs> for information on converting class names into stashes.
619
620/* Still under construction */
621
622Upgrades rv to reference if not already one. Creates new SV for rv to
623point to. If C<classname> is non-null, the SV is blessed into the specified
624class. SV is returned.
625
626 SV* newSVrv(SV* rv, const char* classname);
627
628Copies integer, unsigned integer or double into an SV whose reference is C<rv>. SV is blessed
629if C<classname> is non-null.
630
631 SV* sv_setref_iv(SV* rv, const char* classname, IV iv);
632 SV* sv_setref_uv(SV* rv, const char* classname, UV uv);
633 SV* sv_setref_nv(SV* rv, const char* classname, NV iv);
634
635Copies the pointer value (I<the address, not the string!>) into an SV whose
636reference is rv. SV is blessed if C<classname> is non-null.
637
638 SV* sv_setref_pv(SV* rv, const char* classname, PV iv);
639
640Copies string into an SV whose reference is C<rv>. Set length to 0 to let
641Perl calculate the string length. SV is blessed if C<classname> is non-null.
642
643 SV* sv_setref_pvn(SV* rv, const char* classname, PV iv, STRLEN length);
644
645Tests whether the SV is blessed into the specified class. It does not
646check inheritance relationships.
647
648 int sv_isa(SV* sv, const char* name);
649
650Tests whether the SV is a reference to a blessed object.
651
652 int sv_isobject(SV* sv);
653
654Tests whether the SV is derived from the specified class. SV can be either
655a reference to a blessed object or a string containing a class name. This
656is the function implementing the C<UNIVERSAL::isa> functionality.
657
658 bool sv_derived_from(SV* sv, const char* name);
659
660To check if you've got an object derived from a specific class you have
661to write:
662
663 if (sv_isobject(sv) && sv_derived_from(sv, class)) { ... }
664
665=head2 Creating New Variables
666
667To create a new Perl variable with an undef value which can be accessed from
668your Perl script, use the following routines, depending on the variable type.
669
670 SV* get_sv("package::varname", TRUE);
671 AV* get_av("package::varname", TRUE);
672 HV* get_hv("package::varname", TRUE);
673
674Notice the use of TRUE as the second parameter. The new variable can now
675be set, using the routines appropriate to the data type.
676
677There are additional macros whose values may be bitwise OR'ed with the
678C<TRUE> argument to enable certain extra features. Those bits are:
679
680=over
681
682=item GV_ADDMULTI
683
684Marks the variable as multiply defined, thus preventing the:
685
686 Name <varname> used only once: possible typo
687
688warning.
689
690=item GV_ADDWARN
691
692Issues the warning:
693
694 Had to create <varname> unexpectedly
695
696if the variable did not exist before the function was called.
697
698=back
699
700If you do not specify a package name, the variable is created in the current
701package.
702
703=head2 Reference Counts and Mortality
704
705Perl uses a reference count-driven garbage collection mechanism. SVs,
706AVs, or HVs (xV for short in the following) start their life with a
707reference count of 1. If the reference count of an xV ever drops to 0,
708then it will be destroyed and its memory made available for reuse.
709
710This normally doesn't happen at the Perl level unless a variable is
711undef'ed or the last variable holding a reference to it is changed or
712overwritten. At the internal level, however, reference counts can be
713manipulated with the following macros:
714
715 int SvREFCNT(SV* sv);
716 SV* SvREFCNT_inc(SV* sv);
717 void SvREFCNT_dec(SV* sv);
718
719However, there is one other function which manipulates the reference
720count of its argument. The C<newRV_inc> function, you will recall,
721creates a reference to the specified argument. As a side effect,
722it increments the argument's reference count. If this is not what
723you want, use C<newRV_noinc> instead.
724
725For example, imagine you want to return a reference from an XSUB function.
726Inside the XSUB routine, you create an SV which initially has a reference
727count of one. Then you call C<newRV_inc>, passing it the just-created SV.
728This returns the reference as a new SV, but the reference count of the
729SV you passed to C<newRV_inc> has been incremented to two. Now you
730return the reference from the XSUB routine and forget about the SV.
731But Perl hasn't! Whenever the returned reference is destroyed, the
732reference count of the original SV is decreased to one and nothing happens.
733The SV will hang around without any way to access it until Perl itself
734terminates. This is a memory leak.
735
736The correct procedure, then, is to use C<newRV_noinc> instead of
737C<newRV_inc>. Then, if and when the last reference is destroyed,
738the reference count of the SV will go to zero and it will be destroyed,
739stopping any memory leak.
740
741There are some convenience functions available that can help with the
742destruction of xVs. These functions introduce the concept of "mortality".
743An xV that is mortal has had its reference count marked to be decremented,
744but not actually decremented, until "a short time later". Generally the
745term "short time later" means a single Perl statement, such as a call to
746an XSUB function. The actual determinant for when mortal xVs have their
747reference count decremented depends on two macros, SAVETMPS and FREETMPS.
748See L<perlcall> and L<perlxs> for more details on these macros.
749
750"Mortalization" then is at its simplest a deferred C<SvREFCNT_dec>.
751However, if you mortalize a variable twice, the reference count will
752later be decremented twice.
753
754"Mortal" SVs are mainly used for SVs that are placed on perl's stack.
755For example an SV which is created just to pass a number to a called sub
756is made mortal to have it cleaned up automatically when it's popped off
757the stack. Similarly, results returned by XSUBs (which are pushed on the
758stack) are often made mortal.
759
760To create a mortal variable, use the functions:
761
762 SV* sv_newmortal()
763 SV* sv_2mortal(SV*)
764 SV* sv_mortalcopy(SV*)
765
766The first call creates a mortal SV (with no value), the second converts an existing
767SV to a mortal SV (and thus defers a call to C<SvREFCNT_dec>), and the
768third creates a mortal copy of an existing SV.
769Because C<sv_newmortal> gives the new SV no value,it must normally be given one
770via C<sv_setpv>, C<sv_setiv>, etc. :
771
772 SV *tmp = sv_newmortal();
773 sv_setiv(tmp, an_integer);
774
775As that is multiple C statements it is quite common so see this idiom instead:
776
777 SV *tmp = sv_2mortal(newSViv(an_integer));
778
779
780You should be careful about creating mortal variables. Strange things
781can happen if you make the same value mortal within multiple contexts,
782or if you make a variable mortal multiple times. Thinking of "Mortalization"
783as deferred C<SvREFCNT_dec> should help to minimize such problems.
784For example if you are passing an SV which you I<know> has high enough REFCNT
785to survive its use on the stack you need not do any mortalization.
786If you are not sure then doing an C<SvREFCNT_inc> and C<sv_2mortal>, or
787making a C<sv_mortalcopy> is safer.
788
789The mortal routines are not just for SVs -- AVs and HVs can be
790made mortal by passing their address (type-casted to C<SV*>) to the
791C<sv_2mortal> or C<sv_mortalcopy> routines.
792
793=head2 Stashes and Globs
794
795A B<stash> is a hash that contains all variables that are defined
796within a package. Each key of the stash is a symbol
797name (shared by all the different types of objects that have the same