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