Initial commit of OpenSPARC T2 architecture model.
[OpenSPARC-T2-SAM] / sam-t2 / devtools / v8plus / man / man1 / perlguts.1
CommitLineData
920dae64
AT
1.\" Automatically generated by Pod::Man v1.37, Pod::Parser v1.32
2.\"
3.\" Standard preamble:
4.\" ========================================================================
5.de Sh \" Subsection heading
6.br
7.if t .Sp
8.ne 5
9.PP
10\fB\\$1\fR
11.PP
12..
13.de Sp \" Vertical space (when we can't use .PP)
14.if t .sp .5v
15.if n .sp
16..
17.de Vb \" Begin verbatim text
18.ft CW
19.nf
20.ne \\$1
21..
22.de Ve \" End verbatim text
23.ft R
24.fi
25..
26.\" Set up some character translations and predefined strings. \*(-- will
27.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
28.\" double quote, and \*(R" will give a right double quote. | will give a
29.\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to
30.\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C'
31.\" expand to `' in nroff, nothing in troff, for use with C<>.
32.tr \(*W-|\(bv\*(Tr
33.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
34.ie n \{\
35. ds -- \(*W-
36. ds PI pi
37. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
38. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
39. ds L" ""
40. ds R" ""
41. ds C` ""
42. ds C' ""
43'br\}
44.el\{\
45. ds -- \|\(em\|
46. ds PI \(*p
47. ds L" ``
48. ds R" ''
49'br\}
50.\"
51.\" If the F register is turned on, we'll generate index entries on stderr for
52.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
53.\" entries marked with X<> in POD. Of course, you'll have to process the
54.\" output yourself in some meaningful fashion.
55.if \nF \{\
56. de IX
57. tm Index:\\$1\t\\n%\t"\\$2"
58..
59. nr % 0
60. rr F
61.\}
62.\"
63.\" For nroff, turn off justification. Always turn off hyphenation; it makes
64.\" way too many mistakes in technical documents.
65.hy 0
66.if n .na
67.\"
68.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
69.\" Fear. Run. Save yourself. No user-serviceable parts.
70. \" fudge factors for nroff and troff
71.if n \{\
72. ds #H 0
73. ds #V .8m
74. ds #F .3m
75. ds #[ \f1
76. ds #] \fP
77.\}
78.if t \{\
79. ds #H ((1u-(\\\\n(.fu%2u))*.13m)
80. ds #V .6m
81. ds #F 0
82. ds #[ \&
83. ds #] \&
84.\}
85. \" simple accents for nroff and troff
86.if n \{\
87. ds ' \&
88. ds ` \&
89. ds ^ \&
90. ds , \&
91. ds ~ ~
92. ds /
93.\}
94.if t \{\
95. ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
96. ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
97. ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
98. ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
99. ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
100. ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
101.\}
102. \" troff and (daisy-wheel) nroff accents
103.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
104.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
105.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
106.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
107.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
108.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
109.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
110.ds ae a\h'-(\w'a'u*4/10)'e
111.ds Ae A\h'-(\w'A'u*4/10)'E
112. \" corrections for vroff
113.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
114.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
115. \" for low resolution devices (crt and lpr)
116.if \n(.H>23 .if \n(.V>19 \
117\{\
118. ds : e
119. ds 8 ss
120. ds o a
121. ds d- d\h'-1'\(ga
122. ds D- D\h'-1'\(hy
123. ds th \o'bp'
124. ds Th \o'LP'
125. ds ae ae
126. ds Ae AE
127.\}
128.rm #[ #] #H #V #F C
129.\" ========================================================================
130.\"
131.IX Title "PERLGUTS 1"
132.TH PERLGUTS 1 "2006-01-07" "perl v5.8.8" "Perl Programmers Reference Guide"
133.SH "NAME"
134perlguts \- Introduction to the Perl API
135.SH "DESCRIPTION"
136.IX Header "DESCRIPTION"
137This document attempts to describe how to use the Perl \s-1API\s0, as well as
138to provide some info on the basic workings of the Perl core. It is far
139from complete and probably contains many errors. Please refer any
140questions or comments to the author below.
141.SH "Variables"
142.IX Header "Variables"
143.Sh "Datatypes"
144.IX Subsection "Datatypes"
145Perl has three typedefs that handle Perl's three main data types:
146.PP
147.Vb 3
148\& SV Scalar Value
149\& AV Array Value
150\& HV Hash Value
151.Ve
152.PP
153Each typedef has specific routines that manipulate the various data types.
154.ie n .Sh "What is an ""\s-1IV\s0""?"
155.el .Sh "What is an ``\s-1IV\s0''?"
156.IX Subsection "What is an IV?"
157Perl uses a special typedef \s-1IV\s0 which is a simple signed integer type that is
158guaranteed to be large enough to hold a pointer (as well as an integer).
159Additionally, there is the \s-1UV\s0, which is simply an unsigned \s-1IV\s0.
160.PP
161Perl also uses two special typedefs, I32 and I16, which will always be at
162least 32\-bits and 16\-bits long, respectively. (Again, there are U32 and U16,
163as well.) They will usually be exactly 32 and 16 bits long, but on Crays
164they will both be 64 bits.
165.Sh "Working with SVs"
166.IX Subsection "Working with SVs"
167An \s-1SV\s0 can be created and loaded with one command. There are five types of
168values that can be loaded: an integer value (\s-1IV\s0), an unsigned integer
169value (\s-1UV\s0), a double (\s-1NV\s0), a string (\s-1PV\s0), and another scalar (\s-1SV\s0).
170.PP
171The seven routines are:
172.PP
173.Vb 7
174\& SV* newSViv(IV);
175\& SV* newSVuv(UV);
176\& SV* newSVnv(double);
177\& SV* newSVpv(const char*, STRLEN);
178\& SV* newSVpvn(const char*, STRLEN);
179\& SV* newSVpvf(const char*, ...);
180\& SV* newSVsv(SV*);
181.Ve
182.PP
183\&\f(CW\*(C`STRLEN\*(C'\fR is an integer type (Size_t, usually defined as size_t in
184\&\fIconfig.h\fR) guaranteed to be large enough to represent the size of
185any string that perl can handle.
186.PP
187In the unlikely case of a \s-1SV\s0 requiring more complex initialisation, you
188can create an empty \s-1SV\s0 with newSV(len). If \f(CW\*(C`len\*(C'\fR is 0 an empty \s-1SV\s0 of
189type \s-1NULL\s0 is returned, else an \s-1SV\s0 of type \s-1PV\s0 is returned with len + 1 (for
190the \s-1NUL\s0) bytes of storage allocated, accessible via SvPVX. In both cases
191the \s-1SV\s0 has value undef.
192.PP
193.Vb 2
194\& SV *sv = newSV(0); /* no storage allocated */
195\& SV *sv = newSV(10); /* 10 (+1) bytes of uninitialised storage allocated */
196.Ve
197.PP
198To change the value of an \fIalready-existing\fR \s-1SV\s0, there are eight routines:
199.PP
200.Vb 8
201\& void sv_setiv(SV*, IV);
202\& void sv_setuv(SV*, UV);
203\& void sv_setnv(SV*, double);
204\& void sv_setpv(SV*, const char*);
205\& void sv_setpvn(SV*, const char*, STRLEN)
206\& void sv_setpvf(SV*, const char*, ...);
207\& void sv_vsetpvfn(SV*, const char*, STRLEN, va_list *, SV **, I32, bool *);
208\& void sv_setsv(SV*, SV*);
209.Ve
210.PP
211Notice that you can choose to specify the length of the string to be
212assigned 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
213allow Perl to calculate the length by using \f(CW\*(C`sv_setpv\*(C'\fR or by specifying
2140 as the second argument to \f(CW\*(C`newSVpv\*(C'\fR. Be warned, though, that Perl will
215determine the string's length by using \f(CW\*(C`strlen\*(C'\fR, which depends on the
216string terminating with a \s-1NUL\s0 character.
217.PP
218The arguments of \f(CW\*(C`sv_setpvf\*(C'\fR are processed like \f(CW\*(C`sprintf\*(C'\fR, and the
219formatted output becomes the value.
220.PP
221\&\f(CW\*(C`sv_vsetpvfn\*(C'\fR is an analogue of \f(CW\*(C`vsprintf\*(C'\fR, but it allows you to specify
222either a pointer to a variable argument list or the address and length of
223an array of SVs. The last argument points to a boolean; on return, if that
224boolean is true, then locale-specific information has been used to format
225the string, and the string's contents are therefore untrustworthy (see
226perlsec). This pointer may be \s-1NULL\s0 if that information is not
227important. Note that this function requires you to specify the length of
228the format.
229.PP
230The \f(CW\*(C`sv_set*()\*(C'\fR functions are not generic enough to operate on values
231that have \*(L"magic\*(R". See \*(L"Magic Virtual Tables\*(R" later in this document.
232.PP
233All SVs that contain strings should be terminated with a \s-1NUL\s0 character.
234If it is not NUL-terminated there is a risk of
235core dumps and corruptions from code which passes the string to C
236functions or system calls which expect a NUL-terminated string.
237Perl's own functions typically add a trailing \s-1NUL\s0 for this reason.
238Nevertheless, you should be very careful when you pass a string stored
239in an \s-1SV\s0 to a C function or system call.
240.PP
241To access the actual value that an \s-1SV\s0 points to, you can use the macros:
242.PP
243.Vb 5
244\& SvIV(SV*)
245\& SvUV(SV*)
246\& SvNV(SV*)
247\& SvPV(SV*, STRLEN len)
248\& SvPV_nolen(SV*)
249.Ve
250.PP
251which will automatically coerce the actual scalar type into an \s-1IV\s0, \s-1UV\s0, double,
252or string.
253.PP
254In the \f(CW\*(C`SvPV\*(C'\fR macro, the length of the string returned is placed into the
255variable \f(CW\*(C`len\*(C'\fR (this is a macro, so you do \fInot\fR use \f(CW&len\fR). If you do
256not care what the length of the data is, use the \f(CW\*(C`SvPV_nolen\*(C'\fR macro.
257Historically the \f(CW\*(C`SvPV\*(C'\fR macro with the global variable \f(CW\*(C`PL_na\*(C'\fR has been
258used in this case. But that can be quite inefficient because \f(CW\*(C`PL_na\*(C'\fR must
259be accessed in thread-local storage in threaded Perl. In any case, remember
260that Perl allows arbitrary strings of data that may both contain NULs and
261might not be terminated by a \s-1NUL\s0.
262.PP
263Also remember that C doesn't allow you to safely say \f(CW\*(C`foo(SvPV(s, len),
264len);\*(C'\fR. It might work with your compiler, but it won't work for everyone.
265Break this sort of statement up into separate assignments:
266.PP
267.Vb 5
268\& SV *s;
269\& STRLEN len;
270\& char * ptr;
271\& ptr = SvPV(s, len);
272\& foo(ptr, len);
273.Ve
274.PP
275If you want to know if the scalar value is \s-1TRUE\s0, you can use:
276.PP
277.Vb 1
278\& SvTRUE(SV*)
279.Ve
280.PP
281Although Perl will automatically grow strings for you, if you need to force
282Perl to allocate more memory for your \s-1SV\s0, you can use the macro
283.PP
284.Vb 1
285\& SvGROW(SV*, STRLEN newlen)
286.Ve
287.PP
288which will determine if more memory needs to be allocated. If so, it will
289call the function \f(CW\*(C`sv_grow\*(C'\fR. Note that \f(CW\*(C`SvGROW\*(C'\fR can only increase, not
290decrease, the allocated memory of an \s-1SV\s0 and that it does not automatically
291add a byte for the a trailing \s-1NUL\s0 (perl's own string functions typically do
292\&\f(CW\*(C`SvGROW(sv, len + 1)\*(C'\fR).
293.PP
294If you have an \s-1SV\s0 and want to know what kind of data Perl thinks is stored
295in it, you can use the following macros to check the type of \s-1SV\s0 you have.
296.PP
297.Vb 3
298\& SvIOK(SV*)
299\& SvNOK(SV*)
300\& SvPOK(SV*)
301.Ve
302.PP
303You can get and set the current length of the string stored in an \s-1SV\s0 with
304the following macros:
305.PP
306.Vb 2
307\& SvCUR(SV*)
308\& SvCUR_set(SV*, I32 val)
309.Ve
310.PP
311You can also get a pointer to the end of the string stored in the \s-1SV\s0
312with the macro:
313.PP
314.Vb 1
315\& SvEND(SV*)
316.Ve
317.PP
318But note that these last three macros are valid only if \f(CW\*(C`SvPOK()\*(C'\fR is true.
319.PP
320If you want to append something to the end of string stored in an \f(CW\*(C`SV*\*(C'\fR,
321you can use the following functions:
322.PP
323.Vb 5
324\& void sv_catpv(SV*, const char*);
325\& void sv_catpvn(SV*, const char*, STRLEN);
326\& void sv_catpvf(SV*, const char*, ...);
327\& void sv_vcatpvfn(SV*, const char*, STRLEN, va_list *, SV **, I32, bool);
328\& void sv_catsv(SV*, SV*);
329.Ve
330.PP
331The first function calculates the length of the string to be appended by
332using \f(CW\*(C`strlen\*(C'\fR. In the second, you specify the length of the string
333yourself. The third function processes its arguments like \f(CW\*(C`sprintf\*(C'\fR and
334appends the formatted output. The fourth function works like \f(CW\*(C`vsprintf\*(C'\fR.
335You can specify the address and length of an array of SVs instead of the
336va_list argument. The fifth function extends the string stored in the first
337\&\s-1SV\s0 with the string stored in the second \s-1SV\s0. It also forces the second \s-1SV\s0
338to be interpreted as a string.
339.PP
340The \f(CW\*(C`sv_cat*()\*(C'\fR functions are not generic enough to operate on values that
341have \*(L"magic\*(R". See \*(L"Magic Virtual Tables\*(R" later in this document.
342.PP
343If you know the name of a scalar variable, you can get a pointer to its \s-1SV\s0
344by using the following:
345.PP
346.Vb 1
347\& SV* get_sv("package::varname", FALSE);
348.Ve
349.PP
350This returns \s-1NULL\s0 if the variable does not exist.
351.PP
352If you want to know if this variable (or any other \s-1SV\s0) is actually \f(CW\*(C`defined\*(C'\fR,
353you can call:
354.PP
355.Vb 1
356\& SvOK(SV*)
357.Ve
358.PP
359The 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.
360.PP
361Its address can be used whenever an \f(CW\*(C`SV*\*(C'\fR is needed. Make sure that
362you don't try to compare a random sv with \f(CW&PL_sv_undef\fR. For example
363when interfacing Perl code, it'll work correctly for:
364.PP
365.Vb 1
366\& foo(undef);
367.Ve
368.PP
369But won't work when called as:
370.PP
371.Vb 2
372\& $x = undef;
373\& foo($x);
374.Ve
375.PP
376So to repeat always use \fISvOK()\fR to check whether an sv is defined.
377.PP
378Also you have to be careful when using \f(CW&PL_sv_undef\fR as a value in
379AVs or HVs (see \*(L"AVs, HVs and undefined values\*(R").
380.PP
381There are also the two values \f(CW\*(C`PL_sv_yes\*(C'\fR and \f(CW\*(C`PL_sv_no\*(C'\fR, which contain
382boolean \s-1TRUE\s0 and \s-1FALSE\s0 values, respectively. Like \f(CW\*(C`PL_sv_undef\*(C'\fR, their
383addresses can be used whenever an \f(CW\*(C`SV*\*(C'\fR is needed.
384.PP
385Do not be fooled into thinking that \f(CW\*(C`(SV *) 0\*(C'\fR is the same as \f(CW&PL_sv_undef\fR.
386Take this code:
387.PP
388.Vb 5
389\& SV* sv = (SV*) 0;
390\& if (I-am-to-return-a-real-value) {
391\& sv = sv_2mortal(newSViv(42));
392\& }
393\& sv_setsv(ST(0), sv);
394.Ve
395.PP
396This code tries to return a new \s-1SV\s0 (which contains the value 42) if it should
397return a real value, or undef otherwise. Instead it has returned a \s-1NULL\s0
398pointer which, somewhere down the line, will cause a segmentation violation,
399bus error, or just weird results. Change the zero to \f(CW&PL_sv_undef\fR in the
400first line and all will be well.
401.PP
402To free an \s-1SV\s0 that you've created, call \f(CW\*(C`SvREFCNT_dec(SV*)\*(C'\fR. Normally this
403call is not necessary (see \*(L"Reference Counts and Mortality\*(R").
404.Sh "Offsets"
405.IX Subsection "Offsets"
406Perl provides the function \f(CW\*(C`sv_chop\*(C'\fR to efficiently remove characters
407from the beginning of a string; you give it an \s-1SV\s0 and a pointer to
408somewhere inside the \s-1PV\s0, and it discards everything before the
409pointer. The efficiency comes by means of a little hack: instead of
410actually removing the characters, \f(CW\*(C`sv_chop\*(C'\fR sets the flag \f(CW\*(C`OOK\*(C'\fR
411(offset \s-1OK\s0) to signal to other functions that the offset hack is in
412effect, and it puts the number of bytes chopped off into the \s-1IV\s0 field
413of the \s-1SV\s0. It then moves the \s-1PV\s0 pointer (called \f(CW\*(C`SvPVX\*(C'\fR) forward that
414many bytes, and adjusts \f(CW\*(C`SvCUR\*(C'\fR and \f(CW\*(C`SvLEN\*(C'\fR.
415.PP
416Hence, at this point, the start of the buffer that we allocated lives
417at \f(CW\*(C`SvPVX(sv) \- SvIV(sv)\*(C'\fR in memory and the \s-1PV\s0 pointer is pointing
418into the middle of this allocated storage.
419.PP
420This is best demonstrated by example:
421.PP
422.Vb 8
423\& % ./perl -Ilib -MDevel::Peek -le '$a="12345"; $a=~s/.//; Dump($a)'
424\& SV = PVIV(0x8128450) at 0x81340f0
425\& REFCNT = 1
426\& FLAGS = (POK,OOK,pPOK)
427\& IV = 1 (OFFSET)
428\& PV = 0x8135781 ( "1" . ) "2345"\e0
429\& CUR = 4
430\& LEN = 5
431.Ve
432.PP
433Here the number of bytes chopped off (1) is put into \s-1IV\s0, and
434\&\f(CW\*(C`Devel::Peek::Dump\*(C'\fR helpfully reminds us that this is an offset. The
435portion of the string between the \*(L"real\*(R" and the \*(L"fake\*(R" beginnings is
436shown in parentheses, and the values of \f(CW\*(C`SvCUR\*(C'\fR and \f(CW\*(C`SvLEN\*(C'\fR reflect
437the fake beginning, not the real one.
438.PP
439Something similar to the offset hack is performed on AVs to enable
440efficient shifting and splicing off the beginning of the array; while
441\&\f(CW\*(C`AvARRAY\*(C'\fR points to the first element in the array that is visible from
442Perl, \f(CW\*(C`AvALLOC\*(C'\fR points to the real start of the C array. These are
443usually the same, but a \f(CW\*(C`shift\*(C'\fR operation can be carried out by
444increasing \f(CW\*(C`AvARRAY\*(C'\fR by one and decreasing \f(CW\*(C`AvFILL\*(C'\fR and \f(CW\*(C`AvLEN\*(C'\fR.
445Again, the location of the real start of the C array only comes into
446play when freeing the array. See \f(CW\*(C`av_shift\*(C'\fR in \fIav.c\fR.
447.Sh "What's Really Stored in an \s-1SV\s0?"
448.IX Subsection "What's Really Stored in an SV?"
449Recall that the usual method of determining the type of scalar you have is
450to use \f(CW\*(C`Sv*OK\*(C'\fR macros. Because a scalar can be both a number and a string,
451usually these macros will always return \s-1TRUE\s0 and calling the \f(CW\*(C`Sv*V\*(C'\fR
452macros will do the appropriate conversion of string to integer/double or
453integer/double to string.
454.PP
455If you \fIreally\fR need to know if you have an integer, double, or string
456pointer in an \s-1SV\s0, you can use the following three macros instead:
457.PP
458.Vb 3
459\& SvIOKp(SV*)
460\& SvNOKp(SV*)
461\& SvPOKp(SV*)
462.Ve
463.PP
464These will tell you if you truly have an integer, double, or string pointer
465stored in your \s-1SV\s0. The \*(L"p\*(R" stands for private.
466.PP
467The are various ways in which the private and public flags may differ.
468For example, a tied \s-1SV\s0 may have a valid underlying value in the \s-1IV\s0 slot
469(so SvIOKp is true), but the data should be accessed via the \s-1FETCH\s0
470routine rather than directly, so SvIOK is false. Another is when
471numeric conversion has occurred and precision has been lost: only the
472private flag is set on 'lossy' values. So when an \s-1NV\s0 is converted to an
473\&\s-1IV\s0 with loss, SvIOKp, SvNOKp and SvNOK will be set, while SvIOK wont be.
474.PP
475In general, though, it's best to use the \f(CW\*(C`Sv*V\*(C'\fR macros.
476.Sh "Working with AVs"
477.IX Subsection "Working with AVs"
478There are two ways to create and load an \s-1AV\s0. The first method creates an
479empty \s-1AV:\s0
480.PP
481.Vb 1
482\& AV* newAV();
483.Ve
484.PP
485The second method both creates the \s-1AV\s0 and initially populates it with SVs:
486.PP
487.Vb 1
488\& AV* av_make(I32 num, SV **ptr);
489.Ve
490.PP
491The second argument points to an array containing \f(CW\*(C`num\*(C'\fR \f(CW\*(C`SV*\*(C'\fR's. Once the
492\&\s-1AV\s0 has been created, the SVs can be destroyed, if so desired.
493.PP
494Once the \s-1AV\s0 has been created, the following operations are possible on AVs:
495.PP
496.Vb 4
497\& void av_push(AV*, SV*);
498\& SV* av_pop(AV*);
499\& SV* av_shift(AV*);
500\& void av_unshift(AV*, I32 num);
501.Ve
502.PP
503These should be familiar operations, with the exception of \f(CW\*(C`av_unshift\*(C'\fR.
504This routine adds \f(CW\*(C`num\*(C'\fR elements at the front of the array with the \f(CW\*(C`undef\*(C'\fR
505value. You must then use \f(CW\*(C`av_store\*(C'\fR (described below) to assign values
506to these new elements.
507.PP
508Here are some other functions:
509.PP
510.Vb 3
511\& I32 av_len(AV*);
512\& SV** av_fetch(AV*, I32 key, I32 lval);
513\& SV** av_store(AV*, I32 key, SV* val);
514.Ve
515.PP
516The \f(CW\*(C`av_len\*(C'\fR function returns the highest index value in array (just
517like $#array in Perl). If the array is empty, \-1 is returned. The
518\&\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
519is non\-zero, then \f(CW\*(C`av_fetch\*(C'\fR will store an undef value at that index.
520The \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
521not increment the reference count of \f(CW\*(C`val\*(C'\fR. Thus the caller is responsible
522for taking care of that, and if \f(CW\*(C`av_store\*(C'\fR returns \s-1NULL\s0, the caller will
523have to decrement the reference count to avoid a memory leak. Note that
524\&\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
525return value.
526.PP
527.Vb 3
528\& void av_clear(AV*);
529\& void av_undef(AV*);
530\& void av_extend(AV*, I32 key);
531.Ve
532.PP
533The \f(CW\*(C`av_clear\*(C'\fR function deletes all the elements in the AV* array, but
534does not actually delete the array itself. The \f(CW\*(C`av_undef\*(C'\fR function will
535delete all the elements in the array plus the array itself. The
536\&\f(CW\*(C`av_extend\*(C'\fR function extends the array so that it contains at least \f(CW\*(C`key+1\*(C'\fR
537elements. If \f(CW\*(C`key+1\*(C'\fR is less than the currently allocated length of the array,
538then nothing is done.
539.PP
540If you know the name of an array variable, you can get a pointer to its \s-1AV\s0
541by using the following:
542.PP
543.Vb 1
544\& AV* get_av("package::varname", FALSE);
545.Ve
546.PP
547This returns \s-1NULL\s0 if the variable does not exist.
548.PP
549See \*(L"Understanding the Magic of Tied Hashes and Arrays\*(R" for more
550information on how to use the array access functions on tied arrays.
551.Sh "Working with HVs"
552.IX Subsection "Working with HVs"
553To create an \s-1HV\s0, you use the following routine:
554.PP
555.Vb 1
556\& HV* newHV();
557.Ve
558.PP
559Once the \s-1HV\s0 has been created, the following operations are possible on HVs:
560.PP
561.Vb 2
562\& SV** hv_store(HV*, const char* key, U32 klen, SV* val, U32 hash);
563\& SV** hv_fetch(HV*, const char* key, U32 klen, I32 lval);
564.Ve
565.PP
566The \f(CW\*(C`klen\*(C'\fR parameter is the length of the key being passed in (Note that
567you cannot pass 0 in as a value of \f(CW\*(C`klen\*(C'\fR to tell Perl to measure the
568length of the key). The \f(CW\*(C`val\*(C'\fR argument contains the \s-1SV\s0 pointer to the
569scalar being stored, and \f(CW\*(C`hash\*(C'\fR is the precomputed hash value (zero if
570you want \f(CW\*(C`hv_store\*(C'\fR to calculate it for you). The \f(CW\*(C`lval\*(C'\fR parameter
571indicates whether this fetch is actually a part of a store operation, in
572which case a new undefined value will be added to the \s-1HV\s0 with the supplied
573key and \f(CW\*(C`hv_fetch\*(C'\fR will return as if the value had already existed.
574.PP
575Remember 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
576\&\f(CW\*(C`SV*\*(C'\fR. To access the scalar value, you must first dereference the return
577value. However, you should check to make sure that the return value is
578not \s-1NULL\s0 before dereferencing it.
579.PP
580These two functions check if a hash table entry exists, and deletes it.
581.PP
582.Vb 2
583\& bool hv_exists(HV*, const char* key, U32 klen);
584\& SV* hv_delete(HV*, const char* key, U32 klen, I32 flags);
585.Ve
586.PP
587If \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
588create and return a mortal copy of the deleted value.
589.PP
590And more miscellaneous functions:
591.PP
592.Vb 2
593\& void hv_clear(HV*);
594\& void hv_undef(HV*);
595.Ve
596.PP
597Like their \s-1AV\s0 counterparts, \f(CW\*(C`hv_clear\*(C'\fR deletes all the entries in the hash
598table but does not actually delete the hash table. The \f(CW\*(C`hv_undef\*(C'\fR deletes
599both the entries and the hash table itself.
600.PP
601Perl keeps the actual data in linked list of structures with a typedef of \s-1HE\s0.
602These contain the actual key and value pointers (plus extra administrative
603overhead). The key is a string pointer; the value is an \f(CW\*(C`SV*\*(C'\fR. However,
604once you have an \f(CW\*(C`HE*\*(C'\fR, to get the actual key and value, use the routines
605specified below.
606.PP
607.Vb 16
608\& I32 hv_iterinit(HV*);
609\& /* Prepares starting point to traverse hash table */
610\& HE* hv_iternext(HV*);
611\& /* Get the next entry, and return a pointer to a
612\& structure that has both the key and value */
613\& char* hv_iterkey(HE* entry, I32* retlen);
614\& /* Get the key from an HE structure and also return
615\& the length of the key string */
616\& SV* hv_iterval(HV*, HE* entry);
617\& /* Return an SV pointer to the value of the HE
618\& structure */
619\& SV* hv_iternextsv(HV*, char** key, I32* retlen);
620\& /* This convenience routine combines hv_iternext,
621\& hv_iterkey, and hv_iterval. The key and retlen
622\& arguments are return values for the key and its
623\& length. The value is returned in the SV* argument */
624.Ve
625.PP
626If you know the name of a hash variable, you can get a pointer to its \s-1HV\s0
627by using the following:
628.PP
629.Vb 1
630\& HV* get_hv("package::varname", FALSE);
631.Ve
632.PP
633This returns \s-1NULL\s0 if the variable does not exist.
634.PP
635The hash algorithm is defined in the \f(CW\*(C`PERL_HASH(hash, key, klen)\*(C'\fR macro:
636.PP
637.Vb 4
638\& hash = 0;
639\& while (klen--)
640\& hash = (hash * 33) + *key++;
641\& hash = hash + (hash >> 5); /* after 5.6 */
642.Ve
643.PP
644The last step was added in version 5.6 to improve distribution of
645lower bits in the resulting hash value.
646.PP
647See \*(L"Understanding the Magic of Tied Hashes and Arrays\*(R" for more
648information on how to use the hash access functions on tied hashes.
649.Sh "Hash \s-1API\s0 Extensions"
650.IX Subsection "Hash API Extensions"
651Beginning with version 5.004, the following functions are also supported:
652.PP
653.Vb 2
654\& HE* hv_fetch_ent (HV* tb, SV* key, I32 lval, U32 hash);
655\& HE* hv_store_ent (HV* tb, SV* key, SV* val, U32 hash);
656.Ve
657.PP
658.Vb 2
659\& bool hv_exists_ent (HV* tb, SV* key, U32 hash);
660\& SV* hv_delete_ent (HV* tb, SV* key, I32 flags, U32 hash);
661.Ve
662.PP
663.Vb 1
664\& SV* hv_iterkeysv (HE* entry);
665.Ve
666.PP
667Note that these functions take \f(CW\*(C`SV*\*(C'\fR keys, which simplifies writing
668of extension code that deals with hash structures. These functions
669also allow passing of \f(CW\*(C`SV*\*(C'\fR keys to \f(CW\*(C`tie\*(C'\fR functions without forcing
670you to stringify the keys (unlike the previous set of functions).
671.PP
672They also return and accept whole hash entries (\f(CW\*(C`HE*\*(C'\fR), making their
673use more efficient (since the hash number for a particular string
674doesn't have to be recomputed every time). See perlapi for detailed
675descriptions.
676.PP
677The following macros must always be used to access the contents of hash
678entries. Note that the arguments to these macros must be simple
679variables, since they may get evaluated more than once. See
680perlapi for detailed descriptions of these macros.
681.PP
682.Vb 6
683\& HePV(HE* he, STRLEN len)
684\& HeVAL(HE* he)
685\& HeHASH(HE* he)
686\& HeSVKEY(HE* he)
687\& HeSVKEY_force(HE* he)
688\& HeSVKEY_set(HE* he, SV* sv)
689.Ve
690.PP
691These two lower level macros are defined, but must only be used when
692dealing with keys that are not \f(CW\*(C`SV*\*(C'\fRs:
693.PP
694.Vb 2
695\& HeKEY(HE* he)
696\& HeKLEN(HE* he)
697.Ve
698.PP
699Note that both \f(CW\*(C`hv_store\*(C'\fR and \f(CW\*(C`hv_store_ent\*(C'\fR do not increment the
700reference count of the stored \f(CW\*(C`val\*(C'\fR, which is the caller's responsibility.
701If these functions return a \s-1NULL\s0 value, the caller will usually have to
702decrement the reference count of \f(CW\*(C`val\*(C'\fR to avoid a memory leak.
703.Sh "AVs, HVs and undefined values"
704.IX Subsection "AVs, HVs and undefined values"
705Sometimes you have to store undefined values in AVs or HVs. Although
706this may be a rare case, it can be tricky. That's because you're
707used to using \f(CW&PL_sv_undef\fR if you need an undefined \s-1SV\s0.
708.PP
709For example, intuition tells you that this \s-1XS\s0 code:
710.PP
711.Vb 2
712\& AV *av = newAV();
713\& av_store( av, 0, &PL_sv_undef );
714.Ve
715.PP
716is equivalent to this Perl code:
717.PP
718.Vb 2
719\& my @av;
720\& $av[0] = undef;
721.Ve
722.PP
723Unfortunately, this isn't true. AVs use \f(CW&PL_sv_undef\fR as a marker
724for indicating that an array element has not yet been initialized.
725Thus, \f(CW\*(C`exists $av[0]\*(C'\fR would be true for the above Perl code, but
726false for the array generated by the \s-1XS\s0 code.
727.PP
728Other problems can occur when storing \f(CW&PL_sv_undef\fR in HVs:
729.PP
730.Vb 1
731\& hv_store( hv, "key", 3, &PL_sv_undef, 0 );
732.Ve
733.PP
734This will indeed make the value \f(CW\*(C`undef\*(C'\fR, but if you try to modify
735the value of \f(CW\*(C`key\*(C'\fR, you'll get the following error:
736.PP
737.Vb 1
738\& Modification of non-creatable hash value attempted
739.Ve
740.PP
741In perl 5.8.0, \f(CW&PL_sv_undef\fR was also used to mark placeholders
742in restricted hashes. This caused such hash entries not to appear
743when iterating over the hash or when checking for the keys
744with the \f(CW\*(C`hv_exists\*(C'\fR function.
745.PP
746You can run into similar problems when you store \f(CW&PL_sv_true\fR or
747\&\f(CW&PL_sv_false\fR into AVs or HVs. Trying to modify such elements
748will give you the following error:
749.PP
750.Vb 1
751\& Modification of a read-only value attempted
752.Ve
753.PP
754To make a long story short, you can use the special variables
755\&\f(CW&PL_sv_undef\fR, \f(CW&PL_sv_true\fR and \f(CW&PL_sv_false\fR with AVs and
756HVs, but you have to make sure you know what you're doing.
757.PP
758Generally, if you want to store an undefined value in an \s-1AV\s0
759or \s-1HV\s0, you should not use \f(CW&PL_sv_undef\fR, but rather create a
760new undefined value using the \f(CW\*(C`newSV\*(C'\fR function, for example:
761.PP
762.Vb 2
763\& av_store( av, 42, newSV(0) );
764\& hv_store( hv, "foo", 3, newSV(0), 0 );
765.Ve
766.Sh "References"
767.IX Subsection "References"
768References are a special type of scalar that point to other data types
769(including references).
770.PP
771To create a reference, use either of the following functions:
772.PP
773.Vb 2
774\& SV* newRV_inc((SV*) thing);
775\& SV* newRV_noinc((SV*) thing);
776.Ve
777.PP
778The \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
779functions are identical except that \f(CW\*(C`newRV_inc\*(C'\fR increments the reference
780count of the \f(CW\*(C`thing\*(C'\fR, while \f(CW\*(C`newRV_noinc\*(C'\fR does not. For historical
781reasons, \f(CW\*(C`newRV\*(C'\fR is a synonym for \f(CW\*(C`newRV_inc\*(C'\fR.
782.PP
783Once you have a reference, you can use the following macro to dereference
784the reference:
785.PP
786.Vb 1
787\& SvRV(SV*)
788.Ve
789.PP
790then call the appropriate routines, casting the returned \f(CW\*(C`SV*\*(C'\fR to either an
791\&\f(CW\*(C`AV*\*(C'\fR or \f(CW\*(C`HV*\*(C'\fR, if required.
792.PP
793To determine if an \s-1SV\s0 is a reference, you can use the following macro:
794.PP
795.Vb 1
796\& SvROK(SV*)
797.Ve
798.PP
799To discover what type of value the reference refers to, use the following
800macro and then check the return value.
801.PP
802.Vb 1
803\& SvTYPE(SvRV(SV*))
804.Ve
805.PP
806The most useful types that will be returned are:
807.PP
808.Vb 9
809\& SVt_IV Scalar
810\& SVt_NV Scalar
811\& SVt_PV Scalar
812\& SVt_RV Scalar
813\& SVt_PVAV Array
814\& SVt_PVHV Hash
815\& SVt_PVCV Code
816\& SVt_PVGV Glob (possible a file handle)
817\& SVt_PVMG Blessed or Magical Scalar
818.Ve
819.PP
820.Vb 1
821\& See the sv.h header file for more details.
822.Ve
823.Sh "Blessed References and Class Objects"
824.IX Subsection "Blessed References and Class Objects"
825References are also used to support object-oriented programming. In perl's
826\&\s-1OO\s0 lexicon, an object is simply a reference that has been blessed into a
827package (or class). Once blessed, the programmer may now use the reference
828to access the various methods in the class.
829.PP
830A reference can be blessed into a package with the following function:
831.PP
832.Vb 1
833\& SV* sv_bless(SV* sv, HV* stash);
834.Ve
835.PP
836The \f(CW\*(C`sv\*(C'\fR argument must be a reference value. The \f(CW\*(C`stash\*(C'\fR argument
837specifies which class the reference will belong to. See
838\&\*(L"Stashes and Globs\*(R" for information on converting class names into stashes.
839.PP
840/* Still under construction */
841.PP
842Upgrades rv to reference if not already one. Creates new \s-1SV\s0 for rv to
843point to. If \f(CW\*(C`classname\*(C'\fR is non\-null, the \s-1SV\s0 is blessed into the specified
844class. \s-1SV\s0 is returned.
845.PP
846.Vb 1
847\& SV* newSVrv(SV* rv, const char* classname);
848.Ve
849.PP
850Copies integer, unsigned integer or double into an \s-1SV\s0 whose reference is \f(CW\*(C`rv\*(C'\fR. \s-1SV\s0 is blessed
851if \f(CW\*(C`classname\*(C'\fR is non\-null.
852.PP
853.Vb 3
854\& SV* sv_setref_iv(SV* rv, const char* classname, IV iv);
855\& SV* sv_setref_uv(SV* rv, const char* classname, UV uv);
856\& SV* sv_setref_nv(SV* rv, const char* classname, NV iv);
857.Ve
858.PP
859Copies the pointer value (\fIthe address, not the string!\fR) into an \s-1SV\s0 whose
860reference is rv. \s-1SV\s0 is blessed if \f(CW\*(C`classname\*(C'\fR is non\-null.
861.PP
862.Vb 1
863\& SV* sv_setref_pv(SV* rv, const char* classname, PV iv);
864.Ve
865.PP
866Copies string into an \s-1SV\s0 whose reference is \f(CW\*(C`rv\*(C'\fR. Set length to 0 to let
867Perl calculate the string length. \s-1SV\s0 is blessed if \f(CW\*(C`classname\*(C'\fR is non\-null.
868.PP
869.Vb 1
870\& SV* sv_setref_pvn(SV* rv, const char* classname, PV iv, STRLEN length);
871.Ve
872.PP
873Tests whether the \s-1SV\s0 is blessed into the specified class. It does not
874check inheritance relationships.
875.PP
876.Vb 1
877\& int sv_isa(SV* sv, const char* name);
878.Ve
879.PP
880Tests whether the \s-1SV\s0 is a reference to a blessed object.
881.PP
882.Vb 1
883\& int sv_isobject(SV* sv);
884.Ve
885.PP
886Tests whether the \s-1SV\s0 is derived from the specified class. \s-1SV\s0 can be either
887a reference to a blessed object or a string containing a class name. This
888is the function implementing the \f(CW\*(C`UNIVERSAL::isa\*(C'\fR functionality.
889.PP
890.Vb 1
891\& bool sv_derived_from(SV* sv, const char* name);
892.Ve
893.PP
894To check if you've got an object derived from a specific class you have
895to write:
896.PP
897.Vb 1
898\& if (sv_isobject(sv) && sv_derived_from(sv, class)) { ... }
899.Ve
900.Sh "Creating New Variables"
901.IX Subsection "Creating New Variables"
902To create a new Perl variable with an undef value which can be accessed from
903your Perl script, use the following routines, depending on the variable type.
904.PP
905.Vb 3
906\& SV* get_sv("package::varname", TRUE);
907\& AV* get_av("package::varname", TRUE);
908\& HV* get_hv("package::varname", TRUE);
909.Ve
910.PP
911Notice the use of \s-1TRUE\s0 as the second parameter. The new variable can now
912be set, using the routines appropriate to the data type.
913.PP
914There are additional macros whose values may be bitwise \s-1OR\s0'ed with the
915\&\f(CW\*(C`TRUE\*(C'\fR argument to enable certain extra features. Those bits are:
916.IP "\s-1GV_ADDMULTI\s0" 4
917.IX Item "GV_ADDMULTI"
918Marks the variable as multiply defined, thus preventing the:
919.Sp
920.Vb 1
921\& Name <varname> used only once: possible typo
922.Ve
923.Sp
924warning.
925.IP "\s-1GV_ADDWARN\s0" 4
926.IX Item "GV_ADDWARN"
927Issues the warning:
928.Sp
929.Vb 1
930\& Had to create <varname> unexpectedly
931.Ve
932.Sp
933if the variable did not exist before the function was called.
934.PP
935If you do not specify a package name, the variable is created in the current
936package.
937.Sh "Reference Counts and Mortality"
938.IX Subsection "Reference Counts and Mortality"
939Perl uses a reference count-driven garbage collection mechanism. SVs,
940AVs, or HVs (xV for short in the following) start their life with a
941reference count of 1. If the reference count of an xV ever drops to 0,
942then it will be destroyed and its memory made available for reuse.
943.PP
944This normally doesn't happen at the Perl level unless a variable is
945undef'ed or the last variable holding a reference to it is changed or
946overwritten. At the internal level, however, reference counts can be
947manipulated with the following macros:
948.PP
949.Vb 3
950\& int SvREFCNT(SV* sv);
951\& SV* SvREFCNT_inc(SV* sv);
952\& void SvREFCNT_dec(SV* sv);
953.Ve
954.PP
955However, there is one other function which manipulates the reference
956count of its argument. The \f(CW\*(C`newRV_inc\*(C'\fR function, you will recall,
957creates a reference to the specified argument. As a side effect,
958it increments the argument's reference count. If this is not what
959you want, use \f(CW\*(C`newRV_noinc\*(C'\fR instead.
960.PP
961For example, imagine you want to return a reference from an \s-1XSUB\s0 function.
962Inside the \s-1XSUB\s0 routine, you create an \s-1SV\s0 which initially has a reference
963count of one. Then you call \f(CW\*(C`newRV_inc\*(C'\fR, passing it the just-created \s-1SV\s0.
964This returns the reference as a new \s-1SV\s0, but the reference count of the
965\&\s-1SV\s0 you passed to \f(CW\*(C`newRV_inc\*(C'\fR has been incremented to two. Now you
966return the reference from the \s-1XSUB\s0 routine and forget about the \s-1SV\s0.
967But Perl hasn't! Whenever the returned reference is destroyed, the
968reference count of the original \s-1SV\s0 is decreased to one and nothing happens.
969The \s-1SV\s0 will hang around without any way to access it until Perl itself
970terminates. This is a memory leak.
971.PP
972The correct procedure, then, is to use \f(CW\*(C`newRV_noinc\*(C'\fR instead of
973\&\f(CW\*(C`newRV_inc\*(C'\fR. Then, if and when the last reference is destroyed,
974the reference count of the \s-1SV\s0 will go to zero and it will be destroyed,
975stopping any memory leak.
976.PP
977There are some convenience functions available that can help with the
978destruction of xVs. These functions introduce the concept of \*(L"mortality\*(R".
979An xV that is mortal has had its reference count marked to be decremented,
980but not actually decremented, until \*(L"a short time later\*(R". Generally the
981term \*(L"short time later\*(R" means a single Perl statement, such as a call to
982an \s-1XSUB\s0 function. The actual determinant for when mortal xVs have their
983reference count decremented depends on two macros, \s-1SAVETMPS\s0 and \s-1FREETMPS\s0.
984See perlcall and perlxs for more details on these macros.
985.PP
986\&\*(L"Mortalization\*(R" then is at its simplest a deferred \f(CW\*(C`SvREFCNT_dec\*(C'\fR.
987However, if you mortalize a variable twice, the reference count will
988later be decremented twice.
989.PP
990\&\*(L"Mortal\*(R" SVs are mainly used for SVs that are placed on perl's stack.
991For example an \s-1SV\s0 which is created just to pass a number to a called sub
992is made mortal to have it cleaned up automatically when it's popped off
993the stack. Similarly, results returned by XSUBs (which are pushed on the
994stack) are often made mortal.
995.PP
996To create a mortal variable, use the functions:
997.PP
998.Vb 3
999\& SV* sv_newmortal()
1000\& SV* sv_2mortal(SV*)
1001\& SV* sv_mortalcopy(SV*)
1002.Ve
1003.PP
1004The first call creates a mortal \s-1SV\s0 (with no value), the second converts an existing
1005\&\s-1SV\s0 to a mortal \s-1SV\s0 (and thus defers a call to \f(CW\*(C`SvREFCNT_dec\*(C'\fR), and the
1006third creates a mortal copy of an existing \s-1SV\s0.
1007Because \f(CW\*(C`sv_newmortal\*(C'\fR gives the new \s-1SV\s0 no value,it must normally be given one
1008via \f(CW\*(C`sv_setpv\*(C'\fR, \f(CW\*(C`sv_setiv\*(C'\fR, etc. :
1009.PP
1010.Vb 2
1011\& SV *tmp = sv_newmortal();
1012\& sv_setiv(tmp, an_integer);
1013.Ve
1014.PP
1015As that is multiple C statements it is quite common so see this idiom instead:
1016.PP
1017.Vb 1
1018\& SV *tmp = sv_2mortal(newSViv(an_integer));
1019.Ve
1020.PP
1021You should be careful about creating mortal variables. Strange things
1022can happen if you make the same value mortal within multiple contexts,
1023or if you make a variable mortal multiple times. Thinking of \*(L"Mortalization\*(R"
1024as deferred \f(CW\*(C`SvREFCNT_dec\*(C'\fR should help to minimize such problems.
1025For example if you are passing an \s-1SV\s0 which you \fIknow\fR has high enough \s-1REFCNT\s0
1026to survive its use on the stack you need not do any mortalization.
1027If you are not sure then doing an \f(CW\*(C`SvREFCNT_inc\*(C'\fR and \f(CW\*(C`sv_2mortal\*(C'\fR, or
1028making a \f(CW\*(C`sv_mortalcopy\*(C'\fR is safer.
1029.PP
1030The mortal routines are not just for SVs \*(-- AVs and HVs can be
1031made mortal by passing their address (type\-casted to \f(CW\*(C`SV*\*(C'\fR) to the
1032\&\f(CW\*(C`sv_2mortal\*(C'\fR or \f(CW\*(C`sv_mortalcopy\*(C'\fR routines.
1033.Sh "Stashes and Globs"
1034.IX Subsection "Stashes and Globs"
1035A \fBstash\fR is a hash that contains all variables that are defined
1036within a package. Each key of the stash is a symbol
1037name (shared by all the different types of objects that have the same
1038name), and each value in the hash table is a \s-1GV\s0 (Glob Value). This \s-1GV\s0
1039in turn contains references to the various objects of that name,
1040including (but not limited to) the following:
1041.PP
1042.Vb 6
1043\& Scalar Value
1044\& Array Value
1045\& Hash Value
1046\& I/O Handle
1047\& Format
1048\& Subroutine
1049.Ve
1050.PP
1051There is a single stash called \f(CW\*(C`PL_defstash\*(C'\fR that holds the items that exist
1052in the \f(CW\*(C`main\*(C'\fR package. To get at the items in other packages, append the
1053string \*(L"::\*(R" to the package name. The items in the \f(CW\*(C`Foo\*(C'\fR package are in
1054the stash \f(CW\*(C`Foo::\*(C'\fR in PL_defstash. The items in the \f(CW\*(C`Bar::Baz\*(C'\fR package are
1055in the stash \f(CW\*(C`Baz::\*(C'\fR in \f(CW\*(C`Bar::\*(C'\fR's stash.
1056.PP
1057To get the stash pointer for a particular package, use the function:
1058.PP
1059.Vb 2
1060\& HV* gv_stashpv(const char* name, I32 create)
1061\& HV* gv_stashsv(SV*, I32 create)
1062.Ve
1063.PP
1064The first function takes a literal string, the second uses the string stored
1065in the \s-1SV\s0. Remember that a stash is just a hash table, so you get back an
1066\&\f(CW\*(C`HV*\*(C'\fR. The \f(CW\*(C`create\*(C'\fR flag will create a new package if it is set.
1067.PP
1068The name that \f(CW\*(C`gv_stash*v\*(C'\fR wants is the name of the package whose symbol table
1069you want. The default package is called \f(CW\*(C`main\*(C'\fR. If you have multiply nested
1070packages, pass their names to \f(CW\*(C`gv_stash*v\*(C'\fR, separated by \f(CW\*(C`::\*(C'\fR as in the Perl
1071language itself.
1072.PP
1073Alternately, if you have an \s-1SV\s0 that is a blessed reference, you can find
1074out the stash pointer by using:
1075.PP
1076.Vb 1
1077\& HV* SvSTASH(SvRV(SV*));
1078.Ve
1079.PP
1080then use the following to get the package name itself:
1081.PP
1082.Vb 1
1083\& char* HvNAME(HV* stash);
1084.Ve
1085.PP
1086If you need to bless or re-bless an object you can use the following
1087function:
1088.PP
1089.Vb 1
1090\& SV* sv_bless(SV*, HV* stash)
1091.Ve
1092.PP
1093where the first argument, an \f(CW\*(C`SV*\*(C'\fR, must be a reference, and the second
1094argument is a stash. The returned \f(CW\*(C`SV*\*(C'\fR can now be used in the same way
1095as any other \s-1SV\s0.
1096.PP
1097For more information on references and blessings, consult perlref.
1098.Sh "Double-Typed SVs"
1099.IX Subsection "Double-Typed SVs"
1100Scalar variables normally contain only one type of value, an integer,
1101double, pointer, or reference. Perl will automatically convert the
1102actual scalar data from the stored type into the requested type.
1103.PP
1104Some scalar variables contain more than one type of scalar data. For
1105example, the variable \f(CW$!\fR contains either the numeric value of \f(CW\*(C`errno\*(C'\fR
1106or its string equivalent from either \f(CW\*(C`strerror\*(C'\fR or \f(CW\*(C`sys_errlist[]\*(C'\fR.
1107.PP
1108To force multiple data values into an \s-1SV\s0, you must do two things: use the
1109\&\f(CW\*(C`sv_set*v\*(C'\fR routines to add the additional scalar type, then set a flag
1110so that Perl will believe it contains more than one type of data. The
1111four macros to set the flags are:
1112.PP
1113.Vb 4
1114\& SvIOK_on
1115\& SvNOK_on
1116\& SvPOK_on
1117\& SvROK_on
1118.Ve
1119.PP
1120The particular macro you must use depends on which \f(CW\*(C`sv_set*v\*(C'\fR routine
1121you called first. This is because every \f(CW\*(C`sv_set*v\*(C'\fR routine turns on
1122only the bit for the particular type of data being set, and turns off
1123all the rest.
1124.PP
1125For example, to create a new Perl variable called \*(L"dberror\*(R" that contains
1126both the numeric and descriptive string error values, you could use the
1127following code:
1128.PP
1129.Vb 2
1130\& extern int dberror;
1131\& extern char *dberror_list;
1132.Ve
1133.PP
1134.Vb 4
1135\& SV* sv = get_sv("dberror", TRUE);
1136\& sv_setiv(sv, (IV) dberror);
1137\& sv_setpv(sv, dberror_list[dberror]);
1138\& SvIOK_on(sv);
1139.Ve
1140.PP
1141If the order of \f(CW\*(C`sv_setiv\*(C'\fR and \f(CW\*(C`sv_setpv\*(C'\fR had been reversed, then the
1142macro \f(CW\*(C`SvPOK_on\*(C'\fR would need to be called instead of \f(CW\*(C`SvIOK_on\*(C'\fR.
1143.Sh "Magic Variables"
1144.IX Subsection "Magic Variables"
1145[This section still under construction. Ignore everything here. Post no
1146bills. Everything not permitted is forbidden.]
1147.PP
1148Any \s-1SV\s0 may be magical, that is, it has special features that a normal
1149\&\s-1SV\s0 does not have. These features are stored in the \s-1SV\s0 structure in a
1150linked list of \f(CW\*(C`struct magic\*(C'\fR's, typedef'ed to \f(CW\*(C`MAGIC\*(C'\fR.
1151.PP
1152.Vb 10
1153\& struct magic {
1154\& MAGIC* mg_moremagic;
1155\& MGVTBL* mg_virtual;
1156\& U16 mg_private;
1157\& char mg_type;
1158\& U8 mg_flags;
1159\& SV* mg_obj;
1160\& char* mg_ptr;
1161\& I32 mg_len;
1162\& };
1163.Ve
1164.PP
1165Note this is current as of patchlevel 0, and could change at any time.
1166.Sh "Assigning Magic"
1167.IX Subsection "Assigning Magic"
1168Perl adds magic to an \s-1SV\s0 using the sv_magic function:
1169.PP
1170.Vb 1
1171\& void sv_magic(SV* sv, SV* obj, int how, const char* name, I32 namlen);
1172.Ve
1173.PP
1174The \f(CW\*(C`sv\*(C'\fR argument is a pointer to the \s-1SV\s0 that is to acquire a new magical
1175feature.
1176.PP
1177If \f(CW\*(C`sv\*(C'\fR is not already magical, Perl uses the \f(CW\*(C`SvUPGRADE\*(C'\fR macro to
1178convert \f(CW\*(C`sv\*(C'\fR to type \f(CW\*(C`SVt_PVMG\*(C'\fR. Perl then continues by adding new magic
1179to the beginning of the linked list of magical features. Any prior entry
1180of the same type of magic is deleted. Note that this can be overridden,
1181and multiple instances of the same type of magic can be associated with an
1182\&\s-1SV\s0.
1183.PP
1184The \f(CW\*(C`name\*(C'\fR and \f(CW\*(C`namlen\*(C'\fR arguments are used to associate a string with
1185the magic, typically the name of a variable. \f(CW\*(C`namlen\*(C'\fR is stored in the
1186\&\f(CW\*(C`mg_len\*(C'\fR field and if \f(CW\*(C`name\*(C'\fR is non-null then either a \f(CW\*(C`savepvn\*(C'\fR copy of
1187\&\f(CW\*(C`name\*(C'\fR or \f(CW\*(C`name\*(C'\fR itself is stored in the \f(CW\*(C`mg_ptr\*(C'\fR field, depending on
1188whether \f(CW\*(C`namlen\*(C'\fR is greater than zero or equal to zero respectively. As a
1189special case, if \f(CW\*(C`(name && namlen == HEf_SVKEY)\*(C'\fR then \f(CW\*(C`name\*(C'\fR is assumed
1190to contain an \f(CW\*(C`SV*\*(C'\fR and is stored as-is with its \s-1REFCNT\s0 incremented.
1191.PP
1192The sv_magic function uses \f(CW\*(C`how\*(C'\fR to determine which, if any, predefined
1193\&\*(L"Magic Virtual Table\*(R" should be assigned to the \f(CW\*(C`mg_virtual\*(C'\fR field.
1194See the \*(L"Magic Virtual Tables\*(R" section below. The \f(CW\*(C`how\*(C'\fR argument is also
1195stored in the \f(CW\*(C`mg_type\*(C'\fR field. The value of \f(CW\*(C`how\*(C'\fR should be chosen
1196from the set of macros \f(CW\*(C`PERL_MAGIC_foo\*(C'\fR found in \fIperl.h\fR. Note that before
1197these macros were added, Perl internals used to directly use character
1198literals, so you may occasionally come across old code or documentation
1199referring to 'U' magic rather than \f(CW\*(C`PERL_MAGIC_uvar\*(C'\fR for example.
1200.PP
1201The \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
1202structure. If it is not the same as the \f(CW\*(C`sv\*(C'\fR argument, the reference
1203count of the \f(CW\*(C`obj\*(C'\fR object is incremented. If it is the same, or if
1204the \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,
1205then \f(CW\*(C`obj\*(C'\fR is merely stored, without the reference count being incremented.
1206.PP
1207See also \f(CW\*(C`sv_magicext\*(C'\fR in perlapi for a more flexible way to add magic
1208to an \s-1SV\s0.
1209.PP
1210There is also a function to add magic to an \f(CW\*(C`HV\*(C'\fR:
1211.PP
1212.Vb 1
1213\& void hv_magic(HV *hv, GV *gv, int how);
1214.Ve
1215.PP
1216This 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.
1217.PP
1218To remove the magic from an \s-1SV\s0, call the function sv_unmagic:
1219.PP
1220.Vb 1
1221\& void sv_unmagic(SV *sv, int type);
1222.Ve
1223.PP
1224The \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
1225was initially made magical.
1226.Sh "Magic Virtual Tables"
1227.IX Subsection "Magic Virtual Tables"
1228The \f(CW\*(C`mg_virtual\*(C'\fR field in the \f(CW\*(C`MAGIC\*(C'\fR structure is a pointer to an
1229\&\f(CW\*(C`MGVTBL\*(C'\fR, which is a structure of function pointers and stands for
1230\&\*(L"Magic Virtual Table\*(R" to handle the various operations that might be
1231applied to that variable.
1232.PP
1233The \f(CW\*(C`MGVTBL\*(C'\fR has five pointers to the following routine types:
1234.PP
1235.Vb 5
1236\& int (*svt_get)(SV* sv, MAGIC* mg);
1237\& int (*svt_set)(SV* sv, MAGIC* mg);
1238\& U32 (*svt_len)(SV* sv, MAGIC* mg);
1239\& int (*svt_clear)(SV* sv, MAGIC* mg);
1240\& int (*svt_free)(SV* sv, MAGIC* mg);
1241.Ve
1242.PP
1243This \s-1MGVTBL\s0 structure is set at compile-time in \fIperl.h\fR and there are
1244currently 19 types (or 21 with overloading turned on). These different
1245structures contain pointers to various routines that perform additional
1246actions depending on which function is being called.
1247.PP
1248.Vb 7
1249\& Function pointer Action taken
1250\& ---------------- ------------
1251\& svt_get Do something before the value of the SV is retrieved.
1252\& svt_set Do something after the SV is assigned a value.
1253\& svt_len Report on the SV's length.
1254\& svt_clear Clear something the SV represents.
1255\& svt_free Free any extra storage associated with the SV.
1256.Ve
1257.PP
1258For instance, the \s-1MGVTBL\s0 structure called \f(CW\*(C`vtbl_sv\*(C'\fR (which corresponds
1259to an \f(CW\*(C`mg_type\*(C'\fR of \f(CW\*(C`PERL_MAGIC_sv\*(C'\fR) contains:
1260.PP
1261.Vb 1
1262\& { magic_get, magic_set, magic_len, 0, 0 }
1263.Ve
1264.PP
1265Thus, when an \s-1SV\s0 is determined to be magical and of type \f(CW\*(C`PERL_MAGIC_sv\*(C'\fR,
1266if a get operation is being performed, the routine \f(CW\*(C`magic_get\*(C'\fR is
1267called. All the various routines for the various magical types begin
1268with \f(CW\*(C`magic_\*(C'\fR. \s-1NOTE:\s0 the magic routines are not considered part of
1269the Perl \s-1API\s0, and may not be exported by the Perl library.
1270.PP
1271The current kinds of Magic Virtual Tables are:
1272.PP
1273.Vb 44
1274\& mg_type
1275\& (old-style char and macro) MGVTBL Type of magic
1276\& -------------------------- ------ ----------------------------
1277\& \e0 PERL_MAGIC_sv vtbl_sv Special scalar variable
1278\& A PERL_MAGIC_overload vtbl_amagic %OVERLOAD hash
1279\& a PERL_MAGIC_overload_elem vtbl_amagicelem %OVERLOAD hash element
1280\& c PERL_MAGIC_overload_table (none) Holds overload table (AMT)
1281\& on stash
1282\& B PERL_MAGIC_bm vtbl_bm Boyer-Moore (fast string search)
1283\& D PERL_MAGIC_regdata vtbl_regdata Regex match position data
1284\& (@+ and @- vars)
1285\& d PERL_MAGIC_regdatum vtbl_regdatum Regex match position data
1286\& element
1287\& E PERL_MAGIC_env vtbl_env %ENV hash
1288\& e PERL_MAGIC_envelem vtbl_envelem %ENV hash element
1289\& f PERL_MAGIC_fm vtbl_fm Formline ('compiled' format)
1290\& g PERL_MAGIC_regex_global vtbl_mglob m//g target / study()ed string
1291\& I PERL_MAGIC_isa vtbl_isa @ISA array
1292\& i PERL_MAGIC_isaelem vtbl_isaelem @ISA array element
1293\& k PERL_MAGIC_nkeys vtbl_nkeys scalar(keys()) lvalue
1294\& L PERL_MAGIC_dbfile (none) Debugger %_<filename
1295\& l PERL_MAGIC_dbline vtbl_dbline Debugger %_<filename element
1296\& m PERL_MAGIC_mutex vtbl_mutex ???
1297\& o PERL_MAGIC_collxfrm vtbl_collxfrm Locale collate transformation
1298\& P PERL_MAGIC_tied vtbl_pack Tied array or hash
1299\& p PERL_MAGIC_tiedelem vtbl_packelem Tied array or hash element
1300\& q PERL_MAGIC_tiedscalar vtbl_packelem Tied scalar or handle
1301\& r PERL_MAGIC_qr vtbl_qr precompiled qr// regex
1302\& S PERL_MAGIC_sig vtbl_sig %SIG hash
1303\& s PERL_MAGIC_sigelem vtbl_sigelem %SIG hash element
1304\& t PERL_MAGIC_taint vtbl_taint Taintedness
1305\& U PERL_MAGIC_uvar vtbl_uvar Available for use by extensions
1306\& v PERL_MAGIC_vec vtbl_vec vec() lvalue
1307\& V PERL_MAGIC_vstring (none) v-string scalars
1308\& w PERL_MAGIC_utf8 vtbl_utf8 UTF-8 length+offset cache
1309\& x PERL_MAGIC_substr vtbl_substr substr() lvalue
1310\& y PERL_MAGIC_defelem vtbl_defelem Shadow "foreach" iterator
1311\& variable / smart parameter
1312\& vivification
1313\& * PERL_MAGIC_glob vtbl_glob GV (typeglob)
1314\& # PERL_MAGIC_arylen vtbl_arylen Array length ($#ary)
1315\& . PERL_MAGIC_pos vtbl_pos pos() lvalue
1316\& < PERL_MAGIC_backref vtbl_backref ???
1317\& ~ PERL_MAGIC_ext (none) Available for use by extensions
1318.Ve
1319.PP
1320When an uppercase and lowercase letter both exist in the table, then the
1321uppercase letter is typically used to represent some kind of composite type
1322(a list or a hash), and the lowercase letter is used to represent an element
1323of that composite type. Some internals code makes use of this case
1324relationship. However, 'v' and 'V' (vec and v\-string) are in no way related.
1325.PP
1326The \f(CW\*(C`PERL_MAGIC_ext\*(C'\fR and \f(CW\*(C`PERL_MAGIC_uvar\*(C'\fR magic types are defined
1327specifically for use by extensions and will not be used by perl itself.
1328Extensions can use \f(CW\*(C`PERL_MAGIC_ext\*(C'\fR magic to 'attach' private information
1329to variables (typically objects). This is especially useful because
1330there is no way for normal perl code to corrupt this private information
1331(unlike using extra elements of a hash object).
1332.PP
1333Similarly, \f(CW\*(C`PERL_MAGIC_uvar\*(C'\fR magic can be used much like \fItie()\fR to call a
1334C function any time a scalar's value is used or changed. The \f(CW\*(C`MAGIC\*(C'\fR's
1335\&\f(CW\*(C`mg_ptr\*(C'\fR field points to a \f(CW\*(C`ufuncs\*(C'\fR structure:
1336.PP
1337.Vb 5
1338\& struct ufuncs {
1339\& I32 (*uf_val)(pTHX_ IV, SV*);
1340\& I32 (*uf_set)(pTHX_ IV, SV*);
1341\& IV uf_index;
1342\& };
1343.Ve
1344.PP
1345When 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
1346function will be called with \f(CW\*(C`uf_index\*(C'\fR as the first arg and a pointer to
1347the \s-1SV\s0 as the second. A simple example of how to add \f(CW\*(C`PERL_MAGIC_uvar\*(C'\fR
1348magic is shown below. Note that the ufuncs structure is copied by
1349sv_magic, so you can safely allocate it on the stack.
1350.PP
1351.Vb 10
1352\& void
1353\& Umagic(sv)
1354\& SV *sv;
1355\& PREINIT:
1356\& struct ufuncs uf;
1357\& CODE:
1358\& uf.uf_val = &my_get_fn;
1359\& uf.uf_set = &my_set_fn;
1360\& uf.uf_index = 0;
1361\& sv_magic(sv, 0, PERL_MAGIC_uvar, (char*)&uf, sizeof(uf));
1362.Ve
1363.PP
1364Note that because multiple extensions may be using \f(CW\*(C`PERL_MAGIC_ext\*(C'\fR
1365or \f(CW\*(C`PERL_MAGIC_uvar\*(C'\fR magic, it is important for extensions to take
1366extra care to avoid conflict. Typically only using the magic on
1367objects blessed into the same class as the extension is sufficient.
1368For \f(CW\*(C`PERL_MAGIC_ext\*(C'\fR magic, it may also be appropriate to add an I32
1369\&'signature' at the top of the private data area and check that.
1370.PP
1371Also note that the \f(CW\*(C`sv_set*()\*(C'\fR and \f(CW\*(C`sv_cat*()\*(C'\fR functions described
1372earlier do \fBnot\fR invoke 'set' magic on their targets. This must
1373be done by the user either by calling the \f(CW\*(C`SvSETMAGIC()\*(C'\fR macro after
1374calling these functions, or by using one of the \f(CW\*(C`sv_set*_mg()\*(C'\fR or
1375\&\f(CW\*(C`sv_cat*_mg()\*(C'\fR functions. Similarly, generic C code must call the
1376\&\f(CW\*(C`SvGETMAGIC()\*(C'\fR macro to invoke any 'get' magic if they use an \s-1SV\s0
1377obtained from external sources in functions that don't handle magic.
1378See perlapi for a description of these functions.
1379For example, calls to the \f(CW\*(C`sv_cat*()\*(C'\fR functions typically need to be
1380followed by \f(CW\*(C`SvSETMAGIC()\*(C'\fR, but they don't need a prior \f(CW\*(C`SvGETMAGIC()\*(C'\fR
1381since their implementation handles 'get' magic.
1382.Sh "Finding Magic"
1383.IX Subsection "Finding Magic"
1384.Vb 1
1385\& MAGIC* mg_find(SV*, int type); /* Finds the magic pointer of that type */
1386.Ve
1387.PP
1388This routine returns a pointer to the \f(CW\*(C`MAGIC\*(C'\fR structure stored in the \s-1SV\s0.
1389If the \s-1SV\s0 does not have that magical feature, \f(CW\*(C`NULL\*(C'\fR is returned. Also,
1390if the \s-1SV\s0 is not of type SVt_PVMG, Perl may core dump.
1391.PP
1392.Vb 1
1393\& int mg_copy(SV* sv, SV* nsv, const char* key, STRLEN klen);
1394.Ve
1395.PP
1396This routine checks to see what types of magic \f(CW\*(C`sv\*(C'\fR has. If the mg_type
1397field is an uppercase letter, then the mg_obj is copied to \f(CW\*(C`nsv\*(C'\fR, but
1398the mg_type field is changed to be the lowercase letter.
1399.Sh "Understanding the Magic of Tied Hashes and Arrays"
1400.IX Subsection "Understanding the Magic of Tied Hashes and Arrays"
1401Tied hashes and arrays are magical beasts of the \f(CW\*(C`PERL_MAGIC_tied\*(C'\fR
1402magic type.
1403.PP
1404\&\s-1WARNING:\s0 As of the 5.004 release, proper usage of the array and hash
1405access functions requires understanding a few caveats. Some
1406of these caveats are actually considered bugs in the \s-1API\s0, to be fixed
1407in later releases, and are bracketed with [\s-1MAYCHANGE\s0] below. If
1408you find yourself actually applying such information in this section, be
1409aware that the behavior may change in the future, umm, without warning.
1410.PP
1411The perl tie function associates a variable with an object that implements
1412the various \s-1GET\s0, \s-1SET\s0, etc methods. To perform the equivalent of the perl
1413tie function from an \s-1XSUB\s0, you must mimic this behaviour. The code below
1414carries out the necessary steps \- firstly it creates a new hash, and then
1415creates a second hash which it blesses into the class which will implement
1416the tie methods. Lastly it ties the two hashes together, and returns a
1417reference to the new tied hash. Note that the code below does \s-1NOT\s0 call the
1418\&\s-1TIEHASH\s0 method in the MyTie class \-
1419see \*(L"Calling Perl Routines from within C Programs\*(R" for details on how
1420to do this.
1421.PP
1422.Vb 15
1423\& SV*
1424\& mytie()
1425\& PREINIT:
1426\& HV *hash;
1427\& HV *stash;
1428\& SV *tie;
1429\& CODE:
1430\& hash = newHV();
1431\& tie = newRV_noinc((SV*)newHV());
1432\& stash = gv_stashpv("MyTie", TRUE);
1433\& sv_bless(tie, stash);
1434\& hv_magic(hash, (GV*)tie, PERL_MAGIC_tied);
1435\& RETVAL = newRV_noinc(hash);
1436\& OUTPUT:
1437\& RETVAL
1438.Ve
1439.PP
1440The \f(CW\*(C`av_store\*(C'\fR function, when given a tied array argument, merely
1441copies the magic of the array onto the value to be \*(L"stored\*(R", using
1442\&\f(CW\*(C`mg_copy\*(C'\fR. It may also return \s-1NULL\s0, indicating that the value did not
1443actually need to be stored in the array. [\s-1MAYCHANGE\s0] After a call to
1444\&\f(CW\*(C`av_store\*(C'\fR on a tied array, the caller will usually need to call
1445\&\f(CW\*(C`mg_set(val)\*(C'\fR to actually invoke the perl level \*(L"\s-1STORE\s0\*(R" method on the
1446\&\s-1TIEARRAY\s0 object. If \f(CW\*(C`av_store\*(C'\fR did return \s-1NULL\s0, a call to
1447\&\f(CW\*(C`SvREFCNT_dec(val)\*(C'\fR will also be usually necessary to avoid a memory
1448leak. [/MAYCHANGE]
1449.PP
1450The previous paragraph is applicable verbatim to tied hash access using the
1451\&\f(CW\*(C`hv_store\*(C'\fR and \f(CW\*(C`hv_store_ent\*(C'\fR functions as well.
1452.PP
1453\&\f(CW\*(C`av_fetch\*(C'\fR and the corresponding hash functions \f(CW\*(C`hv_fetch\*(C'\fR and
1454\&\f(CW\*(C`hv_fetch_ent\*(C'\fR actually return an undefined mortal value whose magic
1455has been initialized using \f(CW\*(C`mg_copy\*(C'\fR. Note the value so returned does not
1456need to be deallocated, as it is already mortal. [\s-1MAYCHANGE\s0] But you will
1457need to call \f(CW\*(C`mg_get()\*(C'\fR on the returned value in order to actually invoke
1458the perl level \*(L"\s-1FETCH\s0\*(R" method on the underlying \s-1TIE\s0 object. Similarly,
1459you may also call \f(CW\*(C`mg_set()\*(C'\fR on the return value after possibly assigning
1460a suitable value to it using \f(CW\*(C`sv_setsv\*(C'\fR, which will invoke the \*(L"\s-1STORE\s0\*(R"
1461method on the \s-1TIE\s0 object. [/MAYCHANGE]
1462.PP
1463[\s-1MAYCHANGE\s0]
1464In other words, the array or hash fetch/store functions don't really
1465fetch and store actual values in the case of tied arrays and hashes. They
1466merely call \f(CW\*(C`mg_copy\*(C'\fR to attach magic to the values that were meant to be
1467\&\*(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
1468do the job of invoking the \s-1TIE\s0 methods on the underlying objects. Thus
1469the magic mechanism currently implements a kind of lazy access to arrays
1470and hashes.
1471.PP
1472Currently (as of perl version 5.004), use of the hash and array access
1473functions requires the user to be aware of whether they are operating on
1474\&\*(L"normal\*(R" hashes and arrays, or on their tied variants. The \s-1API\s0 may be
1475changed to provide more transparent access to both tied and normal data
1476types in future versions.
1477[/MAYCHANGE]
1478.PP
1479You would do well to understand that the \s-1TIEARRAY\s0 and \s-1TIEHASH\s0 interfaces
1480are mere sugar to invoke some perl method calls while using the uniform hash
1481and array syntax. The use of this sugar imposes some overhead (typically
1482about two to four extra opcodes per \s-1FETCH/STORE\s0 operation, in addition to
1483the creation of all the mortal variables required to invoke the methods).
1484This overhead will be comparatively small if the \s-1TIE\s0 methods are themselves
1485substantial, but if they are only a few statements long, the overhead
1486will not be insignificant.
1487.Sh "Localizing changes"
1488.IX Subsection "Localizing changes"
1489Perl has a very handy construction
1490.PP
1491.Vb 4
1492\& {
1493\& local $var = 2;
1494\& ...
1495\& }
1496.Ve
1497.PP
1498This construction is \fIapproximately\fR equivalent to
1499.PP
1500.Vb 6
1501\& {
1502\& my $oldvar = $var;
1503\& $var = 2;
1504\& ...
1505\& $var = $oldvar;
1506\& }
1507.Ve
1508.PP
1509The biggest difference is that the first construction would
1510reinstate the initial value of \f(CW$var\fR, irrespective of how control exits
1511the 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
1512more efficient as well.
1513.PP
1514There is a way to achieve a similar task from C via Perl \s-1API:\s0 create a
1515\&\fIpseudo-block\fR, and arrange for some changes to be automatically
1516undone at the end of it, either explicit, or via a non-local exit (via
1517\&\fIdie()\fR). A \fIblock\fR\-like construct is created by a pair of
1518\&\f(CW\*(C`ENTER\*(C'\fR/\f(CW\*(C`LEAVE\*(C'\fR macros (see \*(L"Returning a Scalar\*(R" in perlcall).
1519Such a construct may be created specially for some important localized
1520task, or an existing one (like boundaries of enclosing Perl
1521subroutine/block, or an existing pair for freeing TMPs) may be
1522used. (In the second case the overhead of additional localization must
1523be almost negligible.) Note that any \s-1XSUB\s0 is automatically enclosed in
1524an \f(CW\*(C`ENTER\*(C'\fR/\f(CW\*(C`LEAVE\*(C'\fR pair.
1525.PP
1526Inside such a \fIpseudo-block\fR the following service is available:
1527.ie n .IP """SAVEINT(int i)""" 4
1528.el .IP "\f(CWSAVEINT(int i)\fR" 4
1529.IX Item "SAVEINT(int i)"
1530.PD 0
1531.ie n .IP """SAVEIV(IV i)""" 4
1532.el .IP "\f(CWSAVEIV(IV i)\fR" 4
1533.IX Item "SAVEIV(IV i)"
1534.ie n .IP """SAVEI32(I32 i)""" 4
1535.el .IP "\f(CWSAVEI32(I32 i)\fR" 4
1536.IX Item "SAVEI32(I32 i)"
1537.ie n .IP """SAVELONG(long i)""" 4
1538.el .IP "\f(CWSAVELONG(long i)\fR" 4
1539.IX Item "SAVELONG(long i)"
1540.PD
1541These macros arrange things to restore the value of integer variable
1542\&\f(CW\*(C`i\*(C'\fR at the end of enclosing \fIpseudo-block\fR.
1543.ie n .IP "SAVESPTR(s)" 4
1544.el .IP "\f(CWSAVESPTR(s)\fR" 4
1545.IX Item "SAVESPTR(s)"
1546.PD 0
1547.ie n .IP "SAVEPPTR(p)" 4
1548.el .IP "\f(CWSAVEPPTR(p)\fR" 4
1549.IX Item "SAVEPPTR(p)"
1550.PD
1551These macros arrange things to restore the value of pointers \f(CW\*(C`s\*(C'\fR and
1552\&\f(CW\*(C`p\*(C'\fR. \f(CW\*(C`s\*(C'\fR must be a pointer of a type which survives conversion to
1553\&\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
1554and back.
1555.ie n .IP """SAVEFREESV(SV *sv)""" 4
1556.el .IP "\f(CWSAVEFREESV(SV *sv)\fR" 4
1557.IX Item "SAVEFREESV(SV *sv)"
1558The refcount of \f(CW\*(C`sv\*(C'\fR would be decremented at the end of
1559\&\fIpseudo-block\fR. This is similar to \f(CW\*(C`sv_2mortal\*(C'\fR in that it is also a
1560mechanism for doing a delayed \f(CW\*(C`SvREFCNT_dec\*(C'\fR. However, while \f(CW\*(C`sv_2mortal\*(C'\fR
1561extends the lifetime of \f(CW\*(C`sv\*(C'\fR until the beginning of the next statement,
1562\&\f(CW\*(C`SAVEFREESV\*(C'\fR extends it until the end of the enclosing scope. These
1563lifetimes can be wildly different.
1564.Sp
1565Also compare \f(CW\*(C`SAVEMORTALIZESV\*(C'\fR.
1566.ie n .IP """SAVEMORTALIZESV(SV *sv)""" 4
1567.el .IP "\f(CWSAVEMORTALIZESV(SV *sv)\fR" 4
1568.IX Item "SAVEMORTALIZESV(SV *sv)"
1569Just like \f(CW\*(C`SAVEFREESV\*(C'\fR, but mortalizes \f(CW\*(C`sv\*(C'\fR at the end of the current
1570scope instead of decrementing its reference count. This usually has the
1571effect of keeping \f(CW\*(C`sv\*(C'\fR alive until the statement that called the currently
1572live scope has finished executing.
1573.ie n .IP """SAVEFREEOP(OP *op)""" 4
1574.el .IP "\f(CWSAVEFREEOP(OP *op)\fR" 4
1575.IX Item "SAVEFREEOP(OP *op)"
1576The \f(CW\*(C`OP *\*(C'\fR is \fIop_free()\fRed at the end of \fIpseudo-block\fR.
1577.ie n .IP "SAVEFREEPV(p)" 4
1578.el .IP "\f(CWSAVEFREEPV(p)\fR" 4
1579.IX Item "SAVEFREEPV(p)"
1580The chunk of memory which is pointed to by \f(CW\*(C`p\*(C'\fR is \fISafefree()\fRed at the
1581end of \fIpseudo-block\fR.
1582.ie n .IP """SAVECLEARSV(SV *sv)""" 4
1583.el .IP "\f(CWSAVECLEARSV(SV *sv)\fR" 4
1584.IX Item "SAVECLEARSV(SV *sv)"
1585Clears a slot in the current scratchpad which corresponds to \f(CW\*(C`sv\*(C'\fR at
1586the end of \fIpseudo-block\fR.
1587.ie n .IP """SAVEDELETE(HV *hv, char *key, I32 length)""" 4
1588.el .IP "\f(CWSAVEDELETE(HV *hv, char *key, I32 length)\fR" 4
1589.IX Item "SAVEDELETE(HV *hv, char *key, I32 length)"
1590The key \f(CW\*(C`key\*(C'\fR of \f(CW\*(C`hv\*(C'\fR is deleted at the end of \fIpseudo-block\fR. The
1591string pointed to by \f(CW\*(C`key\*(C'\fR is \fISafefree()\fRed. If one has a \fIkey\fR in
1592short-lived storage, the corresponding string may be reallocated like
1593this:
1594.Sp
1595.Vb 1
1596\& SAVEDELETE(PL_defstash, savepv(tmpbuf), strlen(tmpbuf));
1597.Ve
1598.ie n .IP """SAVEDESTRUCTOR(DESTRUCTORFUNC_NOCONTEXT_t f, void *p)""" 4
1599.el .IP "\f(CWSAVEDESTRUCTOR(DESTRUCTORFUNC_NOCONTEXT_t f, void *p)\fR" 4
1600.IX Item "SAVEDESTRUCTOR(DESTRUCTORFUNC_NOCONTEXT_t f, void *p)"
1601At the end of \fIpseudo-block\fR the function \f(CW\*(C`f\*(C'\fR is called with the
1602only argument \f(CW\*(C`p\*(C'\fR.
1603.ie n .IP """SAVEDESTRUCTOR_X(DESTRUCTORFUNC_t f, void *p)""" 4
1604.el .IP "\f(CWSAVEDESTRUCTOR_X(DESTRUCTORFUNC_t f, void *p)\fR" 4
1605.IX Item "SAVEDESTRUCTOR_X(DESTRUCTORFUNC_t f, void *p)"
1606At the end of \fIpseudo-block\fR the function \f(CW\*(C`f\*(C'\fR is called with the
1607implicit context argument (if any), and \f(CW\*(C`p\*(C'\fR.
1608.ie n .IP """SAVESTACK_POS()""" 4
1609.el .IP "\f(CWSAVESTACK_POS()\fR" 4
1610.IX Item "SAVESTACK_POS()"
1611The current offset on the Perl internal stack (cf. \f(CW\*(C`SP\*(C'\fR) is restored
1612at the end of \fIpseudo-block\fR.
1613.PP
1614The following \s-1API\s0 list contains functions, thus one needs to
1615provide pointers to the modifiable data explicitly (either C pointers,
1616or Perlish \f(CW\*(C`GV *\*(C'\fRs). Where the above macros take \f(CW\*(C`int\*(C'\fR, a similar
1617function takes \f(CW\*(C`int *\*(C'\fR.
1618.ie n .IP """SV* save_scalar(GV *gv)""" 4
1619.el .IP "\f(CWSV* save_scalar(GV *gv)\fR" 4
1620.IX Item "SV* save_scalar(GV *gv)"
1621Equivalent to Perl code \f(CW\*(C`local $gv\*(C'\fR.
1622.ie n .IP """AV* save_ary(GV *gv)""" 4
1623.el .IP "\f(CWAV* save_ary(GV *gv)\fR" 4
1624.IX Item "AV* save_ary(GV *gv)"
1625.PD 0
1626.ie n .IP """HV* save_hash(GV *gv)""" 4
1627.el .IP "\f(CWHV* save_hash(GV *gv)\fR" 4
1628.IX Item "HV* save_hash(GV *gv)"
1629.PD
1630Similar to \f(CW\*(C`save_scalar\*(C'\fR, but localize \f(CW@gv\fR and \f(CW%gv\fR.
1631.ie n .IP """void save_item(SV *item)""" 4
1632.el .IP "\f(CWvoid save_item(SV *item)\fR" 4
1633.IX Item "void save_item(SV *item)"
1634Duplicates the current value of \f(CW\*(C`SV\*(C'\fR, on the exit from the current
1635\&\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
1636using the stored value.
1637.ie n .IP """void save_list(SV **sarg, I32 maxsarg)""" 4
1638.el .IP "\f(CWvoid save_list(SV **sarg, I32 maxsarg)\fR" 4
1639.IX Item "void save_list(SV **sarg, I32 maxsarg)"
1640A variant of \f(CW\*(C`save_item\*(C'\fR which takes multiple arguments via an array
1641\&\f(CW\*(C`sarg\*(C'\fR of \f(CW\*(C`SV*\*(C'\fR of length \f(CW\*(C`maxsarg\*(C'\fR.
1642.ie n .IP """SV* save_svref(SV **sptr)""" 4
1643.el .IP "\f(CWSV* save_svref(SV **sptr)\fR" 4
1644.IX Item "SV* save_svref(SV **sptr)"
1645Similar to \f(CW\*(C`save_scalar\*(C'\fR, but will reinstate an \f(CW\*(C`SV *\*(C'\fR.
1646.ie n .IP """void save_aptr(AV **aptr)""" 4
1647.el .IP "\f(CWvoid save_aptr(AV **aptr)\fR" 4
1648.IX Item "void save_aptr(AV **aptr)"
1649.PD 0
1650.ie n .IP """void save_hptr(HV **hptr)""" 4
1651.el .IP "\f(CWvoid save_hptr(HV **hptr)\fR" 4
1652.IX Item "void save_hptr(HV **hptr)"
1653.PD
1654Similar to \f(CW\*(C`save_svref\*(C'\fR, but localize \f(CW\*(C`AV *\*(C'\fR and \f(CW\*(C`HV *\*(C'\fR.
1655.PP
1656The \f(CW\*(C`Alias\*(C'\fR module implements localization of the basic types within the
1657\&\fIcaller's scope\fR. People who are interested in how to localize things in
1658the containing scope should take a look there too.
1659.SH "Subroutines"
1660.IX Header "Subroutines"
1661.Sh "XSUBs and the Argument Stack"
1662.IX Subsection "XSUBs and the Argument Stack"
1663The \s-1XSUB\s0 mechanism is a simple way for Perl programs to access C subroutines.
1664An \s-1XSUB\s0 routine will have a stack that contains the arguments from the Perl
1665program, and a way to map from the Perl data structures to a C equivalent.
1666.PP
1667The stack arguments are accessible through the \f(CWST(n)\fR macro, which returns
1668the \f(CW\*(C`n\*(C'\fR'th stack argument. Argument 0 is the first argument passed in the
1669Perl subroutine call. These arguments are \f(CW\*(C`SV*\*(C'\fR, and can be used anywhere
1670an \f(CW\*(C`SV*\*(C'\fR is used.
1671.PP
1672Most of the time, output from the C routine can be handled through use of
1673the \s-1RETVAL\s0 and \s-1OUTPUT\s0 directives. However, there are some cases where the
1674argument stack is not already long enough to handle all the return values.
1675An example is the \s-1POSIX\s0 \fItzname()\fR call, which takes no arguments, but returns
1676two, the local time zone's standard and summer time abbreviations.
1677.PP
1678To handle this situation, the \s-1PPCODE\s0 directive is used and the stack is
1679extended using the macro:
1680.PP
1681.Vb 1
1682\& EXTEND(SP, num);
1683.Ve
1684.PP
1685where \f(CW\*(C`SP\*(C'\fR is the macro that represents the local copy of the stack pointer,
1686and \f(CW\*(C`num\*(C'\fR is the number of elements the stack should be extended by.
1687.PP
1688Now that there is room on the stack, values can be pushed on it using \f(CW\*(C`PUSHs\*(C'\fR
1689macro. The pushed values will often need to be \*(L"mortal\*(R" (See
1690\&\*(L"Reference Counts and Mortality\*(R"):
1691.PP
1692.Vb 4
1693\& PUSHs(sv_2mortal(newSViv(an_integer)))
1694\& PUSHs(sv_2mortal(newSVuv(an_unsigned_integer)))
1695\& PUSHs(sv_2mortal(newSVnv(a_double)))
1696\& PUSHs(sv_2mortal(newSVpv("Some String",0)))
1697.Ve
1698.PP
1699And now the Perl program calling \f(CW\*(C`tzname\*(C'\fR, the two values will be assigned
1700as in:
1701.PP
1702.Vb 1
1703\& ($standard_abbrev, $summer_abbrev) = POSIX::tzname;
1704.Ve
1705.PP
1706An alternate (and possibly simpler) method to pushing values on the stack is
1707to use the macro:
1708.PP
1709.Vb 1
1710\& XPUSHs(SV*)
1711.Ve
1712.PP
1713This macro automatically adjust the stack for you, if needed. Thus, you
1714do not need to call \f(CW\*(C`EXTEND\*(C'\fR to extend the stack.
1715.PP
1716Despite their suggestions in earlier versions of this document the macros
1717\&\f(CW\*(C`(X)PUSH[iunp]\*(C'\fR are \fInot\fR suited to XSUBs which return multiple results.
1718For that, either stick to the \f(CW\*(C`(X)PUSHs\*(C'\fR macros shown above, or use the new
1719\&\f(CW\*(C`m(X)PUSH[iunp]\*(C'\fR macros instead; see \*(L"Putting a C value on Perl stack\*(R".
1720.PP
1721For more information, consult perlxs and perlxstut.
1722.Sh "Calling Perl Routines from within C Programs"
1723.IX Subsection "Calling Perl Routines from within C Programs"
1724There are four routines that can be used to call a Perl subroutine from
1725within a C program. These four are:
1726.PP
1727.Vb 4
1728\& I32 call_sv(SV*, I32);
1729\& I32 call_pv(const char*, I32);
1730\& I32 call_method(const char*, I32);
1731\& I32 call_argv(const char*, I32, register char**);
1732.Ve
1733.PP
1734The routine most often used is \f(CW\*(C`call_sv\*(C'\fR. The \f(CW\*(C`SV*\*(C'\fR argument
1735contains either the name of the Perl subroutine to be called, or a
1736reference to the subroutine. The second argument consists of flags
1737that control the context in which the subroutine is called, whether
1738or not the subroutine is being passed arguments, how errors should be
1739trapped, and how to treat return values.
1740.PP
1741All four routines return the number of arguments that the subroutine returned
1742on the Perl stack.
1743.PP
1744These routines used to be called \f(CW\*(C`perl_call_sv\*(C'\fR, etc., before Perl v5.6.0,
1745but those names are now deprecated; macros of the same name are provided for
1746compatibility.
1747.PP
1748When using any of these routines (except \f(CW\*(C`call_argv\*(C'\fR), the programmer
1749must manipulate the Perl stack. These include the following macros and
1750functions:
1751.PP
1752.Vb 11
1753\& dSP
1754\& SP
1755\& PUSHMARK()
1756\& PUTBACK
1757\& SPAGAIN
1758\& ENTER
1759\& SAVETMPS
1760\& FREETMPS
1761\& LEAVE
1762\& XPUSH*()
1763\& POP*()
1764.Ve
1765.PP
1766For a detailed description of calling conventions from C to Perl,
1767consult perlcall.
1768.Sh "Memory Allocation"
1769.IX Subsection "Memory Allocation"
1770\fIAllocation\fR
1771.IX Subsection "Allocation"
1772.PP
1773All memory meant to be used with the Perl \s-1API\s0 functions should be manipulated
1774using the macros described in this section. The macros provide the necessary
1775transparency between differences in the actual malloc implementation that is
1776used within perl.
1777.PP
1778It is suggested that you enable the version of malloc that is distributed
1779with Perl. It keeps pools of various sizes of unallocated memory in
1780order to satisfy allocation requests more quickly. However, on some
1781platforms, it may cause spurious malloc or free errors.
1782.PP
1783The following three macros are used to initially allocate memory :
1784.PP
1785.Vb 3
1786\& Newx(pointer, number, type);
1787\& Newxc(pointer, number, type, cast);
1788\& Newxz(pointer, number, type);
1789.Ve
1790.PP
1791The first argument \f(CW\*(C`pointer\*(C'\fR should be the name of a variable that will
1792point to the newly allocated memory.
1793.PP
1794The second and third arguments \f(CW\*(C`number\*(C'\fR and \f(CW\*(C`type\*(C'\fR specify how many of
1795the specified type of data structure should be allocated. The argument
1796\&\f(CW\*(C`type\*(C'\fR is passed to \f(CW\*(C`sizeof\*(C'\fR. The final argument to \f(CW\*(C`Newxc\*(C'\fR, \f(CW\*(C`cast\*(C'\fR,
1797should be used if the \f(CW\*(C`pointer\*(C'\fR argument is different from the \f(CW\*(C`type\*(C'\fR
1798argument.
1799.PP
1800Unlike the \f(CW\*(C`Newx\*(C'\fR and \f(CW\*(C`Newxc\*(C'\fR macros, the \f(CW\*(C`Newxz\*(C'\fR macro calls \f(CW\*(C`memzero\*(C'\fR
1801to zero out all the newly allocated memory.
1802.PP
1803\fIReallocation\fR
1804.IX Subsection "Reallocation"
1805.PP
1806.Vb 3
1807\& Renew(pointer, number, type);
1808\& Renewc(pointer, number, type, cast);
1809\& Safefree(pointer)
1810.Ve
1811.PP
1812These three macros are used to change a memory buffer size or to free a
1813piece of memory no longer needed. The arguments to \f(CW\*(C`Renew\*(C'\fR and \f(CW\*(C`Renewc\*(C'\fR
1814match those of \f(CW\*(C`New\*(C'\fR and \f(CW\*(C`Newc\*(C'\fR with the exception of not needing the
1815\&\*(L"magic cookie\*(R" argument.
1816.PP
1817\fIMoving\fR
1818.IX Subsection "Moving"
1819.PP
1820.Vb 3
1821\& Move(source, dest, number, type);
1822\& Copy(source, dest, number, type);
1823\& Zero(dest, number, type);
1824.Ve
1825.PP
1826These three macros are used to move, copy, or zero out previously allocated
1827memory. The \f(CW\*(C`source\*(C'\fR and \f(CW\*(C`dest\*(C'\fR arguments point to the source and
1828destination starting points. Perl will move, copy, or zero out \f(CW\*(C`number\*(C'\fR
1829instances of the size of the \f(CW\*(C`type\*(C'\fR data structure (using the \f(CW\*(C`sizeof\*(C'\fR
1830function).
1831.Sh "PerlIO"
1832.IX Subsection "PerlIO"
1833The most recent development releases of Perl has been experimenting with
1834removing Perl's dependency on the \*(L"normal\*(R" standard I/O suite and allowing
1835other stdio implementations to be used. This involves creating a new
1836abstraction layer that then calls whichever implementation of stdio Perl
1837was compiled with. All XSUBs should now use the functions in the PerlIO
1838abstraction layer and not make any assumptions about what kind of stdio
1839is being used.
1840.PP
1841For a complete description of the PerlIO abstraction, consult perlapio.
1842.Sh "Putting a C value on Perl stack"
1843.IX Subsection "Putting a C value on Perl stack"
1844A lot of opcodes (this is an elementary operation in the internal perl
1845stack machine) put an SV* on the stack. However, as an optimization
1846the corresponding \s-1SV\s0 is (usually) not recreated each time. The opcodes
1847reuse specially assigned SVs (\fItarget\fRs) which are (as a corollary)
1848not constantly freed/created.
1849.PP
1850Each of the targets is created only once (but see
1851\&\*(L"Scratchpads and recursion\*(R" below), and when an opcode needs to put
1852an integer, a double, or a string on stack, it just sets the
1853corresponding parts of its \fItarget\fR and puts the \fItarget\fR on stack.
1854.PP
1855The macro to put this target on stack is \f(CW\*(C`PUSHTARG\*(C'\fR, and it is
1856directly used in some opcodes, as well as indirectly in zillions of
1857others, which use it via \f(CW\*(C`(X)PUSH[iunp]\*(C'\fR.
1858.PP
1859Because the target is reused, you must be careful when pushing multiple
1860values on the stack. The following code will not do what you think:
1861.PP
1862.Vb 2
1863\& XPUSHi(10);
1864\& XPUSHi(20);
1865.Ve
1866.PP
1867This translates as "set \f(CW\*(C`TARG\*(C'\fR to 10, push a pointer to \f(CW\*(C`TARG\*(C'\fR onto
1868the stack; set \f(CW\*(C`TARG\*(C'\fR to 20, push a pointer to \f(CW\*(C`TARG\*(C'\fR onto the stack".
1869At the end of the operation, the stack does not contain the values 10
1870and 20, but actually contains two pointers to \f(CW\*(C`TARG\*(C'\fR, which we have set
1871to 20.
1872.PP
1873If you need to push multiple different values then you should either use
1874the \f(CW\*(C`(X)PUSHs\*(C'\fR macros, or else use the new \f(CW\*(C`m(X)PUSH[iunp]\*(C'\fR macros,
1875none of which make use of \f(CW\*(C`TARG\*(C'\fR. The \f(CW\*(C`(X)PUSHs\*(C'\fR macros simply push an
1876SV* on the stack, which, as noted under \*(L"XSUBs and the Argument Stack\*(R",
1877will often need to be \*(L"mortal\*(R". The new \f(CW\*(C`m(X)PUSH[iunp]\*(C'\fR macros make
1878this a little easier to achieve by creating a new mortal for you (via
1879\&\f(CW\*(C`(X)PUSHmortal\*(C'\fR), pushing that onto the stack (extending it if necessary
1880in the case of the \f(CW\*(C`mXPUSH[iunp]\*(C'\fR macros), and then setting its value.
1881Thus, instead of writing this to \*(L"fix\*(R" the example above:
1882.PP
1883.Vb 2
1884\& XPUSHs(sv_2mortal(newSViv(10)))
1885\& XPUSHs(sv_2mortal(newSViv(20)))
1886.Ve
1887.PP
1888you can simply write:
1889.PP
1890.Vb 2
1891\& mXPUSHi(10)
1892\& mXPUSHi(20)
1893.Ve
1894.PP
1895On a related note, if you do use \f(CW\*(C`(X)PUSH[iunp]\*(C'\fR, then you're going to
1896need a \f(CW\*(C`dTARG\*(C'\fR in your variable declarations so that the \f(CW\*(C`*PUSH*\*(C'\fR
1897macros can make use of the local variable \f(CW\*(C`TARG\*(C'\fR. See also \f(CW\*(C`dTARGET\*(C'\fR
1898and \f(CW\*(C`dXSTARG\*(C'\fR.
1899.Sh "Scratchpads"
1900.IX Subsection "Scratchpads"
1901The question remains on when the SVs which are \fItarget\fRs for opcodes
1902are created. The answer is that they are created when the current unit \*(--
1903a subroutine or a file (for opcodes for statements outside of
1904subroutines) \*(-- is compiled. During this time a special anonymous Perl
1905array is created, which is called a scratchpad for the current
1906unit.
1907.PP
1908A scratchpad keeps SVs which are lexicals for the current unit and are
1909targets for opcodes. One can deduce that an \s-1SV\s0 lives on a scratchpad
1910by looking on its flags: lexicals have \f(CW\*(C`SVs_PADMY\*(C'\fR set, and
1911\&\fItarget\fRs have \f(CW\*(C`SVs_PADTMP\*(C'\fR set.
1912.PP
1913The correspondence between OPs and \fItarget\fRs is not 1\-to\-1. Different
1914OPs in the compile tree of the unit can use the same target, if this
1915would not conflict with the expected life of the temporary.
1916.Sh "Scratchpads and recursion"
1917.IX Subsection "Scratchpads and recursion"
1918In fact it is not 100% true that a compiled unit contains a pointer to
1919the scratchpad \s-1AV\s0. In fact it contains a pointer to an \s-1AV\s0 of
1920(initially) one element, and this element is the scratchpad \s-1AV\s0. Why do
1921we need an extra level of indirection?
1922.PP
1923The answer is \fBrecursion\fR, and maybe \fBthreads\fR. Both
1924these can create several execution pointers going into the same
1925subroutine. For the subroutine-child not write over the temporaries
1926for the subroutine-parent (lifespan of which covers the call to the
1927child), the parent and the child should have different
1928scratchpads. (\fIAnd\fR the lexicals should be separate anyway!)
1929.PP
1930So each subroutine is born with an array of scratchpads (of length 1).
1931On each entry to the subroutine it is checked that the current
1932depth of the recursion is not more than the length of this array, and
1933if it is, new scratchpad is created and pushed into the array.
1934.PP
1935The \fItarget\fRs on this scratchpad are \f(CW\*(C`undef\*(C'\fRs, but they are already
1936marked with correct flags.
1937.SH "Compiled code"
1938.IX Header "Compiled code"
1939.Sh "Code tree"
1940.IX Subsection "Code tree"
1941Here we describe the internal form your code is converted to by
1942Perl. Start with a simple example:
1943.PP
1944.Vb 1
1945\& $a = $b + $c;
1946.Ve
1947.PP
1948This is converted to a tree similar to this one:
1949.PP
1950.Vb 5
1951\& assign-to
1952\& / \e
1953\& + $a
1954\& / \e
1955\& $b $c
1956.Ve
1957.PP
1958(but slightly more complicated). This tree reflects the way Perl
1959parsed your code, but has nothing to do with the execution order.
1960There is an additional \*(L"thread\*(R" going through the nodes of the tree
1961which shows the order of execution of the nodes. In our simplified
1962example above it looks like:
1963.PP
1964.Vb 1
1965\& $b ---> $c ---> + ---> $a ---> assign-to
1966.Ve
1967.PP
1968But with the actual compile tree for \f(CW\*(C`$a = $b + $c\*(C'\fR it is different:
1969some nodes \fIoptimized away\fR. As a corollary, though the actual tree
1970contains more nodes than our simplified example, the execution order
1971is the same as in our example.
1972.Sh "Examining the tree"
1973.IX Subsection "Examining the tree"
1974If you have your perl compiled for debugging (usually done with
1975\&\f(CW\*(C`\-DDEBUGGING\*(C'\fR on the \f(CW\*(C`Configure\*(C'\fR command line), you may examine the
1976compiled tree by specifying \f(CW\*(C`\-Dx\*(C'\fR on the Perl command line. The
1977output takes several lines per node, and for \f(CW\*(C`$b+$c\*(C'\fR it looks like
1978this:
1979.PP
1980.Vb 23
1981\& 5 TYPE = add ===> 6
1982\& TARG = 1
1983\& FLAGS = (SCALAR,KIDS)
1984\& {
1985\& TYPE = null ===> (4)
1986\& (was rv2sv)
1987\& FLAGS = (SCALAR,KIDS)
1988\& {
1989\& 3 TYPE = gvsv ===> 4
1990\& FLAGS = (SCALAR)
1991\& GV = main::b
1992\& }
1993\& }
1994\& {
1995\& TYPE = null ===> (5)
1996\& (was rv2sv)
1997\& FLAGS = (SCALAR,KIDS)
1998\& {
1999\& 4 TYPE = gvsv ===> 5
2000\& FLAGS = (SCALAR)
2001\& GV = main::c
2002\& }
2003\& }
2004.Ve
2005.PP
2006This tree has 5 nodes (one per \f(CW\*(C`TYPE\*(C'\fR specifier), only 3 of them are
2007not optimized away (one per number in the left column). The immediate
2008children of the given node correspond to \f(CW\*(C`{}\*(C'\fR pairs on the same level
2009of indentation, thus this listing corresponds to the tree:
2010.PP
2011.Vb 5
2012\& add
2013\& / \e
2014\& null null
2015\& | |
2016\& gvsv gvsv
2017.Ve
2018.PP
2019The execution order is indicated by \f(CW\*(C`===>\*(C'\fR marks, thus it is \f(CW\*(C`3
20204 5 6\*(C'\fR (node \f(CW6\fR is not included into above listing), i.e.,
2021\&\f(CW\*(C`gvsv gvsv add whatever\*(C'\fR.
2022.PP
2023Each of these nodes represents an op, a fundamental operation inside the
2024Perl core. The code which implements each operation can be found in the
2025\&\fIpp*.c\fR files; the function which implements the op with type \f(CW\*(C`gvsv\*(C'\fR
2026is \f(CW\*(C`pp_gvsv\*(C'\fR, and so on. As the tree above shows, different ops have
2027different numbers of children: \f(CW\*(C`add\*(C'\fR is a binary operator, as one would
2028expect, and so has two children. To accommodate the various different
2029numbers of children, there are various types of op data structure, and
2030they link together in different ways.
2031.PP
2032The simplest type of op structure is \f(CW\*(C`OP\*(C'\fR: this has no children. Unary
2033operators, \f(CW\*(C`UNOP\*(C'\fRs, have one child, and this is pointed to by the
2034\&\f(CW\*(C`op_first\*(C'\fR field. Binary operators (\f(CW\*(C`BINOP\*(C'\fRs) have not only an
2035\&\f(CW\*(C`op_first\*(C'\fR field but also an \f(CW\*(C`op_last\*(C'\fR field. The most complex type of
2036op is a \f(CW\*(C`LISTOP\*(C'\fR, which has any number of children. In this case, the
2037first child is pointed to by \f(CW\*(C`op_first\*(C'\fR and the last child by
2038\&\f(CW\*(C`op_last\*(C'\fR. The children in between can be found by iteratively
2039following the \f(CW\*(C`op_sibling\*(C'\fR pointer from the first child to the last.
2040.PP
2041There are also two other op types: a \f(CW\*(C`PMOP\*(C'\fR holds a regular expression,
2042and has no children, and a \f(CW\*(C`LOOP\*(C'\fR may or may not have children. If the
2043\&\f(CW\*(C`op_children\*(C'\fR field is non\-zero, it behaves like a \f(CW\*(C`LISTOP\*(C'\fR. To
2044complicate matters, if a \f(CW\*(C`UNOP\*(C'\fR is actually a \f(CW\*(C`null\*(C'\fR op after
2045optimization (see \*(L"Compile pass 2: context propagation\*(R") it will still
2046have children in accordance with its former type.
2047.PP
2048Another way to examine the tree is to use a compiler back-end module, such
2049as B::Concise.
2050.Sh "Compile pass 1: check routines"
2051.IX Subsection "Compile pass 1: check routines"
2052The tree is created by the compiler while \fIyacc\fR code feeds it
2053the constructions it recognizes. Since \fIyacc\fR works bottom\-up, so does
2054the first pass of perl compilation.
2055.PP
2056What makes this pass interesting for perl developers is that some
2057optimization may be performed on this pass. This is optimization by
2058so-called \*(L"check routines\*(R". The correspondence between node names
2059and corresponding check routines is described in \fIopcode.pl\fR (do not
2060forget to run \f(CW\*(C`make regen_headers\*(C'\fR if you modify this file).
2061.PP
2062A check routine is called when the node is fully constructed except
2063for the execution-order thread. Since at this time there are no
2064back-links to the currently constructed node, one can do most any
2065operation to the top-level node, including freeing it and/or creating
2066new nodes above/below it.
2067.PP
2068The check routine returns the node which should be inserted into the
2069tree (if the top-level node was not modified, check routine returns
2070its argument).
2071.PP
2072By convention, check routines have names \f(CW\*(C`ck_*\*(C'\fR. They are usually
2073called from \f(CW\*(C`new*OP\*(C'\fR subroutines (or \f(CW\*(C`convert\*(C'\fR) (which in turn are
2074called from \fIperly.y\fR).
2075.Sh "Compile pass 1a: constant folding"
2076.IX Subsection "Compile pass 1a: constant folding"
2077Immediately after the check routine is called the returned node is
2078checked for being compile-time executable. If it is (the value is
2079judged to be constant) it is immediately executed, and a \fIconstant\fR
2080node with the \*(L"return value\*(R" of the corresponding subtree is
2081substituted instead. The subtree is deleted.
2082.PP
2083If constant folding was not performed, the execution-order thread is
2084created.
2085.Sh "Compile pass 2: context propagation"
2086.IX Subsection "Compile pass 2: context propagation"
2087When a context for a part of compile tree is known, it is propagated
2088down through the tree. At this time the context can have 5 values
2089(instead of 2 for runtime context): void, boolean, scalar, list, and
2090lvalue. In contrast with the pass 1 this pass is processed from top
2091to bottom: a node's context determines the context for its children.
2092.PP
2093Additional context-dependent optimizations are performed at this time.
2094Since at this moment the compile tree contains back-references (via
2095\&\*(L"thread\*(R" pointers), nodes cannot be \fIfree()\fRd now. To allow
2096optimized-away nodes at this stage, such nodes are \fInull()\fRified instead
2097of \fIfree()\fRing (i.e. their type is changed to \s-1OP_NULL\s0).
2098.Sh "Compile pass 3: peephole optimization"
2099.IX Subsection "Compile pass 3: peephole optimization"
2100After the compile tree for a subroutine (or for an \f(CW\*(C`eval\*(C'\fR or a file)
2101is created, an additional pass over the code is performed. This pass
2102is neither top-down or bottom\-up, but in the execution order (with
2103additional complications for conditionals). These optimizations are
2104done in the subroutine \fIpeep()\fR. Optimizations performed at this stage
2105are subject to the same restrictions as in the pass 2.
2106.Sh "Pluggable runops"
2107.IX Subsection "Pluggable runops"
2108The compile tree is executed in a runops function. There are two runops
2109functions, in \fIrun.c\fR and in \fIdump.c\fR. \f(CW\*(C`Perl_runops_debug\*(C'\fR is used
2110with \s-1DEBUGGING\s0 and \f(CW\*(C`Perl_runops_standard\*(C'\fR is used otherwise. For fine
2111control over the execution of the compile tree it is possible to provide
2112your own runops function.
2113.PP
2114It's probably best to copy one of the existing runops functions and
2115change it to suit your needs. Then, in the \s-1BOOT\s0 section of your \s-1XS\s0
2116file, add the line:
2117.PP
2118.Vb 1
2119\& PL_runops = my_runops;
2120.Ve
2121.PP
2122This function should be as efficient as possible to keep your programs
2123running as fast as possible.
2124.ie n .SH "Examining internal data structures with the ""dump"" functions"
2125.el .SH "Examining internal data structures with the \f(CWdump\fP functions"
2126.IX Header "Examining internal data structures with the dump functions"
2127To aid debugging, the source file \fIdump.c\fR contains a number of
2128functions which produce formatted output of internal data structures.
2129.PP
2130The most commonly used of these functions is \f(CW\*(C`Perl_sv_dump\*(C'\fR; it's used
2131for dumping SVs, AVs, HVs, and CVs. The \f(CW\*(C`Devel::Peek\*(C'\fR module calls
2132\&\f(CW\*(C`sv_dump\*(C'\fR to produce debugging output from Perl\-space, so users of that
2133module should already be familiar with its format.
2134.PP
2135\&\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
2136derivatives, and produces output similar to \f(CW\*(C`perl \-Dx\*(C'\fR; in fact,
2137\&\f(CW\*(C`Perl_dump_eval\*(C'\fR will dump the main root of the code being evaluated,
2138exactly like \f(CW\*(C`\-Dx\*(C'\fR.
2139.PP
2140Other useful functions are \f(CW\*(C`Perl_dump_sub\*(C'\fR, which turns a \f(CW\*(C`GV\*(C'\fR into an
2141op tree, \f(CW\*(C`Perl_dump_packsubs\*(C'\fR which calls \f(CW\*(C`Perl_dump_sub\*(C'\fR on all the
2142subroutines in a package like so: (Thankfully, these are all xsubs, so
2143there is no op tree)
2144.PP
2145.Vb 1
2146\& (gdb) print Perl_dump_packsubs(PL_defstash)
2147.Ve
2148.PP
2149.Vb 1
2150\& SUB attributes::bootstrap = (xsub 0x811fedc 0)
2151.Ve
2152.PP
2153.Vb 1
2154\& SUB UNIVERSAL::can = (xsub 0x811f50c 0)
2155.Ve
2156.PP
2157.Vb 1
2158\& SUB UNIVERSAL::isa = (xsub 0x811f304 0)
2159.Ve
2160.PP
2161.Vb 1
2162\& SUB UNIVERSAL::VERSION = (xsub 0x811f7ac 0)
2163.Ve
2164.PP
2165.Vb 1
2166\& SUB DynaLoader::boot_DynaLoader = (xsub 0x805b188 0)
2167.Ve
2168.PP
2169and \f(CW\*(C`Perl_dump_all\*(C'\fR, which dumps all the subroutines in the stash and
2170the op tree of the main root.
2171.SH "How multiple interpreters and concurrency are supported"
2172.IX Header "How multiple interpreters and concurrency are supported"
2173.Sh "Background and \s-1PERL_IMPLICIT_CONTEXT\s0"
2174.IX Subsection "Background and PERL_IMPLICIT_CONTEXT"
2175The Perl interpreter can be regarded as a closed box: it has an \s-1API\s0
2176for feeding it code or otherwise making it do things, but it also has
2177functions for its own use. This smells a lot like an object, and
2178there are ways for you to build Perl so that you can have multiple
2179interpreters, with one interpreter represented either as a C structure,
2180or inside a thread-specific structure. These structures contain all
2181the context, the state of that interpreter.
2182.PP
2183Two macros control the major Perl build flavors: \s-1MULTIPLICITY\s0 and
2184\&\s-1USE_5005THREADS\s0. The \s-1MULTIPLICITY\s0 build has a C structure
2185that packages all the interpreter state, and there is a similar thread-specific
2186data structure under \s-1USE_5005THREADS\s0. In both cases,
2187\&\s-1PERL_IMPLICIT_CONTEXT\s0 is also normally defined, and enables the
2188support for passing in a \*(L"hidden\*(R" first argument that represents all three
2189data structures.
2190.PP
2191All this obviously requires a way for the Perl internal functions to be
2192either subroutines taking some kind of structure as the first
2193argument, or subroutines taking nothing as the first argument. To
2194enable these two very different ways of building the interpreter,
2195the Perl source (as it does in so many other situations) makes heavy
2196use of macros and subroutine naming conventions.
2197.PP
2198First problem: deciding which functions will be public \s-1API\s0 functions and
2199which will be private. All functions whose names begin \f(CW\*(C`S_\*(C'\fR are private
2200(think \*(L"S\*(R" for \*(L"secret\*(R" or \*(L"static\*(R"). All other functions begin with
2201\&\*(L"Perl_\*(R", but just because a function begins with \*(L"Perl_\*(R" does not mean it is
2202part of the \s-1API\s0. (See \*(L"Internal Functions\*(R".) The easiest way to be \fBsure\fR a
2203function is part of the \s-1API\s0 is to find its entry in perlapi.
2204If it exists in perlapi, it's part of the \s-1API\s0. If it doesn't, and you
2205think it should be (i.e., you need it for your extension), send mail via
2206perlbug explaining why you think it should be.
2207.PP
2208Second problem: there must be a syntax so that the same subroutine
2209declarations and calls can pass a structure as their first argument,
2210or pass nothing. To solve this, the subroutines are named and
2211declared in a particular way. Here's a typical start of a static
2212function used within the Perl guts:
2213.PP
2214.Vb 2
2215\& STATIC void
2216\& S_incline(pTHX_ char *s)
2217.Ve
2218.PP
2219\&\s-1STATIC\s0 becomes \*(L"static\*(R" in C, and may be #define'd to nothing in some
2220configurations in future.
2221.PP
2222A public function (i.e. part of the internal \s-1API\s0, but not necessarily
2223sanctioned for use in extensions) begins like this:
2224.PP
2225.Vb 2
2226\& void
2227\& Perl_sv_setiv(pTHX_ SV* dsv, IV num)
2228.Ve
2229.PP
2230\&\f(CW\*(C`pTHX_\*(C'\fR is one of a number of macros (in perl.h) that hide the
2231details of the interpreter's context. \s-1THX\s0 stands for \*(L"thread\*(R", \*(L"this\*(R",
2232or \*(L"thingy\*(R", as the case may be. (And no, George Lucas is not involved. :\-)
2233The first character could be 'p' for a \fBp\fRrototype, 'a' for \fBa\fRrgument,
2234or '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
2235their variants.
2236.PP
2237When Perl is built without options that set \s-1PERL_IMPLICIT_CONTEXT\s0, there is no
2238first argument containing the interpreter's context. The trailing underscore
2239in the pTHX_ macro indicates that the macro expansion needs a comma
2240after the context argument because other arguments follow it. If
2241\&\s-1PERL_IMPLICIT_CONTEXT\s0 is not defined, pTHX_ will be ignored, and the
2242subroutine is not prototyped to take the extra argument. The form of the
2243macro without the trailing underscore is used when there are no additional
2244explicit arguments.
2245.PP
2246When a core function calls another, it must pass the context. This
2247is normally hidden via macros. Consider \f(CW\*(C`sv_setiv\*(C'\fR. It expands into
2248something like this:
2249.PP
2250.Vb 6
2251\& #ifdef PERL_IMPLICIT_CONTEXT
2252\& #define sv_setiv(a,b) Perl_sv_setiv(aTHX_ a, b)
2253\& /* can't do this for vararg functions, see below */
2254\& #else
2255\& #define sv_setiv Perl_sv_setiv
2256\& #endif
2257.Ve
2258.PP
2259This works well, and means that \s-1XS\s0 authors can gleefully write:
2260.PP
2261.Vb 1
2262\& sv_setiv(foo, bar);
2263.Ve
2264.PP
2265and still have it work under all the modes Perl could have been
2266compiled with.
2267.PP
2268This doesn't work so cleanly for varargs functions, though, as macros
2269imply that the number of arguments is known in advance. Instead we
2270either need to spell them out fully, passing \f(CW\*(C`aTHX_\*(C'\fR as the first
2271argument (the Perl core tends to do this with functions like
2272Perl_warner), or use a context-free version.
2273.PP
2274The context-free version of Perl_warner is called
2275Perl_warner_nocontext, and does not take the extra argument. Instead
2276it does dTHX; to get the context from thread-local storage. We
2277\&\f(CW\*(C`#define warner Perl_warner_nocontext\*(C'\fR so that extensions get source
2278compatibility at the expense of performance. (Passing an arg is
2279cheaper than grabbing it from thread-local storage.)
2280.PP
2281You can ignore [pad]THXx when browsing the Perl headers/sources.
2282Those are strictly for use within the core. Extensions and embedders
2283need only be aware of [pad]THX.
2284.Sh "So what happened to dTHR?"
2285.IX Subsection "So what happened to dTHR?"
2286\&\f(CW\*(C`dTHR\*(C'\fR was introduced in perl 5.005 to support the older thread model.
2287The older thread model now uses the \f(CW\*(C`THX\*(C'\fR mechanism to pass context
2288pointers around, so \f(CW\*(C`dTHR\*(C'\fR is not useful any more. Perl 5.6.0 and
2289later still have it for backward source compatibility, but it is defined
2290to be a no\-op.
2291.Sh "How do I use all this in extensions?"
2292.IX Subsection "How do I use all this in extensions?"
2293When Perl is built with \s-1PERL_IMPLICIT_CONTEXT\s0, extensions that call
2294any functions in the Perl \s-1API\s0 will need to pass the initial context
2295argument somehow. The kicker is that you will need to write it in
2296such a way that the extension still compiles when Perl hasn't been
2297built with \s-1PERL_IMPLICIT_CONTEXT\s0 enabled.
2298.PP
2299There are three ways to do this. First, the easy but inefficient way,
2300which is also the default, in order to maintain source compatibility
2301with extensions: whenever \s-1XSUB\s0.h is #included, it redefines the aTHX
2302and aTHX_ macros to call a function that will return the context.
2303Thus, something like:
2304.PP
2305.Vb 1
2306\& sv_setiv(sv, num);
2307.Ve
2308.PP
2309in your extension will translate to this when \s-1PERL_IMPLICIT_CONTEXT\s0 is
2310in effect:
2311.PP
2312.Vb 1
2313\& Perl_sv_setiv(Perl_get_context(), sv, num);
2314.Ve
2315.PP
2316or to this otherwise:
2317.PP
2318.Vb 1
2319\& Perl_sv_setiv(sv, num);
2320.Ve
2321.PP
2322You have to do nothing new in your extension to get this; since
2323the Perl library provides \fIPerl_get_context()\fR, it will all just
2324work.
2325.PP
2326The second, more efficient way is to use the following template for
2327your Foo.xs:
2328.PP
2329.Vb 4
2330\& #define PERL_NO_GET_CONTEXT /* we want efficiency */
2331\& #include "EXTERN.h"
2332\& #include "perl.h"
2333\& #include "XSUB.h"
2334.Ve
2335.PP
2336.Vb 1
2337\& static my_private_function(int arg1, int arg2);
2338.Ve
2339.PP
2340.Vb 6
2341\& static SV *
2342\& my_private_function(int arg1, int arg2)
2343\& {
2344\& dTHX; /* fetch context */
2345\& ... call many Perl API functions ...
2346\& }
2347.Ve
2348.PP
2349.Vb 1
2350\& [... etc ...]
2351.Ve
2352.PP
2353.Vb 1
2354\& MODULE = Foo PACKAGE = Foo
2355.Ve
2356.PP
2357.Vb 1
2358\& /* typical XSUB */
2359.Ve
2360.PP
2361.Vb 5
2362\& void
2363\& my_xsub(arg)
2364\& int arg
2365\& CODE:
2366\& my_private_function(arg, 10);
2367.Ve
2368.PP
2369Note that the only two changes from the normal way of writing an
2370extension is the addition of a \f(CW\*(C`#define PERL_NO_GET_CONTEXT\*(C'\fR before
2371including the Perl headers, followed by a \f(CW\*(C`dTHX;\*(C'\fR declaration at
2372the start of every function that will call the Perl \s-1API\s0. (You'll
2373know which functions need this, because the C compiler will complain
2374that there's an undeclared identifier in those functions.) No changes
2375are needed for the XSUBs themselves, because the \s-1\fIXS\s0()\fR macro is
2376correctly defined to pass in the implicit context if needed.
2377.PP
2378The third, even more efficient way is to ape how it is done within
2379the Perl guts:
2380.PP
2381.Vb 4
2382\& #define PERL_NO_GET_CONTEXT /* we want efficiency */
2383\& #include "EXTERN.h"
2384\& #include "perl.h"
2385\& #include "XSUB.h"
2386.Ve
2387.PP
2388.Vb 2
2389\& /* pTHX_ only needed for functions that call Perl API */
2390\& static my_private_function(pTHX_ int arg1, int arg2);
2391.Ve
2392.PP
2393.Vb 6
2394\& static SV *
2395\& my_private_function(pTHX_ int arg1, int arg2)
2396\& {
2397\& /* dTHX; not needed here, because THX is an argument */
2398\& ... call Perl API functions ...
2399\& }
2400.Ve
2401.PP
2402.Vb 1
2403\& [... etc ...]
2404.Ve
2405.PP
2406.Vb 1
2407\& MODULE = Foo PACKAGE = Foo
2408.Ve
2409.PP
2410.Vb 1
2411\& /* typical XSUB */
2412.Ve
2413.PP
2414.Vb 5
2415\& void
2416\& my_xsub(arg)
2417\& int arg
2418\& CODE:
2419\& my_private_function(aTHX_ arg, 10);
2420.Ve
2421.PP
2422This implementation never has to fetch the context using a function
2423call, since it is always passed as an extra argument. Depending on
2424your needs for simplicity or efficiency, you may mix the previous
2425two approaches freely.
2426.PP
2427Never add a comma after \f(CW\*(C`pTHX\*(C'\fR yourself\*(--always use the form of the
2428macro with the underscore for functions that take explicit arguments,
2429or the form without the argument for functions with no explicit arguments.
2430.Sh "Should I do anything special if I call perl from multiple threads?"
2431.IX Subsection "Should I do anything special if I call perl from multiple threads?"
2432If you create interpreters in one thread and then proceed to call them in
2433another, you need to make sure perl's own Thread Local Storage (\s-1TLS\s0) slot is
2434initialized correctly in each of those threads.
2435.PP
2436The \f(CW\*(C`perl_alloc\*(C'\fR and \f(CW\*(C`perl_clone\*(C'\fR \s-1API\s0 functions will automatically set
2437the \s-1TLS\s0 slot to the interpreter they created, so that there is no need to do
2438anything special if the interpreter is always accessed in the same thread that
2439created it, and that thread did not create or call any other interpreters
2440afterwards. If that is not the case, you have to set the \s-1TLS\s0 slot of the
2441thread before calling any functions in the Perl \s-1API\s0 on that particular
2442interpreter. This is done by calling the \f(CW\*(C`PERL_SET_CONTEXT\*(C'\fR macro in that
2443thread as the first thing you do:
2444.PP
2445.Vb 2
2446\& /* do this before doing anything else with some_perl */
2447\& PERL_SET_CONTEXT(some_perl);
2448.Ve
2449.PP
2450.Vb 1
2451\& ... other Perl API calls on some_perl go here ...
2452.Ve
2453.Sh "Future Plans and \s-1PERL_IMPLICIT_SYS\s0"
2454.IX Subsection "Future Plans and PERL_IMPLICIT_SYS"
2455Just as \s-1PERL_IMPLICIT_CONTEXT\s0 provides a way to bundle up everything
2456that the interpreter knows about itself and pass it around, so too are
2457there plans to allow the interpreter to bundle up everything it knows
2458about the environment it's running on. This is enabled with the
2459\&\s-1PERL_IMPLICIT_SYS\s0 macro. Currently it only works with \s-1USE_ITHREADS\s0
2460and \s-1USE_5005THREADS\s0 on Windows (see inside iperlsys.h).
2461.PP
2462This allows the ability to provide an extra pointer (called the \*(L"host\*(R"
2463environment) for all the system calls. This makes it possible for
2464all the system stuff to maintain their own state, broken down into
2465seven C structures. These are thin wrappers around the usual system
2466calls (see win32/perllib.c) for the default perl executable, but for a
2467more ambitious host (like the one that would do \fIfork()\fR emulation) all
2468the extra work needed to pretend that different interpreters are
2469actually different \*(L"processes\*(R", would be done here.
2470.PP
2471The Perl engine/interpreter and the host are orthogonal entities.
2472There could be one or more interpreters in a process, and one or
2473more \*(L"hosts\*(R", with free association between them.
2474.SH "Internal Functions"
2475.IX Header "Internal Functions"
2476All of Perl's internal functions which will be exposed to the outside
2477world are prefixed by \f(CW\*(C`Perl_\*(C'\fR so that they will not conflict with \s-1XS\s0
2478functions or functions used in a program in which Perl is embedded.
2479Similarly, all global variables begin with \f(CW\*(C`PL_\*(C'\fR. (By convention,
2480static functions start with \f(CW\*(C`S_\*(C'\fR.)
2481.PP
2482Inside the Perl core, you can get at the functions either with or
2483without the \f(CW\*(C`Perl_\*(C'\fR prefix, thanks to a bunch of defines that live in
2484\&\fIembed.h\fR. This header file is generated automatically from
2485\&\fIembed.pl\fR and \fIembed.fnc\fR. \fIembed.pl\fR also creates the prototyping
2486header files for the internal functions, generates the documentation
2487and a lot of other bits and pieces. It's important that when you add
2488a new function to the core or change an existing one, you change the
2489data in the table in \fIembed.fnc\fR as well. Here's a sample entry from
2490that table:
2491.PP
2492.Vb 1
2493\& Apd |SV** |av_fetch |AV* ar|I32 key|I32 lval
2494.Ve
2495.PP
2496The second column is the return type, the third column the name. Columns
2497after that are the arguments. The first column is a set of flags:
2498.IP "A" 3
2499.IX Item "A"
2500This function is a part of the public \s-1API\s0. All such functions should also
2501have 'd', very few do not.
2502.IP "p" 3
2503.IX Item "p"
2504This function has a \f(CW\*(C`Perl_\*(C'\fR prefix; i.e. it is defined as
2505\&\f(CW\*(C`Perl_av_fetch\*(C'\fR.
2506.IP "d" 3
2507.IX Item "d"
2508This function has documentation using the \f(CW\*(C`apidoc\*(C'\fR feature which we'll
2509look at in a second. Some functions have 'd' but not 'A'; docs are good.
2510.PP
2511Other available flags are:
2512.IP "s" 3
2513.IX Item "s"
2514This is a static function and is defined as \f(CW\*(C`STATIC S_whatever\*(C'\fR, and
2515usually called within the sources as \f(CW\*(C`whatever(...)\*(C'\fR.
2516.IP "n" 3
2517.IX Item "n"
2518This does not need a interpreter context, so the definition has no
2519\&\f(CW\*(C`pTHX\*(C'\fR, and it follows that callers don't use \f(CW\*(C`aTHX\*(C'\fR. (See
2520\&\*(L"Background and \s-1PERL_IMPLICIT_CONTEXT\s0\*(R" in perlguts.)
2521.IP "r" 3
2522.IX Item "r"
2523This function never returns; \f(CW\*(C`croak\*(C'\fR, \f(CW\*(C`exit\*(C'\fR and friends.
2524.IP "f" 3
2525.IX Item "f"
2526This function takes a variable number of arguments, \f(CW\*(C`printf\*(C'\fR style.
2527The argument list should end with \f(CW\*(C`...\*(C'\fR, like this:
2528.Sp
2529.Vb 1
2530\& Afprd |void |croak |const char* pat|...
2531.Ve
2532.IP "M" 3
2533.IX Item "M"
2534This function is part of the experimental development \s-1API\s0, and may change
2535or disappear without notice.
2536.IP "o" 3
2537This function should not have a compatibility macro to define, say,
2538\&\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.
2539.IP "x" 3
2540.IX Item "x"
2541This function isn't exported out of the Perl core.
2542.IP "m" 3
2543.IX Item "m"
2544This is implemented as a macro.
2545.IP "X" 3
2546.IX Item "X"
2547This function is explicitly exported.
2548.IP "E" 3
2549.IX Item "E"
2550This function is visible to extensions included in the Perl core.
2551.IP "b" 3
2552.IX Item "b"
2553Binary backward compatibility; this function is a macro but also has
2554a \f(CW\*(C`Perl_\*(C'\fR implementation (which is exported).
2555.IP "others" 3
2556.IX Item "others"
2557See the comments at the top of \f(CW\*(C`embed.fnc\*(C'\fR for others.
2558.PP
2559If you edit \fIembed.pl\fR or \fIembed.fnc\fR, you will need to run
2560\&\f(CW\*(C`make regen_headers\*(C'\fR to force a rebuild of \fIembed.h\fR and other
2561auto-generated files.
2562.Sh "Formatted Printing of IVs, UVs, and NVs"
2563.IX Subsection "Formatted Printing of IVs, UVs, and NVs"
2564If you are printing IVs, UVs, or \s-1NVS\s0 instead of the \fIstdio\fR\|(3) style
2565formatting codes like \f(CW%d\fR, \f(CW%ld\fR, \f(CW%f\fR, you should use the
2566following macros for portability
2567.PP
2568.Vb 7
2569\& IVdf IV in decimal
2570\& UVuf UV in decimal
2571\& UVof UV in octal
2572\& UVxf UV in hexadecimal
2573\& NVef NV %e-like
2574\& NVff NV %f-like
2575\& NVgf NV %g-like
2576.Ve
2577.PP
2578These will take care of 64\-bit integers and long doubles.
2579For example:
2580.PP
2581.Vb 1
2582\& printf("IV is %"IVdf"\en", iv);
2583.Ve
2584.PP
2585The IVdf will expand to whatever is the correct format for the IVs.
2586.PP
2587If you are printing addresses of pointers, use UVxf combined
2588with \s-1\fIPTR2UV\s0()\fR, do not use \f(CW%lx\fR or \f(CW%p\fR.
2589.Sh "Pointer-To-Integer and Integer-To-Pointer"
2590.IX Subsection "Pointer-To-Integer and Integer-To-Pointer"
2591Because pointer size does not necessarily equal integer size,
2592use the follow macros to do it right.
2593.PP
2594.Vb 4
2595\& PTR2UV(pointer)
2596\& PTR2IV(pointer)
2597\& PTR2NV(pointer)
2598\& INT2PTR(pointertotype, integer)
2599.Ve
2600.PP
2601For example:
2602.PP
2603.Vb 2
2604\& IV iv = ...;
2605\& SV *sv = INT2PTR(SV*, iv);
2606.Ve
2607.PP
2608and
2609.PP
2610.Vb 2
2611\& AV *av = ...;
2612\& UV uv = PTR2UV(av);
2613.Ve
2614.Sh "Source Documentation"
2615.IX Subsection "Source Documentation"
2616There's an effort going on to document the internal functions and
2617automatically produce reference manuals from them \- perlapi is one
2618such manual which details all the functions which are available to \s-1XS\s0
2619writers. perlintern is the autogenerated manual for the functions
2620which are not part of the \s-1API\s0 and are supposedly for internal use only.
2621.PP
2622Source documentation is created by putting \s-1POD\s0 comments into the C
2623source, like this:
2624.PP
2625.Vb 2
2626\& /*
2627\& =for apidoc sv_setiv
2628.Ve
2629.PP
2630.Vb 2
2631\& Copies an integer into the given SV. Does not handle 'set' magic. See
2632\& C<sv_setiv_mg>.
2633.Ve
2634.PP
2635.Vb 2
2636\& =cut
2637\& */
2638.Ve
2639.PP
2640Please try and supply some documentation if you add functions to the
2641Perl core.
2642.Sh "Backwards compatibility"
2643.IX Subsection "Backwards compatibility"
2644The Perl \s-1API\s0 changes over time. New functions are added or the interfaces
2645of existing functions are changed. The \f(CW\*(C`Devel::PPPort\*(C'\fR module tries to
2646provide compatibility code for some of these changes, so \s-1XS\s0 writers don't
2647have to code it themselves when supporting multiple versions of Perl.
2648.PP
2649\&\f(CW\*(C`Devel::PPPort\*(C'\fR generates a C header file \fIppport.h\fR that can also
2650be run as a Perl script. To generate \fIppport.h\fR, run:
2651.PP
2652.Vb 1
2653\& perl -MDevel::PPPort -eDevel::PPPort::WriteFile
2654.Ve
2655.PP
2656Besides checking existing \s-1XS\s0 code, the script can also be used to retrieve
2657compatibility information for various \s-1API\s0 calls using the \f(CW\*(C`\-\-api\-info\*(C'\fR
2658command line switch. For example:
2659.PP
2660.Vb 1
2661\& % perl ppport.h --api-info=sv_magicext
2662.Ve
2663.PP
2664For details, see \f(CW\*(C`perldoc ppport.h\*(C'\fR.
2665.SH "Unicode Support"
2666.IX Header "Unicode Support"
2667Perl 5.6.0 introduced Unicode support. It's important for porters and \s-1XS\s0
2668writers to understand this support and make sure that the code they
2669write does not corrupt Unicode data.
2670.Sh "What \fBis\fP Unicode, anyway?"
2671.IX Subsection "What is Unicode, anyway?"
2672In the olden, less enlightened times, we all used to use \s-1ASCII\s0. Most of
2673us did, anyway. The big problem with \s-1ASCII\s0 is that it's American. Well,
2674no, that's not actually the problem; the problem is that it's not
2675particularly useful for people who don't use the Roman alphabet. What
2676used to happen was that particular languages would stick their own
2677alphabet in the upper range of the sequence, between 128 and 255. Of
2678course, we then ended up with plenty of variants that weren't quite
2679\&\s-1ASCII\s0, and the whole point of it being a standard was lost.
2680.PP
2681Worse still, if you've got a language like Chinese or
2682Japanese that has hundreds or thousands of characters, then you really
2683can't fit them into a mere 256, so they had to forget about \s-1ASCII\s0
2684altogether, and build their own systems using pairs of numbers to refer
2685to one character.
2686.PP
2687To fix this, some people formed Unicode, Inc. and
2688produced a new character set containing all the characters you can
2689possibly think of and more. There are several ways of representing these
2690characters, and the one Perl uses is called \s-1UTF\-8\s0. \s-1UTF\-8\s0 uses
2691a variable number of bytes to represent a character, instead of just
2692one. You can learn more about Unicode at http://www.unicode.org/
2693.Sh "How can I recognise a \s-1UTF\-8\s0 string?"
2694.IX Subsection "How can I recognise a UTF-8 string?"
2695You can't. This is because \s-1UTF\-8\s0 data is stored in bytes just like
2696non\-UTF\-8 data. The Unicode character 200, (\f(CW0xC8\fR for you hex types)
2697capital E with a grave accent, is represented by the two bytes
2698\&\f(CW\*(C`v196.172\*(C'\fR. Unfortunately, the non-Unicode string \f(CW\*(C`chr(196).chr(172)\*(C'\fR
2699has that byte sequence as well. So you can't tell just by looking \- this
2700is what makes Unicode input an interesting problem.
2701.PP
2702The \s-1API\s0 function \f(CW\*(C`is_utf8_string\*(C'\fR can help; it'll tell you if a string
2703contains only valid \s-1UTF\-8\s0 characters. However, it can't do the work for
2704you. On a character-by-character basis, \f(CW\*(C`is_utf8_char\*(C'\fR will tell you
2705whether the current character in a string is valid \s-1UTF\-8\s0.
2706.Sh "How does \s-1UTF\-8\s0 represent Unicode characters?"
2707.IX Subsection "How does UTF-8 represent Unicode characters?"
2708As mentioned above, \s-1UTF\-8\s0 uses a variable number of bytes to store a
2709character. Characters with values 1...128 are stored in one byte, just
2710like good ol' \s-1ASCII\s0. Character 129 is stored as \f(CW\*(C`v194.129\*(C'\fR; this
2711continues up to character 191, which is \f(CW\*(C`v194.191\*(C'\fR. Now we've run out of
2712bits (191 is binary \f(CW10111111\fR) so we move on; 192 is \f(CW\*(C`v195.128\*(C'\fR. And
2713so it goes on, moving to three bytes at character 2048.
2714.PP
2715Assuming you know you're dealing with a \s-1UTF\-8\s0 string, you can find out
2716how long the first character in it is with the \f(CW\*(C`UTF8SKIP\*(C'\fR macro:
2717.PP
2718.Vb 2
2719\& char *utf = "\e305\e233\e340\e240\e201";
2720\& I32 len;
2721.Ve
2722.PP
2723.Vb 3
2724\& len = UTF8SKIP(utf); /* len is 2 here */
2725\& utf += len;
2726\& len = UTF8SKIP(utf); /* len is 3 here */
2727.Ve
2728.PP
2729Another way to skip over characters in a \s-1UTF\-8\s0 string is to use
2730\&\f(CW\*(C`utf8_hop\*(C'\fR, which takes a string and a number of characters to skip
2731over. You're on your own about bounds checking, though, so don't use it
2732lightly.
2733.PP
2734All bytes in a multi-byte \s-1UTF\-8\s0 character will have the high bit set,
2735so you can test if you need to do something special with this
2736character like this (the \s-1\fIUTF8_IS_INVARIANT\s0()\fR is a macro that tests
2737whether the byte can be encoded as a single byte even in \s-1UTF\-8\s0):
2738.PP
2739.Vb 2
2740\& U8 *utf;
2741\& UV uv; /* Note: a UV, not a U8, not a char */
2742.Ve
2743.PP
2744.Vb 6
2745\& if (!UTF8_IS_INVARIANT(*utf))
2746\& /* Must treat this as UTF-8 */
2747\& uv = utf8_to_uv(utf);
2748\& else
2749\& /* OK to treat this character as a byte */
2750\& uv = *utf;
2751.Ve
2752.PP
2753You can also see in that example that we use \f(CW\*(C`utf8_to_uv\*(C'\fR to get the
2754value of the character; the inverse function \f(CW\*(C`uv_to_utf8\*(C'\fR is available
2755for putting a \s-1UV\s0 into \s-1UTF\-8:\s0
2756.PP
2757.Vb 6
2758\& if (!UTF8_IS_INVARIANT(uv))
2759\& /* Must treat this as UTF8 */
2760\& utf8 = uv_to_utf8(utf8, uv);
2761\& else
2762\& /* OK to treat this character as a byte */
2763\& *utf8++ = uv;
2764.Ve
2765.PP
2766You \fBmust\fR convert characters to UVs using the above functions if
2767you're ever in a situation where you have to match \s-1UTF\-8\s0 and non\-UTF\-8
2768characters. You may not skip over \s-1UTF\-8\s0 characters in this case. If you
2769do this, you'll lose the ability to match hi-bit non\-UTF\-8 characters;
2770for instance, if your \s-1UTF\-8\s0 string contains \f(CW\*(C`v196.172\*(C'\fR, and you skip
2771that character, you can never match a \f(CW\*(C`chr(200)\*(C'\fR in a non\-UTF\-8 string.
2772So don't do that!
2773.Sh "How does Perl store \s-1UTF\-8\s0 strings?"
2774.IX Subsection "How does Perl store UTF-8 strings?"
2775Currently, Perl deals with Unicode strings and non-Unicode strings
2776slightly differently. If a string has been identified as being \s-1UTF\-8\s0
2777encoded, Perl will set a flag in the \s-1SV\s0, \f(CW\*(C`SVf_UTF8\*(C'\fR. You can check and
2778manipulate this flag with the following macros:
2779.PP
2780.Vb 3
2781\& SvUTF8(sv)
2782\& SvUTF8_on(sv)
2783\& SvUTF8_off(sv)
2784.Ve
2785.PP
2786This flag has an important effect on Perl's treatment of the string: if
2787Unicode data is not properly distinguished, regular expressions,
2788\&\f(CW\*(C`length\*(C'\fR, \f(CW\*(C`substr\*(C'\fR and other string handling operations will have
2789undesirable results.
2790.PP
2791The problem comes when you have, for instance, a string that isn't
2792flagged is \s-1UTF\-8\s0, and contains a byte sequence that could be \s-1UTF\-8\s0 \-
2793especially when combining non\-UTF\-8 and \s-1UTF\-8\s0 strings.
2794.PP
2795Never forget that the \f(CW\*(C`SVf_UTF8\*(C'\fR flag is separate to the \s-1PV\s0 value; you
2796need be sure you don't accidentally knock it off while you're
2797manipulating SVs. More specifically, you cannot expect to do this:
2798.PP
2799.Vb 4
2800\& SV *sv;
2801\& SV *nsv;
2802\& STRLEN len;
2803\& char *p;
2804.Ve
2805.PP
2806.Vb 3
2807\& p = SvPV(sv, len);
2808\& frobnicate(p);
2809\& nsv = newSVpvn(p, len);
2810.Ve
2811.PP
2812The \f(CW\*(C`char*\*(C'\fR string does not tell you the whole story, and you can't
2813copy or reconstruct an \s-1SV\s0 just by copying the string value. Check if the
2814old \s-1SV\s0 has the \s-1UTF\-8\s0 flag set, and act accordingly:
2815.PP
2816.Vb 5
2817\& p = SvPV(sv, len);
2818\& frobnicate(p);
2819\& nsv = newSVpvn(p, len);
2820\& if (SvUTF8(sv))
2821\& SvUTF8_on(nsv);
2822.Ve
2823.PP
2824In fact, your \f(CW\*(C`frobnicate\*(C'\fR function should be made aware of whether or
2825not it's dealing with \s-1UTF\-8\s0 data, so that it can handle the string
2826appropriately.
2827.PP
2828Since just passing an \s-1SV\s0 to an \s-1XS\s0 function and copying the data of
2829the \s-1SV\s0 is not enough to copy the \s-1UTF\-8\s0 flags, even less right is just
2830passing a \f(CW\*(C`char *\*(C'\fR to an \s-1XS\s0 function.
2831.Sh "How do I convert a string to \s-1UTF\-8\s0?"
2832.IX Subsection "How do I convert a string to UTF-8?"
2833If you're mixing \s-1UTF\-8\s0 and non\-UTF\-8 strings, you might find it necessary
2834to upgrade one of the strings to \s-1UTF\-8\s0. If you've got an \s-1SV\s0, the easiest
2835way to do this is:
2836.PP
2837.Vb 1
2838\& sv_utf8_upgrade(sv);
2839.Ve
2840.PP
2841However, you must not do this, for example:
2842.PP
2843.Vb 2
2844\& if (!SvUTF8(left))
2845\& sv_utf8_upgrade(left);
2846.Ve
2847.PP
2848If you do this in a binary operator, you will actually change one of the
2849strings that came into the operator, and, while it shouldn't be noticeable
2850by the end user, it can cause problems.
2851.PP
2852Instead, \f(CW\*(C`bytes_to_utf8\*(C'\fR will give you a UTF\-8\-encoded \fBcopy\fR of its
2853string argument. This is useful for having the data available for
2854comparisons and so on, without harming the original \s-1SV\s0. There's also
2855\&\f(CW\*(C`utf8_to_bytes\*(C'\fR to go the other way, but naturally, this will fail if
2856the string contains any characters above 255 that can't be represented
2857in a single byte.
2858.Sh "Is there anything else I need to know?"
2859.IX Subsection "Is there anything else I need to know?"
2860Not really. Just remember these things:
2861.IP "\(bu" 3
2862There's no way to tell if a string is \s-1UTF\-8\s0 or not. You can tell if an \s-1SV\s0
2863is \s-1UTF\-8\s0 by looking at is \f(CW\*(C`SvUTF8\*(C'\fR flag. Don't forget to set the flag if
2864something should be \s-1UTF\-8\s0. Treat the flag as part of the \s-1PV\s0, even though
2865it's not \- if you pass on the \s-1PV\s0 to somewhere, pass on the flag too.
2866.IP "\(bu" 3
2867If a string is \s-1UTF\-8\s0, \fBalways\fR use \f(CW\*(C`utf8_to_uv\*(C'\fR to get at the value,
2868unless \f(CW\*(C`UTF8_IS_INVARIANT(*s)\*(C'\fR in which case you can use \f(CW*s\fR.
2869.IP "\(bu" 3
2870When writing a character \f(CW\*(C`uv\*(C'\fR to a \s-1UTF\-8\s0 string, \fBalways\fR use
2871\&\f(CW\*(C`uv_to_utf8\*(C'\fR, unless \f(CW\*(C`UTF8_IS_INVARIANT(uv))\*(C'\fR in which case
2872you can use \f(CW\*(C`*s = uv\*(C'\fR.
2873.IP "\(bu" 3
2874Mixing \s-1UTF\-8\s0 and non\-UTF\-8 strings is tricky. Use \f(CW\*(C`bytes_to_utf8\*(C'\fR to get
2875a new string which is \s-1UTF\-8\s0 encoded. There are tricks you can use to
2876delay deciding whether you need to use a \s-1UTF\-8\s0 string until you get to a
2877high character \- \f(CW\*(C`HALF_UPGRADE\*(C'\fR is one of those.
2878.SH "Custom Operators"
2879.IX Header "Custom Operators"
2880Custom operator support is a new experimental feature that allows you to
2881define your own ops. This is primarily to allow the building of
2882interpreters for other languages in the Perl core, but it also allows
2883optimizations through the creation of \*(L"macro\-ops\*(R" (ops which perform the
2884functions of multiple ops which are usually executed together, such as
2885\&\f(CW\*(C`gvsv, gvsv, add\*(C'\fR.)
2886.PP
2887This feature is implemented as a new op type, \f(CW\*(C`OP_CUSTOM\*(C'\fR. The Perl
2888core does not \*(L"know\*(R" anything special about this op type, and so it will
2889not be involved in any optimizations. This also means that you can
2890define your custom ops to be any op structure \- unary, binary, list and
2891so on \- you like.
2892.PP
2893It's important to know what custom operators won't do for you. They
2894won't let you add new syntax to Perl, directly. They won't even let you
2895add new keywords, directly. In fact, they won't change the way Perl
2896compiles a program at all. You have to do those changes yourself, after
2897Perl has compiled the program. You do this either by manipulating the op
2898tree using a \f(CW\*(C`CHECK\*(C'\fR block and the \f(CW\*(C`B::Generate\*(C'\fR module, or by adding
2899a custom peephole optimizer with the \f(CW\*(C`optimize\*(C'\fR module.
2900.PP
2901When you do this, you replace ordinary Perl ops with custom ops by
2902creating ops with the type \f(CW\*(C`OP_CUSTOM\*(C'\fR and the \f(CW\*(C`pp_addr\*(C'\fR of your own
2903\&\s-1PP\s0 function. This should be defined in \s-1XS\s0 code, and should look like
2904the \s-1PP\s0 ops in \f(CW\*(C`pp_*.c\*(C'\fR. You are responsible for ensuring that your op
2905takes the appropriate number of values from the stack, and you are
2906responsible for adding stack marks if necessary.
2907.PP
2908You should also \*(L"register\*(R" your op with the Perl interpreter so that it
2909can produce sensible error and warning messages. Since it is possible to
2910have multiple custom ops within the one \*(L"logical\*(R" op type \f(CW\*(C`OP_CUSTOM\*(C'\fR,
2911Perl uses the value of \f(CW\*(C`o\->op_ppaddr\*(C'\fR as a key into the
2912\&\f(CW\*(C`PL_custom_op_descs\*(C'\fR and \f(CW\*(C`PL_custom_op_names\*(C'\fR hashes. This means you
2913need to enter a name and description for your op at the appropriate
2914place in the \f(CW\*(C`PL_custom_op_names\*(C'\fR and \f(CW\*(C`PL_custom_op_descs\*(C'\fR hashes.
2915.PP
2916Forthcoming versions of \f(CW\*(C`B::Generate\*(C'\fR (version 1.0 and above) should
2917directly support the creation of custom ops by name.
2918.SH "AUTHORS"
2919.IX Header "AUTHORS"
2920Until May 1997, this document was maintained by Jeff Okamoto
2921<okamoto@corp.hp.com>. It is now maintained as part of Perl
2922itself by the Perl 5 Porters <perl5\-porters@perl.org>.
2923.PP
2924With lots of help and suggestions from Dean Roehrich, Malcolm Beattie,
2925Andreas Koenig, Paul Hudson, Ilya Zakharevich, Paul Marquess, Neil
2926Bowers, Matthew Green, Tim Bunce, Spider Boardman, Ulrich Pfeifer,
2927Stephen McCamant, and Gurusamy Sarathy.
2928.SH "SEE ALSO"
2929.IX Header "SEE ALSO"
2930\&\fIperlapi\fR\|(1), \fIperlintern\fR\|(1), \fIperlxs\fR\|(1), \fIperlembed\fR\|(1)