<?xml version='1.0' encoding='utf-8'?>
<pod xmlns="http://axkit.org/ns/2000/pod2xml">
<head>
	<title>perlguts - Introduction to the Perl API</title>
</head>
<sect1>
<title>perlguts - Introduction to the Perl API</title>
<para>
perlguts - Perl API の紹介
</para>
</sect1>
<sect1>
<title>DESCRIPTION</title>
<para>
This document attempts to describe how to use the Perl API, as well as
to provide some info on the basic workings of the Perl core. It is far
from complete and probably contains many errors. Please refer any
questions or comments to the author below.
</para>
<para>
このドキュメントでは Perl API の使い方、および Perl コアの基本的な動作に
関するいくばくかの情報を提供しようとしています。
完璧からは程遠いものですし、間違いも多いと思います。
疑問点やコメントは後述する著者に対して行なってください。
</para>
</sect1>
<sect1>
<title>Variables</title>
<para>
(変数)
</para>
<sect2>
<title>Datatypes</title>
<para>
(データ型)
</para>
<para>
Perl has three typedefs that handle Perl's three main data types:
</para>
<para>
Perl では、主となる三つのデータ型を扱うために三つの型定義を行なっています:
</para>
<verbatim><![CDATA[
SV  Scalar Value
AV  Array Value
HV  Hash Value
]]></verbatim>
<para>
Each typedef has specific routines that manipulate the various data types.
</para>
<para>
それぞれの typedef には様々なデータ型を操作するための特別なルーチンが
用意されています。
</para>
</sect2>
<sect2>
<title>What is an &quot;IV&quot;?</title>
<para>
(&quot;IV&quot; ってなに?)
</para>
<para>
Perl uses a special typedef IV which is a simple signed integer type that is
guaranteed to be large enough to hold a pointer (as well as an integer).
Additionally, there is the UV, which is simply an unsigned IV.
</para>
<para>
Perl では、符号付き整数でもポインタでも十分に入れることのできる特別な 
typedef である IV を使います。
更に、単に符号なしの IV である UV もあります。
</para>
<para>
Perl also uses two special typedefs, I32 and I16, which will always be at
least 32-bits and 16-bits long, respectively. (Again, there are U32 and U16,
as well.)  They will usually be exactly 32 and 16 bits long, but on Crays
they will both be 64 bits.
</para>
<para>
Perl はまた、二つの特殊な typedef である I32 と I16 を使っています。
これらはそれぞれ、常に最低 32bit、16bit の長さを持っているものです。
(再び、同様に U32 と U16 もあります。)
これらは普通は正確に 32 ビットと 16 ビットですが、Cray では両方とも
64 ビットです。
</para>
</sect2>
<sect2>
<title>Working with SVs</title>
<para>
(SV に対する作業)
</para>
<para>
An SV can be created and loaded with one command.  There are five types of
values that can be loaded: an integer value (IV), an unsigned integer
value (UV), a double (NV), a string (PV), and another scalar (SV).
</para>
<para>
SV は、1 つのコマンドで生成し、値をロードすることができます。
ロードできる値の型には、整数 (IV)、符号なし整数 (UV)、
倍精度 (NV)、文字列 (PV)、その他のスカラ (SV) があります。
</para>
<para>
The seven routines are:
</para>
<para>
これらを行なう、7 つのルーチンは:
</para>
<verbatim><![CDATA[
SV*  newSViv(IV);
SV*  newSVuv(UV);
SV*  newSVnv(double);
SV*  newSVpv(const char*, STRLEN);
SV*  newSVpvn(const char*, STRLEN);
SV*  newSVpvf(const char*, ...);
SV*  newSVsv(SV*);
]]></verbatim>
<para>
<code>STRLEN</code> is an integer type (Size_t, usually defined as size_t in
<filename>config.h</filename>) guaranteed to be large enough to represent the size of
any string that perl can handle.
</para>
<para>
<code>STRLEN</code> は perl が扱えるどんな文字列のサイズも表現するのに十分なだけの
大きさを持つことが保証されている整数型(Size_t, 普通は <filename>config.h</filename> で
size_t として定義されています)。
</para>
<para>
In the unlikely case of a SV requiring more complex initialisation, you
can create an empty SV with newSV(len).  If <code>len</code> is 0 an empty SV of
type NULL is returned, else an SV of type PV is returned with len + 1 (for
the NUL) bytes of storage allocated, accessible via SvPVX.  In both cases
the SV has value undef.
</para>
<para>
あまりなさそうですが、SV がもっと複雑な初期化を必要とする場合、
newSV(len) で空の SV も作成できます。
もし <code>len</code> が 0 なら、NULL 型の空の SV が返され、さもなければ
PV 型の SV は、SvPVX でアクセスできる len + 1 (NUL のため) バイトの領域を
割り当てられて返されます。
両方の場合で、SV の値は未定義値です。
</para>
<verbatim><![CDATA[
SV *sv = newSV(0);   /* no storage allocated  */
SV *sv = newSV(10);  /* 10 (+1) bytes of uninitialised storage allocated  */
]]></verbatim>
<para>
To change the value of an <emphasis>already-existing</emphasis> SV, there are eight routines:
</para>
<para>
<emphasis>既に存在する</emphasis> スカラの値を変更するために 8 つのルーチンがあります:
</para>
<verbatim><![CDATA[
void  sv_setiv(SV*, IV);
void  sv_setuv(SV*, UV);
void  sv_setnv(SV*, double);
void  sv_setpv(SV*, const char*);
void  sv_setpvn(SV*, const char*, STRLEN)
void  sv_setpvf(SV*, const char*, ...);
void  sv_vsetpvfn(SV*, const char*, STRLEN, va_list *, SV **, I32, bool *);
void  sv_setsv(SV*, SV*);
]]></verbatim>
<para>
Notice that you can choose to specify the length of the string to be
assigned by using <code>sv_setpvn</code>, <code>newSVpvn</code>, or <code>newSVpv</code>, or you may
allow Perl to calculate the length by using <code>sv_setpv</code> or by specifying
0 as the second argument to <code>newSVpv</code>.  Be warned, though, that Perl will
determine the string's length by using <code>strlen</code>, which depends on the
string terminating with a NUL character.
</para>
<para>
代入すべき文字列の長さを <code>sv_setpvn</code> や <code>newSVpv</code>、あるいは
<code>newSVpv</code> を使って指定することもできますし、<code>sv_setpv</code> を使ったり
<code>newSVpv</code> の第二引数に 0 を指定することによって、Perl 自身に
文字列の長さを計算させることもできます。
ただし Perl は、NUL 文字で終了することに依存している
<code>strlen</code> を使って長さを計算しているということに注意してください。
</para>
<para>
The arguments of <code>sv_setpvf</code> are processed like <code>sprintf</code>, and the
formatted output becomes the value.
</para>
<para>
<code>sv_setpvf</code> の引数は <code>sprintf</code> と同じように処理され、書式化された
出力が値となります。
</para>
<para>
<code>sv_vsetpvfn</code> is an analogue of <code>vsprintf</code>, but it allows you to specify
either a pointer to a variable argument list or the address and length of
an array of SVs.  The last argument points to a boolean; on return, if that
boolean is true, then locale-specific information has been used to format
the string, and the string's contents are therefore untrustworthy (see
<link xref='perlsec'>perlsec</link>).  This pointer may be NULL if that information is not
important.  Note that this function requires you to specify the length of
the format.
</para>
<para>
<code>sv_vsetpvfn</code> は <code>vsprintf</code> と同じようなものですが、
可変引数リストに対するポインタか
SV の配列のアドレスと長さのいずれかを指定することができます。
最後の引数はブール値を指し示します。
関数から返ってきたときに
これが true であれば、フォーマット文字列としてロカール固有の
情報が使われているのでその文字列の内容は信頼するできないことを
表わしています(<link xref='perlsec'>perlsec</link> を参照)。
ロカールに関する情報が重要でないのなら、
このポインタは NULL であってもかまいません。
この関数はフォーマットの長さを要求していることに注意してください。
</para>
<para>
The <code>sv_set*()</code> functions are not generic enough to operate on values
that have &quot;magic&quot;.  See <link xref='Magic Virtual Tables'>Magic Virtual Tables</link> later in this document.
</para>
<para>
<code>sv_set*()</code> 関数群は“magic”を持っている値に対する
操作に対して充分に一般化されたものではありません。
後述する <link xref='Magic Virtual Tables'>Magic Virtual Tables</link> を参照してください。
</para>
<para>
All SVs that contain strings should be terminated with a NUL character.
If it is not NUL-terminated there is a risk of
core dumps and corruptions from code which passes the string to C
functions or system calls which expect a NUL-terminated string.
Perl's own functions typically add a trailing NUL for this reason.
Nevertheless, you should be very careful when you pass a string stored
in an SV to a C function or system call.
</para>
<para>
すべてのSV は、必須と言うわけではありませんが NUL キャラクターで
終端されているべきです。
この終端の NUL が無かった場合、コアダンプしたり文字列を
(文字列が NUL で終端されていることを期待している) C 関数やシステムコールに
渡すコードをおかしくする危険があります。
Perl 自身の典型的な関数は、この理由により終端に NUL を追加します。
そうであったとしても、あなたが SV に格納されている文字列を C の関数や
システムコールに渡す時には十二分に気をつけるべきなのです。
</para>
<para>
To access the actual value that an SV points to, you can use the macros:
</para>
<para>
SV が指し示す実際の値をアクセスするには、以下のマクロを使えます:
</para>
<verbatim><![CDATA[
SvIV(SV*)
SvUV(SV*)
SvNV(SV*)
SvPV(SV*, STRLEN len)
SvPV_nolen(SV*)
]]></verbatim>
<para>
which will automatically coerce the actual scalar type into an IV, UV, double,
or string.
</para>
<para>
これは実際のスカラの型を自動的にに IV や UV や倍精度や文字列にします。
</para>
<para>
In the <code>SvPV</code> macro, the length of the string returned is placed into the
variable <code>len</code> (this is a macro, so you do <emphasis>not</emphasis> use <code>&amp;len</code>).  If you do
not care what the length of the data is, use the <code>SvPV_nolen</code> macro.
Historically the <code>SvPV</code> macro with the global variable <code>PL_na</code> has been
used in this case.  But that can be quite inefficient because <code>PL_na</code> must
be accessed in thread-local storage in threaded Perl.  In any case, remember
that Perl allows arbitrary strings of data that may both contain NULs and
might not be terminated by a NUL.
</para>
<para>
<code>SvPV</code> マクロでは、返される文字列の長さは、変数 <code>len</code> に格納されます
(これはマクロですから、<code>&amp;len</code> と <emphasis>しないで</emphasis> ください)。
もしデータの長さを気にしないのであれば、<code>SvPV_nolen</code> マクロを
使ってください。
歴史的に、この場合にはグローバル変数 <code>PL_na</code> に <code>SvPV</code> マクロが
使われてきました。
しかしこれは可能ですが効率は良くありません;
なぜなら <code>PL_na</code> はスレッド化した Perl ではスレッドローカルな
領域にアクセスしなければならないからです。
いずれの場合にも、Perl は NUL を含んでいる文字列と NUL で
終端されていないような文字列の両方を扱うことができるということを
覚えておいてください。
</para>
<para>
Also remember that C doesn't allow you to safely say <code>foo(SvPV(s, len),
len);</code>. It might work with your compiler, but it won't work for everyone.
Break this sort of statement up into separate assignments:
</para>
<para>
同様に、Cで <code>SvPV(s, len), len)</code> とすることが安全ではないことを
忘れないでください。
これはあなたの使うコンパイラによってはうまくいきますが、
いつでもそうだとは限らないのです。
そこで、こういったステートメントは以下のように分割します:
</para>
<verbatim><![CDATA[
SV *s;
STRLEN len;
char * ptr;
ptr = SvPV(s, len);
foo(ptr, len);
]]></verbatim>
<para>
If you want to know if the scalar value is TRUE, you can use:
</para>
<para>
単にスカラ値が真かどうかを知りたいだけならば、
</para>
<verbatim><![CDATA[
SvTRUE(SV*)
]]></verbatim>
<para>
Although Perl will automatically grow strings for you, if you need to force
Perl to allocate more memory for your SV, you can use the macro
</para>
<para>
Perl は、SV にもっとメモリを割り当てて欲しいときには自動的に文字列を
大きくしてくれますが、さらにメモリを割り当てさせることが必要であれば
</para>
<verbatim><![CDATA[
SvGROW(SV*, STRLEN newlen)
]]></verbatim>
<para>
which will determine if more memory needs to be allocated.  If so, it will
call the function <code>sv_grow</code>.  Note that <code>SvGROW</code> can only increase, not
decrease, the allocated memory of an SV and that it does not automatically
add a byte for the a trailing NUL (perl's own string functions typically do
<code>SvGROW(sv, len + 1)</code>).
</para>
<para>
というマクロが使えます。
もし必要なら、このマクロが <code>sv_grow</code>を呼びます。
<code>SvGROW</code> は SV に割り当てたメモリを増やすだけで、減らすことは
できないということと、終端の NUL の分のバイトが自動的に加算されない
(perl自身の文字列関数は 大概 <code>SvGROW(sv, len + 1)</code> としています)と
いうことに注意してください。
</para>
<para>
If you have an SV and want to know what kind of data Perl thinks is stored
in it, you can use the following macros to check the type of SV you have.
</para>
<para>
手元にある SV の、 Perl から見たデータの種類を知りたいときには、
その SV の型をチェックするのに
</para>
<verbatim><![CDATA[
SvIOK(SV*)
SvNOK(SV*)
SvPOK(SV*)
]]></verbatim>
<para>
You can get and set the current length of the string stored in an SV with
the following macros:
</para>
<para>
SV に納められた文字列の現在の長さを取得したり設定したりするのに
は以下のマクロが使えます。
</para>
<verbatim><![CDATA[
SvCUR(SV*)
SvCUR_set(SV*, I32 val)
]]></verbatim>
<para>
You can also get a pointer to the end of the string stored in the SV
with the macro:
</para>
<para>
同様に、SV に格納されている文字列の終端へのポインタを以下のマクロを
使って得ることができます。
</para>
<verbatim><![CDATA[
SvEND(SV*)
]]></verbatim>
<para>
But note that these last three macros are valid only if <code>SvPOK()</code> is true.
</para>
<para>
ただし、これらは <code>SvPOK()</code> が真のときだけ有効だということに気を
つけてください。
</para>
<para>
If you want to append something to the end of string stored in an <code>SV*</code>,
you can use the following functions:
</para>
<para>
<code>SV*</code> に格納されている文字列の末尾になにかを追加したいときに以下のような
関数が使えます。
</para>
<verbatim><![CDATA[
void  sv_catpv(SV*, const char*);
void  sv_catpvn(SV*, const char*, STRLEN);
void  sv_catpvf(SV*, const char*, ...);
void  sv_vcatpvfn(SV*, const char*, STRLEN, va_list *, SV **, I32, bool);
void  sv_catsv(SV*, SV*);
]]></verbatim>
<para>
The first function calculates the length of the string to be appended by
using <code>strlen</code>.  In the second, you specify the length of the string
yourself.  The third function processes its arguments like <code>sprintf</code> and
appends the formatted output.  The fourth function works like <code>vsprintf</code>.
You can specify the address and length of an array of SVs instead of the
va_list argument. The fifth function extends the string stored in the first
SV with the string stored in the second SV.  It also forces the second SV
to be interpreted as a string.
</para>
<para>
最初の関数は <code>strlen</code> を使って追加する文字列の長さを計算します。
二番目の関数では、関数を使用する人が文字列の長さを指定します。
三番目の関数はその引数を <code>sprintf</code> の様に処理し、整形された結果を
追加します。
四番目の関数は <code>vsprintf</code> のように動作します。
va_list 引数の代わりに、SV の配列のアドレスと長さを指定することが
できます。
五番目の関数は最初の SV にある文字列を二番目の SV にある文字列で
拡張します。
また、この関数は二番目の SV を強制的に文字列として解釈します。
</para>
<para>
The <code>sv_cat*()</code> functions are not generic enough to operate on values that
have &quot;magic&quot;.  See <link xref='Magic Virtual Tables'>Magic Virtual Tables</link> later in this document.
</para>
<para>
<code>sv_cat*()</code> 関数群は“magic”を持っている値に対する
操作に対して充分に一般化されたものではありません。
後述する <link xref='Magic Virtual Tables'>Magic Virtual Tables</link> を参照してください。
</para>
<para>
If you know the name of a scalar variable, you can get a pointer to its SV
by using the following:
</para>
<para>
スカラ変数の名前がわかれば、その SV へのポインタは
</para>
<verbatim><![CDATA[
SV*  get_sv("package::varname", FALSE);
]]></verbatim>
<para>
This returns NULL if the variable does not exist.
</para>
<para>
を使って得ることができます。
その変数が存在しない場合には NULL が返されます。
</para>
<para>
If you want to know if this variable (or any other SV) is actually <code>defined</code>,
you can call:
</para>
<para>
その変数 (もしくは他の任意の SV) が、実際に <strong>定義されているか</strong> を
知りたいならば、
</para>
<verbatim><![CDATA[
SvOK(SV*)
]]></verbatim>
<para>
The scalar <code>undef</code> value is stored in an SV instance called <code>PL_sv_undef</code>.
</para>
<para>
スカラの <code>undef</code> 値は、<code>PL_sv_undef</code> という SV のインスタンスに
納められています。
</para>
<para>
Its address can be used whenever an <code>SV*</code> is needed. Make sure that
you don't try to compare a random sv with <code>&amp;PL_sv_undef</code>. For example
when interfacing Perl code, it'll work correctly for:
</para>
<para>
そのアドレスは、<code>SV*</code> が必要とされるところで使用することができます。
任意の sv を <code>&amp;PL_sv_undef</code> を比較しようとしないように気をつけてください。
例えば、Perl コードとのインターフェースで、以下は正しく動きます:
</para>
<verbatim><![CDATA[
foo(undef);
]]></verbatim>
<para>
But won't work when called as:
</para>
<para>
しかし、以下のように呼び出すと動作しません:
</para>
<verbatim><![CDATA[
$x = undef;
foo($x);
]]></verbatim>
<para>
So to repeat always use SvOK() to check whether an sv is defined.
</para>
<para>
従って、sv が定義されているかをチェックするために、毎回繰り返して
SvOK() を使ってください。
</para>
<para>
Also you have to be careful when using <code>&amp;PL_sv_undef</code> as a value in
AVs or HVs (see <link xref='AVs, HVs and undefined values'>AVs, HVs and undefined values</link>).
</para>
<para>
また、AV や HV の値として <code>&amp;PL_sv_undef</code> を使うときにも
注意しなければなりません (<link xref='AVs, HVs and undefined values'>AVs, HVs and undefined values</link> を
参照してください)。
</para>
<para>
There are also the two values <code>PL_sv_yes</code> and <code>PL_sv_no</code>, which contain
boolean TRUE and FALSE values, respectively.  Like <code>PL_sv_undef</code>, their
addresses can be used whenever an <code>SV*</code> is needed.
</para>
<para>
ブール値の真と偽を表わす、<code>PL_sv_yes</code> や <code>PL_sv_no</code> という値もあります。
<code>PL_sv_undef</code> と同様に、これらのアドレスも <code>SV*</code> が必要なところで
使うことができます。
</para>
<para>
Do not be fooled into thinking that <code>(SV *) 0</code> is the same as <code>&amp;PL_sv_undef</code>.
Take this code:
</para>
<para>
<code>(SV *0)</code> と <code>&amp;PL_sv_undef</code> が同じであると考えて、だまされてはいけません。
次のようなコードを見てください:
</para>
<verbatim><![CDATA[
SV* sv = (SV*) 0;
if (I-am-to-return-a-real-value) {
        sv = sv_2mortal(newSViv(42));
}
sv_setsv(ST(0), sv);
]]></verbatim>
<para>
This code tries to return a new SV (which contains the value 42) if it should
return a real value, or undef otherwise.  Instead it has returned a NULL
pointer which, somewhere down the line, will cause a segmentation violation,
bus error, or just weird results.  Change the zero to <code>&amp;PL_sv_undef</code> in the
first line and all will be well.
</para>
<para>
このコードは、実値を返さなければならないときには、(値として 42 を
持つ) 新しい SV を返そうとし、さもなくば undef を返そうとします。
ですが、どこかの行でナルポインタを返して、セグメントバイオレーションが
起こるか、何かおかしな結果になってしまいます。
最初の行の 0 を <code>&amp;PL_sv_undef</code> に変えれば、すべてがうまくいきます。
</para>
<para>
To free an SV that you've created, call <code>SvREFCNT_dec(SV*)</code>.  Normally this
call is not necessary (see <link xref='Reference Counts and Mortality'>Reference Counts and Mortality</link>).
</para>
<para>
生成した SV を解放するためには、<code>SvREFCNT_dec(SV*)</code> を呼びます。
普通は、この呼び出しは必要ありません。
<link xref='Reference Counts and Mortality'>Reference Counts and Mortality</link> を参照してください。
</para>
</sect2>
<sect2>
<title>Offsets</title>
<para>
(オフセット)
</para>
<para>
Perl provides the function <code>sv_chop</code> to efficiently remove characters
from the beginning of a string; you give it an SV and a pointer to
somewhere inside the PV, and it discards everything before the
pointer. The efficiency comes by means of a little hack: instead of
actually removing the characters, <code>sv_chop</code> sets the flag <code>OOK</code>
(offset OK) to signal to other functions that the offset hack is in
effect, and it puts the number of bytes chopped off into the IV field
of the SV. It then moves the PV pointer (called <code>SvPVX</code>) forward that
many bytes, and adjusts <code>SvCUR</code> and <code>SvLEN</code>.
</para>
<para>
Perl provides the function <code>sv_chop</code> to efficiently remove characters
from the beginning of a string; you give it an SV and a pointer to
somewhere inside the PV, and it discards everything before the
pointer. The efficiency comes by means of a little hack: instead of
actually removing the characters, <code>sv_chop</code> sets the flag <code>OOK</code>
(offset OK) to signal to other functions that the offset hack is in
effect, and it puts the number of bytes chopped off into the IV field
of the SV. It then moves the PV pointer (called <code>SvPVX</code>) forward that
many bytes, and adjusts <code>SvCUR</code> and <code>SvLEN</code>.
(TBT)
</para>
<para>
Hence, at this point, the start of the buffer that we allocated lives
at <code>SvPVX(sv) - SvIV(sv)</code> in memory and the PV pointer is pointing
into the middle of this allocated storage.
</para>
<para>
Hence, at this point, the start of the buffer that we allocated lives
at <code>SvPVX(sv) - SvIV(sv)</code> in memory and the PV pointer is pointing
into the middle of this allocated storage.
(TBT)
</para>
<para>
This is best demonstrated by example:
</para>
<para>
これは例による最良の実演です:
</para>
<verbatim><![CDATA[
% ./perl -Ilib -MDevel::Peek -le '$a="12345"; $a=~s/.//; Dump($a)'
SV = PVIV(0x8128450) at 0x81340f0
  REFCNT = 1
  FLAGS = (POK,OOK,pPOK)
  IV = 1  (OFFSET)
  PV = 0x8135781 ( "1" . ) "2345"\0
  CUR = 4
  LEN = 5
]]></verbatim>
<para>
Here the number of bytes chopped off (1) is put into IV, and
<code>Devel::Peek::Dump</code> helpfully reminds us that this is an offset. The
portion of the string between the &quot;real&quot; and the &quot;fake&quot; beginnings is
shown in parentheses, and the values of <code>SvCUR</code> and <code>SvLEN</code> reflect
the fake beginning, not the real one.
</para>
<para>
Here the number of bytes chopped off (1) is put into IV, and
<code>Devel::Peek::Dump</code> helpfully reminds us that this is an offset. The
portion of the string between the &quot;real&quot; and the &quot;fake&quot; beginnings is
shown in parentheses, and the values of <code>SvCUR</code> and <code>SvLEN</code> reflect
the fake beginning, not the real one.
(TBT)
</para>
<para>
Something similar to the offset hack is performed on AVs to enable
efficient shifting and splicing off the beginning of the array; while
<code>AvARRAY</code> points to the first element in the array that is visible from
Perl, <code>AvALLOC</code> points to the real start of the C array. These are
usually the same, but a <code>shift</code> operation can be carried out by
increasing <code>AvARRAY</code> by one and decreasing <code>AvFILL</code> and <code>AvLEN</code>.
Again, the location of the real start of the C array only comes into
play when freeing the array. See <code>av_shift</code> in <filename>av.c</filename>.
</para>
<para>
Something similar to the offset hack is performed on AVs to enable
efficient shifting and splicing off the beginning of the array; while
<code>AvARRAY</code> points to the first element in the array that is visible from
Perl, <code>AvALLOC</code> points to the real start of the C array. These are
usually the same, but a <code>shift</code> operation can be carried out by
increasing <code>AvARRAY</code> by one and decreasing <code>AvFILL</code> and <code>AvLEN</code>.
Again, the location of the real start of the C array only comes into
play when freeing the array. See <code>av_shift</code> in <filename>av.c</filename>.
(TBT)
</para>
</sect2>
<sect2>
<title>What's Really Stored in an SV?</title>
<para>
(SV に実際に格納されているものは何ですか?)
</para>
<para>
Recall that the usual method of determining the type of scalar you have is
to use <code>Sv*OK</code> macros.  Because a scalar can be both a number and a string,
usually these macros will always return TRUE and calling the <code>Sv*V</code>
macros will do the appropriate conversion of string to integer/double or
integer/double to string.
</para>
<para>
自分で保持しているスカラの型を決定する通常の方法は、マクロ <code>Sv*OK</code> を
使うものでした。
スカラは数値にも文字列にもなり得ますから、普通、
これらのマクロはいつも真を返します。
そして <code>Sv*V</code> マクロを呼ぶことで、
文字列から整数/倍精度、整数/倍精度から文字列への変換を行ないます。
</para>
<para>
If you <emphasis>really</emphasis> need to know if you have an integer, double, or string
pointer in an SV, you can use the following three macros instead:
</para>
<para>
もし、本当に SV にあるのが整数か、倍精度か、文字列ポインタかを
知りたいのであれば、
</para>
<verbatim><![CDATA[
SvIOKp(SV*)
SvNOKp(SV*)
SvPOKp(SV*)
]]></verbatim>
<para>
These will tell you if you truly have an integer, double, or string pointer
stored in your SV.  The &quot;p&quot; stands for private.
</para>
<para>
というマクロを代わりに使うことができます。
これらのマクロは、実際に SV に入っているものが整数か、倍精度か、
文字列ポインタかを教えてくれます。
</para>
<para>
The are various ways in which the private and public flags may differ.
For example, a tied SV may have a valid underlying value in the IV slot
(so SvIOKp is true), but the data should be accessed via the FETCH
routine rather than directly, so SvIOK is false. Another is when
numeric conversion has occurred and precision has been lost: only the
private flag is set on 'lossy' values. So when an NV is converted to an
IV with loss, SvIOKp, SvNOKp and SvNOK will be set, while SvIOK wont be.
</para>
<para>
The are various ways in which the private and public flags may differ.
For example, a tied SV may have a valid underlying value in the IV slot
(so SvIOKp is true), but the data should be accessed via the FETCH
routine rather than directly, so SvIOK is false. Another is when
numeric conversion has occurred and precision has been lost: only the
private flag is set on 'lossy' values. So when an NV is converted to an
IV with loss, SvIOKp, SvNOKp and SvNOK will be set, while SvIOK wont be.
(TBT)
</para>
<para>
In general, though, it's best to use the <code>Sv*V</code> macros.
</para>
<para>
しかし一般的には、<code>Sv*V</code> マクロを使うだけにした方が良いでしょう。
</para>
</sect2>
<sect2>
<title>Working with AVs</title>
<para>
(AV に対する作業)
</para>
<para>
There are two ways to create and load an AV.  The first method creates an
empty AV:
</para>
<para>
AV を生成して値を設定するのには、二つの方法があります。
最初の方法は、単に空の AV を作るものです:
</para>
<verbatim><![CDATA[
AV*  newAV();
]]></verbatim>
<para>
The second method both creates the AV and initially populates it with SVs:
</para>
<para>
ふたつめの方法は、AV を生成した上で、初期値として SV の値を入れます:
</para>
<verbatim><![CDATA[
AV*  av_make(I32 num, SV **ptr);
]]></verbatim>
<para>
The second argument points to an array containing <code>num</code> <code>SV*</code>'s.  Once the
AV has been created, the SVs can be destroyed, if so desired.
</para>
<para>
二番目の引数は num 個の SV* の配列を指しています。
AV が生成されてしまえば、SV は(それを望むのなら)破棄することができます。
</para>
<para>
Once the AV has been created, the following operations are possible on AVs:
</para>
<para>
いったん AV が生成されると、AV に対して、
</para>
<verbatim><![CDATA[
void  av_push(AV*, SV*);
SV*   av_pop(AV*);
SV*   av_shift(AV*);
void  av_unshift(AV*, I32 num);
]]></verbatim>
<para>
These should be familiar operations, with the exception of <code>av_unshift</code>.
This routine adds <code>num</code> elements at the front of the array with the <code>undef</code>
value.  You must then use <code>av_store</code> (described below) to assign values
to these new elements.
</para>
<para>
といった操作が行えます。
これらは、<code>av_unshift</code> を除いては、お馴染みの演算でしょう。
<code>av_unshift</code> は、配列の先頭に <code>num</code> 個の <code>undef</code> 値の要素を付け加えます。
その後で、(後述する) <code>av_store</code> を使って新しい要素に値を
代入しなければなりません。
</para>
<para>
Here are some other functions:
</para>
<para>
他にもいくつか関数があります:
</para>
<verbatim><![CDATA[
I32   av_len(AV*);
SV**  av_fetch(AV*, I32 key, I32 lval);
SV**  av_store(AV*, I32 key, SV* val);
]]></verbatim>
<para>
The <code>av_len</code> function returns the highest index value in array (just
like $#array in Perl).  If the array is empty, -1 is returned.  The
<code>av_fetch</code> function returns the value at index <code>key</code>, but if <code>lval</code>
is non-zero, then <code>av_fetch</code> will store an undef value at that index.
The <code>av_store</code> function stores the value <code>val</code> at index <code>key</code>, and does
not increment the reference count of <code>val</code>.  Thus the caller is responsible
for taking care of that, and if <code>av_store</code> returns NULL, the caller will
have to decrement the reference count to avoid a memory leak.  Note that
<code>av_fetch</code> and <code>av_store</code> both return <code>SV**</code>'s, not <code>SV*</code>'s as their
return value.
</para>
<para>
関数 <code>av_len</code> は配列における最高位の添え字を(ちょうど Perl の $#array と
同じように)返します。
もし配列が空であれば、-1 を返します。
関数 <code>av_fetch</code> は添え字 <code>key</code> の位置にある値を返しますが、<code>lval</code> が
非ゼロであれば、<code>av_fetch</code> はその位置に undef を格納しようとします。
関数 <code>av_store</code> は添え字 <code>key</code> の位置に値 <code>val</code> を格納し、<code>val</code> の
参照カウントをインクリメントしません。
従って、呼び出し側はこの振る舞いに注意して対処し、<code>av_store</code> が
NULL を返した場合には、メモリリークを防ぐために参照カウントの
デクリメントを行う必要があるでしょう。
<code>av_fetch</code> と <code>av_store</code> の両方ともがその戻り値として
<code>SV*</code> ではなく、<code>SV**</code> を返すということに注意してください。
</para>
<verbatim><![CDATA[
void  av_clear(AV*);
void  av_undef(AV*);
void  av_extend(AV*, I32 key);
]]></verbatim>
<para>
The <code>av_clear</code> function deletes all the elements in the AV* array, but
does not actually delete the array itself.  The <code>av_undef</code> function will
delete all the elements in the array plus the array itself.  The
<code>av_extend</code> function extends the array so that it contains at least <code>key+1</code>
elements.  If <code>key+1</code> is less than the currently allocated length of the array,
then nothing is done.
</para>
<para>
関数 <code>av_clear</code> は、配列 AV* にあるすべての要素を削除しますが、
配列自身の削除は行いません。
関数 <code>av_undef</code> は配列にあるすべての要素に加え、配列自身の削除も行います。
関数 <code>av_extend</code>  は配列を <code>key+1</code> 要素だけ拡張します。
<code>key+1</code> が配列のその時点での長さより短ければ、何も行なわれません。
</para>
<para>
If you know the name of an array variable, you can get a pointer to its AV
by using the following:
</para>
<para>
配列変数の名前がわかっているのであれば、次のようにしてその配列に
対応する AV へのポインタを得ることができます。
</para>
<verbatim><![CDATA[
AV*  get_av("package::varname", FALSE);
]]></verbatim>
<para>
This returns NULL if the variable does not exist.
</para>
<para>
これは変数が存在していない場合には NULL を返します。
</para>
<para>
See <link xref='Understanding the Magic of Tied Hashes and Arrays'>Understanding the Magic of Tied Hashes and Arrays</link> for more
information on how to use the array access functions on tied arrays.
</para>
<para>
tie された配列における配列アクセス関数の使い方についての詳細は
<link xref='Understanding the Magic of Tied Hashes and Arrays'>Understanding the Magic of Tied Hashes and Arrays</link> を参照してください。
</para>
</sect2>
<sect2>
<title>Working with HVs</title>
<para>
(HV に対する作業)
</para>
<para>
To create an HV, you use the following routine:
</para>
<para>
HV を生成するには、
</para>
<verbatim><![CDATA[
HV*  newHV();
]]></verbatim>
<para>
Once the HV has been created, the following operations are possible on HVs:
</para>
<para>
というルーチンを使います。
いったん HV が生成されると HV に対して、
</para>
<verbatim><![CDATA[
SV**  hv_store(HV*, const char* key, U32 klen, SV* val, U32 hash);
SV**  hv_fetch(HV*, const char* key, U32 klen, I32 lval);
]]></verbatim>
<para>
The <code>klen</code> parameter is the length of the key being passed in (Note that
you cannot pass 0 in as a value of <code>klen</code> to tell Perl to measure the
length of the key).  The <code>val</code> argument contains the SV pointer to the
scalar being stored, and <code>hash</code> is the precomputed hash value (zero if
you want <code>hv_store</code> to calculate it for you).  The <code>lval</code> parameter
indicates whether this fetch is actually a part of a store operation, in
which case a new undefined value will be added to the HV with the supplied
key and <code>hv_fetch</code> will return as if the value had already existed.
</para>
<para>
という操作が行えます。
引数 <code>klen</code> は、渡される key の長さです
(Perl にキーの長さを計算させるために、<code>klen</code>&gt; の値として 0 を渡すことは
できないということに注意してください)。
引数 <code>val</code> は、設定されるスカラへの SV ポインタを入れ、hash は、
あらかじめ計算したハッシュ値 (<code>hv_store</code> に計算させる場合には、
ゼロ) です。
引数 <code>lval</code> で、このフェッチ操作が実はストア操作の一部であるかどうかを
示します。
ストア操作であれば、新たなundefind value が与えられた
キーを伴って HV に追加され、<code>hv_fetch</code> はその値が既に
存在していたかのようにリターンします。
</para>
<para>
Remember that <code>hv_store</code> and <code>hv_fetch</code> return <code>SV**</code>'s and not just
<code>SV*</code>.  To access the scalar value, you must first dereference the return
value.  However, you should check to make sure that the return value is
not NULL before dereferencing it.
</para>
<para>
<code>hv_store</code> や <code>hv_fetch</code> は、<code>SV**</code> を返すもので、<code>SV*</code> ではないことに
注意してください。
スカラ値をアクセスするには、まず戻り値の参照外し(dereference)をする
必要があります。
しかし、その前に返却値が NULL でないことを確認すべきです。
</para>
<para>
These two functions check if a hash table entry exists, and deletes it.
</para>
<para>
ハッシュテーブルのエントリが存在するかをチェックし、削除を行う
関数があります。
</para>
<verbatim><![CDATA[
bool  hv_exists(HV*, const char* key, U32 klen);
SV*   hv_delete(HV*, const char* key, U32 klen, I32 flags);
]]></verbatim>
<para>
If <code>flags</code> does not include the <code>G_DISCARD</code> flag then <code>hv_delete</code> will
create and return a mortal copy of the deleted value.
</para>
<para>
<code>flag</code> に <code>G_DISCARD</code> フラグが含まれていなければ、<code>hv_delete</code> は
削除された値の揮発性のコピー(mortal copy)を生成し、それを返します。
</para>
<para>
And more miscellaneous functions:
</para>
<para>
さらに様々な関数があります:
</para>
<verbatim><![CDATA[
void   hv_clear(HV*);
void   hv_undef(HV*);
]]></verbatim>
<para>
Like their AV counterparts, <code>hv_clear</code> deletes all the entries in the hash
table but does not actually delete the hash table.  The <code>hv_undef</code> deletes
both the entries and the hash table itself.
</para>
<para>
引数に AV を取る似たような関数と同様、<code>hv_clear</code> はハッシュテーブルにある
すべてのエントリーを削除しますがハッシュテーブル自身は削除しません。
<code>hv_undef</code> はエントリーとハッシュテーブル自身の両方を削除します。
</para>
<para>
Perl keeps the actual data in linked list of structures with a typedef of HE.
These contain the actual key and value pointers (plus extra administrative
overhead).  The key is a string pointer; the value is an <code>SV*</code>.  However,
once you have an <code>HE*</code>, to get the actual key and value, use the routines
specified below.
</para>
<para>
Perl は実際のデータを HE と typedef された構造体のリンクリストを使って
保持しています。
これらは実際のキーと値のポインタ(それに加えて管理のための
ちょっとしたもの)を保持しています。
キーは文字列へのポインタであり、値は <code>SV*</code> です。
しかしながら、一度 <code>HE*</code> を持てば、実際のキーと値とを取得するためには
以下に挙げるようなルーチンを使います。
</para>
<verbatim><![CDATA[
I32    hv_iterinit(HV*);
        /* Prepares starting point to traverse hash table */
HE*    hv_iternext(HV*);
        /* Get the next entry, and return a pointer to a
           structure that has both the key and value */
char*  hv_iterkey(HE* entry, I32* retlen);
        /* Get the key from an HE structure and also return
           the length of the key string */
SV*    hv_iterval(HV*, HE* entry);
        /* Return an SV pointer to the value of the HE
           structure */
SV*    hv_iternextsv(HV*, char** key, I32* retlen);
        /* This convenience routine combines hv_iternext,
	       hv_iterkey, and hv_iterval.  The key and retlen
	       arguments are return values for the key and its
	       length.  The value is returned in the SV* argument */
]]></verbatim>
<verbatim><![CDATA[
I32    hv_iterinit(HV*);
        /* ハッシュテーブルをたどるための開始点を準備 */
HE*    hv_iternext(HV*);
        /* 次のエントリーを取得して、キーと値両方を持つ構造
           体へのポインタを返す */
char*  hv_iterkey(HE* entry, I32* retlen);
        /* HE 構造体からキーを取得し、そのキー文字列の長さを
           返す */
SV*    hv_iterval(HV*, HE* entry);
        /* HE 構造体の値に対する SV ポインタを返す */
SV*    hv_iternextsv(HV*, char** key, I32* retlen);
        /* この便利なルーチンは、hv_iternext、hv_iterkey、
            hv_itervalを組み合わせたものです。
            引数keyとretlenは、キーとその長さを表わす戻り値です。
            関数の戻り値はSV* で返されます。*/
]]></verbatim>
<para>
If you know the name of a hash variable, you can get a pointer to its HV
by using the following:
</para>
<para>
配列変数の名前がわかるのであれば、
</para>
<verbatim><![CDATA[
HV*  get_hv("package::varname", FALSE);
]]></verbatim>
<para>
This returns NULL if the variable does not exist.
</para>
<para>
を使えば、その変数の HV へのポインタが得られます。
その変数が存在しない場合には NULL を返します。
</para>
<para>
The hash algorithm is defined in the <code>PERL_HASH(hash, key, klen)</code> macro:
</para>
<para>
ハッシュアルゴリズムは <code>PERL_HASH(hash, key, klen)</code> というマクロで
定義されています。
</para>
<verbatim><![CDATA[
hash = 0;
while (klen--)
	hash = (hash * 33) + *key++;
hash = hash + (hash >> 5);			/* after 5.6 */
]]></verbatim>
<para>
The last step was added in version 5.6 to improve distribution of
lower bits in the resulting hash value.
</para>
<para>
最後のステップは、結果となるハッシュ値の低位ビットの分散を改良するために
バージョン 5.6 で追加されました。
</para>
<para>
See <link xref='Understanding the Magic of Tied Hashes and Arrays'>Understanding the Magic of Tied Hashes and Arrays</link> for more
information on how to use the hash access functions on tied hashes.
</para>
<para>
tie されたハッシュに対するハッシュアクセス関数の使い方に
関する詳細は、<link xref='Understanding the Magic of Tied Hashes and Arrays'>Understanding the Magic of Tied Hashes and Arrays</link> を
参照してください。
</para>
</sect2>
<sect2>
<title>Hash API Extensions</title>
<para>
(ハッシュ API 拡張)
</para>
<para>
Beginning with version 5.004, the following functions are also supported:
</para>
<para>
バージョン 5.004 から、以下の関数がサポートされました。
</para>
<verbatim><![CDATA[
HE*     hv_fetch_ent  (HV* tb, SV* key, I32 lval, U32 hash);
HE*     hv_store_ent  (HV* tb, SV* key, SV* val, U32 hash);
]]></verbatim>
<verbatim><![CDATA[
bool    hv_exists_ent (HV* tb, SV* key, U32 hash);
SV*     hv_delete_ent (HV* tb, SV* key, I32 flags, U32 hash);
]]></verbatim>
<verbatim><![CDATA[
SV*     hv_iterkeysv  (HE* entry);
]]></verbatim>
<para>
Note that these functions take <code>SV*</code> keys, which simplifies writing
of extension code that deals with hash structures.  These functions
also allow passing of <code>SV*</code> keys to <code>tie</code> functions without forcing
you to stringify the keys (unlike the previous set of functions).
</para>
<para>
これらの関数が、ハッシュ構造を扱うエクステンションの記述を単純にする
<code>SV*</code> キーを引数にとることに注意してください。
これらの関数はまた、<code>SV*</code> キーを(先に挙げた関数群とは異なり)
文字列化することなしに <code>tie</code> 関数に渡すことを許しています。
</para>
<para>
They also return and accept whole hash entries (<code>HE*</code>), making their
use more efficient (since the hash number for a particular string
doesn't have to be recomputed every time).  See <link xref='perlapi'>perlapi</link> for detailed
descriptions.
</para>
<para>
これらの関数はまた、ハッシュエントリー全体 (<code>HE*</code>) を返したり受け付けて、
より効率良く使用します(特定の文字列に対するハッシュ番号は
毎回計算しなおす必要はないからです)。
詳しくは <link xref='perlapi'>perlapi</link> を参照してください。
</para>
<para>
The following macros must always be used to access the contents of hash
entries.  Note that the arguments to these macros must be simple
variables, since they may get evaluated more than once.  See
<link xref='perlapi'>perlapi</link> for detailed descriptions of these macros.
</para>
<para>
以下に挙げるマクロは、ハッシュエントリーの内容にアクセスするのに
常に使わなければならないものです。
これらのマクロはその引数を二度以上評価する可能性があるので、マクロに
対する引数は単純な変数でなければならないということに注意してください。
これらのマクロに関する詳細は <link xref='perlapi'>perlapi</link> を参照してください。
</para>
<verbatim><![CDATA[
HePV(HE* he, STRLEN len)
HeVAL(HE* he)
HeHASH(HE* he)
HeSVKEY(HE* he)
HeSVKEY_force(HE* he)
HeSVKEY_set(HE* he, SV* sv)
]]></verbatim>
<para>
These two lower level macros are defined, but must only be used when
dealing with keys that are not <code>SV*</code>s:
</para>
<para>
低レベルマクロが二つ定義されていますが、これらは <code>SV*</code> ではないキーを
扱うときにのみ使わなければならないものです。
</para>
<verbatim><![CDATA[
HeKEY(HE* he)
HeKLEN(HE* he)
]]></verbatim>
<para>
Note that both <code>hv_store</code> and <code>hv_store_ent</code> do not increment the
reference count of the stored <code>val</code>, which is the caller's responsibility.
If these functions return a NULL value, the caller will usually have to
decrement the reference count of <code>val</code> to avoid a memory leak.
</para>
<para>
<code>hv_store</code> と <code>hv_store_ent</code> の両方ともが、<code>val</code> に格納されている
参照カウントのインクリメントをしないということに注意してください。
それは呼び出し側の責任です。
これらの関数が NULL を返した場合、
呼び出し側はメモリリークを防ぐために、<code>val</code> の参照カウントの
デクリメントを行う必要が一般にはあるでしょう。
</para>
</sect2>
<sect2>
<title>AVs, HVs and undefined values</title>
<para>
(AV, HV と未定義値)
</para>
<para>
Sometimes you have to store undefined values in AVs or HVs. Although
this may be a rare case, it can be tricky. That's because you're
used to using <code>&amp;PL_sv_undef</code> if you need an undefined SV.
</para>
<para>
AV や HV に未定義値を保管しなければならないこともあります。
これは珍しい場合ですが、手の込んだものになります。
なぜなら、未定義の SV が必要なら、<code>&amp;PL_sv_undef</code> を使うことになるからです。
</para>
<para>
For example, intuition tells you that this XS code:
</para>
<para>
例えば、直感ではこの XS コードは:
</para>
<verbatim><![CDATA[
AV *av = newAV();
av_store( av, 0, &PL_sv_undef );
]]></verbatim>
<para>
is equivalent to this Perl code:
</para>
<para>
以下の Perl コードと等価です:
</para>
<verbatim><![CDATA[
my @av;
$av[0] = undef;
]]></verbatim>
<para>
Unfortunately, this isn't true. AVs use <code>&amp;PL_sv_undef</code> as a marker
for indicating that an array element has not yet been initialized.
Thus, <code>exists $av[0]</code> would be true for the above Perl code, but
false for the array generated by the XS code.
</para>
<para>
残念ながら、これは正しくありません。
AV は、配列要素がまだ初期化されていないことを示すための印として
<code>&amp;PL_sv_undef</code> を使います。
従って、上述の Perl コードは <code>exists $av[0]</code> は真ですが、
XS コードによって生成された配列では偽です。
</para>
<para>
Other problems can occur when storing <code>&amp;PL_sv_undef</code> in HVs:
</para>
<para>
HV に <code>&amp;PL_sv_undef</code> を保管する時にも別の問題が起こりえます:
</para>
<verbatim><![CDATA[
hv_store( hv, "key", 3, &PL_sv_undef, 0 );
]]></verbatim>
<para>
This will indeed make the value <code>undef</code>, but if you try to modify
the value of <code>key</code>, you'll get the following error:
</para>
<para>
実際これは <code>undef</code> 値を作りますが、<code>key</code> の値を変更しようとすると、
以下のようなエラーが出ます:
</para>
<verbatim><![CDATA[
Modification of non-creatable hash value attempted
]]></verbatim>
<para>
In perl 5.8.0, <code>&amp;PL_sv_undef</code> was also used to mark placeholders
in restricted hashes. This caused such hash entries not to appear
when iterating over the hash or when checking for the keys
with the <code>hv_exists</code> function.
</para>
<para>
In perl 5.8.0, <code>&amp;PL_sv_undef</code> was also used to mark placeholders
in restricted hashes. This caused such hash entries not to appear
when iterating over the hash or when checking for the keys
with the <code>hv_exists</code> function.
(TBT)
</para>
<para>
You can run into similar problems when you store <code>&amp;PL_sv_true</code> or
<code>&amp;PL_sv_false</code> into AVs or HVs. Trying to modify such elements
will give you the following error:
</para>
<para>
You can run into similar problems when you store <code>&amp;PL_sv_true</code> or
<code>&amp;PL_sv_false</code> into AVs or HVs. Trying to modify such elements
will give you the following error:
(TBT)
</para>
<verbatim><![CDATA[
Modification of a read-only value attempted
]]></verbatim>
<para>
To make a long story short, you can use the special variables
<code>&amp;PL_sv_undef</code>, <code>&amp;PL_sv_true</code> and <code>&amp;PL_sv_false</code> with AVs and
HVs, but you have to make sure you know what you're doing.
</para>
<para>
To make a long story short, you can use the special variables
<code>&amp;PL_sv_undef</code>, <code>&amp;PL_sv_true</code> and <code>&amp;PL_sv_false</code> with AVs and
HVs, but you have to make sure you know what you're doing.
(TBT)
</para>
<para>
Generally, if you want to store an undefined value in an AV
or HV, you should not use <code>&amp;PL_sv_undef</code>, but rather create a
new undefined value using the <code>newSV</code> function, for example:
</para>
<para>
Generally, if you want to store an undefined value in an AV
or HV, you should not use <code>&amp;PL_sv_undef</code>, but rather create a
new undefined value using the <code>newSV</code> function, for example:
(TBT)
</para>
<verbatim><![CDATA[
av_store( av, 42, newSV(0) );
hv_store( hv, "foo", 3, newSV(0), 0 );
]]></verbatim>
</sect2>
<sect2>
<title>References</title>
<para>
(リファレンス)
</para>
<para>
References are a special type of scalar that point to other data types
(including references).
</para>
<para>
リファレンスは、(リファレンスを含む) 他のスカラ型を指す特別な
スカラ型です。
</para>
<para>
To create a reference, use either of the following functions:
</para>
<para>
リファレンスを生成するには、
</para>
<verbatim><![CDATA[
SV* newRV_inc((SV*) thing);
SV* newRV_noinc((SV*) thing);
]]></verbatim>
<para>
The <code>thing</code> argument can be any of an <code>SV*</code>, <code>AV*</code>, or <code>HV*</code>.  The
functions are identical except that <code>newRV_inc</code> increments the reference
count of the <code>thing</code>, while <code>newRV_noinc</code> does not.  For historical
reasons, <code>newRV</code> is a synonym for <code>newRV_inc</code>.
</para>
<para>
<code>thing</code> には、<code>SV*</code>, <code>AV*</code>, <code>HV*</code> のいずれかを置くことができます。
これら二つの関数は、<code>newRV_inc</code> が <code>thing</code> の参照カウントを
インクリメントするが <code>newRV_noinc</code> はインクリメントしないという点を
除き、同一です。
歴史的な理由により、<code>newRV</code> は <code>newRV_inc</code> の同義語となっています。
</para>
<para>
Once you have a reference, you can use the following macro to dereference
the reference:
</para>
<para>
リファレンスができれば、以下のマクロを使ってリファレンスの参照外し
(dereference)ができます。
</para>
<verbatim><![CDATA[
SvRV(SV*)
]]></verbatim>
<para>
then call the appropriate routines, casting the returned <code>SV*</code> to either an
<code>AV*</code> or <code>HV*</code>, if required.
</para>
<para>
というマクロが使うことができ、返された <code>SV*</code> を <code>AV*</code> か <code>HV*</code> に
キャストして、適切なルーチンを呼ぶことになります。
</para>
<para>
To determine if an SV is a reference, you can use the following macro:
</para>
<para>
SV がリファレンスであるかどうかを確認するために、
以下のマクロを使うことができます。
</para>
<verbatim><![CDATA[
SvROK(SV*)
]]></verbatim>
<para>
To discover what type of value the reference refers to, use the following
macro and then check the return value.
</para>
<para>
リファレンスが参照している型を見つけるために、以下のマクロを
使いその戻り値をチェックします。
</para>
<verbatim><![CDATA[
SvTYPE(SvRV(SV*))
]]></verbatim>
<para>
The most useful types that will be returned are:
</para>
<para>
戻り値として返される型で有益なものは以下の通りです。
</para>
<verbatim><![CDATA[
SVt_IV    Scalar
SVt_NV    Scalar
SVt_PV    Scalar
SVt_RV    Scalar
SVt_PVAV  Array
SVt_PVHV  Hash
SVt_PVCV  Code
SVt_PVGV  Glob (possible a file handle)
SVt_PVMG  Blessed or Magical Scalar
]]></verbatim>
<verbatim><![CDATA[
SVt_IV    スカラ
SVt_NV    スカラ
SVt_PV    スカラ
SVt_RV    スカラ
SVt_PVAV  配列
SVt_PVHV  ハッシュ
SVt_PVCV  コード
SVt_PVGV  グロブ (ファイルハンドルかも)
SVt_PVMG  bress されたかマジカルなスカラ
]]></verbatim>
<verbatim><![CDATA[
See the sv.h header file for more details.
]]></verbatim>
<verbatim><![CDATA[
詳しくはヘッダファイル sv.h を参照してください。
]]></verbatim>
</sect2>
<sect2>
<title>Blessed References and Class Objects</title>
<para>
(bless されたリファレンスとクラスオブジェクト)
</para>
<para>
References are also used to support object-oriented programming.  In perl's
OO lexicon, an object is simply a reference that has been blessed into a
package (or class).  Once blessed, the programmer may now use the reference
to access the various methods in the class.
</para>
<para>
リファレンスはオブジェクト指向プログラミングをサポートするためにも
使われます。
perl のオブジェクト指向用語では、オブジェクトとはパッケージ
(もしくはクラス)に bless された単純なリファレンスです。
一度 bless されれば、プログラマーはそのリファレンスをクラスにおける様々な
メソッドにアクセスするために使うことができます。
</para>
<para>
A reference can be blessed into a package with the following function:
</para>
<para>
以下の関数を使って、リファレンスをパッケージに bless することができます。
</para>
<verbatim><![CDATA[
SV* sv_bless(SV* sv, HV* stash);
]]></verbatim>
<para>
The <code>sv</code> argument must be a reference value.  The <code>stash</code> argument
specifies which class the reference will belong to.  See
<link xref='Stashes and Globs'>Stashes and Globs</link> for information on converting class names into stashes.
</para>
<para>
引数 <code>sv</code> はリファレンス値でなければなりません。
引数 <code>stash</code> はリファレンスが属するクラスを指定します。
クラス名のstashへの変換についての詳細は <link xref='Stashes and Globs'>Stashes and Globs</link> を
参照してください。
</para>
<para>
/* Still under construction */
</para>
<para>
/* Still under construction */
</para>
<para>
Upgrades rv to reference if not already one.  Creates new SV for rv to
point to.  If <code>classname</code> is non-null, the SV is blessed into the specified
class.  SV is returned.
</para>
<para>
まだ存在していなければ、rv をリファレンスにアップグレードします。
rv が指し示すための新たな SV を生成します。
<code>classname</code> がナルでなければ、SV は指定されたクラスに bless され、
SV が返されます。
</para>
<verbatim><![CDATA[
SV* newSVrv(SV* rv, const char* classname);
]]></verbatim>
<para>
Copies integer, unsigned integer or double into an SV whose reference is <code>rv</code>.  SV is blessed
if <code>classname</code> is non-null.
</para>
<para>
整数、符号なし整数、倍精度実数を <code>rv</code> が参照している SV へコピーします。
SV は <code>classname</code> がナルでなければblessされます。
</para>
<verbatim><![CDATA[
SV* sv_setref_iv(SV* rv, const char* classname, IV iv);
SV* sv_setref_uv(SV* rv, const char* classname, UV uv);
SV* sv_setref_nv(SV* rv, const char* classname, NV iv);
]]></verbatim>
<para>
Copies the pointer value (<emphasis>the address, not the string!</emphasis>) into an SV whose
reference is rv.  SV is blessed if <code>classname</code> is non-null.
</para>
<para>
ポインタ値(<strong>アドレスであって、文字列ではありません!</strong>)を rv が
参照しているSVへコピーします。
SV は <code>classname</code> がナルでなければ bless されます。
</para>
<verbatim><![CDATA[
SV* sv_setref_pv(SV* rv, const char* classname, PV iv);
]]></verbatim>
<para>
Copies string into an SV whose reference is <code>rv</code>.  Set length to 0 to let
Perl calculate the string length.  SV is blessed if <code>classname</code> is non-null.
</para>
<para>
文字列を <code>rv</code> が参照している SV へコピーします。
length に 0 を設定すると、Perl が文字列の長さを計算します。
SV は <code>classname</code> がナルでなければ bless されます。
</para>
<verbatim><![CDATA[
SV* sv_setref_pvn(SV* rv, const char* classname, PV iv, STRLEN length);
]]></verbatim>
<para>
Tests whether the SV is blessed into the specified class.  It does not
check inheritance relationships.
</para>
<para>
SV が特定のクラスに bless されているかどうかを検査します。
これは継承の関係のチェックはしません。
</para>
<verbatim><![CDATA[
int  sv_isa(SV* sv, const char* name);
]]></verbatim>
<para>
Tests whether the SV is a reference to a blessed object.
</para>
<para>
SV が bless されたオブジェクトのリファレンスであるかどうかを検査します。
</para>
<verbatim><![CDATA[
int  sv_isobject(SV* sv);
]]></verbatim>
<para>
Tests whether the SV is derived from the specified class. SV can be either
a reference to a blessed object or a string containing a class name. This
is the function implementing the <code>UNIVERSAL::isa</code> functionality.
</para>
<para>
SV が特定のクラスから派生したものがどうかを検査します。
SV は bless されたオブジェクトのリファレンスでも、
クラス名を保持している文字列であってもかまいません。
これは <code>UNIVERSAL::isa</code> の機能を実装している関数です。
</para>
<verbatim><![CDATA[
bool sv_derived_from(SV* sv, const char* name);
]]></verbatim>
<para>
To check if you've got an object derived from a specific class you have
to write:
</para>
<para>
ある特定のクラスの派生オブジェクトを受け取ったかどうか検査するには、
以下のように書く必要があります。
</para>
<verbatim><![CDATA[
if (sv_isobject(sv) && sv_derived_from(sv, class)) { ... }
]]></verbatim>
</sect2>
<sect2>
<title>Creating New Variables</title>
<para>
(新しい変数の作成)
</para>
<para>
To create a new Perl variable with an undef value which can be accessed from
your Perl script, use the following routines, depending on the variable type.
</para>
<para>
undef という値を持つあなたの Perl スクリプトからアクセスできる新たな
Perl の変数を生成するには、以下に示すルーチンを変数の型に応じて
使います。
</para>
<verbatim><![CDATA[
SV*  get_sv("package::varname", TRUE);
AV*  get_av("package::varname", TRUE);
HV*  get_hv("package::varname", TRUE);
]]></verbatim>
<para>
Notice the use of TRUE as the second parameter.  The new variable can now
be set, using the routines appropriate to the data type.
</para>
<para>
二番目のパラメータとして TRUE を使っているということに注意してください。
新しい変数はここでデータ型に対する適切なルーチンを使うことで
設定することができます。
</para>
<para>
There are additional macros whose values may be bitwise OR'ed with the
<code>TRUE</code> argument to enable certain extra features.  Those bits are:
</para>
<para>
<code>TRUE</code> 引数とビット和を取って、幾つかの追加機能を有効とするような
二つのマクロがあります。
</para>
<list>
<item><itemtext>GV_ADDMULTI</itemtext>
<para>
Marks the variable as multiply defined, thus preventing the:
</para>
<para>
変数に多重定義 (multiply defined) であると印を付け:
</para>
<verbatim><![CDATA[
Name <varname> used only once: possible typo
]]></verbatim>
<para>
warning.
</para>
<para>
警告を防ぎます。
</para>
</item>
<item><itemtext>GV_ADDWARN</itemtext>
<para>
Issues the warning:
</para>
<para>
以下の警告を:
</para>
<verbatim><![CDATA[
Had to create <varname> unexpectedly
]]></verbatim>
<para>
if the variable did not exist before the function was called.
</para>
<para>
変数が、その関数の呼び出し以前に存在してなかった場合に発生させます。
</para>
</item>
</list>
<para>
If you do not specify a package name, the variable is created in the current
package.
</para>
<para>
パッケージ名を指定しなかった場合、変数はカレントパッケージで
生成されます。
</para>
</sect2>
<sect2>
<title>Reference Counts and Mortality</title>
<para>
(参照カウントと揮発性)
</para>
<para>
Perl uses a reference count-driven garbage collection mechanism. SVs,
AVs, or HVs (xV for short in the following) start their life with a
reference count of 1.  If the reference count of an xV ever drops to 0,
then it will be destroyed and its memory made available for reuse.
</para>
<para>
Perl は参照カウント駆動(reference count-driven)のガベージコレクション
機構を使用しています。
SV、AV、そしてHV(以下 xV と省略します)
はその一生を参照カウント 1 から始めます。
xV の参照カウントが0まで落ちた場合、そのリファレンスは破棄されて、
それが使っていたメモリは
再利用できるようにされます。
</para>
<para>
This normally doesn't happen at the Perl level unless a variable is
undef'ed or the last variable holding a reference to it is changed or
overwritten.  At the internal level, however, reference counts can be
manipulated with the following macros:
</para>
<para>
これは、Perl レベルにおいては、変数が undef されるとかリファレンスを
保持している最後の変数が変更されたとか上書きされるということがない限りは
起こりません。
しかし内部的には、参照カウントは以下に挙げるマクロを使って
操作することができます。
</para>
<verbatim><![CDATA[
int SvREFCNT(SV* sv);
SV* SvREFCNT_inc(SV* sv);
void SvREFCNT_dec(SV* sv);
]]></verbatim>
<para>
However, there is one other function which manipulates the reference
count of its argument.  The <code>newRV_inc</code> function, you will recall,
creates a reference to the specified argument.  As a side effect,
it increments the argument's reference count.  If this is not what
you want, use <code>newRV_noinc</code> instead.
</para>
<para>
その引数の参照カウントを操作する別の関数が一つあります。
<code>newRV_inc</code> という関数がそれです。
これは指定された引数の参照を生成して、その副作用として引数の
参照カウントをインクリメントします。
もしこの副作用が邪魔であれば、<code>newRV_noinc</code> を代わりに使ってください。
</para>
<para>
For example, imagine you want to return a reference from an XSUB function.
Inside the XSUB routine, you create an SV which initially has a reference
count of one.  Then you call <code>newRV_inc</code>, passing it the just-created SV.
This returns the reference as a new SV, but the reference count of the
SV you passed to <code>newRV_inc</code> has been incremented to two.  Now you
return the reference from the XSUB routine and forget about the SV.
But Perl hasn't!  Whenever the returned reference is destroyed, the
reference count of the original SV is decreased to one and nothing happens.
The SV will hang around without any way to access it until Perl itself
terminates.  This is a memory leak.
</para>
<para>
たとえば、XSUB 関数からリファレンスを返したいと思ったとしましょう。
XSUB ルーチンの中で、初期値として参照カウント 1 を持つ SV を生成します。
それから今作成した SV を引数にして <code>newRV_inc</code> を呼びます。
これは新たな SV としての参照を返しますが、<code>newRV_inc</code> に引数として渡した
SV の参照カウントは 2 にインクリメントされます。
ここで XSUB ルーチンからそのリファレンスを戻り値として返し、SV のことは
忘れましょう。
けれども Perl は忘れてません! 
戻り値で返されたリファレンスが破棄されたときにはいつも、元々の SV の
参照カウントが 1 へと減じられ、そして何事もおこりません。
その SV は、Perl 自身が終了するまではそれにアクセスするなんの手段も
持たずに中ぶらりんになります。
</para>
<para>
The correct procedure, then, is to use <code>newRV_noinc</code> instead of
<code>newRV_inc</code>.  Then, if and when the last reference is destroyed,
the reference count of the SV will go to zero and it will be destroyed,
stopping any memory leak.
</para>
<para>
ここでの正しい手順は、<code>newRV_inc</code> ではなく <code>newRV_noinc</code> を
使うということです。
これによって、最後のリファレンスが破棄されたときに
SV のリファレンスカウントは0となってその SV が破棄されて、メモリ
リークを食い止めます。
</para>
<para>
There are some convenience functions available that can help with the
destruction of xVs.  These functions introduce the concept of &quot;mortality&quot;.
An xV that is mortal has had its reference count marked to be decremented,
but not actually decremented, until &quot;a short time later&quot;.  Generally the
term &quot;short time later&quot; means a single Perl statement, such as a call to
an XSUB function.  The actual determinant for when mortal xVs have their
reference count decremented depends on two macros, SAVETMPS and FREETMPS.
See <link xref='perlcall'>perlcall</link> and <link xref='perlxs'>perlxs</link> for more details on these macros.
</para>
<para>
xV を破棄するのを助けるような便利な関数が幾つかあります。
これらの関数は「揮発性」(mortality) のコンセプトを導入します。
ある揮発性の xV はその参照カウントをデクリメントするようにマークしますが、
実際には「ちょっと後」(a short time later)までデクリメントが
行なわれません。
一般的には、「ちょっと後」とは、XSUB 関数の呼び出しのような
Perl の一つの文です。
揮発性の xV が持っている参照カウントの
デクリメントを行うタイミングの決定は二つのマクロ、SAVETMPS と
FREETMPS に依存しています。
これら二つのマクロについての説明は
<link xref='perlcall'>perlcall</link> と <link xref='perlxs'>perlxs</link> を参照してください。
</para>
<para>
&quot;Mortalization&quot; then is at its simplest a deferred <code>SvREFCNT_dec</code>.
However, if you mortalize a variable twice, the reference count will
later be decremented twice.
</para>
<para>
「揮発化」(&quot;Mortalization&quot;) はそれから、<code>SvREFCNT_dec</code> に決定権を委ねます。
しかし、ある変数を二度揮発的にした場合、その参照カウントは後で
二度デクリメントされます。
</para>
<para>
&quot;Mortal&quot; SVs are mainly used for SVs that are placed on perl's stack.
For example an SV which is created just to pass a number to a called sub
is made mortal to have it cleaned up automatically when it's popped off
the stack. Similarly, results returned by XSUBs (which are pushed on the
stack) are often made mortal.
</para>
<para>
「揮発性」SVs は主に、perl のスタックに置かれる SV に対して使われます。
For example an SV which is created just to pass a number to a called sub
is made mortal to have it cleaned up automatically when it's popped off
the stack. Similarly, results returned by XSUBs (which are pushed on the
stack) are often made mortal.
(TBT)
</para>
<para>
To create a mortal variable, use the functions:
</para>
<para>
揮発性の変数を生成するには、以下の関数を使います:
</para>
<verbatim><![CDATA[
SV*  sv_newmortal()
SV*  sv_2mortal(SV*)
SV*  sv_mortalcopy(SV*)
]]></verbatim>
<para>
The first call creates a mortal SV (with no value), the second converts an existing
SV to a mortal SV (and thus defers a call to <code>SvREFCNT_dec</code>), and the
third creates a mortal copy of an existing SV.
Because <code>sv_newmortal</code> gives the new SV no value,it must normally be given one
via <code>sv_setpv</code>, <code>sv_setiv</code>, etc. :
</para>
<para>
最初のものは(値のない)揮発性の SV を生成し、ふたつめは既にある SV を
揮発性の SV に変換します(そして、このために <code>SvREFCNT_dec</code> を呼び出しを
遅らせます)。
三つめは、既に存在する SV の揮発性のコピーを生成します。
<code>sv_newmortal</code> は値のない新しい SV を作るので、普通は
<code>sv_setpv</code>, <code>sv_setiv</code> などを使って作らなければなりません:
</para>
<verbatim><![CDATA[
SV *tmp = sv_newmortal();
sv_setiv(tmp, an_integer);
]]></verbatim>
<para>
As that is multiple C statements it is quite common so see this idiom instead:
</para>
<para>
これは C の複数文なので、代わりにこの慣用法がとても一般的です:
</para>
<verbatim><![CDATA[
SV *tmp = sv_2mortal(newSViv(an_integer));
]]></verbatim>
<para>
You should be careful about creating mortal variables.  Strange things
can happen if you make the same value mortal within multiple contexts,
or if you make a variable mortal multiple times. Thinking of &quot;Mortalization&quot;
as deferred <code>SvREFCNT_dec</code> should help to minimize such problems.
For example if you are passing an SV which you <emphasis>know</emphasis> has high enough REFCNT
to survive its use on the stack you need not do any mortalization.
If you are not sure then doing an <code>SvREFCNT_inc</code> and <code>sv_2mortal</code>, or
making a <code>sv_mortalcopy</code> is safer.
</para>
<para>
揮発性の変数を生成するに当たっては十分注意すべきです。
もし、同じ変数を複合コンテキストの中で揮発性にしたり、ある変数を複数回
揮発性にしてしまったりすればおかしな自体が起こるかもしれません。
Thinking of &quot;Mortalization&quot;
as deferred <code>SvREFCNT_dec</code> should help to minimize such problems.
For example if you are passing an SV which you <emphasis>know</emphasis> has high enough REFCNT
to survive its use on the stack you need not do any mortalization.
If you are not sure then doing an <code>SvREFCNT_inc</code> and <code>sv_2mortal</code>, or
making a <code>sv_mortalcopy</code> is safer.
(TBT)
</para>
<para>
The mortal routines are not just for SVs -- AVs and HVs can be
made mortal by passing their address (type-casted to <code>SV*</code>) to the
<code>sv_2mortal</code> or <code>sv_mortalcopy</code> routines.
</para>
<para>
揮発性のルーチンは、単に SV のためだけではありません。
AV や HV も、<code>sv_2mortal</code> や <code>sv_mortalcopy</code> ルーチンに、アドレスを
(<code>SV*</code> にキャストして) 渡すことで、揮発性にすることができます。
</para>
</sect2>
<sect2>
<title>Stashes and Globs</title>
<para>
(スタッシュとグロブ)
</para>
<para>
A <strong>stash</strong> is a hash that contains all variables that are defined
within a package.  Each key of the stash is a symbol
name (shared by all the different types of objects that have the same
name), and each value in the hash table is a GV (Glob Value).  This GV
in turn contains references to the various objects of that name,
including (but not limited to) the following:
</para>
<para>
<strong>スタッシュ</strong> (&quot;stash&quot;)とは、パッケージ内で定義された全ての変数が
入っているハッシュのことです。
ハッシュテーブルにあるそれぞれの key は、(同じ名前のすべての異なる型の
オブジェクトで共有される) シンボル名で、ハッシュテーブルの個々の
値は、(グローバル値のための) GV と呼ばれます。
GV には、以下のものを含む (これらに限りませんが)、その名前の様々な
オブジェクトへのリファレンスが次々に入ることになります。
</para>
<verbatim><![CDATA[
Scalar Value
Array Value
Hash Value
I/O Handle
Format
Subroutine
]]></verbatim>
<para>
There is a single stash called <code>PL_defstash</code> that holds the items that exist
in the <code>main</code> package.  To get at the items in other packages, append the
string &quot;::&quot; to the package name.  The items in the <code>Foo</code> package are in
the stash <code>Foo::</code> in PL_defstash.  The items in the <code>Bar::Baz</code> package are
in the stash <code>Baz::</code> in <code>Bar::</code>'s stash.
</para>
<para>
<code>main</code> パッケージにあるアイテムを保持する <code>PL_defstash</code> と呼ばれる
スタッシュがあります。
他のパッケージにあるアイテムを取得するため
には、パッケージ名に「::」を付加します。
<code>Foo</code> というパッケージにあるアイテムは <code>Foo::</code> という
PL_defstash の中にあります。
パッケージ <code>Bar::Baz</code> にあるアイテムは <code>Bar::</code> のスタッシュの中の
<code>Baz::</code> のスタッシュの中にあります。
</para>
<para>
To get the stash pointer for a particular package, use the function:
</para>
<para>
特定のパッケージの HV ポインタの入手には、以下の関数が使えます:
</para>
<verbatim><![CDATA[
HV*  gv_stashpv(const char* name, I32 flags)
HV*  gv_stashsv(SV*, I32 flags)
]]></verbatim>
<para>
The first function takes a literal string, the second uses the string stored
in the SV.  Remember that a stash is just a hash table, so you get back an
<code>HV*</code>.  The <code>flags</code> flag will create a new package if it is set to GV_ADD.
</para>
<para>
最初の関数が、リテラル文字列をとり、二番目が SV に入れた文字列を使います。
stash は単なるハッシュなので、<code>HV*</code> を受け取るということを
忘れないでください。
<code>flags</code> フラグが GV_ADD にセットされている場合には新たなパッケージを
生成します。
</para>
<para>
The name that <code>gv_stash*v</code> wants is the name of the package whose symbol table
you want.  The default package is called <code>main</code>.  If you have multiply nested
packages, pass their names to <code>gv_stash*v</code>, separated by <code>::</code> as in the Perl
language itself.
</para>
<para>
<code>gv_stash*v</code> が要求する name はシンボルテーブルを手に入れようとする
パッケージの名前です。
デフォルトのパッケージは、<code>main</code> というものです。
多重にネストしたパッケージであれば、Perl での場合と同様に、
<code>::</code> で区切って <code>gv_stash*v</code> に名前を渡すのが正しい方法です。
</para>
<para>
Alternately, if you have an SV that is a blessed reference, you can find
out the stash pointer by using:
</para>
<para>
あるいは、もし bless されたリファレンスである SV があれば、
以下のようにしてを使ってもスタッシュポインタを探すことができ:
</para>
<verbatim><![CDATA[
HV*  SvSTASH(SvRV(SV*));
]]></verbatim>
<para>
then use the following to get the package name itself:
</para>
<para>
パッケージ名自身は、以下のようにして得られます:
</para>
<verbatim><![CDATA[
char*  HvNAME(HV* stash);
]]></verbatim>
<para>
If you need to bless or re-bless an object you can use the following
function:
</para>
<para>
Perl スクリプトへ bless された値を返す必要があれば、以下の関数が使えます:
</para>
<verbatim><![CDATA[
SV*  sv_bless(SV*, HV* stash)
]]></verbatim>
<para>
where the first argument, an <code>SV*</code>, must be a reference, and the second
argument is a stash.  The returned <code>SV*</code> can now be used in the same way
as any other SV.
</para>
<para>
最初の引数 <code>SV*</code> はリファレンスで、二番目の引数がスタッシュです。
返された <code>SV*</code> は、他の SV と同様に使うことができます。
</para>
<para>
For more information on references and blessings, consult <link xref='perlref'>perlref</link>.
</para>
<para>
リファレンスと bless についてのより詳しい情報は <link xref='perlref'>perlref</link> を
参照してください。
</para>
</sect2>
<sect2>
<title>Double-Typed SVs</title>
<para>
(二重型 SV)
</para>
<para>
Scalar variables normally contain only one type of value, an integer,
double, pointer, or reference.  Perl will automatically convert the
actual scalar data from the stored type into the requested type.
</para>
<para>
スカラ変数は通常、整数、倍精度、ポインタ、リファレンスのうちの
いずれか一つの型をとります。
Perl は実際のデータに対して、蓄積されている型から要求されている型へ、
自動的に変換を行ないます。
</para>
<para>
Some scalar variables contain more than one type of scalar data.  For
example, the variable <code>$!</code> contains either the numeric value of <code>errno</code>
or its string equivalent from either <code>strerror</code> or <code>sys_errlist[]</code>.
</para>
<para>
ある種のスカラ変数は、複数の型のスカラデータを持つようになっています。
たとえば変数 <code>$!</code> は、<code>errno</code> の数値としての値と、
<code>strerror</code> や <code>sys_errlist[]</code> から得たのと同値な文字列を持っています。
</para>
<para>
To force multiple data values into an SV, you must do two things: use the
<code>sv_set*v</code> routines to add the additional scalar type, then set a flag
so that Perl will believe it contains more than one type of data.  The
four macros to set the flags are:
</para>
<para>
SV に複数のデータ値を入れるようにするには、二つのことを
しなくてはなりません。
スカラ型を別に追加するために <code>sv_set*v</code> ルーチンを使用すること。
それから、フラグを設定して Perl に複数のデータを
持っていることを知らせることです。
フラグを設定するための四つのマクロは以下のものです:
</para>
<verbatim><![CDATA[
SvIOK_on
SvNOK_on
SvPOK_on
SvROK_on
]]></verbatim>
<para>
The particular macro you must use depends on which <code>sv_set*v</code> routine
you called first.  This is because every <code>sv_set*v</code> routine turns on
only the bit for the particular type of data being set, and turns off
all the rest.
</para>
<para>
使用するマクロは、最初にどの <code>sv_set*v</code> ルーチンを呼ぶのかに
関わってきます。
これは、<code>sv_set*v</code> ルーチンはすべて特定のデータ型のビットだけを
設定して、他をクリアしてしまうからです。
</para>
<para>
For example, to create a new Perl variable called &quot;dberror&quot; that contains
both the numeric and descriptive string error values, you could use the
following code:
</para>
<para>
たとえば、&quot;dberror&quot; という新しい Perl 変数を作って、エラー値を数値と
メッセージ文字列で持つようにするには、以下のように書きます:
</para>
<verbatim><![CDATA[
extern int  dberror;
extern char *dberror_list;
]]></verbatim>
<verbatim><![CDATA[
SV* sv = get_sv("dberror", TRUE);
sv_setiv(sv, (IV) dberror);
sv_setpv(sv, dberror_list[dberror]);
SvIOK_on(sv);
]]></verbatim>
<para>
If the order of <code>sv_setiv</code> and <code>sv_setpv</code> had been reversed, then the
macro <code>SvPOK_on</code> would need to be called instead of <code>SvIOK_on</code>.
</para>
<para>
<code>sv_setiv</code> と <code>sv_setpv</code> の順序が逆であった場合、<code>SvIOK_on</code> マクロの
代わりに <code>SvPOK_on</code> マクロを呼ばなければなりません。
</para>
</sect2>
<sect2>
<title>Magic Variables</title>
<para>
(マジック変数)
</para>
<para>
[This section still under construction.  Ignore everything here.  Post no
bills.  Everything not permitted is forbidden.]
</para>
<para>
[This section still under construction.  Ignore everything here.  Post no
bills.  Everything not permitted is forbidden.]
(TBT)
</para>
<para>
Any SV may be magical, that is, it has special features that a normal
SV does not have.  These features are stored in the SV structure in a
linked list of <code>struct magic</code>'s, typedef'ed to <code>MAGIC</code>.
</para>
<para>
すべての SV は magical、つまり、通常の SV が持っていないような特殊な
属性を持つようにすることができます。
これらの属性は <code>MAGIC</code> として typedef されている <code>struct magic</code> の
リンクリストにある SV 構造体に格納されます。
</para>
<verbatim><![CDATA[
struct magic {
    MAGIC*      mg_moremagic;
    MGVTBL*     mg_virtual;
    U16         mg_private;
    char        mg_type;
    U8          mg_flags;
    I32         mg_len;
    SV*         mg_obj;
    char*       mg_ptr;
};
]]></verbatim>
<para>
Note this is current as of patchlevel 0, and could change at any time.
</para>
<para>
これは、パッチレベル 0 の時点でのものです。
変更される可能性があります。
</para>
</sect2>
<sect2>
<title>Assigning Magic</title>
<para>
(マジックの代入)
</para>
<para>
Perl adds magic to an SV using the sv_magic function:
</para>
<para>
Perl は sv_magic 関数を使った SV にマジックを追加します。
</para>
<verbatim><![CDATA[
void sv_magic(SV* sv, SV* obj, int how, const char* name, I32 namlen);
]]></verbatim>
<para>
The <code>sv</code> argument is a pointer to the SV that is to acquire a new magical
feature.
</para>
<para>
引数 <code>sv</code> は、新たにマジック機能を獲得する SV へのポインタです。
</para>
<para>
If <code>sv</code> is not already magical, Perl uses the <code>SvUPGRADE</code> macro to
convert <code>sv</code> to type <code>SVt_PVMG</code>. Perl then continues by adding new magic
to the beginning of the linked list of magical features.  Any prior entry
of the same type of magic is deleted.  Note that this can be overridden,
and multiple instances of the same type of magic can be associated with an
SV.
</para>
<para>
<code>sv</code> がまだマジカルでなければ、Perl は <code>sv</code> を <code>SVt_PVMG</code> に変換
するために <code>SvUPGRADE</code> を使います。
Perl はそれから、マジック機能のリンクリストの先頭にそれを追加します。
以前に存在していた同じタイプのマジックは削除されます。
これはオーバーライドすることができ、
複数の同じ型のマジックのインスタンスを一つの SV に
結び付けることができるということに注意してください。
</para>
<para>
The <code>name</code> and <code>namlen</code> arguments are used to associate a string with
the magic, typically the name of a variable. <code>namlen</code> is stored in the
<code>mg_len</code> field and if <code>name</code> is non-null then either a <code>savepvn</code> copy of
<code>name</code> or <code>name</code> itself is stored in the <code>mg_ptr</code> field, depending on
whether <code>namlen</code> is greater than zero or equal to zero respectively.  As a
special case, if <code>(name &amp;&amp; namlen == HEf_SVKEY)</code> then <code>name</code> is assumed
to contain an <code>SV*</code> and is stored as-is with its REFCNT incremented.
</para>
<para>
引数 <code>name</code> と <code>namlen</code> はある文字列と magic とを結び付けるために
使われます。
典型的には変数の名前です。
<code>namlen</code> は <code>mg_len</code> フィールドに格納され、<code>name</code> がヌルなら、
<code>name</code> の <code>savepvn</code> コピーか、<code>name</code> 自身 is stored in the <code>mg_ptr</code> field, depending on
whether <code>namlen</code> is greater than zero or equal to zero respectively.  As a
special case, if <code>(name &amp;&amp; namlen == HEf_SVKEY)</code> then <code>name</code> is assumed
to contain an <code>SV*</code> and is stored as-is with its REFCNT incremented.
(TBT)
</para>
<para>
The sv_magic function uses <code>how</code> to determine which, if any, predefined
&quot;Magic Virtual Table&quot; should be assigned to the <code>mg_virtual</code> field.
See the <link xref='Magic Virtual Tables'>Magic Virtual Tables</link> section below.  The <code>how</code> argument is also
stored in the <code>mg_type</code> field. The value of <code>how</code> should be chosen
from the set of macros <code>PERL_MAGIC_foo</code> found in <filename>perl.h</filename>. Note that before
these macros were added, Perl internals used to directly use character
literals, so you may occasionally come across old code or documentation
referring to 'U' magic rather than <code>PERL_MAGIC_uvar</code> for example.
</para>
<para>
関数 sv_magic は <code>how</code> を、あらかじめ定義されている
マジック仮想テーブル(&quot;Magic Virtual Table&quot;) のどれを
<code>mg_virtual</code> フィールドに設定するかを決定するのに使います。
See the <link xref='Magic Virtual Tables'>Magic Virtual Tables</link> section below.  The <code>how</code> argument is also
stored in the <code>mg_type</code> field. The value of <code>how</code> should be chosen
from the set of macros <code>PERL_MAGIC_foo</code> found in <filename>perl.h</filename>. Note that before
these macros were added, Perl internals used to directly use character
literals, so you may occasionally come across old code or documentation
referring to 'U' magic rather than <code>PERL_MAGIC_uvar</code> for example.
(TBT)
</para>
<para>
The <code>obj</code> argument is stored in the <code>mg_obj</code> field of the <code>MAGIC</code>
structure.  If it is not the same as the <code>sv</code> argument, the reference
count of the <code>obj</code> object is incremented.  If it is the same, or if
the <code>how</code> argument is <code>PERL_MAGIC_arylen</code>, or if it is a NULL pointer,
then <code>obj</code> is merely stored, without the reference count being incremented.
</para>
<para>
引数 <code>obj</code> は <code>MAGIC</code> 構造体の <code>mg_obj</code> フィールドに格納されます。
これが <code>sv</code> 引数と同じでなかった場合、<code>obj</code> の参照カウントは
インクリメントされます。
同じであった場合、もしくは引数 <code>how</code> が
<code>PERL_MAGIC_arylen</code> かナルポインタであった場合には、<code>obj</code> は
参照カウントのインクリメントをさせることなく格納されます。
</para>
<para>
See also <code>sv_magicext</code> in <link xref='perlapi'>perlapi</link> for a more flexible way to add magic
to an SV.
</para>
<para>
SV にマジックを追加する、より柔軟な方法については <link xref='perlapi'>perlapi</link> の
<code>sv_magicext</code> も参照してください。
</para>
<para>
There is also a function to add magic to an <code>HV</code>:
</para>
<para>
同様に <code>HV</code> にマジックを付加する関数があります。
</para>
<verbatim><![CDATA[
void hv_magic(HV *hv, GV *gv, int how);
]]></verbatim>
<para>
This simply calls <code>sv_magic</code> and coerces the <code>gv</code> argument into an <code>SV</code>.
</para>
<para>
これは単純に <code>sv_magic</code> を呼び出し、引数 <code>gv</code> を強制的に <code>SV</code> にします。
</para>
<para>
To remove the magic from an SV, call the function sv_unmagic:
</para>
<para>
SV からマジックを取り除くには、sv_unmagic という関数を呼び出します。
</para>
<verbatim><![CDATA[
void sv_unmagic(SV *sv, int type);
]]></verbatim>
<para>
The <code>type</code> argument should be equal to the <code>how</code> value when the <code>SV</code>
was initially made magical.
</para>
<para>
引数 <code>type</code> は、<code>SV</code> が magical にされたときの <code>how</code> の値と同じに
なるようにすべきです。
</para>
</sect2>
<sect2>
<title>Magic Virtual Tables</title>
<para>
(マジック仮想テーブル)
</para>
<para>
The <code>mg_virtual</code> field in the <code>MAGIC</code> structure is a pointer to an
<code>MGVTBL</code>, which is a structure of function pointers and stands for
&quot;Magic Virtual Table&quot; to handle the various operations that might be
applied to that variable.
</para>
<para>
<code>MAGIC</code> 構造体の <code>mg_virtual</code> フィールドは <code>MGVTBL</code> へのポインタで、
これは関数ポインタの構造体であり、また対応する変数に対して
適用される可能性のあるさまざまな操作を扱うための
「マジック仮想テーブル」(&quot;Magic Virtual Table&quot;) を意味しています。
</para>
<para>
The <code>MGVTBL</code> has five (or sometimes eight) pointers to the following
routine types:
</para>
<para>
<code>MGVTBL</code> は、以下に挙げる 5 種類(あるいは時々 8 種類)の
ポインタを持っています。
</para>
<verbatim><![CDATA[
int  (*svt_get)(SV* sv, MAGIC* mg);
int  (*svt_set)(SV* sv, MAGIC* mg);
U32  (*svt_len)(SV* sv, MAGIC* mg);
int  (*svt_clear)(SV* sv, MAGIC* mg);
int  (*svt_free)(SV* sv, MAGIC* mg);
]]></verbatim>
<verbatim><![CDATA[
int  (*svt_copy)(SV *sv, MAGIC* mg, SV *nsv, const char *name, int namlen);
int  (*svt_dup)(MAGIC *mg, CLONE_PARAMS *param);
int  (*svt_local)(SV *nsv, MAGIC *mg);
]]></verbatim>
<para>
This MGVTBL structure is set at compile-time in <filename>perl.h</filename> and there are
currently 19 types (or 21 with overloading turned on).  These different
structures contain pointers to various routines that perform additional
actions depending on which function is being called.
</para>
<para>
この MGVTBL は <filename>perl.h</filename> の中でコンパイル時に設定され、現在 19 の型
(オーバーロード込みで 21)があります。
これらの異なった構造体は、関数が呼び出されたときに依存して
追加動作を行うような様々なルーチンへのポインタを保持しています。
</para>
<verbatim><![CDATA[
Function pointer    Action taken
----------------    ------------
svt_get             Do something before the value of the SV is retrieved.
svt_set             Do something after the SV is assigned a value.
svt_len             Report on the SV's length.
svt_clear           Clear something the SV represents.
svt_free            Free any extra storage associated with the SV.
]]></verbatim>
<verbatim><![CDATA[
関数ポインタ     その振る舞い
    ----------------    ------------
    svt_get             SV の値が取得された前に何かを行う。
    svt_set             SV に値を代入した後で何かを行う。
    svt_len             SV の長さを報告する。
    svt_clear		SV が表わしているものををクリアする。
    svt_free            SV に結び付けられてい領域を解放する。
]]></verbatim>
<verbatim><![CDATA[
svt_copy            copy tied variable magic to a tied element
svt_dup             duplicate a magic structure during thread cloning
svt_local           copy magic to local value during 'local'
]]></verbatim>
<verbatim><![CDATA[
svt_copy            tie された変数のマジックを tie された要素にコピーする
svt_dup             スレッドのクローン化中にマジック構造体を複製する
svt_local           'local' 中にマジックをローカル変数にコピーする
]]></verbatim>
<para>
For instance, the MGVTBL structure called <code>vtbl_sv</code> (which corresponds
to an <code>mg_type</code> of <code>PERL_MAGIC_sv</code>) contains:
</para>
<para>
たとえば、<code>vtbl_sv</code> (<code>PERL_MAGIC_sv</code> の <code>mg_type</code> に対応します)と
呼ばれる MGVTBL 構造体の内容は以下の様になっています。
</para>
<verbatim><![CDATA[
{ magic_get, magic_set, magic_len, 0, 0 }
]]></verbatim>
<para>
Thus, when an SV is determined to be magical and of type <code>PERL_MAGIC_sv</code>,
if a get operation is being performed, the routine <code>magic_get</code> is
called.  All the various routines for the various magical types begin
with <code>magic_</code>.  NOTE: the magic routines are not considered part of
the Perl API, and may not be exported by the Perl library.
</para>
<para>
したがって、ある SV がマジカルであると決定されてその型が
<code>PERL_MAGIC_sv</code> であったとき、操作が実行されたならば、<code>magic_get</code> が
呼び出されます。
マジカル型に対するルーチンはすべて、<code>magic_</code> で始まります。
NOTE: マジックルーチンは Perl API の一部として扱われず、
Perl ライブラリによってエクスポートされません。
</para>
<para>
The last three slots are a recent addition, and for source code
compatibility they are only checked for if one of the three flags
MGf_COPY, MGf_DUP or MGf_LOCAL is set in mg_flags. This means that most
code can continue declaring a vtable as a 5-element value. These three are
currently used exclusively by the threading code, and are highly subject
to change.
</para>
<para>
The last three slots are a recent addition, and for source code
compatibility they are only checked for if one of the three flags
MGf_COPY, MGf_DUP or MGf_LOCAL is set in mg_flags. This means that most
code can continue declaring a vtable as a 5-element value. These three are
currently used exclusively by the threading code, and are highly subject
to change.
(TBT)
</para>
<para>
The current kinds of Magic Virtual Tables are:
</para>
<para>
現時点でのMagic Virtual Tables の種類は以下の通りです。
</para>
<verbatim><![CDATA[
mg_type
(old-style char and macro)   MGVTBL          Type of magic
--------------------------   ------          -------------
\0 PERL_MAGIC_sv             vtbl_sv         Special scalar variable
A  PERL_MAGIC_overload       vtbl_amagic     %OVERLOAD hash
a  PERL_MAGIC_overload_elem  vtbl_amagicelem %OVERLOAD hash element
c  PERL_MAGIC_overload_table (none)          Holds overload table (AMT)
                                             on stash
B  PERL_MAGIC_bm             vtbl_bm         Boyer-Moore (fast string search)
D  PERL_MAGIC_regdata        vtbl_regdata    Regex match position data
                                             (@+ and @- vars)
d  PERL_MAGIC_regdatum       vtbl_regdatum   Regex match position data
                                             element
E  PERL_MAGIC_env            vtbl_env        %ENV hash
e  PERL_MAGIC_envelem        vtbl_envelem    %ENV hash element
f  PERL_MAGIC_fm             vtbl_fm         Formline ('compiled' format)
g  PERL_MAGIC_regex_global   vtbl_mglob      m//g target / study()ed string
H  PERL_MAGIC_hints          vtbl_sig        %^H hash
h  PERL_MAGIC_hintselem      vtbl_hintselem  %^H hash element
I  PERL_MAGIC_isa            vtbl_isa        @ISA array
i  PERL_MAGIC_isaelem        vtbl_isaelem    @ISA array element
k  PERL_MAGIC_nkeys          vtbl_nkeys      scalar(keys()) lvalue
L  PERL_MAGIC_dbfile         (none)          Debugger %_<filename
l  PERL_MAGIC_dbline         vtbl_dbline     Debugger %_<filename element
o  PERL_MAGIC_collxfrm       vtbl_collxfrm   Locale collate transformation
P  PERL_MAGIC_tied           vtbl_pack       Tied array or hash
p  PERL_MAGIC_tiedelem       vtbl_packelem   Tied array or hash element
q  PERL_MAGIC_tiedscalar     vtbl_packelem   Tied scalar or handle
r  PERL_MAGIC_qr             vtbl_qr         precompiled qr// regex
S  PERL_MAGIC_sig            vtbl_sig        %SIG hash
s  PERL_MAGIC_sigelem        vtbl_sigelem    %SIG hash element
t  PERL_MAGIC_taint          vtbl_taint      Taintedness
U  PERL_MAGIC_uvar           vtbl_uvar       Available for use by extensions
v  PERL_MAGIC_vec            vtbl_vec        vec() lvalue
V  PERL_MAGIC_vstring        (none)          v-string scalars
w  PERL_MAGIC_utf8           vtbl_utf8       UTF-8 length+offset cache
x  PERL_MAGIC_substr         vtbl_substr     substr() lvalue
y  PERL_MAGIC_defelem        vtbl_defelem    Shadow "foreach" iterator
                                             variable / smart parameter
                                             vivification
#  PERL_MAGIC_arylen         vtbl_arylen     Array length ($#ary)
.  PERL_MAGIC_pos            vtbl_pos        pos() lvalue
<  PERL_MAGIC_backref        vtbl_backref    back pointer to a weak ref 
~  PERL_MAGIC_ext            (none)          Available for use by extensions
:  PERL_MAGIC_symtab         (none)          hash used as symbol table
%  PERL_MAGIC_rhash          (none)          hash used as restricted hash
@  PERL_MAGIC_arylen_p       vtbl_arylen_p   pointer to $#a from @a
]]></verbatim>
<verbatim><![CDATA[
mg_type
(old-style char and macro)   MGVTBL          Type of magic
--------------------------   ------          -------------
\0 PERL_MAGIC_sv             vtbl_sv         特殊スカラ変数
A  PERL_MAGIC_overload       vtbl_amagic     %OVERLOAD ハッシュ
a  PERL_MAGIC_overload_elem  vtbl_amagicelem %OVERLOAD ハッシュ要素
c  PERL_MAGIC_overload_table (none)          スタッシュのオーバーロード
                                             テーブル(AMT) を保持
B  PERL_MAGIC_bm             vtbl_bm         Boyer-Moore (高速文字列検索)
D  PERL_MAGIC_regdata        vtbl_regdata    正規表現マッチング位置データ
                                             (@+ と @- の変数)
d  PERL_MAGIC_regdatum       vtbl_regdatum   正規表現マッチング位置データ
                                             要素
E  PERL_MAGIC_env            vtbl_env        %ENV ハッシュ
e  PERL_MAGIC_envelem        vtbl_envelem    %ENV ハッシュ要素
f  PERL_MAGIC_fm             vtbl_fm         フォーム行(「コンパイル済み」
                                             フォーマット)
g  PERL_MAGIC_regex_global   vtbl_mglob      m//g のターゲット / study() した文字列
H  PERL_MAGIC_hints          vtbl_sig        %^H ハッシュ
h  PERL_MAGIC_hintselem      vtbl_hintselem  %^H ハッシュ要素
I  PERL_MAGIC_isa            vtbl_isa        @ISA 配列
i  PERL_MAGIC_isaelem        vtbl_isaelem    @ISA 配列要素
k  PERL_MAGIC_nkeys          vtbl_nkeys      scalar(keys()) 左辺値
L  PERL_MAGIC_dbfile         (none)          デバッガの %_<filename
l  PERL_MAGIC_dbline         vtbl_dbline     デバッガの %_<filename 要素
o  PERL_MAGIC_collxfrm       vtbl_collxfrm   ロケール照合変換
P  PERL_MAGIC_tied           vtbl_pack       tie された配列やハッシュ
p  PERL_MAGIC_tiedelem       vtbl_packelem   tie された配列やハッシュの要素
q  PERL_MAGIC_tiedscalar     vtbl_packelem   tie されたスカラやハンドル
r  PERL_MAGIC_qr             vtbl_qr         事前コンパイルされた qr// 正規表現
S  PERL_MAGIC_sig            vtbl_sig        %SIG ハッシュ
s  PERL_MAGIC_sigelem        vtbl_sigelem    %SIG ハッシュ要素
t  PERL_MAGIC_taint          vtbl_taint      汚染性
U  PERL_MAGIC_uvar           vtbl_uvar       エクステンションで使用可能
v  PERL_MAGIC_vec            vtbl_vec        vec() 左辺値
V  PERL_MAGIC_vstring        (none)          v-文字列スカラ
w  PERL_MAGIC_utf8           vtbl_utf8       UTF-8 長さ+オフセットキャッシュ
x  PERL_MAGIC_substr         vtbl_substr     substr() 左辺値
y  PERL_MAGIC_defelem        vtbl_defelem    影の "foreach" 反復子
                                             変数 / スマート引数
                                             自動有効化
#  PERL_MAGIC_arylen         vtbl_arylen     配列の長さ ($#ary)
.  PERL_MAGIC_pos            vtbl_pos        pos() 左辺値
<  PERL_MAGIC_backref        vtbl_backref    弱いリファレンスへの後方ポインタ
~  PERL_MAGIC_ext            (none)          エクステンションで使用可能
:  PERL_MAGIC_symtab         (none)          シンボルテーブルとして使われるハッシュ
%  PERL_MAGIC_rhash          (none)          制限ハッシュとして使われるハッシュ
@  PERL_MAGIC_arylen_p       vtbl_arylen_p   @a から $#a へのポインタ
]]></verbatim>
<para>
When an uppercase and lowercase letter both exist in the table, then the
uppercase letter is typically used to represent some kind of composite type
(a list or a hash), and the lowercase letter is used to represent an element
of that composite type. Some internals code makes use of this case
relationship.  However, 'v' and 'V' (vec and v-string) are in no way related.
</para>
<para>
テーブル中で大文字小文字の両方が存在していた場合、大文字は典型的には複合型
(リストもしくはハッシュ)の種類を表わすのに使われ、小文字はその複合型の
要素を表わすのに使われます。
内部コードにはこの大文字小文字の関係を使っているものもあります。
しかし、'v' と 'V' (ベクタと v-文字列) は全く関係がありません。
</para>
<para>
The <code>PERL_MAGIC_ext</code> and <code>PERL_MAGIC_uvar</code> magic types are defined
specifically for use by extensions and will not be used by perl itself.
Extensions can use <code>PERL_MAGIC_ext</code> magic to 'attach' private information
to variables (typically objects).  This is especially useful because
there is no way for normal perl code to corrupt this private information
(unlike using extra elements of a hash object).
</para>
<para>
マジック型 <code>PERL_MAGIC_ext</code> と <code>PERL_MAGIC_uvar</code> は
エクステンションから使われ、Perl 自身からは使われないように特別に
定義されています。
エクステンションは <code>PERL_MAGIC_ext</code> マジックを、
プライベート情報を変数(典型的なオブジェクト)に「アタッチ」(attach)
するために使うことができます。
これは、通常の perl コードが(ハッシュオブジェクトの要素を使うのとは違って)
そのプライベート情報を壊す恐れがないのでとても便利です。
</para>
<para>
Similarly, <code>PERL_MAGIC_uvar</code> magic can be used much like tie() to call a
C function any time a scalar's value is used or changed.  The <code>MAGIC</code>'s
<code>mg_ptr</code> field points to a <code>ufuncs</code> structure:
</para>
<para>
Similarly, <code>PERL_MAGIC_uvar</code> magic can be used much like tie() to call a
C function any time a scalar's value is used or changed.  The <code>MAGIC</code>'s
<code>mg_ptr</code> field points to a <code>ufuncs</code> structure:
(TBT)
</para>
<verbatim><![CDATA[
struct ufuncs {
    I32 (*uf_val)(pTHX_ IV, SV*);
    I32 (*uf_set)(pTHX_ IV, SV*);
    IV uf_index;
};
]]></verbatim>
<para>
When the SV is read from or written to, the <code>uf_val</code> or <code>uf_set</code>
function will be called with <code>uf_index</code> as the first arg and a pointer to
the SV as the second.  A simple example of how to add <code>PERL_MAGIC_uvar</code>
magic is shown below.  Note that the ufuncs structure is copied by
sv_magic, so you can safely allocate it on the stack.
</para>
<para>
When the SV is read from or written to, the <code>uf_val</code> or <code>uf_set</code>
function will be called with <code>uf_index</code> as the first arg and a pointer to
the SV as the second.  A simple example of how to add <code>PERL_MAGIC_uvar</code>
magic is shown below.  Note that the ufuncs structure is copied by
sv_magic, so you can safely allocate it on the stack.
(TBT)
</para>
<verbatim><![CDATA[
void
Umagic(sv)
    SV *sv;
PREINIT:
    struct ufuncs uf;
CODE:
    uf.uf_val   = &my_get_fn;
    uf.uf_set   = &my_set_fn;
    uf.uf_index = 0;
    sv_magic(sv, 0, PERL_MAGIC_uvar, (char*)&uf, sizeof(uf));
]]></verbatim>
<para>
Attaching <code>PERL_MAGIC_uvar</code> to arrays is permissible but has no effect.
</para>
<para>
<code>PERL_MAGIC_uvar</code> を配列にアタッチすることは可能ですが、何の意味も
ありません。
</para>
<para>
For hashes there is a specialized hook that gives control over hash
keys (but not values).  This hook calls <code>PERL_MAGIC_uvar</code> 'get' magic
if the &quot;set&quot; function in the <code>ufuncs</code> structure is NULL.  The hook
is activated whenever the hash is accessed with a key specified as
an <code>SV</code> through the functions <code>hv_store_ent</code>, <code>hv_fetch_ent</code>,
<code>hv_delete_ent</code>, and <code>hv_exists_ent</code>.  Accessing the key as a string
through the functions without the <code>..._ent</code> suffix circumvents the
hook.  See <link xref='Hash::Util::Fieldhash#Guts'>Hash::Util::Fieldhash/Guts</link> for a detailed description.
</para>
<para>
For hashes there is a specialized hook that gives control over hash
keys (but not values).  This hook calls <code>PERL_MAGIC_uvar</code> 'get' magic
if the &quot;set&quot; function in the <code>ufuncs</code> structure is NULL.  The hook
is activated whenever the hash is accessed with a key specified as
an <code>SV</code> through the functions <code>hv_store_ent</code>, <code>hv_fetch_ent</code>,
<code>hv_delete_ent</code>, and <code>hv_exists_ent</code>.  Accessing the key as a string
through the functions without the <code>..._ent</code> suffix circumvents the
hook.  See <link xref='Hash::Util::Fieldhash#Guts'>Hash::Util::Fieldhash/Guts</link> for a detailed description.
(TBT)
</para>
<para>
Note that because multiple extensions may be using <code>PERL_MAGIC_ext</code>
or <code>PERL_MAGIC_uvar</code> magic, it is important for extensions to take
extra care to avoid conflict.  Typically only using the magic on
objects blessed into the same class as the extension is sufficient.
For <code>PERL_MAGIC_ext</code> magic, it may also be appropriate to add an I32
'signature' at the top of the private data area and check that.
</para>
<para>
複数のエクステンションが <code>PERL_MAGIC_ext</code> や <code>PERL_MAGIC_uvar</code> マジックを
使う可能性があるので、エクステンションがそれを扱うには気をつけることが
重要であることに注意してください。
典型的には、これはオブジェクトをエクステンションが扱えるように同じクラスに
bless するときにのみ使います。
<code>PERL_MAGIC_ext</code> マジックでは、これはまた、プライベートなデータ領域の
先頭においてそれをチェックするために I32「シグネチャ」(signature) を
付加するのに適切なものです。
</para>
<para>
Also note that the <code>sv_set*()</code> and <code>sv_cat*()</code> functions described
earlier do <strong>not</strong> invoke 'set' magic on their targets.  This must
be done by the user either by calling the <code>SvSETMAGIC()</code> macro after
calling these functions, or by using one of the <code>sv_set*_mg()</code> or
<code>sv_cat*_mg()</code> functions.  Similarly, generic C code must call the
<code>SvGETMAGIC()</code> macro to invoke any 'get' magic if they use an SV
obtained from external sources in functions that don't handle magic.
See <link xref='perlapi'>perlapi</link> for a description of these functions.
For example, calls to the <code>sv_cat*()</code> functions typically need to be
followed by <code>SvSETMAGIC()</code>, but they don't need a prior <code>SvGETMAGIC()</code>
since their implementation handles 'get' magic.
</para>
<para>
<code>sv_set*()</code> と <code>sv_cat*()</code> といった関数群はそのターゲットに対して
'set' マジックを <strong>起動しない</strong> ということにも注意してください。
これには、ユーザーが <code>svSETMAGIC</code> マクロを呼び出した後でこれらの関数を
呼び出すか、あるいは <code>sv_set*_mg()</code> か
<code>sv_cat*_mg()</code> の何れかの関数を使わなければなりません。
同様に、一般的な C コードは、
それがマジックを扱っていないような関数から得られた
SV を使っているのであれば、
'get' マジックを起動するために
<code>SvGETMAGIC</code> を呼び出さなければなりません。
これらの関数については <link xref='perlapi'>perlapi</link> を参照してください。
例えば、<code>sv_cat*()</code> 関数群の
呼び出しは通常引き続いて <code>SvSETMAGIC()</code> を呼び出す必要がありますが、
<code>SvGETMAGIC</code> が先行している必要はありません;
なぜなら、その実装は 'get' マジックを扱うからです。
</para>
</sect2>
<sect2>
<title>Finding Magic</title>
<para>
(マジックを見つけだす)
</para>
<verbatim><![CDATA[
MAGIC* mg_find(SV*, int type); /* Finds the magic pointer of that type */
]]></verbatim>
<para>
This routine returns a pointer to the <code>MAGIC</code> structure stored in the SV.
If the SV does not have that magical feature, <code>NULL</code> is returned.  Also,
if the SV is not of type SVt_PVMG, Perl may core dump.
</para>
<para>
このルーチンは SV に格納されている <code>MAGIC</code> 構造体へのポインタを
返します。
SV がマジカル機能を持っていなければ、<code>NULL</code> が返されます。
また、SV が Svt_PVMG の型でなければ Perl はコアダンプするかもしれません。
</para>
<verbatim><![CDATA[
int mg_copy(SV* sv, SV* nsv, const char* key, STRLEN klen);
]]></verbatim>
<para>
This routine checks to see what types of magic <code>sv</code> has.  If the mg_type
field is an uppercase letter, then the mg_obj is copied to <code>nsv</code>, but
the mg_type field is changed to be the lowercase letter.
</para>
<para>
このルーチンは <code>sv</code> が持っているマジックの型を検査します。
mg_type フィールドが大文字であれば、mg_obj が <code>nsv</code> にコピーされますが、
mg_type フィールドは小文字に変更されます。
</para>
</sect2>
<sect2>
<title>Understanding the Magic of Tied Hashes and Arrays</title>
<para>
(tie されたハッシュと配列のマジックを理解する)
</para>
<para>
Tied hashes and arrays are magical beasts of the <code>PERL_MAGIC_tied</code>
magic type.
</para>
<para>
tie されたハッシュと配列は <code>PERL_MAGIC_tied</code> マジック型の magical beast です。
</para>
<para>
WARNING: As of the 5.004 release, proper usage of the array and hash
access functions requires understanding a few caveats.  Some
of these caveats are actually considered bugs in the API, to be fixed
in later releases, and are bracketed with [MAYCHANGE] below. If
you find yourself actually applying such information in this section, be
aware that the behavior may change in the future, umm, without warning.
</para>
<para>
警告: リリース 5.004 以降、配列やハッシュに対するアクセス
関数の正しい使い方は、幾つかの注意点を理解していることを要求しています。
これら幾つかの注意点は実際には API におけるバグとして
みなされるものであって、将来のリリースにおいては修正されます。
また、注意点は [MAYCHANGE] というブラケットで囲まれています。
このセクションにある情報をあなたが実際に使おうというのであれば、
将来それらは警告なしに変わる可能性があることに注意してください。
</para>
<para>
The perl tie function associates a variable with an object that implements
the various GET, SET, etc methods.  To perform the equivalent of the perl
tie function from an XSUB, you must mimic this behaviour.  The code below
carries out the necessary steps - firstly it creates a new hash, and then
creates a second hash which it blesses into the class which will implement
the tie methods. Lastly it ties the two hashes together, and returns a
reference to the new tied hash.  Note that the code below does NOT call the
TIEHASH method in the MyTie class -
see <link xref='Calling Perl Routines from within C Programs'>Calling Perl Routines from within C Programs</link> for details on how
to do this.
</para>
<para>
perl の tie 関数は、ある変数と GET、SET 等といった様々なメソッドを
実装しているオブジェクトとを結び付けるものです。
XSUB から perl の tie 関数と等価な働きをさせるには、
ちょっとしたオマジナイをしなければなりません。
以下の例が必要なステップです。
まず最初にハッシュを作り、それから
tie メソッドを実装するクラスに bless した二番目のハッシュを作ります。
最後に二つのハッシュを tie し、新たに生成した tie されたハッシュに対する
リファレンスを返します。
以下の例では MyTie クラスの中で TIEHASH を呼び出していないということに
注意してください。
この件に関する詳細は <link xref='Calling Perl Routines from within C Programs'>Calling Perl Routines from within C Programs</link> を
参照してください。
</para>
<verbatim><![CDATA[
SV*
mytie()
PREINIT:
    HV *hash;
    HV *stash;
    SV *tie;
CODE:
    hash = newHV();
    tie = newRV_noinc((SV*)newHV());
    stash = gv_stashpv("MyTie", GV_ADD);
    sv_bless(tie, stash);
    hv_magic(hash, (GV*)tie, PERL_MAGIC_tied);
    RETVAL = newRV_noinc(hash);
OUTPUT:
    RETVAL
]]></verbatim>
<para>
The <code>av_store</code> function, when given a tied array argument, merely
copies the magic of the array onto the value to be &quot;stored&quot;, using
<code>mg_copy</code>.  It may also return NULL, indicating that the value did not
actually need to be stored in the array.  [MAYCHANGE] After a call to
<code>av_store</code> on a tied array, the caller will usually need to call
<code>mg_set(val)</code> to actually invoke the perl level &quot;STORE&quot; method on the
TIEARRAY object.  If <code>av_store</code> did return NULL, a call to
<code>SvREFCNT_dec(val)</code> will also be usually necessary to avoid a memory
leak. [/MAYCHANGE]
</para>
<para>
tie された配列を引数に与えられたときの <code>av_store</code> 関数は、単に配列の
magic を <code>mg_copy</code> を使って「保管」されるように値をコピーするだけです。
この関数は、その値が実際には配列に格納する必要のないものであることを
示す NULL を返す可能性があります。
[MAYCHANGE]
tie された配列に対して <code>av_store</code> を呼び出した後、呼び出し側は TIEARRAY
オブジェクトに対して Perl レベルの &quot;STORE&quot; メソッドを起動するために
<code>av_store</code> を呼び出すことが通常は必要となります。
<code>av_store</code> が NULL を返したならば、メモリリークを防ぐために
<code>SvREFCNT_dec(val)</code> を呼び出すことが必要となります。
[/MAYCHANGE]
</para>
<para>
The previous paragraph is applicable verbatim to tied hash access using the
<code>hv_store</code> and <code>hv_store_ent</code> functions as well.
</para>
<para>
先のパラグラフの説明は、tie されたハッシュにアクセスするのに使用する
<code>hv_store</code> と <code>hv_store_ent</code> についても同様です。
</para>
<para>
<code>av_fetch</code> and the corresponding hash functions <code>hv_fetch</code> and
<code>hv_fetch_ent</code> actually return an undefined mortal value whose magic
has been initialized using <code>mg_copy</code>.  Note the value so returned does not
need to be deallocated, as it is already mortal.  [MAYCHANGE] But you will
need to call <code>mg_get()</code> on the returned value in order to actually invoke
the perl level &quot;FETCH&quot; method on the underlying TIE object.  Similarly,
you may also call <code>mg_set()</code> on the return value after possibly assigning
a suitable value to it using <code>sv_setsv</code>,  which will invoke the &quot;STORE&quot;
method on the TIE object. [/MAYCHANGE]
</para>
<para>
<code>av_fetch</code> と、対応するハッシュ関数 <code>hv_fetch</code> および <code>hv_fetch_ent</code> は
実際には <code>mg_copy</code> を使って初期化が行なわれている未定義の揮発値を返します。
返された値はすでに揮発性なので、解放する必要がないことに注意してください。
[MAYCHANGE]
しかし、TIE オブジェクトに対応した perl レベルの
&quot;FETCH&quot; メソッドを実行するには、返されたその値に対して
<code>mg_get()</code> を呼び出す必要があるでしょう。
同様に、TIE オブジェクトに対する &quot;STORE&quot; メソッドの起動である
<code>sv_setsv</code> を使って適切な値を代入した後で、返された値に対して
<code>mg_set()</code> を呼び出すことができます。
[/MAYCHANGE]
</para>
<para>
[MAYCHANGE]
In other words, the array or hash fetch/store functions don't really
fetch and store actual values in the case of tied arrays and hashes.  They
merely call <code>mg_copy</code> to attach magic to the values that were meant to be
&quot;stored&quot; or &quot;fetched&quot;.  Later calls to <code>mg_get</code> and <code>mg_set</code> actually
do the job of invoking the TIE methods on the underlying objects.  Thus
the magic mechanism currently implements a kind of lazy access to arrays
and hashes.
</para>
<para>
[MAYCHANGE]
言い換えれば、配列やハッシュをフェッチしたりストアする関数は、
tie されている配列やハッシュに対する場合には実際に値をフェッチしたり
保管したりするわけではないということです。
それらの関数は「保管」されたり「フェッチ」された値に対してマジックを
付加するために、単に <code>mg_copy</code> を呼び出すだけです。
</para>
<para>
Currently (as of perl version 5.004), use of the hash and array access
functions requires the user to be aware of whether they are operating on
&quot;normal&quot; hashes and arrays, or on their tied variants.  The API may be
changed to provide more transparent access to both tied and normal data
types in future versions.
[/MAYCHANGE]
</para>
<para>
現在(バージョン 5.004)、ハッシュや配列に対するアクセス関数を使用する
際には、ユーザーが「通常の」ハッシュや配列なのか、あるいはそれが
tie されたものであるのかを気をつけることが要求されています。
将来のバージョンでは、この API は tie されたデータに対するアクセスと
通常のデータに対するアクセスをより透過的にするために変更されるかも
しれません。
[/MAYCHANGE]
</para>
<para>
You would do well to understand that the TIEARRAY and TIEHASH interfaces
are mere sugar to invoke some perl method calls while using the uniform hash
and array syntax.  The use of this sugar imposes some overhead (typically
about two to four extra opcodes per FETCH/STORE operation, in addition to
the creation of all the mortal variables required to invoke the methods).
This overhead will be comparatively small if the TIE methods are themselves
substantial, but if they are only a few statements long, the overhead
will not be insignificant.
</para>
<para>
TIEARRAY や TIEHASH といったインターフェースが、統一的な
ハッシュ/配列構文を使うための perl メソッドを起動をするための単なる
砂糖であることを良く理解したことでしょう。
これらの砂糖の使用はいくらかのオーバーヘッド(通常、FETCH/STORE 操作
当たり二つから四つの余分なオペコード、それに加えてメソッドを
起動するために必要なすべての揮発性変数の生成)を招きます。
このオーバーヘッドは TIE メソッド自身がしっかりしたものであれば、ほぼ
同等なくらい小さなものでしかありませんが、ほんの少し文が長いだけでも
オーバーヘッドは無視できないものになります。
</para>
</sect2>
<sect2>
<title>Localizing changes</title>
<para>
(変更をローカル化する)
</para>
<para>
Perl has a very handy construction
</para>
<para>
Perl には非常に便利な構造があります。
</para>
<verbatim><![CDATA[
{
  local $var = 2;
  ...
}
]]></verbatim>
<para>
This construction is <emphasis>approximately</emphasis> equivalent to
</para>
<para>
この構造は以下のものと <emphasis>ほぼ</emphasis> 同じです
</para>
<verbatim><![CDATA[
{
  my $oldvar = $var;
  $var = 2;
  ...
  $var = $oldvar;
}
]]></verbatim>
<para>
The biggest difference is that the first construction would
reinstate the initial value of $var, irrespective of how control exits
the block: <code>goto</code>, <code>return</code>, <code>die</code>/<code>eval</code>, etc. It is a little bit
more efficient as well.
</para>
<para>
両者の最も大きな違いは、最初のものが
<code>goto</code>、<code>return</code>、<code>die</code>/<code>eval</code> など
どのようにブロックから脱出しようとも、
$var の元々の値を復帰するということです。
効率といった面では大きな違いはありません。
</para>
<para>
There is a way to achieve a similar task from C via Perl API: create a
<emphasis>pseudo-block</emphasis>, and arrange for some changes to be automatically
undone at the end of it, either explicit, or via a non-local exit (via
die()). A <emphasis>block</emphasis>-like construct is created by a pair of
<code>ENTER</code>/<code>LEAVE</code> macros (see <link xref='perlcall#Returning_a_Scalar'>perlcall/&quot;Returning a Scalar&quot;</link>).
Such a construct may be created specially for some important localized
task, or an existing one (like boundaries of enclosing Perl
subroutine/block, or an existing pair for freeing TMPs) may be
used. (In the second case the overhead of additional localization must
be almost negligible.) Note that any XSUB is automatically enclosed in
an <code>ENTER</code>/<code>LEAVE</code> pair.
</para>
<para>
Perl API を通して C から同様の処理を行う方法もあります。
<emphasis>擬似ブロック</emphasis>(pseudo-block)を生成し、そのブロックの最後で自動的に
復帰するような幾つかの変更を行います。
ブロックから抜けるのは、明示的に抜けるための指示があっても良いし、
非局所的な脱出(die() を使ったもの)でもかまいません。
ブロックに似たこの構造は <code>ENTER</code>/<code>LEAVE</code> マクロのペアによって
生成されます(<link xref='perlcall#Returning_a_Scalar'>perlcall/&quot;Returning a Scalar&quot;</link> を参照してください)。
このような構造ではなにか重要なローカル化された
タスクのための特別なものを作成したり、あるいは
既に存在しているもの(Perl のサブルーチン/ブロックに束縛されたものとか、
あるいは解放する一時変数のペア)を使うことも可能です
(二番目のケースでは、ローカル化するためのオーバーヘッドはほとんど
無視できるものです)。
すべての XSUB は自動的に <code>ENTER</code>/<code>LEAVE</code> の
ペアによって囲まれているということに注意してください。
</para>
<para>
Inside such a <emphasis>pseudo-block</emphasis> the following service is available:
</para>
<para>
このような <emphasis>擬似ブロック</emphasis> の中では以下のサービスが利用可能です:
</para>
<list>
<item><itemtext><code>SAVEINT(int i)</code></itemtext>
</item>
<item><itemtext><code>SAVEIV(IV i)</code></itemtext>
</item>
<item><itemtext><code>SAVEI32(I32 i)</code></itemtext>
</item>
<item><itemtext><code>SAVELONG(long i)</code></itemtext>
<para>
These macros arrange things to restore the value of integer variable
<code>i</code> at the end of enclosing <emphasis>pseudo-block</emphasis>.
</para>
<para>
これらのマクロはそれを囲む <emphasis>擬似ブロック</emphasis> において
整数変数 <code>i</code> の値をリストアするようにします。
</para>
</item>
<item><itemtext><code>SAVESPTR(s)</code></itemtext>
</item>
<item><itemtext><code>SAVEPPTR(p)</code></itemtext>
<para>
These macros arrange things to restore the value of pointers <code>s</code> and
<code>p</code>. <code>s</code> must be a pointer of a type which survives conversion to
<code>SV*</code> and back, <code>p</code> should be able to survive conversion to <code>char*</code>
and back.
</para>
<para>
これらのマクロは、ポインタ<code>s</code>もしくは <code>p</code> の値を
リストアします。
<code>s</code> は <code>SV*</code> に対する型変換をできるポインタでなければなりません。
<code>p</code> は <code>char*</code> への型変換が可能であるべきものです。
</para>
</item>
<item><itemtext><code>SAVEFREESV(SV *sv)</code></itemtext>
<para>
The refcount of <code>sv</code> would be decremented at the end of
<emphasis>pseudo-block</emphasis>.  This is similar to <code>sv_2mortal</code> in that it is also a
mechanism for doing a delayed <code>SvREFCNT_dec</code>.  However, while <code>sv_2mortal</code>
extends the lifetime of <code>sv</code> until the beginning of the next statement,
<code>SAVEFREESV</code> extends it until the end of the enclosing scope.  These
lifetimes can be wildly different.
</para>
<para>
<emphasis>擬似ブロック</emphasis> の終端において <code>sv</code> の参照カウントは
デクリメントされます。
これは、遅延した <code>SvREFCNT_dec</code> を行うための機構という意味で
<code>sv_2motral</code> に似たものです。
However, while <code>sv_2mortal</code>
extends the lifetime of <code>sv</code> until the beginning of the next statement,
<code>SAVEFREESV</code> extends it until the end of the enclosing scope.  These
lifetimes can be wildly different.
(TBT)
</para>
<para>
Also compare <code>SAVEMORTALIZESV</code>.
</para>
<para>
また、<code>SAVEMORTALIZESV</code> を比較します。
</para>
</item>
<item><itemtext><code>SAVEMORTALIZESV(SV *sv)</code></itemtext>
<para>
Just like <code>SAVEFREESV</code>, but mortalizes <code>sv</code> at the end of the current
scope instead of decrementing its reference count.  This usually has the
effect of keeping <code>sv</code> alive until the statement that called the currently
live scope has finished executing.
</para>
<para>
Just like <code>SAVEFREESV</code>, but mortalizes <code>sv</code> at the end of the current
scope instead of decrementing its reference count.  This usually has the
effect of keeping <code>sv</code> alive until the statement that called the currently
live scope has finished executing.
(TBT)
</para>
</item>
<item><itemtext><code>SAVEFREEOP(OP *op)</code></itemtext>
<para>
The <code>OP *</code> is op_free()ed at the end of <emphasis>pseudo-block</emphasis>.
</para>
<para>
<code>OP *</code> は <emphasis>擬似ブロック</emphasis> の終端において op_free() されます。
</para>
</item>
<item><itemtext><code>SAVEFREEPV(p)</code></itemtext>
<para>
The chunk of memory which is pointed to by <code>p</code> is Safefree()ed at the
end of <emphasis>pseudo-block</emphasis>.
</para>
<para>
<code>p</code> によって指し示されているメモリの塊は <emphasis>擬似ブロック</emphasis> の終端で
Safefree() されます。
</para>
</item>
<item><itemtext><code>SAVECLEARSV(SV *sv)</code></itemtext>
<para>
Clears a slot in the current scratchpad which corresponds to <code>sv</code> at
the end of <emphasis>pseudo-block</emphasis>.
</para>
<para>
<strong>擬似ブロック</strong> の終端において、
<code>sv</code> に対応している
カレントのスクラッチパッドにおけるスロットをクリアします。
</para>
</item>
<item><itemtext><code>SAVEDELETE(HV *hv, char *key, I32 length)</code></itemtext>
<para>
The key <code>key</code> of <code>hv</code> is deleted at the end of <emphasis>pseudo-block</emphasis>. The
string pointed to by <code>key</code> is Safefree()ed.  If one has a <emphasis>key</emphasis> in
short-lived storage, the corresponding string may be reallocated like
this:
</para>
<para>
<emphasis>擬似ブロック</emphasis> の終端で <code>hv</code> にあるキー <code>key</code> は削除されます。
<code>key</code> によって指し示されている文字列は Safefree() されます。
short-lived storageにある <emphasis>key</emphasis> を持っているものがあった場合には
以下のようにして対応する文字列が再割り当てされます。
</para>
<verbatim><![CDATA[
SAVEDELETE(PL_defstash, savepv(tmpbuf), strlen(tmpbuf));
]]></verbatim>
</item>
<item><itemtext><code>SAVEDESTRUCTOR(DESTRUCTORFUNC_NOCONTEXT_t f, void *p)</code></itemtext>
<para>
At the end of <emphasis>pseudo-block</emphasis> the function <code>f</code> is called with the
only argument <code>p</code>.
</para>
<para>
<emphasis>擬似ブロック</emphasis> の終端において関数 <code>f</code> が呼び出されます。
この関数 <code>f</code> は <code>p</code> のみを引数に取ります。
</para>
</item>
<item><itemtext><code>SAVEDESTRUCTOR_X(DESTRUCTORFUNC_t f, void *p)</code></itemtext>
<para>
At the end of <emphasis>pseudo-block</emphasis> the function <code>f</code> is called with the
implicit context argument (if any), and <code>p</code>.
</para>
<para>
<emphasis>疑似ブロック</emphasis> の最後に、関数 <code>f</code> が(もしあれば)暗黙のコンテキスト
引数と <code>p</code> で呼び出されます。
</para>
</item>
<item><itemtext><code>SAVESTACK_POS()</code></itemtext>
<para>
The current offset on the Perl internal stack (cf. <code>SP</code>) is restored
at the end of <emphasis>pseudo-block</emphasis>.
</para>
<para>
<emphasis>擬似ブロック</emphasis> の終端において Perl の内部スタック(<code>SP</code>)のカレント
オフセットがリストアされます。
</para>
</item>
</list>
<para>
The following API list contains functions, thus one needs to
provide pointers to the modifiable data explicitly (either C pointers,
or Perlish <code>GV *</code>s).  Where the above macros take <code>int</code>, a similar
function takes <code>int *</code>.
</para>
<para>
以下の API リストは、変更可能なデータを指し示すポインタ
(C のポインタか、Perl 的な <code>GV *</code> のいずれか)
を必要とする関数群です。
前述の <code>int</code> を引数に取るマクロに似て、
<code>int *</code> を引数に取る関数があります。
</para>
<list>
<item><itemtext><code>SV* save_scalar(GV *gv)</code></itemtext>
<para>
Equivalent to Perl code <code>local $gv</code>.
</para>
<para>
Perl コード <code>local $gv</code> と等価です。
</para>
</item>
<item><itemtext><code>AV* save_ary(GV *gv)</code></itemtext>
</item>
<item><itemtext><code>HV* save_hash(GV *gv)</code></itemtext>
<para>
Similar to <code>save_scalar</code>, but localize <code>@gv</code> and <code>%gv</code>.
</para>
<para>
<code>save_scalar</code> に似ていますが、<code>@gv</code> と <code>%gv</code> の局所化を行います。
</para>
</item>
<item><itemtext><code>void save_item(SV *item)</code></itemtext>
<para>
Duplicates the current value of <code>SV</code>, on the exit from the current
<code>ENTER</code>/<code>LEAVE</code> <emphasis>pseudo-block</emphasis> will restore the value of <code>SV</code>
using the stored value. It doesn't handle magic. Use <code>save_scalar</code> if
magic is affected.
</para>
<para>
<code>SV</code> のカレントの値を複製し、カレントの <code>ENTER</code>/<code>LEAVE</code>
<strong>擬似ブロック</strong> を抜けるときに <code>SV</code> の保存した値を復帰します。
マジックを扱いません。
マジックを有効にしたい場合は <code>save_scalar</code> を使ってください。
</para>
</item>
<item><itemtext><code>void save_list(SV **sarg, I32 maxsarg)</code></itemtext>
<para>
A variant of <code>save_item</code> which takes multiple arguments via an array
<code>sarg</code> of <code>SV*</code> of length <code>maxsarg</code>.
</para>
<para>
複数の引数を長さ <code>maxarg</code> の <code>SV*</code> の配列 <code>sarg</code> として取る
<code>save_item</code> の複数の値を取るバリエーションです。
</para>
</item>
<item><itemtext><code>SV* save_svref(SV **sptr)</code></itemtext>
<para>
Similar to <code>save_scalar</code>, but will reinstate an <code>SV *</code>.
</para>
<para>
<code>save_scalar</code> に似ていますが、<code>SV *</code> の復帰を行います。
</para>
</item>
<item><itemtext><code>void save_aptr(AV **aptr)</code></itemtext>
</item>
<item><itemtext><code>void save_hptr(HV **hptr)</code></itemtext>
<para>
Similar to <code>save_svref</code>, but localize <code>AV *</code> and <code>HV *</code>.
</para>
<para>
<code>save_svref</code> に似ていますが、<code>AV *</code> と <code>HV *</code> のローカル化を行います。
</para>
</item>
</list>
<para>
The <code>Alias</code> module implements localization of the basic types within the
<emphasis>caller's scope</emphasis>.  People who are interested in how to localize things in
the containing scope should take a look there too.
</para>
<para>
<code>Alias</code> モジュールは <strong>呼び出し側のスコープ</strong> 中での基本型のローカル化を
実装します。
スコープを持った何かのローカル化に興味のある人は
そこに何があるかも見ておいた方が良いでしょう。
</para>
</sect2>
</sect1>
<sect1>
<title>Subroutines</title>
<sect2>
<title>XSUBs and the Argument Stack</title>
<para>
(XSUB と引数スタック)
</para>
<para>
The XSUB mechanism is a simple way for Perl programs to access C subroutines.
An XSUB routine will have a stack that contains the arguments from the Perl
program, and a way to map from the Perl data structures to a C equivalent.
</para>
<para>
XSUB の仕組みは、Perl プログラムが C のサブルーチンを
アクセスするための単純な方法です。
XSUB には、Perl プログラムからの引数を入れるスタックと、Perl のデータ
構造を C の等価なものにマッピングする方法を用意しています。
</para>
<para>
The stack arguments are accessible through the <code>ST(n)</code> macro, which returns
the <code>n</code>'th stack argument.  Argument 0 is the first argument passed in the
Perl subroutine call.  These arguments are <code>SV*</code>, and can be used anywhere
an <code>SV*</code> is used.
</para>
<para>
スタック引数は <code>ST(n)</code> というマクロを使ってアクセスできます。
これは、<code>n</code> 番目のスタック引数を返すものです。
引数 0 は、Perl のサブルーチン呼び出しで渡された最初の引数です。
これらの引数は <code>SV*</code> で、<code>SV*</code> が使われるところであればどこでも
使うことができます。
</para>
<para>
Most of the time, output from the C routine can be handled through use of
the RETVAL and OUTPUT directives.  However, there are some cases where the
argument stack is not already long enough to handle all the return values.
An example is the POSIX tzname() call, which takes no arguments, but returns
two, the local time zone's standard and summer time abbreviations.
</para>
<para>
ほとんどの場合には、C ルーチンからの出力は RETVAL 指示子と
OUTPUT 指示子を使って扱うことができます。
しかし、引数スタックのスペースがすべての返却値を扱うのに十分で
なくなる場合があります。
例としては、引数をとらないでローカルなタイムゾーンと夏時間の省略形の
二つの返却値を返す、POSIX の tzname() の呼び出しがあります。
</para>
<para>
To handle this situation, the PPCODE directive is used and the stack is
extended using the macro:
</para>
<para>
このような状況を扱うためには、PPCODE ディレクティブを使い、さらに
スタックを以下のマクロを使って拡張します:
</para>
<verbatim><![CDATA[
EXTEND(SP, num);
]]></verbatim>
<para>
where <code>SP</code> is the macro that represents the local copy of the stack pointer,
and <code>num</code> is the number of elements the stack should be extended by.
</para>
<para>
ここで <code>SP</code> はスタックポインタで、<code>num</code> はスタックを拡張すべき
要素の数です。
</para>
<para>
Now that there is room on the stack, values can be pushed on it using <code>PUSHs</code>
macro. The pushed values will often need to be &quot;mortal&quot; (See
<link xref='Reference Counts and Mortality'>/Reference Counts and Mortality</link>):
</para>
<para>
スタック上に場所を確保したら、<code>PUSHs</code> マクロを使って値をスタックへ
プッシュします。
The pushed values will often need to be &quot;mortal&quot; (See
<link xref='Reference Counts and Mortality'>/Reference Counts and Mortality</link>):
(TBT)
</para>
<verbatim><![CDATA[
PUSHs(sv_2mortal(newSViv(an_integer)))
PUSHs(sv_2mortal(newSVuv(an_unsigned_integer)))
PUSHs(sv_2mortal(newSVnv(a_double)))
PUSHs(sv_2mortal(newSVpv("Some String",0)))
]]></verbatim>
<para>
And now the Perl program calling <code>tzname</code>, the two values will be assigned
as in:
</para>
<para>
これで、<code>tzname</code> を呼ぶ Perl プログラムでは、二つの値は
以下のように代入できます。
</para>
<verbatim><![CDATA[
($standard_abbrev, $summer_abbrev) = POSIX::tzname;
]]></verbatim>
<para>
An alternate (and possibly simpler) method to pushing values on the stack is
to use the macro:
</para>
<para>
スタックに値を積む、別の (おそらくはより簡単な) 方法は、
以下のマクロを使うことです。
</para>
<verbatim><![CDATA[
XPUSHs(SV*)
]]></verbatim>
<para>
This macro automatically adjust the stack for you, if needed.  Thus, you
do not need to call <code>EXTEND</code> to extend the stack.
</para>
<para>
こちらのマクロは、必要ならば自動的にスタックを調整してくれます。
このため、<code>EXTEND</code> をスタックを拡張するために呼ぶ必要はありません。
</para>
<para>
Despite their suggestions in earlier versions of this document the macros
<code>(X)PUSH[iunp]</code> are <emphasis>not</emphasis> suited to XSUBs which return multiple results.
For that, either stick to the <code>(X)PUSHs</code> macros shown above, or use the new
<code>m(X)PUSH[iunp]</code> macros instead; see <link xref='Putting a C value on Perl stack'>/Putting a C value on Perl stack</link>.
</para>
<para>
Despite their suggestions in earlier versions of this document the macros
<code>(X)PUSH[iunp]</code> are <emphasis>not</emphasis> suited to XSUBs which return multiple results.
For that, either stick to the <code>(X)PUSHs</code> macros shown above, or use the new
<code>m(X)PUSH[iunp]</code> macros instead; see <link xref='Putting a C value on Perl stack'>/Putting a C value on Perl stack</link>.
(TBT)
</para>
<para>
For more information, consult <link xref='perlxs'>perlxs</link> and <link xref='perlxstut'>perlxstut</link>.
</para>
<para>
より詳しい情報は、<link xref='perlxs'>perlxs</link> と <link xref='perlxstut'>perlxstut</link> を参照してください。
</para>
</sect2>
<sect2>
<title>Calling Perl Routines from within C Programs</title>
<para>
(CプログラムからのPerlルーチンの呼び出し)
</para>
<para>
There are four routines that can be used to call a Perl subroutine from
within a C program.  These four are:
</para>
<para>
C プログラムから Perl サブルーチンを呼び出すために使用することのできる
ルーチンが 四つあります。
その四つは:
</para>
<verbatim><![CDATA[
I32  call_sv(SV*, I32);
I32  call_pv(const char*, I32);
I32  call_method(const char*, I32);
I32  call_argv(const char*, I32, register char**);
]]></verbatim>
<para>
The routine most often used is <code>call_sv</code>.  The <code>SV*</code> argument
contains either the name of the Perl subroutine to be called, or a
reference to the subroutine.  The second argument consists of flags
that control the context in which the subroutine is called, whether
or not the subroutine is being passed arguments, how errors should be
trapped, and how to treat return values.
</para>
<para>
最もよく使われるはずのものは、<code>call_sv</code> です。
引数 <code>SV*</code> には呼び出される Perl サブルーチンの名前か、その
サブルーチンへのリファレンスが含まれます。
二番目の引数には、そのサブルーチンが呼び出されたコンテキストを制御する
フラグが置かれます。
これはサブルーチンに引数が渡されたか渡されていないか、エラーを
どのようにトラップすべきなのか、どのように戻り値を返すのかを
制御するものです。
</para>
<para>
All four routines return the number of arguments that the subroutine returned
on the Perl stack.
</para>
<para>
四つのルーチンはいずれも、サブルーチンが Perl スタック上に返した
引数の数を返します。
</para>
<para>
These routines used to be called <code>perl_call_sv</code>, etc., before Perl v5.6.0,
but those names are now deprecated; macros of the same name are provided for
compatibility.
</para>
<para>
These routines used to be called <code>perl_call_sv</code>, etc., before Perl v5.6.0,
しかしこれらの名前は現在では非推奨です; 同じ名前のマクロが互換性のために
提供されています。
(TBT)
</para>
<para>
When using any of these routines (except <code>call_argv</code>), the programmer
must manipulate the Perl stack.  These include the following macros and
functions:
</para>
<para>
これらのルーチンを使うときには(<code>call_argv</code> を除いて)、プログラマが
Perl スタックを操作しなくてはなりません。
以下のマクロと関数が用意されています:
</para>
<verbatim><![CDATA[
dSP
SP
PUSHMARK()
PUTBACK
SPAGAIN
ENTER
SAVETMPS
FREETMPS
LEAVE
XPUSH*()
POP*()
]]></verbatim>
<para>
For a detailed description of calling conventions from C to Perl,
consult <link xref='perlcall'>perlcall</link>.
</para>
<para>
C から Perl を呼び出す約束ごとについての詳しい記述は
<link xref='perlcall'>perlcall</link> を参照してください。
</para>
</sect2>
<sect2>
<title>Memory Allocation</title>
<para>
(メモリ割り当て)
</para>
<sect3>
<title>Allocation</title>
<para>
(割り当て)
</para>
<para>
All memory meant to be used with the Perl API functions should be manipulated
using the macros described in this section.  The macros provide the necessary
transparency between differences in the actual malloc implementation that is
used within perl.
</para>
<para>
Perl API 関数と共に使うような全てのメモリはこのセクションで
説明されているマクロを使って扱うべきです。
マクロは実際の malloc の
実装と、perl で使われているものとの差を透過的にします。
</para>
<para>
It is suggested that you enable the version of malloc that is distributed
with Perl.  It keeps pools of various sizes of unallocated memory in
order to satisfy allocation requests more quickly.  However, on some
platforms, it may cause spurious malloc or free errors.
</para>
<para>
Perl と一緒に配布されていて、あなたがこれを使うことを推奨されている
malloc の変種です。
これは様々な大きさの未割り付けのメモリをプールしておき、
より早く割り付け要求に応えようとするものです。
しかしながら一部のプラットフォームでは、これは不法なmallocエラーや
freeエラーを引き起こす可能性があります。
</para>
<para>
The following three macros are used to initially allocate memory :
</para>
<para>
これら三つのマクロはメモリの割り付けのために使われます:
</para>
<verbatim><![CDATA[
Newx(pointer, number, type);
Newxc(pointer, number, type, cast);
Newxz(pointer, number, type);
]]></verbatim>
<para>
The first argument <code>pointer</code> should be the name of a variable that will
point to the newly allocated memory.
</para>
<para>
1 番目の引数 <code>pointer</code> は、新たにメモリを割り付けられる変数の
名前にします。
</para>
<para>
The second and third arguments <code>number</code> and <code>type</code> specify how many of
the specified type of data structure should be allocated.  The argument
<code>type</code> is passed to <code>sizeof</code>.  The final argument to <code>Newxc</code>, <code>cast</code>,
should be used if the <code>pointer</code> argument is different from the <code>type</code>
argument.
</para>
<para>
3 番目と 4 番目の引数 <code>number</code> と <code>type</code> は、指定された構造体を
どれだけ割り付けるのかを指定します。
引数 <code>type</code> は <code>sizeof</code> に渡されます。
<code>Newxc</code>に対する最後の引数 <code>cast</code>は、引数 <code>pointer</code> が
引数 <code>type</code> と異なるときに使うべきものです。
</para>
<para>
Unlike the <code>Newx</code> and <code>Newxc</code> macros, the <code>Newxz</code> macro calls <code>memzero</code>
to zero out all the newly allocated memory.
</para>
<para>
<code>Newx</code> や <code>Newxc</code> とは異なり、<code>Newxz</code> は割り付けたメモリのすべてを
ゼロで埋めるために <code>memzero</code> を呼び出します。
</para>
</sect3>
<sect3>
<title>Reallocation</title>
<verbatim><![CDATA[
Renew(pointer, number, type);
Renewc(pointer, number, type, cast);
Safefree(pointer)
]]></verbatim>
<para>
These three macros are used to change a memory buffer size or to free a
piece of memory no longer needed.  The arguments to <code>Renew</code> and <code>Renewc</code>
match those of <code>New</code> and <code>Newc</code> with the exception of not needing the
&quot;magic cookie&quot; argument.
</para>
<para>
上記の三つのマクロは、メモリのバッファーサイズを変更したりもう
使わなくなったメモリ領域を解放するために使われます。
<code>Renew</code> と
<code>Renewc</code> の引数は、“魔法のクッキー”引数が必要ないということを
除きそれぞれ <code>New</code> と <code>Renewc</code> に一致します。
</para>
</sect3>
<sect3>
<title>Moving</title>
<verbatim><![CDATA[
Move(source, dest, number, type);
Copy(source, dest, number, type);
Zero(dest, number, type);
]]></verbatim>
<para>
These three macros are used to move, copy, or zero out previously allocated
memory.  The <code>source</code> and <code>dest</code> arguments point to the source and
destination starting points.  Perl will move, copy, or zero out <code>number</code>
instances of the size of the <code>type</code> data structure (using the <code>sizeof</code>
function).
</para>
<para>
この三つのマクロは、それぞれ割り付けたメモリ領域に対する移動、
複写、ゼロで埋めるといったことに使われます。
<code>source</code> と <code>dest</code> という引数は、転送元と転送先の開始番地への
ポインタです。
Perl は、構造体 <code>type</code> の大きさ (<code>sizeof</code> 関数を使います)のインスタンスの
<code>number</code> 個分だけ、移動、複写、ゼロ埋めを行います。
</para>
</sect3>
</sect2>
<sect2>
<title>PerlIO</title>
<para>
The most recent development releases of Perl has been experimenting with
removing Perl's dependency on the &quot;normal&quot; standard I/O suite and allowing
other stdio implementations to be used.  This involves creating a new
abstraction layer that then calls whichever implementation of stdio Perl
was compiled with.  All XSUBs should now use the functions in the PerlIO
abstraction layer and not make any assumptions about what kind of stdio
is being used.
</para>
<para>
最新リリースの Perl の開発では、Perl の「通常の」標準入出力ライブラリに
依存している部分を取り除くことと、Perl で別の標準入出力の実装が
使えるようにすることが試みられました。
これにより必然的に、Perl と共にコンパイルされた標準入出力の実装を
呼び出すような新しい抽象層が作られました。
すべての XSUB は、今では PerlIO 抽象層の関数を使うべきで、
これまで使っていた標準入出力に関してのすべての仮定はすべきではありません。
</para>
<para>
For a complete description of the PerlIO abstraction, consult <link xref='perlapio'>perlapio</link>.
</para>
<para>
PerlIO 抽象化に関する詳しい記述は  <link xref='perlapio'>perlapio</link> を参照してください。
</para>
</sect2>
<sect2>
<title>Putting a C value on Perl stack</title>
<para>
(C での値を Perl スタックに入れる)
</para>
<para>
A lot of opcodes (this is an elementary operation in the internal perl
stack machine) put an SV* on the stack. However, as an optimization
the corresponding SV is (usually) not recreated each time. The opcodes
reuse specially assigned SVs (<emphasis>target</emphasis>s) which are (as a corollary)
not constantly freed/created.
</para>
<para>
たくさんのオペコード(これは内部的な perl スタックマシンでの基本的な
操作です)が SV をスタックに置きます。
しかしながら、SV に対する最適化のようなものは(通常は)毎回
行なわれるわけではありません。
オペコードは解放されたり、生成されることのない特別に割り当てられた
SVs (<emphasis>target</emphasis>s) を再利用します。
</para>
<para>
Each of the targets is created only once (but see
<link xref='Scratchpads and recursion'>Scratchpads and recursion</link> below), and when an opcode needs to put
an integer, a double, or a string on stack, it just sets the
corresponding parts of its <emphasis>target</emphasis> and puts the <emphasis>target</emphasis> on stack.
</para>
<para>
それぞれの targets は、一度だけ生成して(ただし、後述する
<link xref='Scratchpads and recursion'>Scratchpads and recursion</link> を参照のこと)、オペコードがスタックに
整数値、倍精度実数値、文字列といったものを置くことを必要とするときに、
スタックに <emphasis>target</emphasis> を置きます。
</para>
<para>
The macro to put this target on stack is <code>PUSHTARG</code>, and it is
directly used in some opcodes, as well as indirectly in zillions of
others, which use it via <code>(X)PUSH[iunp]</code>.
</para>
<para>
この target をスタックに置くためのマクロが <code>PUSHTARG</code> です。
このマクロは、他の多くのマクロが <code>(X)PUSH[iunp]</code> を通じて間接的に
使っているのと同様に、幾つかのオペコードで直接使われています。
</para>
<para>
Because the target is reused, you must be careful when pushing multiple
values on the stack. The following code will not do what you think:
</para>
<para>
Because the target is reused, you must be careful when pushing multiple
values on the stack. The following code will not do what you think:
(TBT)
</para>
<verbatim><![CDATA[
XPUSHi(10);
XPUSHi(20);
]]></verbatim>
<para>
This translates as &quot;set <code>TARG</code> to 10, push a pointer to <code>TARG</code> onto
the stack; set <code>TARG</code> to 20, push a pointer to <code>TARG</code> onto the stack&quot;.
At the end of the operation, the stack does not contain the values 10
and 20, but actually contains two pointers to <code>TARG</code>, which we have set
to 20.
</para>
<para>
This translates as &quot;set <code>TARG</code> to 10, push a pointer to <code>TARG</code> onto
the stack; set <code>TARG</code> to 20, push a pointer to <code>TARG</code> onto the stack&quot;.
At the end of the operation, the stack does not contain the values 10
and 20, but actually contains two pointers to <code>TARG</code>, which we have set
to 20.
(TBT)
</para>
<para>
If you need to push multiple different values then you should either use
the <code>(X)PUSHs</code> macros, or else use the new <code>m(X)PUSH[iunp]</code> macros,
none of which make use of <code>TARG</code>.  The <code>(X)PUSHs</code> macros simply push an
SV* on the stack, which, as noted under <link xref='XSUBs and the Argument Stack'>/XSUBs and the Argument Stack</link>,
will often need to be &quot;mortal&quot;.  The new <code>m(X)PUSH[iunp]</code> macros make
this a little easier to achieve by creating a new mortal for you (via
<code>(X)PUSHmortal</code>), pushing that onto the stack (extending it if necessary
in the case of the <code>mXPUSH[iunp]</code> macros), and then setting its value.
Thus, instead of writing this to &quot;fix&quot; the example above:
</para>
<para>
If you need to push multiple different values then you should either use
the <code>(X)PUSHs</code> macros, or else use the new <code>m(X)PUSH[iunp]</code> macros,
none of which make use of <code>TARG</code>.  The <code>(X)PUSHs</code> macros simply push an
SV* on the stack, which, as noted under <link xref='XSUBs and the Argument Stack'>/XSUBs and the Argument Stack</link>,
will often need to be &quot;mortal&quot;.  The new <code>m(X)PUSH[iunp]</code> macros make
this a little easier to achieve by creating a new mortal for you (via
<code>(X)PUSHmortal</code>), pushing that onto the stack (extending it if necessary
in the case of the <code>mXPUSH[iunp]</code> macros), and then setting its value.
Thus, instead of writing this to &quot;fix&quot; the example above:
(TBT)
</para>
<verbatim><![CDATA[
XPUSHs(sv_2mortal(newSViv(10)))
XPUSHs(sv_2mortal(newSViv(20)))
]]></verbatim>
<para>
you can simply write:
</para>
<para>
you can simply write:
(TBT)
</para>
<verbatim><![CDATA[
mXPUSHi(10)
mXPUSHi(20)
]]></verbatim>
<para>
On a related note, if you do use <code>(X)PUSH[iunp]</code>, then you're going to
need a <code>dTARG</code> in your variable declarations so that the <code>*PUSH*</code>
macros can make use of the local variable <code>TARG</code>.  See also <code>dTARGET</code>
and <code>dXSTARG</code>.
</para>
<para>
On a related note, if you do use <code>(X)PUSH[iunp]</code>, then you're going to
need a <code>dTARG</code> in your variable declarations so that the <code>*PUSH*</code>
macros can make use of the local variable <code>TARG</code>.  See also <code>dTARGET</code>
and <code>dXSTARG</code>.
(TBT)
</para>
</sect2>
<sect2>
<title>Scratchpads</title>
<para>
(スクラッチパッド)
</para>
<para>
The question remains on when the SVs which are <emphasis>target</emphasis>s for opcodes
are created. The answer is that they are created when the current unit --
a subroutine or a file (for opcodes for statements outside of
subroutines) -- is compiled. During this time a special anonymous Perl
array is created, which is called a scratchpad for the current
unit.
</para>
<para>
残っている疑問は、オペコードに対する <emphasis>target</emphasis>s である SV をいつ
生成するのかということでしょう。
その答えは、カレントユニット -- サブルーチンもしくは(サブルーチンの
外側にある文のためのオペコードのための)ファイル -- が
コンパイルされたときです。
この間、特別な無名配列が生成されます。
これはカレントユニットのためのスクラッチパッド (scrachpad) と
呼ばれるものです。
</para>
<para>
A scratchpad keeps SVs which are lexicals for the current unit and are
targets for opcodes. One can deduce that an SV lives on a scratchpad
by looking on its flags: lexicals have <code>SVs_PADMY</code> set, and
<emphasis>target</emphasis>s have <code>SVs_PADTMP</code> set.
</para>
<para>
スクラッチパッドはカレントユニットのためのレキシカルやオペコードの
ための target である SV を保持します。
SV があるスクラッチパッドを、
SV のフラグを見ることによって推測することができます。
レキシカルでは
<code>SVs_PADMY</code> されていて、<emphasis>target</emphasis>s では <code>SVs_PADTMP</code> が
セットされています。
</para>
<para>
The correspondence between OPs and <emphasis>target</emphasis>s is not 1-to-1. Different
OPs in the compile tree of the unit can use the same target, if this
would not conflict with the expected life of the temporary.
</para>
<para>
オペコードと <emphasis>target</emphasis>s の間の対応は一対一ではありません。
あるユニットの翻訳木 (compile tree)にある異なるオペコードは、
これが一時変数の expected life と衝突していなければ同じ target を使うことが
できます。
</para>
</sect2>
<sect2>
<title>Scratchpads and recursion</title>
<para>
(スクラッチパッドと再帰)
</para>
<para>
In fact it is not 100% true that a compiled unit contains a pointer to
the scratchpad AV. In fact it contains a pointer to an AV of
(initially) one element, and this element is the scratchpad AV. Why do
we need an extra level of indirection?
</para>
<para>
コンパイルされたユニットがスクラッチパッド AV へのポインタを
保持しているということは、100% 本当のことではありません。
実際は、(初期値では)一要素の AV へのポインタを保持していて、この要素が
スクラッチパッド AV なのです。
なぜ、こういう余計な間接レベルを必要としているのでしょう?
</para>
<para>
The answer is <strong>recursion</strong>, and maybe <strong>threads</strong>. Both
these can create several execution pointers going into the same
subroutine. For the subroutine-child not write over the temporaries
for the subroutine-parent (lifespan of which covers the call to the
child), the parent and the child should have different
scratchpads. (<emphasis>And</emphasis> the lexicals should be separate anyway!)
</para>
<para>
その答えは <strong>再帰</strong> と、おそらく <strong>スレッド</strong> です。
これら二つは同じサブルーチンに対する別々の実行ポインタを
生成しようとするかもしれません。
子サブルーチンが(呼び出す子サブルーチンを覆っている寿命を持つ)
親サブルーチンの一時変数を上書きしてしまわないように、
親と子では、異なるスクラッチパッドを持つようにすべきです
(<strong>かつ</strong>、レキシカルは分けておくべきなのです!)。
</para>
<para>
So each subroutine is born with an array of scratchpads (of length 1).
On each entry to the subroutine it is checked that the current
depth of the recursion is not more than the length of this array, and
if it is, new scratchpad is created and pushed into the array.
</para>
<para>
各サブルーチンは、スクラッチパッドの(長さが 1 の)配列を伴って生成されます。
サブルーチンに対する各エントリーはその時点での再帰の深さが
この配列の長さよりも大きくないことをチェックします。
そして、もしそうであれば、新たなスクラッチパッドが生成されて配列へと
プッシュされます。
</para>
<para>
The <emphasis>target</emphasis>s on this scratchpad are <code>undef</code>s, but they are already
marked with correct flags.
</para>
<para>
このスクラッチパッドにある <emphasis>target</emphasis>s は <code>undef</code> ですが、これらはすでに
正しいフラグによってマークされています。
</para>
</sect2>
</sect1>
<sect1>
<title>Compiled code</title>
<para>
(コンパイルされたコード)
</para>
<sect2>
<title>Code tree</title>
<para>
(コード木)
</para>
<para>
Here we describe the internal form your code is converted to by
Perl. Start with a simple example:
</para>
<para>
ここで、Perl によって変換されたプログラムの内部形式を説明しましょう。
簡単な例から始めます。
</para>
<verbatim><![CDATA[
$a = $b + $c;
]]></verbatim>
<para>
This is converted to a tree similar to this one:
</para>
<para>
これは次のような木構造へ変換されます(実際にはもっと複雑です)。
</para>
<verbatim><![CDATA[
assign-to
           /           \
          +             $a
        /   \
      $b     $c
]]></verbatim>
<para>
(but slightly more complicated).  This tree reflects the way Perl
parsed your code, but has nothing to do with the execution order.
There is an additional &quot;thread&quot; going through the nodes of the tree
which shows the order of execution of the nodes.  In our simplified
example above it looks like:
</para>
<para>
この木構造は、Perl があなたのプログラムを解析したやり方を
反映していますが、実行の順序については反映していません。
ノードの実行順序を表わす木構造のノードを辿ろうとする別の
「スレッド」(thread) があります。
先の簡単な例では、次のようになります。
</para>
<verbatim><![CDATA[
$b ---> $c ---> + ---> $a ---> assign-to
]]></verbatim>
<para>
But with the actual compile tree for <code>$a = $b + $c</code> it is different:
some nodes <emphasis>optimized away</emphasis>.  As a corollary, though the actual tree
contains more nodes than our simplified example, the execution order
is the same as in our example.
</para>
<para>
しかし、<code>$a = $b + $c</code> に対する実際の解析木はこれと異なります。
一部のノードが<strong>最適化</strong>されています。
その結果として、実際の木構造が私たちの単純な例よりも多くのノードを
持っていたとしても、その実行順序は同じになります。
</para>
</sect2>
<sect2>
<title>Examining the tree</title>
<para>
(木を検査する)
</para>
<para>
If you have your perl compiled for debugging (usually done with
<code>-DDEBUGGING</code> on the <code>Configure</code> command line), you may examine the
compiled tree by specifying <code>-Dx</code> on the Perl command line.  The
output takes several lines per node, and for <code>$b+$c</code> it looks like
this:
</para>
<para>
perl をデバッグ用にコンパイルした(通常は <code>Configure</code> のコマンドラインで
<code>-DDEBUGGING</code> を使って行います)場合、Perl のコマンドラインで
<code>-Dx</code> を指定することによって解析木を検査することができます。
その出力はノード毎に数行を取り、<code>$b+$c</code> は以下のようになります。
</para>
<verbatim><![CDATA[
5           TYPE = add  ===> 6
            TARG = 1
            FLAGS = (SCALAR,KIDS)
            {
                TYPE = null  ===> (4)
                  (was rv2sv)
                FLAGS = (SCALAR,KIDS)
                {
3                   TYPE = gvsv  ===> 4
                    FLAGS = (SCALAR)
                    GV = main::b
                }
            }
            {
                TYPE = null  ===> (5)
                  (was rv2sv)
                FLAGS = (SCALAR,KIDS)
                {
4                   TYPE = gvsv  ===> 5
                    FLAGS = (SCALAR)
                    GV = main::c
                }
            }
]]></verbatim>
<para>
This tree has 5 nodes (one per <code>TYPE</code> specifier), only 3 of them are
not optimized away (one per number in the left column).  The immediate
children of the given node correspond to <code>{}</code> pairs on the same level
of indentation, thus this listing corresponds to the tree:
</para>
<para>
この木には五つのノード(<code>TYPE</code> 毎にひとつ)があって、そのうちの
三つだけが最適化されないものです(左側に数字のあるもの)。
与えられたノードのすぐ下にある子供は同じレベルのインデントにある <code>{}</code> の
ペアに対応します。
したがって、このリストは以下の木に対応します。
</para>
<verbatim><![CDATA[
add
                 /     \
               null    null
                |       |
               gvsv    gvsv
]]></verbatim>
<para>
The execution order is indicated by <code>===&gt;</code> marks, thus it is <code>3
4 5 6</code> (node <code>6</code> is not included into above listing), i.e.,
<code>gvsv gvsv add whatever</code>.
</para>
<para>
実行順序は <code>===&gt;</code> マークによって表わされますから、<code>3 4 5 6</code>
(ノード <code>6</code>は、上にあるリストには含まれません)となります。
つまり、<code>gvsv gvsv add whatever</code> ということになります。
</para>
<para>
Each of these nodes represents an op, a fundamental operation inside the
Perl core. The code which implements each operation can be found in the
<filename>pp*.c</filename> files; the function which implements the op with type <code>gvsv</code>
is <code>pp_gvsv</code>, and so on. As the tree above shows, different ops have
different numbers of children: <code>add</code> is a binary operator, as one would
expect, and so has two children. To accommodate the various different
numbers of children, there are various types of op data structure, and
they link together in different ways.
</para>
<para>
Each of these nodes represents an op, a fundamental operation inside the
Perl core. The code which implements each operation can be found in the
<filename>pp*.c</filename> files; the function which implements the op with type <code>gvsv</code>
is <code>pp_gvsv</code>, and so on. As the tree above shows, different ops have
different numbers of children: <code>add</code> is a binary operator, as one would
expect, and so has two children. To accommodate the various different
numbers of children, there are various types of op data structure, and
they link together in different ways.
(TBT)
</para>
<para>
The simplest type of op structure is <code>OP</code>: this has no children. Unary
operators, <code>UNOP</code>s, have one child, and this is pointed to by the
<code>op_first</code> field. Binary operators (<code>BINOP</code>s) have not only an
<code>op_first</code> field but also an <code>op_last</code> field. The most complex type of
op is a <code>LISTOP</code>, which has any number of children. In this case, the
first child is pointed to by <code>op_first</code> and the last child by
<code>op_last</code>. The children in between can be found by iteratively
following the <code>op_sibling</code> pointer from the first child to the last.
</para>
<para>
The simplest type of op structure is <code>OP</code>: this has no children. Unary
operators, <code>UNOP</code>s, have one child, and this is pointed to by the
<code>op_first</code> field. Binary operators (<code>BINOP</code>s) have not only an
<code>op_first</code> field but also an <code>op_last</code> field. The most complex type of
op is a <code>LISTOP</code>, which has any number of children. In this case, the
first child is pointed to by <code>op_first</code> and the last child by
<code>op_last</code>. The children in between can be found by iteratively
following the <code>op_sibling</code> pointer from the first child to the last.
(TBT)
</para>
<para>
There are also two other op types: a <code>PMOP</code> holds a regular expression,
and has no children, and a <code>LOOP</code> may or may not have children. If the
<code>op_children</code> field is non-zero, it behaves like a <code>LISTOP</code>. To
complicate matters, if a <code>UNOP</code> is actually a <code>null</code> op after
optimization (see <link xref='Compile pass 2: context propagation'>/Compile pass 2: context propagation</link>) it will still
have children in accordance with its former type.
</para>
<para>
There are also two other op types: a <code>PMOP</code> holds a regular expression,
and has no children, and a <code>LOOP</code> may or may not have children. If the
<code>op_children</code> field is non-zero, it behaves like a <code>LISTOP</code>. To
complicate matters, if a <code>UNOP</code> is actually a <code>null</code> op after
optimization (see <link xref='Compile pass 2: context propagation'>/Compile pass 2: context propagation</link>) it will still
have children in accordance with its former type.
(TBT)
</para>
<para>
Another way to examine the tree is to use a compiler back-end module, such
as <link xref='B::Concise'>B::Concise</link>.
</para>
<para>
Another way to examine the tree is to use a compiler back-end module, such
as <link xref='B::Concise'>B::Concise</link>.
(TBT)
</para>
</sect2>
<sect2>
<title>Compile pass 1: check routines</title>
<para>
The tree is created by the compiler while <emphasis>yacc</emphasis> code feeds it
the constructions it recognizes. Since <emphasis>yacc</emphasis> works bottom-up, so does
the first pass of perl compilation.
</para>
<para>
この木構造は、<emphasis>yacc</emphasis> が perl プログラムを読み込んでその構造を解析している
間にコンパイラによって生成されます。
yacc はボトムアップで動作するので、perl によるコンパイルの最初のパスで
行なわれます。
</para>
<para>
What makes this pass interesting for perl developers is that some
optimization may be performed on this pass.  This is optimization by
so-called &quot;check routines&quot;.  The correspondence between node names
and corresponding check routines is described in <filename>opcode.pl</filename> (do not
forget to run <code>make regen_headers</code> if you modify this file).
</para>
<para>
perl 開発者にとって興味深いのは、このパスで行なわれるいくつかの
最適化でしょう。
これは、&quot;check routines&quot; とも呼ばれる最適化です。
ノード名と対応するチェックルーチンとの間の対応は <filename>opcode.pl</filename> に
記述されています(このファイルを修正した場合には、<code>make regen_headers</code> を
実行することを忘れないでください)。
</para>
<para>
A check routine is called when the node is fully constructed except
for the execution-order thread.  Since at this time there are no
back-links to the currently constructed node, one can do most any
operation to the top-level node, including freeing it and/or creating
new nodes above/below it.
</para>
<para>
チェックルーチンは、ノードが実行順序スレッドを除いて完全に
構築されたときに呼び出されます。
この時点では、構築されたノードに対する back-line が存在しないので、
トップレベルノードに対して、新たなノードを生成したりノードを
解放したりすることを含めて、ほとんどの操作を行うことができます。
</para>
<para>
The check routine returns the node which should be inserted into the
tree (if the top-level node was not modified, check routine returns
its argument).
</para>
<para>
このチェックルーチンは木に挿入すべきノードを返します(トップレベルの
ノードが変更されていなければ、チェックルーチンはその引数を返します)。
</para>
<para>
By convention, check routines have names <code>ck_*</code>. They are usually
called from <code>new*OP</code> subroutines (or <code>convert</code>) (which in turn are
called from <filename>perly.y</filename>).
</para>
<para>
規約により、チェックルーチンは <code>ck_*</code> のような名前を持ちます。
これらは通常サブルーチン <code>new*OP</code> (もしくは <code>convert</code>) から
呼び出されます(これらのサブルーチンは <filename>perly.y</filename> から呼び出されます)。
</para>
</sect2>
<sect2>
<title>Compile pass 1a: constant folding</title>
<para>
(コンパイルパス1a: 定数の畳み込み)
</para>
<para>
Immediately after the check routine is called the returned node is
checked for being compile-time executable.  If it is (the value is
judged to be constant) it is immediately executed, and a <emphasis>constant</emphasis>
node with the &quot;return value&quot; of the corresponding subtree is
substituted instead.  The subtree is deleted.
</para>
<para>
チェックルーチンが呼び出された直後に、返されたノードはコンパイル時
実行のためのチェックが行なわれます。
もしそうであれば(値が定数であると判定された)、そのノードは即座に
実行されて、「戻り値」に対応する部分木は <strong>定数</strong> ノードで置換され、
部分木が削除されます。
</para>
<para>
If constant folding was not performed, the execution-order thread is
created.
</para>
<para>
定数の畳み込み(constant folding)が働かなければ、実行順序スレッドが
生成されます。
</para>
</sect2>
<sect2>
<title>Compile pass 2: context propagation</title>
<para>
(コンパイルパス2: コンテキスト伝播)
</para>
<para>
When a context for a part of compile tree is known, it is propagated
down through the tree.  At this time the context can have 5 values
(instead of 2 for runtime context): void, boolean, scalar, list, and
lvalue.  In contrast with the pass 1 this pass is processed from top
to bottom: a node's context determines the context for its children.
</para>
<para>
解析木の一部分のコンテキストがわかっているとき、それは木の末端へ
伝播します。
このとき、コンテキストは(実行時コンテキストの二種類ではなく)
無効、真偽値、スカラ、リスト、左辺値の五種類の値を持つことができます。
パス 1 とは対照的に、このパスではトップから末端へと処理が進みます。
あるノードのコンテキストは、その下にある部分のコンテキストを決定します。
</para>
<para>
Additional context-dependent optimizations are performed at this time.
Since at this moment the compile tree contains back-references (via
&quot;thread&quot; pointers), nodes cannot be free()d now.  To allow
optimized-away nodes at this stage, such nodes are null()ified instead
of free()ing (i.e. their type is changed to OP_NULL).
</para>
<para>
コンテキストに依存した最適化はこのときに行なわれます。
この動作では解析木が(“スレッド”ポインタを通じて)後方参照を
含んでいるので、ノードをこの時に free() することはできません。
このステージでノードを最適化するのを許すために、対象となるノードは
free() されるかわりに null() されます(つまり、そのノードの型が
OP_NULL に変えられるということ)。
</para>
</sect2>
<sect2>
<title>Compile pass 3: peephole optimization</title>
<para>
(コンパイルパス 3: 覗き穴最適化)
</para>
<para>
After the compile tree for a subroutine (or for an <code>eval</code> or a file)
is created, an additional pass over the code is performed. This pass
is neither top-down or bottom-up, but in the execution order (with
additional complications for conditionals).  These optimizations are
done in the subroutine peep().  Optimizations performed at this stage
are subject to the same restrictions as in the pass 2.
</para>
<para>
サブルーチン(もしくは <code>eval</code> かファイル)に対する解析木が生成された後で、
そのコードに対する追加パスが実行されます。
このパスはトップダウンでもボトムアップでもなく、(条件に対する
複雑さを伴った)実行順序です。
これらの最適化はサブルーチン peep() で行なわれます。
このステージで行なわれる最適化はパス 2 でのものと同じ制限に従います。
</para>
</sect2>
<sect2>
<title>Pluggable runops</title>
<para>
The compile tree is executed in a runops function.  There are two runops
functions, in <filename>run.c</filename> and in <filename>dump.c</filename>.  <code>Perl_runops_debug</code> is used
with DEBUGGING and <code>Perl_runops_standard</code> is used otherwise.  For fine
control over the execution of the compile tree it is possible to provide
your own runops function.
</para>
<para>
The compile tree is executed in a runops function.  There are two runops
functions, in <filename>run.c</filename> and in <filename>dump.c</filename>.  <code>Perl_runops_debug</code> is used
with DEBUGGING and <code>Perl_runops_standard</code> is used otherwise.  For fine
control over the execution of the compile tree it is possible to provide
your own runops function.
(TBT)
</para>
<para>
It's probably best to copy one of the existing runops functions and
change it to suit your needs.  Then, in the BOOT section of your XS
file, add the line:
</para>
<para>
It's probably best to copy one of the existing runops functions and
change it to suit your needs.  Then, in the BOOT section of your XS
file, add the line:
(TBT)
</para>
<verbatim><![CDATA[
PL_runops = my_runops;
]]></verbatim>
<para>
This function should be as efficient as possible to keep your programs
running as fast as possible.
</para>
<para>
This function should be as efficient as possible to keep your programs
running as fast as possible.
(TBT)
</para>
</sect2>
</sect1>
<sect1>
<title>Examining internal data structures with the <code>dump</code> functions</title>
<para>
To aid debugging, the source file <filename>dump.c</filename> contains a number of
functions which produce formatted output of internal data structures.
</para>
<para>
To aid debugging, the source file <filename>dump.c</filename> contains a number of
functions which produce formatted output of internal data structures.
(TBT)
</para>
<para>
The most commonly used of these functions is <code>Perl_sv_dump</code>; it's used
for dumping SVs, AVs, HVs, and CVs. The <code>Devel::Peek</code> module calls
<code>sv_dump</code> to produce debugging output from Perl-space, so users of that
module should already be familiar with its format.
</para>
<para>
The most commonly used of these functions is <code>Perl_sv_dump</code>; it's used
for dumping SVs, AVs, HVs, and CVs. The <code>Devel::Peek</code> module calls
<code>sv_dump</code> to produce debugging output from Perl-space, so users of that
module should already be familiar with its format.
(TBT)
</para>
<para>
<code>Perl_op_dump</code> can be used to dump an <code>OP</code> structure or any of its
derivatives, and produces output similar to <code>perl -Dx</code>; in fact,
<code>Perl_dump_eval</code> will dump the main root of the code being evaluated,
exactly like <code>-Dx</code>.
</para>
<para>
<code>Perl_op_dump</code> can be used to dump an <code>OP</code> structure or any of its
derivatives, and produces output similar to <code>perl -Dx</code>; in fact,
<code>Perl_dump_eval</code> will dump the main root of the code being evaluated,
exactly like <code>-Dx</code>.
(TBT)
</para>
<para>
Other useful functions are <code>Perl_dump_sub</code>, which turns a <code>GV</code> into an
op tree, <code>Perl_dump_packsubs</code> which calls <code>Perl_dump_sub</code> on all the
subroutines in a package like so: (Thankfully, these are all xsubs, so
there is no op tree)
</para>
<para>
Other useful functions are <code>Perl_dump_sub</code>, which turns a <code>GV</code> into an
op tree, <code>Perl_dump_packsubs</code> which calls <code>Perl_dump_sub</code> on all the
subroutines in a package like so: (Thankfully, these are all xsubs, so
there is no op tree)
(TBT)
</para>
<verbatim><![CDATA[
(gdb) print Perl_dump_packsubs(PL_defstash)
]]></verbatim>
<verbatim><![CDATA[
SUB attributes::bootstrap = (xsub 0x811fedc 0)
]]></verbatim>
<verbatim><![CDATA[
SUB UNIVERSAL::can = (xsub 0x811f50c 0)
]]></verbatim>
<verbatim><![CDATA[
SUB UNIVERSAL::isa = (xsub 0x811f304 0)
]]></verbatim>
<verbatim><![CDATA[
SUB UNIVERSAL::VERSION = (xsub 0x811f7ac 0)
]]></verbatim>
<verbatim><![CDATA[
SUB DynaLoader::boot_DynaLoader = (xsub 0x805b188 0)
]]></verbatim>
<para>
and <code>Perl_dump_all</code>, which dumps all the subroutines in the stash and
the op tree of the main root.
</para>
<para>
and <code>Perl_dump_all</code>, which dumps all the subroutines in the stash and
the op tree of the main root.
(TBT)
</para>
</sect1>
<sect1>
<title>How multiple interpreters and concurrency are supported</title>
<sect2>
<title>Background and PERL_IMPLICIT_CONTEXT</title>
<para>
The Perl interpreter can be regarded as a closed box: it has an API
for feeding it code or otherwise making it do things, but it also has
functions for its own use.  This smells a lot like an object, and
there are ways for you to build Perl so that you can have multiple
interpreters, with one interpreter represented either as a C structure,
or inside a thread-specific structure.  These structures contain all
the context, the state of that interpreter.
</para>
<para>
The Perl interpreter can be regarded as a closed box: it has an API
for feeding it code or otherwise making it do things, but it also has
functions for its own use.  This smells a lot like an object, and
there are ways for you to build Perl so that you can have multiple
interpreters, with one interpreter represented either as a C structure,
or inside a thread-specific structure.  These structures contain all
the context, the state of that interpreter.
(TBT)
</para>
<para>
One macro controls the major Perl build flavor: MULTIPLICITY. The
MULTIPLICITY build has a C structure that packages all the interpreter
state. With multiplicity-enabled perls, PERL_IMPLICIT_CONTEXT is also
normally defined, and enables the support for passing in a &quot;hidden&quot; first
argument that represents all three data structures. MULTIPLICITY makes
mutli-threaded perls possible (with the ithreads threading model, related
to the macro USE_ITHREADS.)
</para>
<para>
One macro controls the major Perl build flavor: MULTIPLICITY. The
MULTIPLICITY build has a C structure that packages all the interpreter
state. With multiplicity-enabled perls, PERL_IMPLICIT_CONTEXT is also
normally defined, and enables the support for passing in a &quot;hidden&quot; first
argument that represents all three data structures. MULTIPLICITY makes
mutli-threaded perls possible (with the ithreads threading model, related
to the macro USE_ITHREADS.)
(TBT)
</para>
<para>
Two other &quot;encapsulation&quot; macros are the PERL_GLOBAL_STRUCT and
PERL_GLOBAL_STRUCT_PRIVATE (the latter turns on the former, and the
former turns on MULTIPLICITY.)  The PERL_GLOBAL_STRUCT causes all the
internal variables of Perl to be wrapped inside a single global struct,
struct perl_vars, accessible as (globals) &amp;PL_Vars or PL_VarsPtr or
the function  Perl_GetVars().  The PERL_GLOBAL_STRUCT_PRIVATE goes
one step further, there is still a single struct (allocated in main()
either from heap or from stack) but there are no global data symbols
pointing to it.  In either case the global struct should be initialised
as the very first thing in main() using Perl_init_global_struct() and
correspondingly tear it down after perl_free() using Perl_free_global_struct(),
please see <filename>miniperlmain.c</filename> for usage details.  You may also need
to use <code>dVAR</code> in your coding to &quot;declare the global variables&quot;
when you are using them.  dTHX does this for you automatically.
</para>
<para>
Two other &quot;encapsulation&quot; macros are the PERL_GLOBAL_STRUCT and
PERL_GLOBAL_STRUCT_PRIVATE (the latter turns on the former, and the
former turns on MULTIPLICITY.)  The PERL_GLOBAL_STRUCT causes all the
internal variables of Perl to be wrapped inside a single global struct,
struct perl_vars, accessible as (globals) &amp;PL_Vars or PL_VarsPtr or
the function  Perl_GetVars().  The PERL_GLOBAL_STRUCT_PRIVATE goes
one step further, there is still a single struct (allocated in main()
either from heap or from stack) but there are no global data symbols
pointing to it.  In either case the global struct should be initialised
as the very first thing in main() using Perl_init_global_struct() and
correspondingly tear it down after perl_free() using Perl_free_global_struct(),
please see <filename>miniperlmain.c</filename> for usage details.  You may also need
to use <code>dVAR</code> in your coding to &quot;declare the global variables&quot;
when you are using them.  dTHX does this for you automatically.
(TBT)
</para>
<para>
To see whether you have non-const data you can use a BSD-compatible <code>nm</code>:
</para>
<para>
To see whether you have non-const data you can use a BSD-compatible <code>nm</code>:
(TBT)
</para>
<verbatim><![CDATA[
nm libperl.a | grep -v ' [TURtr] '
]]></verbatim>
<para>
If this displays any <code>D</code> or <code>d</code> symbols, you have non-const data.
</para>
<para>
If this displays any <code>D</code> or <code>d</code> symbols, you have non-const data.
(TBT)
</para>
<para>
For backward compatibility reasons defining just PERL_GLOBAL_STRUCT
doesn't actually hide all symbols inside a big global struct: some
PerlIO_xxx vtables are left visible.  The PERL_GLOBAL_STRUCT_PRIVATE
then hides everything (see how the PERLIO_FUNCS_DECL is used).
</para>
<para>
For backward compatibility reasons defining just PERL_GLOBAL_STRUCT
doesn't actually hide all symbols inside a big global struct: some
PerlIO_xxx vtables are left visible.  The PERL_GLOBAL_STRUCT_PRIVATE
then hides everything (see how the PERLIO_FUNCS_DECL is used).
(TBT)
</para>
<para>
All this obviously requires a way for the Perl internal functions to be
either subroutines taking some kind of structure as the first
argument, or subroutines taking nothing as the first argument.  To
enable these two very different ways of building the interpreter,
the Perl source (as it does in so many other situations) makes heavy
use of macros and subroutine naming conventions.
</para>
<para>
All this obviously requires a way for the Perl internal functions to be
either subroutines taking some kind of structure as the first
argument, or subroutines taking nothing as the first argument.  To
enable these two very different ways of building the interpreter,
the Perl source (as it does in so many other situations) makes heavy
use of macros and subroutine naming conventions.
(TBT)
</para>
<para>
First problem: deciding which functions will be public API functions and
which will be private.  All functions whose names begin <code>S_</code> are private
(think &quot;S&quot; for &quot;secret&quot; or &quot;static&quot;).  All other functions begin with
&quot;Perl_&quot;, but just because a function begins with &quot;Perl_&quot; does not mean it is
part of the API. (See <link xref='Internal Functions'>/Internal Functions</link>.) The easiest way to be <strong>sure</strong> a
function is part of the API is to find its entry in <link xref='perlapi'>perlapi</link>.
If it exists in <link xref='perlapi'>perlapi</link>, it's part of the API.  If it doesn't, and you
think it should be (i.e., you need it for your extension), send mail via
<link xref='perlbug'>perlbug</link> explaining why you think it should be.
</para>
<para>
First problem: deciding which functions will be public API functions and
which will be private.  All functions whose names begin <code>S_</code> are private
(think &quot;S&quot; for &quot;secret&quot; or &quot;static&quot;).  All other functions begin with
&quot;Perl_&quot;, but just because a function begins with &quot;Perl_&quot; does not mean it is
part of the API. (See <link xref='Internal Functions'>/Internal Functions</link>.) The easiest way to be <strong>sure</strong> a
function is part of the API is to find its entry in <link xref='perlapi'>perlapi</link>.
If it exists in <link xref='perlapi'>perlapi</link>, it's part of the API.  If it doesn't, and you
think it should be (i.e., you need it for your extension), send mail via
<link xref='perlbug'>perlbug</link> explaining why you think it should be.
(TBT)
</para>
<para>
Second problem: there must be a syntax so that the same subroutine
declarations and calls can pass a structure as their first argument,
or pass nothing.  To solve this, the subroutines are named and
declared in a particular way.  Here's a typical start of a static
function used within the Perl guts:
</para>
<para>
Second problem: there must be a syntax so that the same subroutine
declarations and calls can pass a structure as their first argument,
or pass nothing.  To solve this, the subroutines are named and
declared in a particular way.  Here's a typical start of a static
function used within the Perl guts:
(TBT)
</para>
<verbatim><![CDATA[
STATIC void
S_incline(pTHX_ char *s)
]]></verbatim>
<para>
STATIC becomes &quot;static&quot; in C, and may be #define'd to nothing in some
configurations in future.
</para>
<para>
STATIC becomes &quot;static&quot; in C, and may be #define'd to nothing in some
configurations in future.
(TBT)
</para>
<para>
A public function (i.e. part of the internal API, but not necessarily
sanctioned for use in extensions) begins like this:
</para>
<para>
A public function (i.e. part of the internal API, but not necessarily
sanctioned for use in extensions) begins like this:
(TBT)
</para>
<verbatim><![CDATA[
void
Perl_sv_setiv(pTHX_ SV* dsv, IV num)
]]></verbatim>
<para>
<code>pTHX_</code> is one of a number of macros (in perl.h) that hide the
details of the interpreter's context.  THX stands for &quot;thread&quot;, &quot;this&quot;,
or &quot;thingy&quot;, as the case may be.  (And no, George Lucas is not involved. :-)
The first character could be 'p' for a <strong>p</strong>rototype, 'a' for <strong>a</strong>rgument,
or 'd' for <strong>d</strong>eclaration, so we have <code>pTHX</code>, <code>aTHX</code> and <code>dTHX</code>, and
their variants.
</para>
<para>
<code>pTHX_</code> is one of a number of macros (in perl.h) that hide the
details of the interpreter's context.  THX stands for &quot;thread&quot;, &quot;this&quot;,
or &quot;thingy&quot;, as the case may be.  (And no, George Lucas is not involved. :-)
The first character could be 'p' for a <strong>p</strong>rototype, 'a' for <strong>a</strong>rgument,
or 'd' for <strong>d</strong>eclaration, so we have <code>pTHX</code>, <code>aTHX</code> and <code>dTHX</code>, and
their variants.
(TBT)
</para>
<para>
When Perl is built without options that set PERL_IMPLICIT_CONTEXT, there is no
first argument containing the interpreter's context.  The trailing underscore
in the pTHX_ macro indicates that the macro expansion needs a comma
after the context argument because other arguments follow it.  If
PERL_IMPLICIT_CONTEXT is not defined, pTHX_ will be ignored, and the
subroutine is not prototyped to take the extra argument.  The form of the
macro without the trailing underscore is used when there are no additional
explicit arguments.
</para>
<para>
When Perl is built without options that set PERL_IMPLICIT_CONTEXT, there is no
first argument containing the interpreter's context.  The trailing underscore
in the pTHX_ macro indicates that the macro expansion needs a comma
after the context argument because other arguments follow it.  If
PERL_IMPLICIT_CONTEXT is not defined, pTHX_ will be ignored, and the
subroutine is not prototyped to take the extra argument.  The form of the
macro without the trailing underscore is used when there are no additional
explicit arguments.
(TBT)
</para>
<para>
When a core function calls another, it must pass the context.  This
is normally hidden via macros.  Consider <code>sv_setiv</code>.  It expands into
something like this:
</para>
<para>
When a core function calls another, it must pass the context.  This
is normally hidden via macros.  Consider <code>sv_setiv</code>.  It expands into
something like this:
(TBT)
</para>
<verbatim><![CDATA[
#ifdef PERL_IMPLICIT_CONTEXT
  #define sv_setiv(a,b)      Perl_sv_setiv(aTHX_ a, b)
  /* can't do this for vararg functions, see below */
#else
  #define sv_setiv           Perl_sv_setiv
#endif
]]></verbatim>
<para>
This works well, and means that XS authors can gleefully write:
</para>
<para>
This works well, and means that XS authors can gleefully write:
(TBT)
</para>
<verbatim><![CDATA[
sv_setiv(foo, bar);
]]></verbatim>
<para>
and still have it work under all the modes Perl could have been
compiled with.
</para>
<para>
and still have it work under all the modes Perl could have been
compiled with.
(TBT)
</para>
<para>
This doesn't work so cleanly for varargs functions, though, as macros
imply that the number of arguments is known in advance.  Instead we
either need to spell them out fully, passing <code>aTHX_</code> as the first
argument (the Perl core tends to do this with functions like
Perl_warner), or use a context-free version.
</para>
<para>
This doesn't work so cleanly for varargs functions, though, as macros
imply that the number of arguments is known in advance.  Instead we
either need to spell them out fully, passing <code>aTHX_</code> as the first
argument (the Perl core tends to do this with functions like
Perl_warner), or use a context-free version.
(TBT)
</para>
<para>
The context-free version of Perl_warner is called
Perl_warner_nocontext, and does not take the extra argument.  Instead
it does dTHX; to get the context from thread-local storage.  We
<code>#define warner Perl_warner_nocontext</code> so that extensions get source
compatibility at the expense of performance.  (Passing an arg is
cheaper than grabbing it from thread-local storage.)
</para>
<para>
The context-free version of Perl_warner is called
Perl_warner_nocontext, and does not take the extra argument.  Instead
it does dTHX; to get the context from thread-local storage.  We
<code>#define warner Perl_warner_nocontext</code> so that extensions get source
compatibility at the expense of performance.  (Passing an arg is
cheaper than grabbing it from thread-local storage.)
(TBT)
</para>
<para>
You can ignore [pad]THXx when browsing the Perl headers/sources.
Those are strictly for use within the core.  Extensions and embedders
need only be aware of [pad]THX.
</para>
<para>
You can ignore [pad]THXx when browsing the Perl headers/sources.
Those are strictly for use within the core.  Extensions and embedders
need only be aware of [pad]THX.
(TBT)
</para>
</sect2>
<sect2>
<title>So what happened to dTHR?</title>
<para>
<code>dTHR</code> was introduced in perl 5.005 to support the older thread model.
The older thread model now uses the <code>THX</code> mechanism to pass context
pointers around, so <code>dTHR</code> is not useful any more.  Perl 5.6.0 and
later still have it for backward source compatibility, but it is defined
to be a no-op.
</para>
<para>
<code>dTHR</code> was introduced in perl 5.005 to support the older thread model.
The older thread model now uses the <code>THX</code> mechanism to pass context
pointers around, so <code>dTHR</code> is not useful any more.  Perl 5.6.0 and
later still have it for backward source compatibility, but it is defined
to be a no-op.
(TBT)
</para>
</sect2>
<sect2>
<title>How do I use all this in extensions?</title>
<para>
When Perl is built with PERL_IMPLICIT_CONTEXT, extensions that call
any functions in the Perl API will need to pass the initial context
argument somehow.  The kicker is that you will need to write it in
such a way that the extension still compiles when Perl hasn't been
built with PERL_IMPLICIT_CONTEXT enabled.
</para>
<para>
When Perl is built with PERL_IMPLICIT_CONTEXT, extensions that call
any functions in the Perl API will need to pass the initial context
argument somehow.  The kicker is that you will need to write it in
such a way that the extension still compiles when Perl hasn't been
built with PERL_IMPLICIT_CONTEXT enabled.
(TBT)
</para>
<para>
There are three ways to do this.  First, the easy but inefficient way,
which is also the default, in order to maintain source compatibility
with extensions: whenever XSUB.h is #included, it redefines the aTHX
and aTHX_ macros to call a function that will return the context.
Thus, something like:
</para>
<para>
There are three ways to do this.  First, the easy but inefficient way,
which is also the default, in order to maintain source compatibility
with extensions: whenever XSUB.h is #included, it redefines the aTHX
and aTHX_ macros to call a function that will return the context.
Thus, something like:
(TBT)
</para>
<verbatim><![CDATA[
sv_setiv(sv, num);
]]></verbatim>
<para>
in your extension will translate to this when PERL_IMPLICIT_CONTEXT is
in effect:
</para>
<para>
in your extension will translate to this when PERL_IMPLICIT_CONTEXT is
in effect:
(TBT)
</para>
<verbatim><![CDATA[
Perl_sv_setiv(Perl_get_context(), sv, num);
]]></verbatim>
<para>
or to this otherwise:
</para>
<para>
or to this otherwise:
(TBT)
</para>
<verbatim><![CDATA[
Perl_sv_setiv(sv, num);
]]></verbatim>
<para>
You have to do nothing new in your extension to get this; since
the Perl library provides Perl_get_context(), it will all just
work.
</para>
<para>
You have to do nothing new in your extension to get this; since
the Perl library provides Perl_get_context(), it will all just
work.
(TBT)
</para>
<para>
The second, more efficient way is to use the following template for
your Foo.xs:
</para>
<para>
The second, more efficient way is to use the following template for
your Foo.xs:
(TBT)
</para>
<verbatim><![CDATA[
#define PERL_NO_GET_CONTEXT     /* we want efficiency */
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
]]></verbatim>
<verbatim><![CDATA[
STATIC void my_private_function(int arg1, int arg2);
]]></verbatim>
<verbatim><![CDATA[
STATIC void
my_private_function(int arg1, int arg2)
{
    dTHX;       /* fetch context */
    ... call many Perl API functions ...
}
]]></verbatim>
<verbatim><![CDATA[
[... etc ...]
]]></verbatim>
<verbatim><![CDATA[
MODULE = Foo            PACKAGE = Foo
]]></verbatim>
<verbatim><![CDATA[
/* typical XSUB */
]]></verbatim>
<verbatim><![CDATA[
void
my_xsub(arg)
        int arg
    CODE:
        my_private_function(arg, 10);
]]></verbatim>
<para>
Note that the only two changes from the normal way of writing an
extension is the addition of a <code>#define PERL_NO_GET_CONTEXT</code> before
including the Perl headers, followed by a <code>dTHX;</code> declaration at
the start of every function that will call the Perl API.  (You'll
know which functions need this, because the C compiler will complain
that there's an undeclared identifier in those functions.)  No changes
are needed for the XSUBs themselves, because the XS() macro is
correctly defined to pass in the implicit context if needed.
</para>
<para>
Note that the only two changes from the normal way of writing an
extension is the addition of a <code>#define PERL_NO_GET_CONTEXT</code> before
including the Perl headers, followed by a <code>dTHX;</code> declaration at
the start of every function that will call the Perl API.  (You'll
know which functions need this, because the C compiler will complain
that there's an undeclared identifier in those functions.)  No changes
are needed for the XSUBs themselves, because the XS() macro is
correctly defined to pass in the implicit context if needed.
(TBT)
</para>
<para>
The third, even more efficient way is to ape how it is done within
the Perl guts:
</para>
<para>
The third, even more efficient way is to ape how it is done within
the Perl guts:
(TBT)
</para>
<verbatim><![CDATA[
#define PERL_NO_GET_CONTEXT     /* we want efficiency */
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
]]></verbatim>
<verbatim><![CDATA[
/* pTHX_ only needed for functions that call Perl API */
STATIC void my_private_function(pTHX_ int arg1, int arg2);
]]></verbatim>
<verbatim><![CDATA[
STATIC void
my_private_function(pTHX_ int arg1, int arg2)
{
    /* dTHX; not needed here, because THX is an argument */
    ... call Perl API functions ...
}
]]></verbatim>
<verbatim><![CDATA[
[... etc ...]
]]></verbatim>
<verbatim><![CDATA[
MODULE = Foo            PACKAGE = Foo
]]></verbatim>
<verbatim><![CDATA[
/* typical XSUB */
]]></verbatim>
<verbatim><![CDATA[
void
my_xsub(arg)
        int arg
    CODE:
        my_private_function(aTHX_ arg, 10);
]]></verbatim>
<para>
This implementation never has to fetch the context using a function
call, since it is always passed as an extra argument.  Depending on
your needs for simplicity or efficiency, you may mix the previous
two approaches freely.
</para>
<para>
This implementation never has to fetch the context using a function
call, since it is always passed as an extra argument.  Depending on
your needs for simplicity or efficiency, you may mix the previous
two approaches freely.
(TBT)
</para>
<para>
Never add a comma after <code>pTHX</code> yourself--always use the form of the
macro with the underscore for functions that take explicit arguments,
or the form without the argument for functions with no explicit arguments.
</para>
<para>
Never add a comma after <code>pTHX</code> yourself--always use the form of the
macro with the underscore for functions that take explicit arguments,
or the form without the argument for functions with no explicit arguments.
(TBT)
</para>
<para>
If one is compiling Perl with the <code>-DPERL_GLOBAL_STRUCT</code> the <code>dVAR</code>
definition is needed if the Perl global variables (see <filename>perlvars.h</filename>
or <filename>globvar.sym</filename>) are accessed in the function and <code>dTHX</code> is not
used (the <code>dTHX</code> includes the <code>dVAR</code> if necessary).  One notices
the need for <code>dVAR</code> only with the said compile-time define, because
otherwise the Perl global variables are visible as-is.
</para>
<para>
If one is compiling Perl with the <code>-DPERL_GLOBAL_STRUCT</code> the <code>dVAR</code>
definition is needed if the Perl global variables (see <filename>perlvars.h</filename>
or <filename>globvar.sym</filename>) are accessed in the function and <code>dTHX</code> is not
used (the <code>dTHX</code> includes the <code>dVAR</code> if necessary).  One notices
the need for <code>dVAR</code> only with the said compile-time define, because
otherwise the Perl global variables are visible as-is.
(TBT)
</para>
</sect2>
<sect2>
<title>Should I do anything special if I call perl from multiple threads?</title>
<para>
If you create interpreters in one thread and then proceed to call them in
another, you need to make sure perl's own Thread Local Storage (TLS) slot is
initialized correctly in each of those threads.
</para>
<para>
If you create interpreters in one thread and then proceed to call them in
another, you need to make sure perl's own Thread Local Storage (TLS) slot is
initialized correctly in each of those threads.
(TBT)
</para>
<para>
The <code>perl_alloc</code> and <code>perl_clone</code> API functions will automatically set
the TLS slot to the interpreter they created, so that there is no need to do
anything special if the interpreter is always accessed in the same thread that
created it, and that thread did not create or call any other interpreters
afterwards.  If that is not the case, you have to set the TLS slot of the
thread before calling any functions in the Perl API on that particular
interpreter.  This is done by calling the <code>PERL_SET_CONTEXT</code> macro in that
thread as the first thing you do:
</para>
<para>
The <code>perl_alloc</code> and <code>perl_clone</code> API functions will automatically set
the TLS slot to the interpreter they created, so that there is no need to do
anything special if the interpreter is always accessed in the same thread that
created it, and that thread did not create or call any other interpreters
afterwards.  If that is not the case, you have to set the TLS slot of the
thread before calling any functions in the Perl API on that particular
interpreter.  This is done by calling the <code>PERL_SET_CONTEXT</code> macro in that
thread as the first thing you do:
(TBT)
</para>
<verbatim><![CDATA[
/* do this before doing anything else with some_perl */
PERL_SET_CONTEXT(some_perl);
]]></verbatim>
<verbatim><![CDATA[
... other Perl API calls on some_perl go here ...
]]></verbatim>
</sect2>
<sect2>
<title>Future Plans and PERL_IMPLICIT_SYS</title>
<para>
Just as PERL_IMPLICIT_CONTEXT provides a way to bundle up everything
that the interpreter knows about itself and pass it around, so too are
there plans to allow the interpreter to bundle up everything it knows
about the environment it's running on.  This is enabled with the
PERL_IMPLICIT_SYS macro.  Currently it only works with USE_ITHREADS on
Windows.
</para>
<para>
Just as PERL_IMPLICIT_CONTEXT provides a way to bundle up everything
that the interpreter knows about itself and pass it around, so too are
there plans to allow the interpreter to bundle up everything it knows
about the environment it's running on.  This is enabled with the
PERL_IMPLICIT_SYS macro.  Currently it only works with USE_ITHREADS on
Windows.
(TBT)
</para>
<para>
This allows the ability to provide an extra pointer (called the &quot;host&quot;
environment) for all the system calls.  This makes it possible for
all the system stuff to maintain their own state, broken down into
seven C structures.  These are thin wrappers around the usual system
calls (see win32/perllib.c) for the default perl executable, but for a
more ambitious host (like the one that would do fork() emulation) all
the extra work needed to pretend that different interpreters are
actually different &quot;processes&quot;, would be done here.
</para>
<para>
This allows the ability to provide an extra pointer (called the &quot;host&quot;
environment) for all the system calls.  This makes it possible for
all the system stuff to maintain their own state, broken down into
seven C structures.  These are thin wrappers around the usual system
calls (see win32/perllib.c) for the default perl executable, but for a
more ambitious host (like the one that would do fork() emulation) all
the extra work needed to pretend that different interpreters are
actually different &quot;processes&quot;, would be done here.
(TBT)
</para>
<para>
The Perl engine/interpreter and the host are orthogonal entities.
There could be one or more interpreters in a process, and one or
more &quot;hosts&quot;, with free association between them.
</para>
<para>
The Perl engine/interpreter and the host are orthogonal entities.
There could be one or more interpreters in a process, and one or
more &quot;hosts&quot;, with free association between them.
(TBT)
</para>
</sect2>
</sect1>
<sect1>
<title>Internal Functions</title>
<para>
All of Perl's internal functions which will be exposed to the outside
world are prefixed by <code>Perl_</code> so that they will not conflict with XS
functions or functions used in a program in which Perl is embedded.
Similarly, all global variables begin with <code>PL_</code>. (By convention,
static functions start with <code>S_</code>.)
</para>
<para>
All of Perl's internal functions which will be exposed to the outside
world are prefixed by <code>Perl_</code> so that they will not conflict with XS
functions or functions used in a program in which Perl is embedded.
Similarly, all global variables begin with <code>PL_</code>. (By convention,
static functions start with <code>S_</code>.)
(TBT)
</para>
<para>
Inside the Perl core, you can get at the functions either with or
without the <code>Perl_</code> prefix, thanks to a bunch of defines that live in
<filename>embed.h</filename>. This header file is generated automatically from
<filename>embed.pl</filename> and <filename>embed.fnc</filename>. <filename>embed.pl</filename> also creates the prototyping
header files for the internal functions, generates the documentation
and a lot of other bits and pieces. It's important that when you add
a new function to the core or change an existing one, you change the
data in the table in <filename>embed.fnc</filename> as well. Here's a sample entry from
that table:
</para>
<para>
Inside the Perl core, you can get at the functions either with or
without the <code>Perl_</code> prefix, thanks to a bunch of defines that live in
<filename>embed.h</filename>. This header file is generated automatically from
<filename>embed.pl</filename> and <filename>embed.fnc</filename>. <filename>embed.pl</filename> also creates the prototyping
header files for the internal functions, generates the documentation
and a lot of other bits and pieces. It's important that when you add
a new function to the core or change an existing one, you change the
data in the table in <filename>embed.fnc</filename> as well. Here's a sample entry from
that table:
(TBT)
</para>
<verbatim><![CDATA[
Apd |SV**   |av_fetch   |AV* ar|I32 key|I32 lval
]]></verbatim>
<para>
The second column is the return type, the third column the name. Columns
after that are the arguments. The first column is a set of flags:
</para>
<para>
The second column is the return type, the third column the name. Columns
after that are the arguments. The first column is a set of flags:
(TBT)
</para>
<list>
<item><itemtext>A</itemtext>
<para>
This function is a part of the public API. All such functions should also
have 'd', very few do not.
</para>
<para>
This function is a part of the public API. All such functions should also
have 'd', very few do not.
(TBT)
</para>
</item>
<item><itemtext>p</itemtext>
<para>
This function has a <code>Perl_</code> prefix; i.e. it is defined as
<code>Perl_av_fetch</code>.
</para>
<para>
This function has a <code>Perl_</code> prefix; i.e. it is defined as
<code>Perl_av_fetch</code>.
(TBT)
</para>
</item>
<item><itemtext>d</itemtext>
<para>
This function has documentation using the <code>apidoc</code> feature which we'll
look at in a second.  Some functions have 'd' but not 'A'; docs are good.
</para>
<para>
This function has documentation using the <code>apidoc</code> feature which we'll
look at in a second.  Some functions have 'd' but not 'A'; docs are good.
(TBT)
</para>
</item>
</list>
<para>
Other available flags are:
</para>
<para>
Other available flags are:
(TBT)
</para>
<list>
<item><itemtext>s</itemtext>
<para>
This is a static function and is defined as <code>STATIC S_whatever</code>, and
usually called within the sources as <code>whatever(...)</code>.
</para>
<para>
This is a static function and is defined as <code>STATIC S_whatever</code>, and
usually called within the sources as <code>whatever(...)</code>.
(TBT)
</para>
</item>
<item><itemtext>n</itemtext>
<para>
This does not need a interpreter context, so the definition has no
<code>pTHX</code>, and it follows that callers don't use <code>aTHX</code>.  (See
<link xref='perlguts#Background and PERL_IMPLICIT_CONTEXT'>perlguts/Background and PERL_IMPLICIT_CONTEXT</link>.)
</para>
<para>
This does not need a interpreter context, so the definition has no
<code>pTHX</code>, and it follows that callers don't use <code>aTHX</code>.  (See
<link xref='perlguts#Background and PERL_IMPLICIT_CONTEXT'>perlguts/Background and PERL_IMPLICIT_CONTEXT</link>.)
(TBT)
</para>
</item>
<item><itemtext>r</itemtext>
<para>
This function never returns; <code>croak</code>, <code>exit</code> and friends.
</para>
<para>
This function never returns; <code>croak</code>, <code>exit</code> and friends.
(TBT)
</para>
</item>
<item><itemtext>f</itemtext>
<para>
This function takes a variable number of arguments, <code>printf</code> style.
The argument list should end with <code>...</code>, like this:
</para>
<para>
This function takes a variable number of arguments, <code>printf</code> style.
The argument list should end with <code>...</code>, like this:
(TBT)
</para>
<verbatim><![CDATA[
Afprd   |void   |croak          |const char* pat|...
]]></verbatim>
</item>
<item><itemtext>M</itemtext>
<para>
This function is part of the experimental development API, and may change
or disappear without notice.
</para>
<para>
This function is part of the experimental development API, and may change
or disappear without notice.
(TBT)
</para>
</item>
<item><itemtext>o</itemtext>
<para>
This function should not have a compatibility macro to define, say,
<code>Perl_parse</code> to <code>parse</code>. It must be called as <code>Perl_parse</code>.
</para>
<para>
This function should not have a compatibility macro to define, say,
<code>Perl_parse</code> to <code>parse</code>. It must be called as <code>Perl_parse</code>.
(TBT)
</para>
</item>
<item><itemtext>x</itemtext>
<para>
This function isn't exported out of the Perl core.
</para>
<para>
この関数は Perl コアの外側へエクスポートされません。
</para>
</item>
<item><itemtext>m</itemtext>
<para>
This is implemented as a macro.
</para>
<para>
これはマクロとして実装されています。
</para>
</item>
<item><itemtext>X</itemtext>
<para>
This function is explicitly exported.
</para>
<para>
この関数は明示的にエクスポートされます。
</para>
</item>
<item><itemtext>E</itemtext>
<para>
This function is visible to extensions included in the Perl core.
</para>
<para>
この関数は Perl コアに含まれるエクステンションから見えます。
</para>
</item>
<item><itemtext>b</itemtext>
<para>
Binary backward compatibility; this function is a macro but also has
a <code>Perl_</code> implementation (which is exported).
</para>
<para>
Binary backward compatibility; this function is a macro but also has
a <code>Perl_</code> implementation (which is exported).
(TBT)
</para>
</item>
<item><itemtext>others</itemtext>
<para>
See the comments at the top of <code>embed.fnc</code> for others.
</para>
<para>
See the comments at the top of <code>embed.fnc</code> for others.
(TBT)
</para>
</item>
</list>
<para>
If you edit <filename>embed.pl</filename> or <filename>embed.fnc</filename>, you will need to run
<code>make regen_headers</code> to force a rebuild of <filename>embed.h</filename> and other
auto-generated files.
</para>
<para>
If you edit <filename>embed.pl</filename> or <filename>embed.fnc</filename>, you will need to run
<code>make regen_headers</code> to force a rebuild of <filename>embed.h</filename> and other
auto-generated files.
(TBT)
</para>
<sect2>
<title>Formatted Printing of IVs, UVs, and NVs</title>
<para>
If you are printing IVs, UVs, or NVS instead of the stdio(3) style
formatting codes like <code>%d</code>, <code>%ld</code>, <code>%f</code>, you should use the
following macros for portability
</para>
<para>
If you are printing IVs, UVs, or NVS instead of the stdio(3) style
formatting codes like <code>%d</code>, <code>%ld</code>, <code>%f</code>, you should use the
following macros for portability
(TBT)
</para>
<verbatim><![CDATA[
IVdf            IV in decimal
UVuf            UV in decimal
UVof            UV in octal
UVxf            UV in hexadecimal
NVef            NV %e-like
NVff            NV %f-like
NVgf            NV %g-like
]]></verbatim>
<para>
These will take care of 64-bit integers and long doubles.
For example:
</para>
<para>
These will take care of 64-bit integers and long doubles.
For example:
(TBT)
</para>
<verbatim><![CDATA[
printf("IV is %"IVdf"\n", iv);
]]></verbatim>
<para>
The IVdf will expand to whatever is the correct format for the IVs.
</para>
<para>
The IVdf will expand to whatever is the correct format for the IVs.
(TBT)
</para>
<para>
If you are printing addresses of pointers, use UVxf combined
with PTR2UV(), do not use %lx or %p.
</para>
<para>
If you are printing addresses of pointers, use UVxf combined
with PTR2UV(), do not use %lx or %p.
(TBT)
</para>
</sect2>
<sect2>
<title>Pointer-To-Integer and Integer-To-Pointer</title>
<para>
Because pointer size does not necessarily equal integer size,
use the follow macros to do it right.
</para>
<para>
Because pointer size does not necessarily equal integer size,
use the follow macros to do it right.
(TBT)
</para>
<verbatim><![CDATA[
PTR2UV(pointer)
PTR2IV(pointer)
PTR2NV(pointer)
INT2PTR(pointertotype, integer)
]]></verbatim>
<para>
For example:
</para>
<para>
例えば:
</para>
<verbatim><![CDATA[
IV  iv = ...;
SV *sv = INT2PTR(SV*, iv);
]]></verbatim>
<para>
and
</para>
<para>
および
</para>
<verbatim><![CDATA[
AV *av = ...;
UV  uv = PTR2UV(av);
]]></verbatim>
</sect2>
<sect2>
<title>Exception Handling</title>
<para>
There are a couple of macros to do very basic exception handling in XS
modules. You have to define <code>NO_XSLOCKS</code> before including <filename>XSUB.h</filename> to
be able to use these macros:
</para>
<para>
There are a couple of macros to do very basic exception handling in XS
modules. You have to define <code>NO_XSLOCKS</code> before including <filename>XSUB.h</filename> to
be able to use these macros:
(TBT)
</para>
<verbatim><![CDATA[
#define NO_XSLOCKS
#include "XSUB.h"
]]></verbatim>
<para>
You can use these macros if you call code that may croak, but you need
to do some cleanup before giving control back to Perl. For example:
</para>
<para>
You can use these macros if you call code that may croak, but you need
to do some cleanup before giving control back to Perl. For example:
(TBT)
</para>
<verbatim><![CDATA[
dXCPT;    /* set up necessary variables */
]]></verbatim>
<verbatim><![CDATA[
XCPT_TRY_START {
  code_that_may_croak();
} XCPT_TRY_END
]]></verbatim>
<verbatim><![CDATA[
XCPT_CATCH
{
  /* do cleanup here */
  XCPT_RETHROW;
}
]]></verbatim>
<para>
Note that you always have to rethrow an exception that has been
caught. Using these macros, it is not possible to just catch the
exception and ignore it. If you have to ignore the exception, you
have to use the <code>call_*</code> function.
</para>
<para>
Note that you always have to rethrow an exception that has been
caught. Using these macros, it is not possible to just catch the
exception and ignore it. If you have to ignore the exception, you
have to use the <code>call_*</code> function.
(TBT)
</para>
<para>
The advantage of using the above macros is that you don't have
to setup an extra function for <code>call_*</code>, and that using these
macros is faster than using <code>call_*</code>.
</para>
<para>
The advantage of using the above macros is that you don't have
to setup an extra function for <code>call_*</code>, and that using these
macros is faster than using <code>call_*</code>.
(TBT)
</para>
</sect2>
<sect2>
<title>Source Documentation</title>
<para>
There's an effort going on to document the internal functions and
automatically produce reference manuals from them - <link xref='perlapi'>perlapi</link> is one
such manual which details all the functions which are available to XS
writers. <link xref='perlintern'>perlintern</link> is the autogenerated manual for the functions
which are not part of the API and are supposedly for internal use only.
</para>
<para>
There's an effort going on to document the internal functions and
automatically produce reference manuals from them - <link xref='perlapi'>perlapi</link> is one
such manual which details all the functions which are available to XS
writers. <link xref='perlintern'>perlintern</link> is the autogenerated manual for the functions
which are not part of the API and are supposedly for internal use only.
(TBT)
</para>
<para>
Source documentation is created by putting POD comments into the C
source, like this:
</para>
<para>
Source documentation is created by putting POD comments into the C
source, like this:
(TBT)
</para>
<verbatim><![CDATA[
/*
=for apidoc sv_setiv
]]></verbatim>
<verbatim><![CDATA[
Copies an integer into the given SV.  Does not handle 'set' magic.  See
C<sv_setiv_mg>.
]]></verbatim>
<verbatim><![CDATA[
=cut
*/
]]></verbatim>
<para>
Please try and supply some documentation if you add functions to the
Perl core.
</para>
<para>
Please try and supply some documentation if you add functions to the
Perl core.
(TBT)
</para>
</sect2>
<sect2>
<title>Backwards compatibility</title>
<para>
(後方互換性)
</para>
<para>
The Perl API changes over time. New functions are added or the interfaces
of existing functions are changed. The <code>Devel::PPPort</code> module tries to
provide compatibility code for some of these changes, so XS writers don't
have to code it themselves when supporting multiple versions of Perl.
</para>
<para>
The Perl API changes over time. New functions are added or the interfaces
of existing functions are changed. The <code>Devel::PPPort</code> module tries to
provide compatibility code for some of these changes, so XS writers don't
have to code it themselves when supporting multiple versions of Perl.
(TBT)
</para>
<para>
<code>Devel::PPPort</code> generates a C header file <filename>ppport.h</filename> that can also
be run as a Perl script. To generate <filename>ppport.h</filename>, run:
</para>
<para>
<code>Devel::PPPort</code> generates a C header file <filename>ppport.h</filename> that can also
be run as a Perl script. To generate <filename>ppport.h</filename>, run:
(TBT)
</para>
<verbatim><![CDATA[
perl -MDevel::PPPort -eDevel::PPPort::WriteFile
]]></verbatim>
<para>
Besides checking existing XS code, the script can also be used to retrieve
compatibility information for various API calls using the <code>--api-info</code>
command line switch. For example:
</para>
<para>
Besides checking existing XS code, the script can also be used to retrieve
compatibility information for various API calls using the <code>--api-info</code>
command line switch. For example:
(TBT)
</para>
<verbatim><![CDATA[
% perl ppport.h --api-info=sv_magicext
]]></verbatim>
<para>
For details, see <code>perldoc ppport.h</code>.
</para>
<para>
詳細については、<code>perldoc ppport.h</code> を参照してください。
</para>
</sect2>
</sect1>
<sect1>
<title>Unicode Support</title>
<para>
(Unicode 対応)
</para>
<para>
Perl 5.6.0 introduced Unicode support. It's important for porters and XS
writers to understand this support and make sure that the code they
write does not corrupt Unicode data.
</para>
<para>
Perl 5.6.0 introduced Unicode support. It's important for porters and XS
writers to understand this support and make sure that the code they
write does not corrupt Unicode data.
(TBT)
</para>
<sect2>
<title>What <strong>is</strong> Unicode, anyway?</title>
<para>
(ところで、Unicode って <strong>何</strong> ?)
</para>
<para>
In the olden, less enlightened times, we all used to use ASCII. Most of
us did, anyway. The big problem with ASCII is that it's American. Well,
no, that's not actually the problem; the problem is that it's not
particularly useful for people who don't use the Roman alphabet. What
used to happen was that particular languages would stick their own
alphabet in the upper range of the sequence, between 128 and 255. Of
course, we then ended up with plenty of variants that weren't quite
ASCII, and the whole point of it being a standard was lost.
</para>
<para>
In the olden, less enlightened times, we all used to use ASCII. Most of
us did, anyway. The big problem with ASCII is that it's American. Well,
no, that's not actually the problem; the problem is that it's not
particularly useful for people who don't use the Roman alphabet. What
used to happen was that particular languages would stick their own
alphabet in the upper range of the sequence, between 128 and 255. Of
course, we then ended up with plenty of variants that weren't quite
ASCII, and the whole point of it being a standard was lost.
(TBT)
</para>
<para>
Worse still, if you've got a language like Chinese or
Japanese that has hundreds or thousands of characters, then you really
can't fit them into a mere 256, so they had to forget about ASCII
altogether, and build their own systems using pairs of numbers to refer
to one character.
</para>
<para>
Worse still, if you've got a language like Chinese or
Japanese that has hundreds or thousands of characters, then you really
can't fit them into a mere 256, so they had to forget about ASCII
altogether, and build their own systems using pairs of numbers to refer
to one character.
(TBT)
</para>
<para>
To fix this, some people formed Unicode, Inc. and
produced a new character set containing all the characters you can
possibly think of and more. There are several ways of representing these
characters, and the one Perl uses is called UTF-8. UTF-8 uses
a variable number of bytes to represent a character. You can learn more
about Unicode and Perl's Unicode model in <link xref='perlunicode'>perlunicode</link>.
</para>
<para>
To fix this, some people formed Unicode, Inc. and
produced a new character set containing all the characters you can
possibly think of and more. There are several ways of representing these
characters, and the one Perl uses is called UTF-8. UTF-8 uses
a variable number of bytes to represent a character. You can learn more
about Unicode and Perl's Unicode model in <link xref='perlunicode'>perlunicode</link>.
(TBT)
</para>
</sect2>
<sect2>
<title>How can I recognise a UTF-8 string?</title>
<para>
(UTF-8 文字列を認識するには?)
</para>
<para>
You can't. This is because UTF-8 data is stored in bytes just like
non-UTF-8 data. The Unicode character 200, (<code>0xC8</code> for you hex types)
capital E with a grave accent, is represented by the two bytes
<code>v196.172</code>. Unfortunately, the non-Unicode string <code>chr(196).chr(172)</code>
has that byte sequence as well. So you can't tell just by looking - this
is what makes Unicode input an interesting problem.
</para>
<para>
You can't. This is because UTF-8 data is stored in bytes just like
non-UTF-8 data. The Unicode character 200, (<code>0xC8</code> for you hex types)
capital E with a grave accent, is represented by the two bytes
<code>v196.172</code>. Unfortunately, the non-Unicode string <code>chr(196).chr(172)</code>
has that byte sequence as well. So you can't tell just by looking - this
is what makes Unicode input an interesting problem.
(TBT)
</para>
<para>
In general, you either have to know what you're dealing with, or you
have to guess.  The API function <code>is_utf8_string</code> can help; it'll tell
you if a string contains only valid UTF-8 characters. However, it can't
do the work for you. On a character-by-character basis, <code>is_utf8_char</code>
will tell you whether the current character in a string is valid UTF-8.
</para>
<para>
In general, you either have to know what you're dealing with, or you
have to guess.  The API function <code>is_utf8_string</code> can help; it'll tell
you if a string contains only valid UTF-8 characters. However, it can't
do the work for you. On a character-by-character basis, <code>is_utf8_char</code>
will tell you whether the current character in a string is valid UTF-8. 
(TBT)
</para>
</sect2>
<sect2>
<title>How does UTF-8 represent Unicode characters?</title>
<para>
As mentioned above, UTF-8 uses a variable number of bytes to store a
character. Characters with values 0...127 are stored in one byte, just
like good ol' ASCII. Character 128 is stored as <code>v194.128</code>; this
continues up to character 191, which is <code>v194.191</code>. Now we've run out of
bits (191 is binary <code>10111111</code>) so we move on; 192 is <code>v195.128</code>. And
so it goes on, moving to three bytes at character 2048.
</para>
<para>
As mentioned above, UTF-8 uses a variable number of bytes to store a
character. Characters with values 0...127 are stored in one byte, just
like good ol' ASCII. Character 128 is stored as <code>v194.128</code>; this
continues up to character 191, which is <code>v194.191</code>. Now we've run out of
bits (191 is binary <code>10111111</code>) so we move on; 192 is <code>v195.128</code>. And
so it goes on, moving to three bytes at character 2048.
(TBT)
</para>
<para>
Assuming you know you're dealing with a UTF-8 string, you can find out
how long the first character in it is with the <code>UTF8SKIP</code> macro:
</para>
<para>
Assuming you know you're dealing with a UTF-8 string, you can find out
how long the first character in it is with the <code>UTF8SKIP</code> macro:
(TBT)
</para>
<verbatim><![CDATA[
char *utf = "\305\233\340\240\201";
I32 len;
]]></verbatim>
<verbatim><![CDATA[
len = UTF8SKIP(utf); /* len is 2 here */
utf += len;
len = UTF8SKIP(utf); /* len is 3 here */
]]></verbatim>
<para>
Another way to skip over characters in a UTF-8 string is to use
<code>utf8_hop</code>, which takes a string and a number of characters to skip
over. You're on your own about bounds checking, though, so don't use it
lightly.
</para>
<para>
Another way to skip over characters in a UTF-8 string is to use
<code>utf8_hop</code>, which takes a string and a number of characters to skip
over. You're on your own about bounds checking, though, so don't use it
lightly.
(TBT)
</para>
<para>
All bytes in a multi-byte UTF-8 character will have the high bit set,
so you can test if you need to do something special with this
character like this (the UTF8_IS_INVARIANT() is a macro that tests
whether the byte can be encoded as a single byte even in UTF-8):
</para>
<para>
All bytes in a multi-byte UTF-8 character will have the high bit set,
so you can test if you need to do something special with this
character like this (the UTF8_IS_INVARIANT() is a macro that tests
whether the byte can be encoded as a single byte even in UTF-8):
(TBT)
</para>
<verbatim><![CDATA[
U8 *utf;
UV uv;	/* Note: a UV, not a U8, not a char */
]]></verbatim>
<verbatim><![CDATA[
if (!UTF8_IS_INVARIANT(*utf))
    /* Must treat this as UTF-8 */
    uv = utf8_to_uv(utf);
else
    /* OK to treat this character as a byte */
    uv = *utf;
]]></verbatim>
<para>
You can also see in that example that we use <code>utf8_to_uv</code> to get the
value of the character; the inverse function <code>uv_to_utf8</code> is available
for putting a UV into UTF-8:
</para>
<para>
You can also see in that example that we use <code>utf8_to_uv</code> to get the
value of the character; the inverse function <code>uv_to_utf8</code> is available
for putting a UV into UTF-8:
(TBT)
</para>
<verbatim><![CDATA[
if (!UTF8_IS_INVARIANT(uv))
    /* Must treat this as UTF8 */
    utf8 = uv_to_utf8(utf8, uv);
else
    /* OK to treat this character as a byte */
    *utf8++ = uv;
]]></verbatim>
<para>
You <strong>must</strong> convert characters to UVs using the above functions if
you're ever in a situation where you have to match UTF-8 and non-UTF-8
characters. You may not skip over UTF-8 characters in this case. If you
do this, you'll lose the ability to match hi-bit non-UTF-8 characters;
for instance, if your UTF-8 string contains <code>v196.172</code>, and you skip
that character, you can never match a <code>chr(200)</code> in a non-UTF-8 string.
So don't do that!
</para>
<para>
You <strong>must</strong> convert characters to UVs using the above functions if
you're ever in a situation where you have to match UTF-8 and non-UTF-8
characters. You may not skip over UTF-8 characters in this case. If you
do this, you'll lose the ability to match hi-bit non-UTF-8 characters;
for instance, if your UTF-8 string contains <code>v196.172</code>, and you skip
that character, you can never match a <code>chr(200)</code> in a non-UTF-8 string.
So don't do that!
(TBT)
</para>
</sect2>
<sect2>
<title>How does Perl store UTF-8 strings?</title>
<para>
Currently, Perl deals with Unicode strings and non-Unicode strings
slightly differently. A flag in the SV, <code>SVf_UTF8</code>, indicates that the
string is internally encoded as UTF-8. Without it, the byte value is the
codepoint number and vice versa (in other words, the string is encoded
as iso-8859-1). You can check and manipulate this flag with the
following macros:
</para>
<para>
Currently, Perl deals with Unicode strings and non-Unicode strings
slightly differently. A flag in the SV, <code>SVf_UTF8</code>, indicates that the
string is internally encoded as UTF-8. Without it, the byte value is the
codepoint number and vice versa (in other words, the string is encoded
as iso-8859-1). You can check and manipulate this flag with the
following macros:
(TBT)
</para>
<verbatim><![CDATA[
SvUTF8(sv)
SvUTF8_on(sv)
SvUTF8_off(sv)
]]></verbatim>
<para>
This flag has an important effect on Perl's treatment of the string: if
Unicode data is not properly distinguished, regular expressions,
<code>length</code>, <code>substr</code> and other string handling operations will have
undesirable results.
</para>
<para>
This flag has an important effect on Perl's treatment of the string: if
Unicode data is not properly distinguished, regular expressions,
<code>length</code>, <code>substr</code> and other string handling operations will have
undesirable results.
(TBT)
</para>
<para>
The problem comes when you have, for instance, a string that isn't
flagged as UTF-8, and contains a byte sequence that could be UTF-8 -
especially when combining non-UTF-8 and UTF-8 strings.
</para>
<para>
The problem comes when you have, for instance, a string that isn't
flagged as UTF-8, and contains a byte sequence that could be UTF-8 -
especially when combining non-UTF-8 and UTF-8 strings.
(TBT)
</para>
<para>
Never forget that the <code>SVf_UTF8</code> flag is separate to the PV value; you
need be sure you don't accidentally knock it off while you're
manipulating SVs. More specifically, you cannot expect to do this:
</para>
<para>
Never forget that the <code>SVf_UTF8</code> flag is separate to the PV value; you
need be sure you don't accidentally knock it off while you're
manipulating SVs. More specifically, you cannot expect to do this:
(TBT)
</para>
<verbatim><![CDATA[
SV *sv;
SV *nsv;
STRLEN len;
char *p;
]]></verbatim>
<verbatim><![CDATA[
p = SvPV(sv, len);
frobnicate(p);
nsv = newSVpvn(p, len);
]]></verbatim>
<para>
The <code>char*</code> string does not tell you the whole story, and you can't
copy or reconstruct an SV just by copying the string value. Check if the
old SV has the UTF8 flag set, and act accordingly:
</para>
<para>
The <code>char*</code> string does not tell you the whole story, and you can't
copy or reconstruct an SV just by copying the string value. Check if the
old SV has the UTF8 flag set, and act accordingly:
(TBT)
</para>
<verbatim><![CDATA[
p = SvPV(sv, len);
frobnicate(p);
nsv = newSVpvn(p, len);
if (SvUTF8(sv))
    SvUTF8_on(nsv);
]]></verbatim>
<para>
In fact, your <code>frobnicate</code> function should be made aware of whether or
not it's dealing with UTF-8 data, so that it can handle the string
appropriately.
</para>
<para>
In fact, your <code>frobnicate</code> function should be made aware of whether or
not it's dealing with UTF-8 data, so that it can handle the string
appropriately.
(TBT)
</para>
<para>
Since just passing an SV to an XS function and copying the data of
the SV is not enough to copy the UTF8 flags, even less right is just
passing a <code>char *</code> to an XS function.
</para>
<para>
Since just passing an SV to an XS function and copying the data of
the SV is not enough to copy the UTF8 flags, even less right is just
passing a <code>char *</code> to an XS function.
(TBT)
</para>
</sect2>
<sect2>
<title>How do I convert a string to UTF-8?</title>
<para>
If you're mixing UTF-8 and non-UTF-8 strings, it is necessary to upgrade
one of the strings to UTF-8. If you've got an SV, the easiest way to do
this is:
</para>
<para>
If you're mixing UTF-8 and non-UTF-8 strings, it is necessary to upgrade
one of the strings to UTF-8. If you've got an SV, the easiest way to do
this is:
(TBT)
</para>
<verbatim><![CDATA[
sv_utf8_upgrade(sv);
]]></verbatim>
<para>
However, you must not do this, for example:
</para>
<para>
However, you must not do this, for example:
(TBT)
</para>
<verbatim><![CDATA[
if (!SvUTF8(left))
    sv_utf8_upgrade(left);
]]></verbatim>
<para>
If you do this in a binary operator, you will actually change one of the
strings that came into the operator, and, while it shouldn't be noticeable
by the end user, it can cause problems in deficient code.
</para>
<para>
If you do this in a binary operator, you will actually change one of the
strings that came into the operator, and, while it shouldn't be noticeable
by the end user, it can cause problems in deficient code.
(TBT)
</para>
<para>
Instead, <code>bytes_to_utf8</code> will give you a UTF-8-encoded <strong>copy</strong> of its
string argument. This is useful for having the data available for
comparisons and so on, without harming the original SV. There's also
<code>utf8_to_bytes</code> to go the other way, but naturally, this will fail if
the string contains any characters above 255 that can't be represented
in a single byte.
</para>
<para>
Instead, <code>bytes_to_utf8</code> will give you a UTF-8-encoded <strong>copy</strong> of its
string argument. This is useful for having the data available for
comparisons and so on, without harming the original SV. There's also
<code>utf8_to_bytes</code> to go the other way, but naturally, this will fail if
the string contains any characters above 255 that can't be represented
in a single byte.
(TBT)
</para>
</sect2>
<sect2>
<title>Is there anything else I need to know?</title>
<para>
(他に知っておくべきことは?)
</para>
<para>
Not really. Just remember these things:
</para>
<para>
実際にはありません。
単に以下のことを覚えておいてください:
</para>
<list>
<item><para>
There's no way to tell if a string is UTF-8 or not. You can tell if an SV
is UTF-8 by looking at is <code>SvUTF8</code> flag. Don't forget to set the flag if
something should be UTF-8. Treat the flag as part of the PV, even though
it's not - if you pass on the PV to somewhere, pass on the flag too.
</para>
<para>
There's no way to tell if a string is UTF-8 or not. You can tell if an SV
is UTF-8 by looking at is <code>SvUTF8</code> flag. Don't forget to set the flag if
something should be UTF-8. Treat the flag as part of the PV, even though
it's not - if you pass on the PV to somewhere, pass on the flag too.
(TBT)
</para>
</item>
<item><para>
If a string is UTF-8, <strong>always</strong> use <code>utf8_to_uv</code> to get at the value,
unless <code>UTF8_IS_INVARIANT(*s)</code> in which case you can use <code>*s</code>.
</para>
<para>
If a string is UTF-8, <strong>always</strong> use <code>utf8_to_uv</code> to get at the value,
unless <code>UTF8_IS_INVARIANT(*s)</code> in which case you can use <code>*s</code>.
(TBT)
</para>
</item>
<item><para>
When writing a character <code>uv</code> to a UTF-8 string, <strong>always</strong> use
<code>uv_to_utf8</code>, unless <code>UTF8_IS_INVARIANT(uv))</code> in which case
you can use <code>*s = uv</code>.
</para>
<para>
When writing a character <code>uv</code> to a UTF-8 string, <strong>always</strong> use
<code>uv_to_utf8</code>, unless <code>UTF8_IS_INVARIANT(uv))</code> in which case
you can use <code>*s = uv</code>.
(TBT)
</para>
</item>
<item><para>
Mixing UTF-8 and non-UTF-8 strings is tricky. Use <code>bytes_to_utf8</code> to get
a new string which is UTF-8 encoded. There are tricks you can use to
delay deciding whether you need to use a UTF-8 string until you get to a
high character - <code>HALF_UPGRADE</code> is one of those.
</para>
<para>
Mixing UTF-8 and non-UTF-8 strings is tricky. Use <code>bytes_to_utf8</code> to get
a new string which is UTF-8 encoded. There are tricks you can use to
delay deciding whether you need to use a UTF-8 string until you get to a
high character - <code>HALF_UPGRADE</code> is one of those.
(TBT)
</para>
</item>
</list>
</sect2>
</sect1>
<sect1>
<title>Custom Operators</title>
<para>
Custom operator support is a new experimental feature that allows you to
define your own ops. This is primarily to allow the building of
interpreters for other languages in the Perl core, but it also allows
optimizations through the creation of &quot;macro-ops&quot; (ops which perform the
functions of multiple ops which are usually executed together, such as
<code>gvsv, gvsv, add</code>.)
</para>
<para>
Custom operator support is a new experimental feature that allows you to
define your own ops. This is primarily to allow the building of
interpreters for other languages in the Perl core, but it also allows
optimizations through the creation of &quot;macro-ops&quot; (ops which perform the
functions of multiple ops which are usually executed together, such as
<code>gvsv, gvsv, add</code>.)
(TBT)
</para>
<para>
This feature is implemented as a new op type, <code>OP_CUSTOM</code>. The Perl
core does not &quot;know&quot; anything special about this op type, and so it will
not be involved in any optimizations. This also means that you can
define your custom ops to be any op structure - unary, binary, list and
so on - you like.
</para>
<para>
This feature is implemented as a new op type, <code>OP_CUSTOM</code>. The Perl
core does not &quot;know&quot; anything special about this op type, and so it will
not be involved in any optimizations. This also means that you can
define your custom ops to be any op structure - unary, binary, list and
so on - you like.
(TBT)
</para>
<para>
It's important to know what custom operators won't do for you. They
won't let you add new syntax to Perl, directly. They won't even let you
add new keywords, directly. In fact, they won't change the way Perl
compiles a program at all. You have to do those changes yourself, after
Perl has compiled the program. You do this either by manipulating the op
tree using a <code>CHECK</code> block and the <code>B::Generate</code> module, or by adding
a custom peephole optimizer with the <code>optimize</code> module.
</para>
<para>
It's important to know what custom operators won't do for you. They
won't let you add new syntax to Perl, directly. They won't even let you
add new keywords, directly. In fact, they won't change the way Perl
compiles a program at all. You have to do those changes yourself, after
Perl has compiled the program. You do this either by manipulating the op
tree using a <code>CHECK</code> block and the <code>B::Generate</code> module, or by adding
a custom peephole optimizer with the <code>optimize</code> module.
(TBT)
</para>
<para>
When you do this, you replace ordinary Perl ops with custom ops by
creating ops with the type <code>OP_CUSTOM</code> and the <code>pp_addr</code> of your own
PP function. This should be defined in XS code, and should look like
the PP ops in <code>pp_*.c</code>. You are responsible for ensuring that your op
takes the appropriate number of values from the stack, and you are
responsible for adding stack marks if necessary.
</para>
<para>
When you do this, you replace ordinary Perl ops with custom ops by
creating ops with the type <code>OP_CUSTOM</code> and the <code>pp_addr</code> of your own
PP function. This should be defined in XS code, and should look like
the PP ops in <code>pp_*.c</code>. You are responsible for ensuring that your op
takes the appropriate number of values from the stack, and you are
responsible for adding stack marks if necessary.
(TBT)
</para>
<para>
You should also &quot;register&quot; your op with the Perl interpreter so that it
can produce sensible error and warning messages. Since it is possible to
have multiple custom ops within the one &quot;logical&quot; op type <code>OP_CUSTOM</code>,
Perl uses the value of <code>o-&gt;op_ppaddr</code> as a key into the
<code>PL_custom_op_descs</code> and <code>PL_custom_op_names</code> hashes. This means you
need to enter a name and description for your op at the appropriate
place in the <code>PL_custom_op_names</code> and <code>PL_custom_op_descs</code> hashes.
</para>
<para>
You should also &quot;register&quot; your op with the Perl interpreter so that it
can produce sensible error and warning messages. Since it is possible to
have multiple custom ops within the one &quot;logical&quot; op type <code>OP_CUSTOM</code>,
Perl uses the value of <code>o-&gt;op_ppaddr</code> as a key into the
<code>PL_custom_op_descs</code> and <code>PL_custom_op_names</code> hashes. This means you
need to enter a name and description for your op at the appropriate
place in the <code>PL_custom_op_names</code> and <code>PL_custom_op_descs</code> hashes.
(TBT)
</para>
<para>
Forthcoming versions of <code>B::Generate</code> (version 1.0 and above) should
directly support the creation of custom ops by name.
</para>
<para>
Forthcoming versions of <code>B::Generate</code> (version 1.0 and above) should
directly support the creation of custom ops by name.
(TBT)
</para>
</sect1>
<sect1>
<title>AUTHORS</title>
<para>
Until May 1997, this document was maintained by Jeff Okamoto
&lt;okamoto@corp.hp.com&gt;.  It is now maintained as part of Perl
itself by the Perl 5 Porters &lt;perl5-porters@perl.org&gt;.
</para>
<para>
Until May 1997, this document was maintained by Jeff Okamoto
&lt;okamoto@corp.hp.com&gt;.  It is now maintained as part of Perl
itself by the Perl 5 Porters &lt;perl5-porters@perl.org&gt;.
(TBT)
</para>
<para>
With lots of help and suggestions from Dean Roehrich, Malcolm Beattie,
Andreas Koenig, Paul Hudson, Ilya Zakharevich, Paul Marquess, Neil
Bowers, Matthew Green, Tim Bunce, Spider Boardman, Ulrich Pfeifer,
Stephen McCamant, and Gurusamy Sarathy.
</para>
<para>
With lots of help and suggestions from Dean Roehrich, Malcolm Beattie,
Andreas Koenig, Paul Hudson, Ilya Zakharevich, Paul Marquess, Neil
Bowers, Matthew Green, Tim Bunce, Spider Boardman, Ulrich Pfeifer,
Stephen McCamant, and Gurusamy Sarathy.
(TBT)
</para>
</sect1>
<sect1>
<title>SEE ALSO</title>
<para>
perlapi(1), perlintern(1), perlxs(1), perlembed(1)
</para>
<para>
Created: KIMURA Koichi
Updated: Kentaro Shirakata &lt;argrath@ub32.org&gt; (5.10.0-)
</para>
</sect1>
</pod>
