<?xml version='1.0' encoding='utf-8'?>
<pod xmlns="http://axkit.org/ns/2000/pod2xml">
<head>
	<title>perlmod - Perl modules (packages and symbol tables)</title>
</head>
<sect1>
<title>perlmod - Perl modules (packages and symbol tables)</title>
<para>
perlmod - Perl のモジュール (パッケージとシンボルテーブル)
</para>
</sect1>
<sect1>
<title>DESCRIPTION</title>
<sect2>
<title>Packages
<index>package</index> <index>namespace</index> <index>variable, global</index> <index>global variable</index> <index>global</index></title>
<para>
(パッケージ)
</para>
<para>
Perl provides a mechanism for alternative namespaces to protect
packages from stomping on each other's variables.  In fact, there's
really no such thing as a global variable in Perl.  The package
statement declares the compilation unit as being in the given
namespace.  The scope of the package declaration is from the
declaration itself through the end of the enclosing block, <code>eval</code>,
or file, whichever comes first (the same scope as the my() and
local() operators).  Unqualified dynamic identifiers will be in
this namespace, except for those few identifiers that if unqualified,
default to the main package instead of the current one as described
below.  A package statement affects only dynamic variables--including
those you've used local() on--but <emphasis>not</emphasis> lexical variables created
with my().  Typically it would be the first declaration in a file
included by the <code>do</code>, <code>require</code>, or <code>use</code> operators.  You can
switch into a package in more than one place; it merely influences
which symbol table is used by the compiler for the rest of that
block.  You can refer to variables and filehandles in other packages
by prefixing the identifier with the package name and a double
colon: <code>$Package::Variable</code>.  If the package name is null, the
<code>main</code> package is assumed.  That is, <code>$::sail</code> is equivalent to
<code>$main::sail</code>.
</para>
<para>
Perlは、他のパッケージの変数によってあるパッケージが壊されるのを
防ぐために、選択的名前空間(alternative namespace)の機構を提供しています。
実際のところ、グローバル変数は Perl にはないのです。
package 文は、コンパイル単位を与えられた名前空間にあるように宣言します。
そのパッケージ宣言のスコープは宣言それ自身から、宣言を囲むブロック、
または <code>eval</code>、ファイルの最初に現れたものまでです
(my() や locla() 演算子のスコープと同じ)。
修飾されていない動的識別子(dynamic identifiers)はその名前空間に
存在するようになりますが、例外として以下に述べるように、いくつかの識別子は
修飾されないと現在のパッケージではなく main パッケージに存在します。
パッケージ文は(local() を使った)動的変数にのみ効果を持ちますが、
my() によって生成されたレキシカル変数には影響 <emphasis>しません</emphasis>。
典型的には、これは <code>do</code>, <code>require</code>, <code>use</code> 演算子を使ってインクルードされた
ファイルの先頭の宣言となります。
二ヶ所以上でパッケージを切り替えることができます。
それによって、ブロックの残りの部分に対してコンパイラが
使うシンボルテーブルに影響を及ぼすにすぎません。
他のパッケージから識別子にそのパッケージ名とダブルコロンを前置して
<code>$Package::Variable</code> のようにすることで、変数やファイルハンドルを
参照することができます。
パッケージ名が空であれば、<code>main</code> が仮定されます。
つまり、<code>$::sail</code> と <code>$main::sail</code> は等価になります。
</para>
<para>
The old package delimiter was a single quote, but double colon is now the
preferred delimiter, in part because it's more readable to humans, and
in part because it's more readable to <strong>emacs</strong> macros.  It also makes C++
programmers feel like they know what's going on--as opposed to using the
single quote as separator, which was there to make Ada programmers feel
like they knew what was going on.  Because the old-fashioned syntax is still
supported for backwards compatibility, if you try to use a string like
<code>&quot;This is $owner's house&quot;</code>, you'll be accessing <code>$owner::s</code>; that is,
the $s variable in package <code>owner</code>, which is probably not what you meant.
Use braces to disambiguate, as in <code>&quot;This is ${owner}'s house&quot;</code>.
<index>::</index> <index>'</index>
</para>
<para>
古いパッケージ区切り子はシングルクォートでしたが、現在はダブルコロンを
使うのが推奨されています。
なぜなら、この方が人間が読みやすいということと、<strong>emacs</strong> マクロで
読みやすいからです。
これはまた、C++ プログラマに自分が知っていることのように
思わせるようにもします。
それは以前のシングルクォートが Ada プログラマに馴染みのもので
あったことと同じです。
古い構文も互換性のためにまだサポートされているので、
<code>&quot;This is $owner's house&quot;</code> のようにすると、これは <code>$owner::s</code> を
アクセスします;
つまり、パッケージ <code>owner</code> にある $s という変数をアクセスするのですが、
これはあなたの望んだ動作ではないでしょう。
<code>&quot;This is ${owner}'s house&quot;</code> のようにブレースを使うことによって
曖昧さを除去します。
<index>::</index> <index>'</index>
</para>
<para>
Packages may themselves contain package separators, as in
<code>$OUTER::INNER::var</code>.  This implies nothing about the order of
name lookups, however.  There are no relative packages: all symbols
are either local to the current package, or must be fully qualified
from the outer package name down.  For instance, there is nowhere
within package <code>OUTER</code> that <code>$INNER::var</code> refers to
<code>$OUTER::INNER::var</code>.  <code>INNER</code> refers to a totally
separate global package.
</para>
<para>
パッケージは <code>$OUTER::INNER::var</code> のように、パッケージセパレータを
含むことができます。
しかしながらこれは、名前の検索に関してなんの仮定も行いません。
相対パッケージはありません: 全てのシンボルはカレントのパッケージに
ローカルであるか外側のパッケージから完全に修飾されていなければなりません。
たとえば、パッケージ <code>OUTER</code> から <code>$INNER::var</code> を
参照するには <code>$OUTER::INNER::var</code> とします。
<code>INNER</code> はグローバルパッケージから完全に分離されたものとして
参照します。
</para>
<para>
Only identifiers starting with letters (or underscore) are stored
in a package's symbol table.  All other symbols are kept in package
<code>main</code>, including all punctuation variables, like $_.  In addition,
when unqualified, the identifiers STDIN, STDOUT, STDERR, ARGV,
ARGVOUT, ENV, INC, and SIG are forced to be in package <code>main</code>,
even when used for other purposes than their built-in ones.  If you
have a package called <code>m</code>, <code>s</code>, or <code>y</code>, then you can't use the
qualified form of an identifier because it would be instead interpreted
as a pattern match, a substitution, or a transliteration.
<index>variable, punctuation</index>
</para>
<para>
文字(もしくはアンダースコア)で始まる識別子だけがパッケージの
シンボルテーブルに格納されます。
その他のシンボルは、$_ のような句読点変数の全てを含め、全て
パッケージ <code>main</code> にとどめられます。
それに加え、STDIN, STDOUT, STDERR, ARGV, ARGVOUT, ENV, INC, SIG といった
識別子は、たとえ組み込みでない他の目的のために使っていた場合でも
強制的にパッケージ <code>main</code> に置かれます。
また、<code>m</code>、<code>s</code>, <code>y</code> といった名前のパッケージを使っている場合、
修飾形式の識別子を使うことができません。
なぜなら、そういったものはパターンマッチ、置換、変換として
解釈されてしまうからです。
<index>variable, punctuation</index>
</para>
<para>
Variables beginning with underscore used to be forced into package
main, but we decided it was more useful for package writers to be able
to use leading underscore to indicate private variables and method names.
However, variables and functions named with a single <code>_</code>, such as
$_ and <code>sub _</code>, are still forced into the package <code>main</code>.  See also
<link xref='perlvar#Technical_Note_on_the_Syntax_o'>perlvar/&quot;Technical Note on the Syntax of Variable Names&quot;</link>.
</para>
<para>
アンダースコアで始まる名前を持った変数は強制的にパッケージ main に
置かれるように使われていましたが、アンダーススコアで始めることを、
パッケージの作者が変数やメソッド名がパッケージにプライベートな
ものであることを示すことに使えるようにするのがより便利だろうと
考えてこれを決めました。
しかし、$_ や <code>sub _</code> のように、単一の <code>_</code> で始まる名前の変数や関数は
未だに強制的にパッケージ <code>main</code> となります。
<link xref='perlvar#Technical_Note_on_the_Syntax_o'>perlvar/&quot;Technical Note on the Syntax of Variable Names&quot;</link> も
参照してください。
</para>
<para>
<code>eval</code>ed strings are compiled in the package in which the eval() was
compiled.  (Assignments to <code>$SIG{}</code>, however, assume the signal
handler specified is in the <code>main</code> package.  Qualify the signal handler
name if you wish to have a signal handler in a package.)  For an
example, examine <filename>perldb.pl</filename> in the Perl library.  It initially switches
to the <code>DB</code> package so that the debugger doesn't interfere with variables
in the program you are trying to debug.  At various points, however, it
temporarily switches back to the <code>main</code> package to evaluate various
expressions in the context of the <code>main</code> package (or wherever you came
from).  See <link xref='perldebug'>perldebug</link>.
</para>
<para>
<code>eval</code> された文字列は、eval() がコンパイルされたパッケージで
コンパイルされます。
(しかし、<code>$SIG{}</code> への代入は、指定したシグナルハンドラが、
パッケージ main にあるものとして扱います。
シグナルハンドラを別のパッケージにおきたい場合には、そのシグナルハンドラ名に
パッケージ名を付けてください。)
たとえば、Perl ライブラリの <filename>perldb.pl</filename> を参照してください。
最初に、デバッグしようとするプログラムの変数を、デバッガーが壊さないように、
パッケージ <code>DB</code> に切り替えます。
しかし、多くのポイントで、さまざまな式をパッケージ <code>main</code> (あるいは
もともと指定してたパッケージ) で評価するために、一時的に
パッケージ <code>main</code> に戻るようにしています。
<link xref='perldebug'>perldebug</link> を参照してください。
</para>
<para>
The special symbol <code>__PACKAGE__</code> contains the current package, but cannot
(easily) be used to construct variable names.
</para>
<para>
特殊シンボル <code>__PACKAGE__</code> はカレントパッケージを保持していますが、
変数名を構築するために使うことは(簡単には)できません。
</para>
<para>
See <link xref='perlsub'>perlsub</link> for other scoping issues related to my() and local(),
and <link xref='perlref'>perlref</link> regarding closures.
</para>
<para>
my() と local() に関連したスコープについては <link xref='perlsub'>perlsub</link> を、クロージャに
ついては <link xref='perlref'>perlref</link> 参照してください。
</para>
</sect2>
<sect2>
<title>Symbol Tables
<index>symbol table</index> <index>stash</index> <index>%::</index> <index>%main::</index> <index>typeglob</index> <index>glob</index> <index>alias</index></title>
<para>
(シンボルテーブル)
</para>
<para>
The symbol table for a package happens to be stored in the hash of that
name with two colons appended.  The main symbol table's name is thus
<code>%main::</code>, or <code>%::</code> for short.  Likewise the symbol table for the nested
package mentioned earlier is named <code>%OUTER::INNER::</code>.
</para>
<para>
パッケージのシンボルテーブルは、パッケージ名に二つのコロンを付けた名前の
ハッシュに蓄えられます。
つまり、main のシンボルテーブルは <code>%main::</code>、または短く <code>%::</code> となります。
同様に、先に述べたネストしたパッケージは <code>%OUTER::INNER::</code> となります。
</para>
<para>
The value in each entry of the hash is what you are referring to when you
use the <code>*name</code> typeglob notation.  In fact, the following have the same
effect, though the first is more efficient because it does the symbol
table lookups at compile time:
</para>
<para>
ハッシュの個々のエントリの値は、<code>*name</code> 記法を使ったときに参照するものです。
実際、以下に例示したものは、最初のものがシンボルテーブルを
コンパイル時に検索するのでより効率が良いものの、同じ効果を持っています:
</para>
<verbatim><![CDATA[
local *main::foo    = *main::bar;
local $main::{foo}  = $main::{bar};
]]></verbatim>
<para>
(Be sure to note the <strong>vast</strong> difference between the second line above
and <code>local $main::foo = $main::bar</code>. The former is accessing the hash
<code>%main::</code>, which is the symbol table of package <code>main</code>. The latter is
simply assigning scalar <code>$bar</code> in package <code>main</code> to scalar <code>$foo</code> of
the same package.)
</para>
<para>
(上記の 2 行目と <code>local $main::foo = $main::The</code> との <strong>大きな</strong> 違いに
注意してください。
前者は <code>%main::</code>、つまり <code>main</code> パッケージのシンボルテーブルを
アクセスしています。
後者は単に <code>main</code> パッケージのスカラ <code>$bar</code> を同じパッケージの
スカラ <code>$foo</code> に代入しています。)
</para>
<para>
You can use this to print out all the variables in a package, for
instance.  The standard but antiquated <filename>dumpvar.pl</filename> library and
the CPAN module Devel::Symdump make use of this.
</para>
<para>
たとえばこれを、パッケージ内のすべての変数を出力するために使うことができます。
標準ですが古風な <filename>dumpvar.pl</filename> ライブラリと
CPAN モジュール Devel::Symdump で実際に行えます。
</para>
<para>
Assignment to a typeglob performs an aliasing operation, i.e.,
</para>
<para>
型グロブに対する代入は、エイリアス操作を行います;
例えば:
</para>
<verbatim><![CDATA[
*dick = *richard;
]]></verbatim>
<para>
causes variables, subroutines, formats, and file and directory handles
accessible via the identifier <code>richard</code> also to be accessible via the
identifier <code>dick</code>.  If you want to alias only a particular variable or
subroutine, assign a reference instead:
</para>
<para>
は、richard という識別子でアクセスできる変数、サブルーチン、
ファイルハンドルを<code>dick</code> という識別子でもアクセスできるようにします。
リファレンスを使えば、特定の変数だけとかサブルーチンだけ、と
いうように個別に別名を付けることができます:
</para>
<verbatim><![CDATA[
*dick = \$richard;
]]></verbatim>
<para>
Which makes $richard and $dick the same variable, but leaves
@richard and @dick as separate arrays.  Tricky, eh?
</para>
<para>
これは、$richard と $dick を同じ変数にしますが、@richard と @dick は
別の配列のままです。
解りづらいですか?
</para>
<para>
There is one subtle difference between the following statements:
</para>
<para>
以下の 2 つの文には、微妙な違いがあります:
</para>
<verbatim><![CDATA[
*foo = *bar;
*foo = \$bar;
]]></verbatim>
<para>
<code>*foo = *bar</code> makes the typeglobs themselves synonymous while
<code>*foo = \$bar</code> makes the SCALAR portions of two distinct typeglobs
refer to the same scalar value. This means that the following code:
</para>
<para>
<code>*foo = *bar</code> は型グロブそのものを同期させますが、一方
<code>*foo = \$bar</code> 同じスカラ値を示す二つの区別した型グロブの SCALAR 部を
作ります。
これが意味するのは、以下のコードは:
</para>
<verbatim><![CDATA[
$bar = 1;
*foo = \$bar;       # Make $foo an alias for $bar
]]></verbatim>
<verbatim><![CDATA[
{
    local $bar = 2; # Restrict changes to block
    print $foo;     # Prints '1'!
}
]]></verbatim>
<para>
Would print '1', because <code>$foo</code> holds a reference to the <emphasis>original</emphasis>
<code>$bar</code> -- the one that was stuffed away by <code>local()</code> and which will be
restored when the block ends. Because variables are accessed through the
typeglob, you can use <code>*foo = *bar</code> to create an alias which can be
localized. (But be aware that this means you can't have a separate
<code>@foo</code> and <code>@bar</code>, etc.)
</para>
<para>
<code>$foo</code> は <emphasis>元の</emphasis> <code>$bar</code> -- <code>local()</code> によって追いやられ、ブロックが
終わる時に復元されるもの -- へのリファレンスを保持しているので '1' が
表示されます。
変数は型グロブを通してアクセスされるので、ローカル化できるエイリアスを
作るために <code>*foo = *bar</code> とすることができます。
(しかし、これは <code>@foo</code> と <code>@bar</code> などを別々に保持することが
できないということに注意してください。)
</para>
<para>
What makes all of this important is that the Exporter module uses glob
aliasing as the import/export mechanism. Whether or not you can properly
localize a variable that has been exported from a module depends on how
it was exported:
</para>
<para>
これらのことが重要である理由は、Exporter モジュールはインポート/エクスポート
機構としてグロブによるエイリアスを使うからです。
モジュールからエクスポートされた変数を適切にローカル化できるかどうかは
どのようにエクスポートされたかに依存します:
</para>
<verbatim><![CDATA[
@EXPORT = qw($FOO); # Usual form, can't be localized
@EXPORT = qw(*FOO); # Can be localized
]]></verbatim>
<verbatim><![CDATA[
@EXPORT = qw($FOO); # 通常の形式、ローカル化できない
@EXPORT = qw(*FOO); # ローカル化できる
]]></verbatim>
<para>
You can work around the first case by using the fully qualified name
(<code>$Package::FOO</code>) where you need a local value, or by overriding it
by saying <code>*FOO = *Package::FOO</code> in your script.
</para>
<para>
1 つ目の場合は、ローカルな値が必要なところで完全修飾名
(<code>$Package::FOO</code>) を使うか、プログラム中で <code>*FOO = *Package::FOO</code> として
上書きすることで回避できます。
</para>
<para>
The <code>*x = \$y</code> mechanism may be used to pass and return cheap references
into or from subroutines if you don't want to copy the whole
thing.  It only works when assigning to dynamic variables, not
lexicals.
</para>
<para>
<code>*x = \$y</code> 機構は、全てをコピーすることを望まないときに、低コストな
リファレンスをサブルーチンに渡したりサブルーチンから返すために
使うことができます。
これは動的変数に対する代入のときにのみ働き、レキシカル変数では
働きません。
</para>
<verbatim><![CDATA[
%some_hash = ();			# can't be my()
*some_hash = fn( \%another_hash );
sub fn {
	local *hashsym = shift;
	# now use %hashsym normally, and you
	# will affect the caller's %another_hash
	my %nhash = (); # do what you want
	return \%nhash;
}
]]></verbatim>
<verbatim><![CDATA[
%some_hash = ();			# my() にできない
*some_hash = fn( \%another_hash );
sub fn {
	local *hashsym = shift;
	# ここで %hashsym を普通に使うと、
	# 呼び出し元の %another_hash に影響を与える
	my %nhash = (); # したいことをする
	return \%nhash;
}
]]></verbatim>
<para>
On return, the reference will overwrite the hash slot in the
symbol table specified by the *some_hash typeglob.  This
is a somewhat tricky way of passing around references cheaply
when you don't want to have to remember to dereference variables
explicitly.
</para>
<para>
リターンのときに、このリファレンスは *some_hash 型グロブによって
指定されるシンボルテーブル中にあるハッシュスロットを上書きします。
これは、変数のデリファレンスを明示的に行うことを考えたくないようなときに、
簡単にリファレンスに関するものを渡すトリッキーなやり方です。
</para>
<para>
Another use of symbol tables is for making &quot;constant&quot; scalars.
<index>constant</index> <index>scalar, constant</index>
</para>
<para>
シンボルテーブルの別の使い方は、「定数」スカラを生成するためのものです。
<index>constant</index> <index>scalar, constant</index>
</para>
<verbatim><![CDATA[
*PI = \3.14159265358979;
]]></verbatim>
<para>
Now you cannot alter <code>$PI</code>, which is probably a good thing all in all.
This isn't the same as a constant subroutine, which is subject to
optimization at compile-time.  A constant subroutine is one prototyped
to take no arguments and to return a constant expression.  See
<link xref='perlsub'>perlsub</link> for details on these.  The <code>use constant</code> pragma is a
convenient shorthand for these.
</para>
<para>
この後、<code>$PI</code> を変更することはできません。
これはコンパイル時に最適化が行われる定数サブルーチンとは異なっていて、
最適化は行われません。
定数サブルーチンは引数を取らず定数式を返すようになってプロトタイプが
なされているサブルーチンです。
これに関する詳細は <link xref='perlsub'>perlsub</link> を参照してください。
<code>use constant</code> プラグマは定数サブルーチンを使いやすくします。
</para>
<para>
You can say <code>*foo{PACKAGE}</code> and <code>*foo{NAME}</code> to find out what name and
package the *foo symbol table entry comes from.  This may be useful
in a subroutine that gets passed typeglobs as arguments:
</para>
<para>
*foo シンボルテーブルにある名前やパッケージを探し出すために、
<code>*foo{PACKAGE}</code> や <code>*foo{NAME}</code> とすることができます。
これは引数として型グロブを渡されるサブルーチン内で便利です。
</para>
<verbatim><![CDATA[
sub identify_typeglob {
    my $glob = shift;
    print 'You gave me ', *{$glob}{PACKAGE}, '::', *{$glob}{NAME}, "\n";
}
identify_typeglob *foo;
identify_typeglob *bar::baz;
]]></verbatim>
<para>
This prints
</para>
<para>
これは以下のものを出力します:
</para>
<verbatim><![CDATA[
You gave me main::foo
You gave me bar::baz
]]></verbatim>
<para>
The <code>*foo{THING}</code> notation can also be used to obtain references to the
individual elements of *foo.  See <link xref='perlref'>perlref</link>.
</para>
<para>
<code>*foo{THING}</code> 記法は、*foo に属する個々の要素に対するリファレンスを
得るためにも使うことができます。
<link xref='perlref'>perlref</link> を参照してください。
</para>
<para>
Subroutine definitions (and declarations, for that matter) need
not necessarily be situated in the package whose symbol table they
occupy.  You can define a subroutine outside its package by
explicitly qualifying the name of the subroutine:
</para>
<para>
サブルーチン定義(およびついでに言えば宣言) は、それらがいるシンボル
テーブルのパッケージ内にいる必要はありません。
サブルーチン名を明示的に修飾することで、パッケージ外のサブルーチンを
定義できます:
</para>
<verbatim><![CDATA[
package main;
sub Some_package::foo { ... }   # &foo defined in Some_package
]]></verbatim>
<para>
This is just a shorthand for a typeglob assignment at compile time:
</para>
<para>
これはコンパイル時の型グロブへの代入の簡単な表現であり:
</para>
<verbatim><![CDATA[
BEGIN { *Some_package::foo = sub { ... } }
]]></verbatim>
<para>
and is <emphasis>not</emphasis> the same as writing:
</para>
<para>
以下のように書くのは同じ <emphasis>ではありません</emphasis>:
</para>
<verbatim><![CDATA[
{
	package Some_package;
	sub foo { ... }
}
]]></verbatim>
<para>
In the first two versions, the body of the subroutine is
lexically in the main package, <emphasis>not</emphasis> in Some_package. So
something like this:
</para>
<para>
最初の 2 つは、サブルーチンの本体は Some_package <emphasis>ではなく</emphasis>
main パッケージになります。
それで、以下のようにすると:
</para>
<verbatim><![CDATA[
package main;
]]></verbatim>
<verbatim><![CDATA[
$Some_package::name = "fred";
$main::name = "barney";
]]></verbatim>
<verbatim><![CDATA[
sub Some_package::foo {
	print "in ", __PACKAGE__, ": \$name is '$name'\n";
}
]]></verbatim>
<verbatim><![CDATA[
Some_package::foo();
]]></verbatim>
<para>
prints:
</para>
<para>
以下のように表示され:
</para>
<verbatim><![CDATA[
in main: $name is 'barney'
]]></verbatim>
<para>
rather than:
</para>
<para>
以下のようにはなりません:
</para>
<verbatim><![CDATA[
in Some_package: $name is 'fred'
]]></verbatim>
<para>
This also has implications for the use of the SUPER:: qualifier
(see <link xref='perlobj'>perlobj</link>).
</para>
<para>
SUPER:: 限定子の使用についても影響があります(<link xref='perlobj'>perlobj</link> を参照して下さい)。
</para>
</sect2>
<sect2>
<title>BEGIN, CHECK, INIT and END
<index>BEGIN</index> <index>CHECK</index> <index>INIT</index> <index>END</index></title>
<para>
Four specially named code blocks are executed at the beginning and at the end
of a running Perl program.  These are the <code>BEGIN</code>, <code>CHECK</code>, <code>INIT</code>, and
<code>END</code> blocks.
</para>
<para>
4 つの特殊な名前のついたコードブロックは、Perl プログラムの開始時および
終了時に実行されます。
それは <code>BEGIN</code>, <code>CHECK</code>, <code>INIT</code>, <code>END</code> ブロックです。
</para>
<para>
These code blocks can be prefixed with <code>sub</code> to give the appearance of a
subroutine (although this is not considered good style).  One should note
that these code blocks don't really exist as named subroutines (despite
their appearance). The thing that gives this away is the fact that you can
have <strong>more than one</strong> of these code blocks in a program, and they will get
<strong>all</strong> executed at the appropriate moment.  So you can't execute any of
these code blocks by name.
</para>
<para>
これらのコードブロックは、サブルーチンのような見た目を与えるために
<code>sub</code> を前置できます(しかしこれはよいスタイルとは考えられていません)。
これらのコードブロックは実際には(その見た目に反して)名前付きサブルーチンの
ようには存在していないということは注意するべきでしょう。
これで明かされることは、これらのコードブロックはプログラム中に <strong>複数</strong>
持つことができ、<strong>全て</strong> が適切な瞬間に実行されるということです。
従って、これらのコードブロックはどれも名前で実行できません。
</para>
<para>
A <code>BEGIN</code> code block is executed as soon as possible, that is, the moment
it is completely defined, even before the rest of the containing file (or
string) is parsed.  You may have multiple <code>BEGIN</code> blocks within a file (or
eval'ed string) -- they will execute in order of definition.  Because a <code>BEGIN</code>
code block executes immediately, it can pull in definitions of subroutines
and such from other files in time to be visible to the rest of the compile
and run time.  Once a <code>BEGIN</code> has run, it is immediately undefined and any
code it used is returned to Perl's memory pool.
</para>
<para>
<code>BEGIN</code> コードブロックは、できるだけ早く、つまり、たとえファイル
(または文字列)の残りが解析されていなくても、定義された瞬間に実行されます。
ファイル(または eval された文字列)内に複数の <code>BEGIN</code> ブロックを
置くこともでき、それらは定義された順番に実行されます。
<code>BEGIN</code> ブロックは即座に実行されるので、サブルーチンなどの定義を
他のファイルから読み込んでコンパイル時と実行時の残りの部分から見えるように
することができます。
<code>BEGIN</code> が実行されれば、それは即座に未定義になり、使われたコードの
全ては Perl のメモリープールに返されます。
</para>
<para>
It should be noted that <code>BEGIN</code> code blocks <strong>are</strong> executed inside string
<code>eval()</code>'s.  The <code>CHECK</code> and <code>INIT</code> code blocks are <strong>not</strong> executed inside
a string eval, which e.g. can be a problem in a mod_perl environment.
</para>
<para>
<code>BEGIN</code> コードブロックは文字列の <code>eval()</code> の内側で <strong>実行される</strong> ことに
注意した方が良いでしょう。
<code>CHECK</code> と <code>INIT</code> コードブロックは文字列 eval の内側で <strong>実行されません</strong>;
これは mod_perl 環境で問題になることがあります。
</para>
<para>
An <code>END</code> code block is executed as late as possible, that is, after
perl has finished running the program and just before the interpreter
is being exited, even if it is exiting as a result of a die() function.
(But not if it's morphing into another program via <code>exec</code>, or
being blown out of the water by a signal--you have to trap that yourself
(if you can).)  You may have multiple <code>END</code> blocks within a file--they
will execute in reverse order of definition; that is: last in, first
out (LIFO).  <code>END</code> blocks are not executed when you run perl with the
<code>-c</code> switch, or if compilation fails.
</para>
<para>
<code>END</code> コードブロックは、できるだけ遅く、つまり、たとえ die() 関数の
結果であっても、perl がプログラムの実行を終えた後、
インタプリタが終了する直前に実行されます
(しかし、<code>exec</code> を使って別のプログラムになったりとか、シグナルによって
撃沈されるときはそうではありません。
(できるものなら) 自分でトラップしなければなりません)。
ファイル内に複数の END ブロックを置くこともでき、定義とは
逆の順序で実行されます。
つまり、最後に入ったものが最初に出る(LIFO) ということです。
<code>END</code> ブロックは <code>-c</code> オプション付きで起動されたり、コンパイルに
失敗した場合は実行されません。
</para>
<para>
Note that <code>END</code> code blocks are <strong>not</strong> executed at the end of a string
<code>eval()</code>: if any <code>END</code> code blocks are created in a string <code>eval()</code>,
they will be executed just as any other <code>END</code> code block of that package
in LIFO order just before the interpreter is being exited.
</para>
<para>
文字列の <code>eval()</code> の最後では <code>END</code> コードブロックは実行 <strong>されない</strong> ことに
注意してください: 文字列 <code>eval()</code> の中で <code>END</code> コードブロックが
作成されると、これらはこのパッケージのその他の <code>END</code> コードブロックと
同様に、インタプリタが終了する直前に LIFO 順で実行されます。
</para>
<para>
Inside an <code>END</code> code block, <code>$?</code> contains the value that the program is
going to pass to <code>exit()</code>.  You can modify <code>$?</code> to change the exit
value of the program.  Beware of changing <code>$?</code> by accident (e.g. by
running something via <code>system</code>).
<index>$?</index>
</para>
<para>
<code>END</code> コードブロックの内側では、<code>$?</code> はそのプログラムが <code>exit()</code> に
渡した値が入っています。
プログラムの返す終了コードを変更するために、この変数の値を
変更することができます。
間違って <code>$?</code> を変えてしまうことに注意してください(たとえば <code>system</code> を
使って何かを実行するなど)。
</para>
<para>
<code>CHECK</code> and <code>INIT</code> code blocks are useful to catch the transition between
the compilation phase and the execution phase of the main program.
</para>
<para>
<code>CHECK</code> と <code>INIT</code> コードブロックは、メインプログラムの
コンパイルフェーズと実行フェーズの遷移を捕捉したい場合に便利です。
</para>
<para>
<code>CHECK</code> code blocks are run just after the <strong>initial</strong> Perl compile phase ends
and before the run time begins, in LIFO order.  <code>CHECK</code> code blocks are used
in the Perl compiler suite to save the compiled state of the program.
</para>
<para>
<code>CHECK</code> コードブロックは、<strong>最初の</strong> Perl コンパイルフェーズ終了直後、
実行時が開始する直前に、LIFO 順で実行されます。
<code>CHECK</code> コードブロックは Perl コンパイラスイートがプログラムのコンパイル
状態を保存するために使われます。
</para>
<para>
<code>INIT</code> blocks are run just before the Perl runtime begins execution, in
&quot;first in, first out&quot; (FIFO) order. For example, the code generators
documented in <link xref='perlcc'>perlcc</link> make use of <code>INIT</code> blocks to initialize and
resolve pointers to XSUBs.
</para>
<para>
<code>INIT</code> ブロックは Perl ランタイムが実行を開始する直前に、「先入れ先出し」
(FIFO) 順で実行されます。
例えば、<link xref='perlcc'>perlcc</link> で文書化されているコードジェネレータは <code>INIT</code> ブロックを
初期化と、XSUB へのポインタの解決に使います。
</para>
<para>
When you use the <strong>-n</strong> and <strong>-p</strong> switches to Perl, <code>BEGIN</code> and
<code>END</code> work just as they do in <strong>awk</strong>, as a degenerate case.
Both <code>BEGIN</code> and <code>CHECK</code> blocks are run when you use the <strong>-c</strong>
switch for a compile-only syntax check, although your main code
is not.
</para>
<para>
Perlに対するスイッチ <strong>-n</strong> と <strong>-p</strong> を使った場合、<code>BEGIN</code> と <code>END</code> は
(退化して) <strong>awk</strong> のそれと同じように、動作します。
<strong>-c</strong> スイッチによって構文チェックのみ行われる場合、メインのコードが
実行されないのとは対照的に <code>BEGIN</code> と <code>CHECK</code> の両方のブロックは
実行されます。
</para>
<para>
The <strong>begincheck</strong> program makes it all clear, eventually:
</para>
<para>
<strong>begincheck</strong> プログラムは、最終的にこれら全てをはっきりさせます:
</para>
<verbatim><![CDATA[
#!/usr/bin/perl
]]></verbatim>
<verbatim><![CDATA[
# begincheck
]]></verbatim>
<verbatim><![CDATA[
print         " 8. Ordinary code runs at runtime.\n";
]]></verbatim>
<verbatim><![CDATA[
END { print   "14.   So this is the end of the tale.\n" }
INIT { print  " 5. INIT blocks run FIFO just before runtime.\n" }
CHECK { print " 4.   So this is the fourth line.\n" }
]]></verbatim>
<verbatim><![CDATA[
print         " 9.   It runs in order, of course.\n";
]]></verbatim>
<verbatim><![CDATA[
BEGIN { print " 1. BEGIN blocks run FIFO during compilation.\n" }
END { print   "13.   Read perlmod for the rest of the story.\n" }
CHECK { print " 3. CHECK blocks run LIFO at compilation's end.\n" }
INIT { print  " 6.   Run this again, using Perl's -c switch.\n" }
]]></verbatim>
<verbatim><![CDATA[
print         "10.   This is anti-obfuscated code.\n";
]]></verbatim>
<verbatim><![CDATA[
END { print   "12. END blocks run LIFO at quitting time.\n" }
BEGIN { print " 2.   So this line comes out second.\n" }
INIT { print  " 7.   You'll see the difference right away.\n" }
]]></verbatim>
<verbatim><![CDATA[
print         "11.   It merely _looks_ like it should be confusing.\n";
]]></verbatim>
<verbatim><![CDATA[
__END__
]]></verbatim>
</sect2>
<sect2>
<title>Perl Classes
<index>class</index> <index>@ISA</index></title>
<para>
(Perl のクラス)
</para>
<para>
There is no special class syntax in Perl, but a package may act
as a class if it provides subroutines to act as methods.  Such a
package may also derive some of its methods from another class (package)
by listing the other package name(s) in its global @ISA array (which
must be a package global, not a lexical).
</para>
<para>
Perl 5 にはクラスのための特別な構文はありませんが、メソッドとして
機能するサブルーチンを提供するパッケージはクラスとして機能できます。
そのようなパッケージでは、他のクラス(パッケージ)の名前を配列 @ISA
(パッケージグローバルでなければならず、レキシカルにはできません)に
並べることで、そのクラスからメソッドのいくつかを
引き込んでくることができます。
</para>
<para>
For more on this, see <link xref='perltoot'>perltoot</link> and <link xref='perlobj'>perlobj</link>.
</para>
<para>
詳しくは、<link xref='perltoot'>perltoot</link> と <link xref='perlobj'>perlobj</link> を参照してください。
</para>
</sect2>
<sect2>
<title>Perl Modules
<index>module</index></title>
<para>
(Perl のモジュール)
</para>
<para>
A module is just a set of related functions in a library file, i.e.,
a Perl package with the same name as the file.  It is specifically
designed to be reusable by other modules or programs.  It may do this
by providing a mechanism for exporting some of its symbols into the
symbol table of any package using it, or it may function as a class
definition and make its semantics available implicitly through
method calls on the class and its objects, without explicitly
exporting anything.  Or it can do a little of both.
</para>
<para>
モジュールは、ライブラリファイル、つまりファイルとして同じ名前を持つ
Perl のパッケージにある関係している関数の集合です。
他のモジュールやプログラムから再利用が可能なように特に設計されています。
そのモジュールを使用する任意のパッケージのシンボルテーブルで、
自分のシンボルの一部をエクスポートする機能を用意することでこれを
行なっているとも言え、あるいは、モジュールはクラス定義として
機能することもでき、明示的にシンボルをエクスポートしなくても、
クラスやそのオブジェクトに対するメソッド呼び出しを通して暗黙のうちに
意味が通じるようにすることができます。
両方を少しずつ、同時に使うことも可能です。
</para>
<para>
For example, to start a traditional, non-OO module called Some::Module,
create a file called <filename>Some/Module.pm</filename> and start with this template:
</para>
<para>
たとえば Some::Module と呼ばれる伝統的な、非 OO モジュールを始めるには、
以下のテンプレートを使って <filename>Some/Module.pm</filename> というファイルを作成します:
</para>
<verbatim><![CDATA[
package Some::Module;  # assumes Some/Module.pm
]]></verbatim>
<verbatim><![CDATA[
use strict;
use warnings;
]]></verbatim>
<verbatim><![CDATA[
BEGIN {
    use Exporter   ();
    our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
]]></verbatim>
<verbatim><![CDATA[
# set the version for version checking
$VERSION     = 1.00;
# if using RCS/CVS, this may be preferred
$VERSION = sprintf "%d.%03d", q$Revision: 1.1 $ =~ /(\d+)/g;
]]></verbatim>
<verbatim><![CDATA[
@ISA         = qw(Exporter);
@EXPORT      = qw(&func1 &func2 &func4);
%EXPORT_TAGS = ( );     # eg: TAG => [ qw!name1 name2! ],
]]></verbatim>
<verbatim><![CDATA[
# your exported package globals go here,
# as well as any optionally exported functions
@EXPORT_OK   = qw($Var1 %Hashit &func3);
    }
    our @EXPORT_OK;
]]></verbatim>
<verbatim><![CDATA[
# exported package globals go here
our $Var1;
our %Hashit;
]]></verbatim>
<verbatim><![CDATA[
# non-exported package globals go here
our @more;
our $stuff;
]]></verbatim>
<verbatim><![CDATA[
# initialize package globals, first exported ones
$Var1   = '';
%Hashit = ();
]]></verbatim>
<verbatim><![CDATA[
# then the others (which are still accessible as $Some::Module::stuff)
$stuff  = '';
@more   = ();
]]></verbatim>
<verbatim><![CDATA[
# all file-scoped lexicals must be created before
# the functions below that use them.
]]></verbatim>
<verbatim><![CDATA[
# file-private lexicals go here
my $priv_var    = '';
my %secret_hash = ();
]]></verbatim>
<verbatim><![CDATA[
# here's a file-private function as a closure,
# callable as &$priv_func;  it cannot be prototyped.
my $priv_func = sub {
    # stuff goes here.
};
]]></verbatim>
<verbatim><![CDATA[
# make all your functions, whether exported or not;
# remember to put something interesting in the {} stubs
sub func1      {}    # no prototype
sub func2()    {}    # proto'd void
sub func3($$)  {}    # proto'd to 2 scalars
]]></verbatim>
<verbatim><![CDATA[
# this one isn't exported, but could be called!
sub func4(\%)  {}    # proto'd to 1 hash ref
]]></verbatim>
<verbatim><![CDATA[
END { }       # module clean-up code here (global destructor)
]]></verbatim>
<verbatim><![CDATA[
## YOUR CODE GOES HERE
]]></verbatim>
<verbatim><![CDATA[
1;  # don't forget to return a true value from the file
]]></verbatim>
<para>
Then go on to declare and use your variables in functions without
any qualifications.  See <link xref='Exporter'>Exporter</link> and the <link xref='perlmodlib'>perlmodlib</link> for
details on mechanics and style issues in module creation.
</para>
<para>
こうしてから宣言に移れば、関数の中で変数を修飾しないでも使うことができます。
モジュールの作成に関する仕組みやスタイルに関する詳細は
<link xref='Exporter'>Exporter</link> と <link xref='perlmodlib'>perlmodlib</link> を参照してください。
</para>
<para>
Perl modules are included into your program by saying
</para>
<para>
Perl のモジュールは以下のようにして、プログラムに取り込まれます:
</para>
<verbatim><![CDATA[
use Module;
]]></verbatim>
<para>
or
</para>
<para>
または:
</para>
<verbatim><![CDATA[
use Module LIST;
]]></verbatim>
<para>
This is exactly equivalent to
</para>
<para>
これは以下のものと全く等価です:
</para>
<verbatim><![CDATA[
BEGIN { require Module; import Module; }
]]></verbatim>
<para>
or
</para>
<para>
または:
</para>
<verbatim><![CDATA[
BEGIN { require Module; import Module LIST; }
]]></verbatim>
<para>
As a special case
</para>
<para>
特殊な場合として
</para>
<verbatim><![CDATA[
use Module ();
]]></verbatim>
<para>
is exactly equivalent to
</para>
<para>
というのは、以下のものと全く等価です:
</para>
<verbatim><![CDATA[
BEGIN { require Module; }
]]></verbatim>
<para>
All Perl module files have the extension <filename>.pm</filename>.  The <code>use</code> operator
assumes this so you don't have to spell out &quot;<filename>Module.pm</filename>&quot; in quotes.
This also helps to differentiate new modules from old <filename>.pl</filename> and
<filename>.ph</filename> files.  Module names are also capitalized unless they're
functioning as pragmas; pragmas are in effect compiler directives,
and are sometimes called &quot;pragmatic modules&quot; (or even &quot;pragmata&quot;
if you're a classicist).
</para>
<para>
すべての Perl のモジュールは <filename>.pm</filename> という拡張子を持っていて、
<code>use</code> 演算子はこれをデフォルトにしていますから、クォートで括って、
&quot;<filename>Module.pm</filename>&quot; と書く必要はありません。
これはまた、新しいモジュールと古い<filename>.pl</filename> ファイルや <filename>.ph</filename> ファイルとに
差をつけるのにも役立っています。
モジュール名はプラグマとして働くもの以外は、先頭を大文字にします;
プラグマは、コンパイラ指示子であり、「プラグマ的モジュール」
(pragmatic module、あるいは古典学者であれば「プラグマタ」(pagmata)) と
呼ぶ人もあります。
</para>
<para>
The two statements:
</para>
<para>
以下の二つの文は:
</para>
<verbatim><![CDATA[
require SomeModule;
require "SomeModule.pm";
]]></verbatim>
<para>
differ from each other in two ways.  In the first case, any double
colons in the module name, such as <code>Some::Module</code>, are translated
into your system's directory separator, usually &quot;/&quot;.   The second
case does not, and would have to be specified literally.  The other
difference is that seeing the first <code>require</code> clues in the compiler
that uses of indirect object notation involving &quot;SomeModule&quot;, as
in <code>$ob = purge SomeModule</code>, are method calls, not function calls.
(Yes, this really can make a difference.)
</para>
<para>
それぞれ異なったものです。
最初のものは <code>Some::Module</code> のような名前にあるダブルコロンはすべて
使っているシステムのディレクトリセパレータに変換されます(通常は &quot;/&quot;)。
二番目のものではそうではなく、そういった文字そのものとして扱われます。
そのほかの違いは最初の <code>require</code> ではコンパイラが
&quot;SomeModule&quot; に関して間接的オブジェクト記法を使用し、
<code>$ob = purge SomeModule</code> は関数呼び出しではなくメソッド呼び出しと
みなします(そう、これが決定的な違いですね)。
</para>
<para>
Because the <code>use</code> statement implies a <code>BEGIN</code> block, the importing
of semantics happens as soon as the <code>use</code> statement is compiled,
before the rest of the file is compiled.  This is how it is able
to function as a pragma mechanism, and also how modules are able to
declare subroutines that are then visible as list or unary operators for
the rest of the current file.  This will not work if you use <code>require</code>
instead of <code>use</code>.  With <code>require</code> you can get into this problem:
</para>
<para>
<code>use</code> 文は <code>BEGIN</code> ブロックを使っていますから、内容のインポートは、
<code>use</code> 文がコンパイルされるとすぐに、ファイルの残りがコンパイルされる前に
行なわれます。
それによってモジュールがプラグマとして機能することができ、また、
カレントのファイルの残りの部分でリストか単項の演算子として
参照することのできるサブルーチンの宣言ができるのです。
これは、<code>use</code> の代わりに <code>require</code> を使ったのでは、うまく動きません:
</para>
<verbatim><![CDATA[
require Cwd;		# make Cwd:: accessible
$here = Cwd::getcwd();
]]></verbatim>
<verbatim><![CDATA[
use Cwd;			# import names from Cwd::
$here = getcwd();
]]></verbatim>
<verbatim><![CDATA[
require Cwd;	    	# make Cwd:: accessible
$here = getcwd(); 		# oops! no main::getcwd()
]]></verbatim>
<para>
In general, <code>use Module ()</code> is recommended over <code>require Module</code>,
because it determines module availability at compile time, not in the
middle of your program's execution.  An exception would be if two modules
each tried to <code>use</code> each other, and each also called a function from
that other module.  In that case, it's easy to use <code>require</code> instead.
</para>
<para>
一般的に言って、<code>use Module ()</code> の方が <code>require Module</code> よりも
推奨されます。
なぜなら、そうすることによってプログラムの実行時ではなく、
コンパイル時にモジュールのチェックができるからです。
二つのモジュールが互いに <code>use</code> しようとしているときは例外で、
それぞれ他のモジュールから関数を呼び出されます。
この場合、<code>require</code> してしまう方が簡単です。
</para>
<para>
Perl packages may be nested inside other package names, so we can have
package names containing <code>::</code>.  But if we used that package name
directly as a filename it would make for unwieldy or impossible
filenames on some systems.  Therefore, if a module's name is, say,
<code>Text::Soundex</code>, then its definition is actually found in the library
file <filename>Text/Soundex.pm</filename>.
</para>
<para>
Perlのパッケージは、他のパッケージ名の内側にネストすることができるので、
<code>::</code> を含めたパッケージ名を使うことができます。
しかし、そういったパッケージ名をファイル名として直接使ってしまえば、
一部のシステムでは手に負えなかったり、使うことのできないファイル名と
なってしまうでしょう。
したがって、モジュールの名前が <code>Text::Soundex</code> というものであったとすると、
そのライブラリファイルは実際には <filename>Text/Soundex.pm</filename> として定義されます。
</para>
<para>
Perl modules always have a <filename>.pm</filename> file, but there may also be
dynamically linked executables (often ending in <filename>.so</filename>) or autoloaded
subroutine definitions (often ending in <filename>.al</filename>) associated with the
module.  If so, these will be entirely transparent to the user of
the module.  It is the responsibility of the <filename>.pm</filename> file to load
(or arrange to autoload) any additional functionality.  For example,
although the POSIX module happens to do both dynamic loading and
autoloading, the user can say just <code>use POSIX</code> to get it all.
</para>
<para>
Perl のモジュールは <filename>.pm</filename> ファイルを常に持っていますが、そのモジュールに
対応して動的にリンクされる実行ファイル(しばしば <filename>.so</filename> で終わります)や、
自動ロードサブルーチン定義(しばしば <filename>.al</filename> で終わります)が
存在する場合があります。
そういった場合、それらはモジュールのユーザーからも完全に透過的に見えます。
追加機能をロードする (あるいは、自動ロードの準備をする) のは
<filename>.pm</filename> ファイルの責任となります。
例えば、POSIX モジュールは、たまたま、動的ロードも自動ロードも
行ないますが、使う側は、すべてを使えるようにするために 
<code>use POSIX</code> と書くことができるだけです。
</para>
</sect2>
<sect2>
<title>Making your module threadsafe
<index>threadsafe</index> <index>thread safe</index>
<index>module, threadsafe</index> <index>module, thread safe</index>
<index>CLONE</index> <index>CLONE_SKIP</index> <index>thread</index> <index>threads</index> <index>ithread</index></title>
<para>
(モジュールをスレッドセーフにする)
</para>
<para>
Since 5.6.0, Perl has had support for a new type of threads called
interpreter threads (ithreads). These threads can be used explicitly
and implicitly.
</para>
<para>
5.6.0 から、Perl はインタプリタスレッド (iスレッド) と呼ばれる新しいタイプの
スレッドに対応しています。
これらのスレッドは明示的または暗示的に使われます。
</para>
<para>
Ithreads work by cloning the data tree so that no data is shared
between different threads. These threads can be used by using the <code>threads</code>
module or by doing fork() on win32 (fake fork() support). When a
thread is cloned all Perl data is cloned, however non-Perl data cannot
be cloned automatically.  Perl after 5.7.2 has support for the <code>CLONE</code>
special subroutine.  In <code>CLONE</code> you can do whatever
you need to do,
like for example handle the cloning of non-Perl data, if necessary.
<code>CLONE</code> will be called once as a class method for every package that has it
defined (or inherits it).  It will be called in the context of the new thread,
so all modifications are made in the new area.  Currently CLONE is called with
no parameters other than the invocant package name, but code should not assume
that this will remain unchanged, as it is likely that in future extra parameters
will be passed in to give more information about the state of cloning.
</para>
<para>
iスレッドはデータツリーをクローン化することで動作するので、スレッド間では
何のデータも共有されません。
これらのスレッドは、<code>threads</code> を使うか、win32 で fork() を行う
(偽の fork() 対応)ことで使われます。
スレッドがクローン化されると、全ての Perl のデータはクローン化されますが、
非 Perl データは自動的にはクローン化できません。
5.7.2 以降の Perl は <code>CLONE</code> 特殊サブルーチンに対応しています。
<code>CLONE</code> 内部では、例えば(もし必要なら)非 perl データのクローン化の
処理といった、必要なことはなんでもできます。
<code>CLONE</code> は定義(または継承)されたパッケージ毎に一度、クラスメソッドとして
呼び出されます。
これは新しいスレッドのコンテキストで呼び出されるので、全ての変更は
新しいスレッドで行われます。
現在のところ CLONE は呼び出し元のパッケージ名以外の引数なしで
呼び出されますが、コード側はこれがずっと続くと仮定するべきではありません;
将来、クローン化の状態についてさらなる情報を与えるために追加の引数が
渡されるかもしれないからです。
</para>
<para>
If you want to CLONE all objects you will need to keep track of them per
package. This is simply done using a hash and Scalar::Util::weaken().
</para>
<para>
全てのオブジェクトを CLONE したい場合は、それらをパッケージ毎に記録しておく
必要があります。
これは単純にハッシュと Scalar::Util::weaken() を使うことで実現できます。
</para>
<para>
Perl after 5.8.7 has support for the <code>CLONE_SKIP</code> special subroutine.
Like <code>CLONE</code>, <code>CLONE_SKIP</code> is called once per package; however, it is
called just before cloning starts, and in the context of the parent
thread. If it returns a true value, then no objects of that class will
be cloned; or rather, they will be copied as unblessed, undef values.
This provides a simple mechanism for making a module threadsafe; just add
<code>sub CLONE_SKIP { 1 }</code> at the top of the class, and <code>DESTROY()</code> will be
now only be called once per object. Of course, if the child thread needs
to make use of the objects, then a more sophisticated approach is
needed.
</para>
<para>
5.8.7 以降の Perl は <code>CLONE_SKIP</code> 特殊サブルーチンに対応しています。
<code>CLONE</code> と同様、<code>CLONE_SKIP</code> はパッケージ毎に 1 回呼び出されます;
しかし、これはクローン化が開始する直前に、親スレッドのコンテキストで
呼び出されます。
これが真の値を返すと、このクラスのオブジェクトはクローン化されません;
厳密に言うと、bless されていない undef 値としてコピーされます。
これはモジュールをスレッドセーフにする単純な機構を提供します;
単にクラスの先頭に <code>sub CLONE_SKIP { 1 }</code> を追加することで、
<code>DESTROY()</code> はオブジェクト毎に 1 度だけ呼び出されるようになります。
もちろん、もし子スレッドがこのオブジェクトを使う必要があるなら、より
洗練された手法が必要です。
</para>
<para>
Like <code>CLONE</code>, <code>CLONE_SKIP</code> is currently called with no parameters other
than the invocant package name, although that may change. Similarly, to
allow for future expansion, the return value should be a single <code>0</code> or
<code>1</code> value.
</para>
<para>
<code>CLONE</code> と同様に、<code>CLONE_SKIP</code> は現在のところ呼び出し元のパッケージ名
以外の引数なしで呼び出されますが、これは変更されるかもしれません。
同様に、将来の拡張のために、返り値は単一の <code>0</code> か <code>1</code> であるべきです。
</para>
</sect2>
</sect1>
<sect1>
<title>SEE ALSO</title>
<para>
See <link xref='perlmodlib'>perlmodlib</link> for general style issues related to building Perl
modules and classes, as well as descriptions of the standard library
and CPAN, <link xref='Exporter'>Exporter</link> for how Perl's standard import/export mechanism
works, <link xref='perltoot'>perltoot</link> and <link xref='perltooc'>perltooc</link> for an in-depth tutorial on
creating classes, <link xref='perlobj'>perlobj</link> for a hard-core reference document on
objects, <link xref='perlsub'>perlsub</link> for an explanation of functions and scoping,
and <link xref='perlxstut'>perlxstut</link> and <link xref='perlguts'>perlguts</link> for more information on writing
extension modules.
</para>
<para>
標準ライブラリや CPAN と同じくらい説明されている Perl のモジュールと
クラスに関する一般的なスタイルについては <link xref='perlmodlib'>perlmodlib</link> を参照してください。
Perl の標準インポート/エクスポート機構がどのように動作しているのかは
<link xref='Exporter'>Exporter</link> を、クラスの作成に関する詳細なチュートリアルは
<link xref='perltoot'>perltoot</link> と <link xref='perltooc'>perltooc</link> を、オブジェクトに関するハードコアな
リファレンスのドキュメントは <link xref='perlobj'>perlobj</link> を、関数とスコーピングの説明は
<link xref='perlsub'>perlsub</link> を、エクステンションモジュールの記述に関する詳細は
<link xref='perlxstut'>perlxstut</link> と <link xref='perlguts'>perlguts</link> を参照してください。
</para>
<para>
Created: KIMURA Koichi
Updated: Kentaro Shirakata &lt;argrath@ub32.org&gt; (5.8.8-)
</para>
</sect1>
</pod>
