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