blog20100901

2013/08/20 - プログラミング言語 Perl にまつわる etc. - Perl monger
参考 : perldoc, perldoc.jp, search.cpan.org, perldoc.perl.org ...
「 初めての Perl 第 6 版 」(オライリー・ジャパン発行 ISBN978-4-87311-567-2) 」
「 続・初めての Perl 改訂版 」(オライリー・ジャパン発行 ISBN4-87311-305-9) 」
「 Effective Perl 第 2 版 」(翔泳社発行 ISBN978-4-7981-3981-4) 」 ... etc,.

Perl Perl_6 翻訳

Perl perlmod [翻訳] パッケージ, シンボルテーブル, 特別なコードブロック (d057)

Perl perlmod [翻訳] パッケージ, シンボルテーブル, 特別なコードブロック (d057)

目次 - Perl Index

Theme



Perl について、復習を兼ねて断片的な情報を掲載して行く連載その d057 回。

Perl で、「 alternative namespace 」( 選択的名前空間 ? 代替名前空間 ? ) のメカニズムを提供するというディレクティブ「 package 」や「 symbol table 」を確認する。

以下は perlmod - perldoc.jp の日本語訳を参照しつつ原文を *自家用* に要約・翻訳したものです。正確な情報はリンク先のドキュメントを参照してください。

 ・Packages
 ・Symbol table
 ・BEGIN, UNITCHECK, CHECK, INIT, END
 ・Perl のクラス
 ・Perl のモジュール
 ・モジュールをスレッドセーフにする
 ・SEE ALSO



Packages



Perl provides a mechanism for alternative namespaces to protect packages from stomping on each other's variables.


Perl は提供します メカニズムを 代替名前空間のための package の保護のために 踏みつけることから 互いの変数を.

In fact, there's really no such thing as a global variable in Perl.


実際のところ, それは本当です グローバル変数のようなものはありません Perl では.

The package statement declares the compilation unit as being in the given namespace.


package 構文は 宣言します コンパイル単位を 与えられた名前空間にあるとして.

The scope of the package declaration is from the declaration itself through the end of the enclosing block, eval, or file, whichever comes first (the same scope as the my() and local() operators).


packeage のスコープ宣言は 宣言それ自身から 終わりまでです 囲むブロック, eval, またはファイル, いずれか早いものの ( 同じスコープです my() と local() 演算子と ).

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.


制限されていない動的な識別子は この名前空間にあります, いくつかの識別子を除いて 制限されていない場合は, デフォルトで main package になります 現在のそれの代わりに 以下で説明するように.

A package statement affects only dynamic variables--including those you've used local() on--but not lexical variables created with my().


package 構文は 影響します 動的変数にのみ -- 含めて あなたが使用したものを local を -- my() で作成したレキシカル変数ではなく.

Typically it would be the first declaration in a file included by the do, require, or use operators.


典型的には それは最初に宣言されます do, require, または use 演算子によってインクルードされたファイルで.

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.


あなたは切り替え出来ます package を 複数の場所で; それは 単に影響を与えるだけです 利用されるシンボルテーブルに コンパイラによって その残りのブロックのために.

You can refer to variables and filehandles in other packages by prefixing the identifier with the package name and a double colon: $Package::Variable.


あなたは参照出来ます 変数とファイルハンドルを 他の package 内の 識別子をプレフィクスにすることで package 名とダブルコロンの: $Package::Variable.

If the package name is null, the main package is assumed.


もし package 名が null なら, main package が仮定されます.

That is, $::sail is equivalent to $main::sail.


つまり, $::sail は 等価です $main::sail に.

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 emacs macros.


古い package のデリミタはシングルクォートです, しかし ダブルコロンが現在推奨のデリミタです, 理由のひとつは それがより読みやすいことです 人に, それと 理由のひとつは それがより読みやすいことです emacs のマクロに.

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.


それはまた C++ プログラマをします それを知っている気分に 何が行われているか -- 利用することと対照的に シングルクォートを セパレータとして, それは Ada プログラマをしていました それを知っている気分に 何が行われているか.

Because the old-fashioned syntax is still supported for backwards compatibility, if you try to use a string like "This is $owner's house", you'll be accessing $owner::s; that is, the $s variable in package owner, which is probably not what you meant.


昔ながらの構文はまだサポートされています 後方互換を理由として, もしあなたがトライした場合 文字列の利用を "This is $owner's house" のような, あなたはアクセスします $owner::s に; つまり, $s 変数です package owner の, これは多分 あなたが意味したことではありません.

Use braces to disambiguate, as in "This is ${owner}'s house".


ブレースを利用して 曖昧さを除去します, "This is ${owner}'s house" のように.

Packages may themselves contain package separators, as in $OUTER::INNER::var.


package は それら自身で含むことも出来ます package セパレータを, $OUTER::INNER::var のように.

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.


相対的な package はありません: 全てのシンボルは いずれかです カレント package に local または 完全に修飾されている 外側の package 名の下で.

For instance, there is nowhere within package OUTER that $INNER::var refers to $OUTER::INNER::var. INNER refers to a totally separate global package.


例えば, ありません package OUTER の中には $INNER::var が示す $OUTER::INNER::var は. INNER は示します 完全に別のグローバル package を.

Only identifiers starting with letters (or underscore) are stored in a package's symbol table.


文字 ( または アンダースコア ) で始まる識別子のみが 格納されます package のシンボルテーブルに.

All other symbols are kept in package main, including all punctuation variables, like $_.


他のすべてのシンボルは キープされます package main に, 含みます 全ての句読法変数を, $_ のような.

In addition, when unqualified, the identifiers STDIN, STDOUT, STDERR, ARGV, ARGVOUT, ENV, INC, and SIG are forced to be in package main, even when used for other purposes than their built-in ones.


加えて, 修飾されていないとき, 識別子 STDIN, STDOUT, STDERR, ARGV, ARGVOUT, ENV, INC, それと SIG が 強制されます package main 内にあることを, 利用するときでも 組み込みのもの以外の目的のために.

If you have a package called m, s, or y, 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.


もしあなたが package の呼び出しで m, s, または y を持っているなら, そのときあなたは利用出来ません 修飾された形式を 識別子の なぜならそれは 代わりに解釈されるので パターンマッチ, 置換, または 変換として.

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.


アンダースコアで始まる変数は 利用されていました 強制的に package main で, しかし 私たちは 決めました それは より便利だと package 製作者のために 使用出来るようにすることが 先導するアンダースコアが示す プライベート変数 それと メソッドを.

However, variables and functions named with a single _, such as $_ and sub _, are still forced into the package main.


しかしながら, 変数とファンクションの名前は 単一の _ の, $_ それと sub _ のような, は まだ 強制的に package main です.

See also "The Syntax of Variable Names" in perlvar.


また参照してください "The Syntax of Variable Names" in perlvar を.

evaled strings are compiled in the package in which the eval() was compiled.


eval された文字列は コンパイルされます package で eval() がコンパイルされた.

(Assignments to $SIG{}, however, assume the signal handler specified is in the main package. Qualify the signal handler name if you wish to have a signal handler in a package.)


( 割当は $SIG{} への, しかしながら, みなします 指定されたシグナルハンドラだと main package で. 修飾します シグナル名を もしあなたが望むなら 持つことを シグナルハンドラを package で. )

For an example, examine perldb.pl in the Perl library.


例えば, 調べます perldb.pl を Perl ライブラリの.

It initially switches to the DB package so that the debugger doesn't interfere with variables in the program you are trying to debug.


それは 最初にスイッチします DB package に デバッガが 干渉しないようにするために 変数に あなたがデバッグをトライするプログラムで.

At various points, however, it temporarily switches back to the main package to evaluate various expressions in the context of the main package (or wherever you came from). See perldebug.


様々なポイントで, しかしながら, 一時的に戻ります main package に 評価するために 様々な式を main package のコンテキストで. 参照してください perldebug を.

The special symbol __PACKAGE__ contains the current package, but cannot (easily) be used to construct variable names.


特別なシンボル __PACKAGE__ は含みます カレント package を, しかし 利用は出来ません ( 簡単には ) 変数名の構築には.


Symbol table



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 %main::, or %:: for short. Likewise the symbol table for the nested package mentioned earlier is named %OUTER::INNER::.


シンボルテーブルは package のための 格納されます その名前のハッシュに 2 つのコロンを付加した. main シンボルテーブルの名前は 従って %main:: です, または ショートでは %:: です. 従って シンボルテーブルは 前で言及したネストした package のための 名付けられます %OUTER::INNER:: と.

The value in each entry of the hash is what you are referring to when you use the *name typeglob notation.


ハッシュの各エントリの value は あなたが参照するものです あなたが利用したときに タイプグロブの記法 *name を.


local *main::foo = *main::bar;



You can use this to print out all the variables in a package, for instance. The standard but antiquated dumpvar.pl library and the CPAN module Devel::Symdump make use of this.


あなたはこれを利用出来ます すべての変数の出力に package の, 例えば. 標準ですが古風な dumpver.pl ライブラリ それと CPAN モジュール Devel::Symdump はこれを利用します.

The results of creating new symbol table entries directly or modifying any entries that are not already typeglobs are undefined and subject to change between releases of perl.


直接新しいシンボルテーブルを作成するまたは既にタイプグロブではない任意のエントリを修正する結果は 未定義で 変更の対象です perl のリリースの間で.

Assignment to a typeglob performs an aliasing operation, i.e.,


タイプグロブへの割り当ては 行います エイリアシング操作を, i.e.,


*dick = *richard;



causes variables, subroutines, formats, and file and directory handles accessible via the identifier richard also to be accessible via the identifier dick. If you want to alias only a particular variable or subroutine, assign a reference instead:


変数, サブルーチン, フォーマット, それと ファイルとディレクトリハンドルをアクセス可能にします 識別子 richard から またアクセス可能です 識別子 dick からも. もしあなたが望むなら 特定の変数またはサブルーチンのみのエイリアスを, リファレンスを割り当てます 代わりに:


*dick = \$richard;



Which makes $richard and $dick the same variable, but leaves @richard and @dick as separate arrays. Tricky, eh?


これは $richard と $dick を同じ変数にします, しかし @richard と @dick は別の配列のままにします. トリッキーですか, でしょう ?

There is one subtle difference between the following statements:


微妙な違いがあります 次の構文の間には:


*foo = *bar;
*foo = \$bar;



*foo = *bar makes the typeglobs themselves synonymous while *foo = \$bar makes the SCALAR portions of two distinct typeglobs refer to the same scalar value. This means that the following code:


*foo = *bar は タイプグロブそれ自身を同義にします 一方 *foo = \$bar は 2 つの別のタイプグロブの SCALAR 部分が参照するようにします 同じスカラ値を. これは意味します 次のコードを:


$bar = 1;
*foo = \$bar; # Make $foo an alias for $bar ( $foo を $bar のエイリアスにする )

{
local $bar = 2; # Restrict changes to block ( 変更を制限する ブロックに )
print $foo; # Prints '1' ! ( '1' を出力 ! )
}



Would print '1', because $foo holds a reference to the original $bar. The one that was stuffed away by local() and which will be restored when the block ends. Because variables are accessed through the typeglob, you can use *foo = *bar to create an alias which can be localized. (But be aware that this means you can't have a separate @foo and @bar, etc.)


'1' を出力します, なぜなら $foo は保持しているからです オリジナルの $bar への参照を. これは local() によって片づけられて 復元されます ブロックが終了したときに. なぜなら 変数はアクセスされるからです タイプグロブをとおして, あなたは利用出来ます *foo = *bar を エイリアスの作成に ローカライズ出来る. ( しかし 留意してください これは意味します あなたが分けて持てないことを @foo と @bar, etc. を)

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:


なぜこれのすべてが重要になるのか それは Exporter モジュールが利用するからです グロブエイリアシングを import/export メカニズムとして. いずれにせよ あなたが適切にローカライズ出来るかどうかは モジュールからエクスポートされた変数を 依存します それがどのようにエクスポートされたかに.


@EXPORT = qw($FOO); # Usual form, can't be localized ( 通常の形式, ローカライズ出来ない )
@EXPORT = qw(*FOO); # Can be loalized ( ローカライズ出来る )



You can work around the first case by using the fully qualified name ($Package::FOO) where you need a local value, or by overriding it by saying *FOO = *Package::FOO in your script.


あなたは回避できます 最初のケースを 完全修飾名 ( $Package::Foo ) を利用することで あなたがローカルな値が必要なところで, または 上書きによって *FOO = *Package::FOO ということによる あなたのスクリプト内で.

The *x = \$y 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.


*x = \$y のメカニズムは 利用することが出来ます 渡すこと それと 返すことに 安いリファレンスを サブルーチン に または から もしあなたが望まないなら すべてのもののコピーを. それは 割当てたときだけ動作します 動的変数に, レキシカルではない.


%some_hash = (); # can't be my() ( my() は出来ません )
*some_hash = fn( \%another_hash );
sub fn {
local *hashsym = shift;
# now use %hashsym normally, and you ( いま利用すると %hashsym を 普通に,
# will affect the caller's %another_hash ( 影響を与える 呼び出しもとの %another_hash に )
my %nhash = (); # do what you want ( する あなたが望むことを )
return \%nhash;
}



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.


return で, リファレンスは上書きします シンボルテーブルのハッシュのスロットを 指定された *some_hash タイプグロブによって. これは ややトリッキーな方法です リファレンス周りを安く渡すための あなたが望まないときに 覚えておくことを 明示的な変数のデリファレンスを.

Another use of symbol tables is for making "constant" scalars.


シンボルテーブルの他の利用は "定数" スカラを生成するためで.


*PI = \3.14159265358979;



Now you cannot alter $PI, 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 perlsub for details on these. The use constant pragma is a convenient shorthand for these.


いま あなたは変更できません $PI を, これはおそらく良いものです 全体として. これは同じではありません 定数サブルーチンと, これは最適化の対象になります コンパイル時に. 定数サブルーチンは プロトタイプ化したものです 引数を取らない それと 定数式を返す. 参照してください perlsub を これらの詳細のために. use constant プラグマは 便利な省略形です これらのための.

You can say *foo{PACKAGE} and *foo{NAME} 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:


あなは言えます *foo{PACKAGE} それと *foo{NAME} と 探し出すために 名前と package を *foo のシンボルテーブルエントリからくる. これは便利でもあります サブルーチンで 引数として渡されたタイプグロブの取得で:


sub identify_typeglob {
my $glob = shift;
print 'You gave me ', *{$glob}{PACKAGE},
'::', *{$glob}{NAME}, "\n";
}
identify_typeglob *foo
identify_typeglob *bar::baz



This prints


これは出力します


You gave me main::foo
You gave me bar::baz



The *foo{THING} notation can also be used to obtain references to the individual elements of *foo. See perlref.


*foo{THING} 記法はまた利用出来ます リファレンスを得ることにも *foo の各エレメントへの. 参照してください perlref を.

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:


サブルーチンの定義 ( それと 宣言, ついでに言えば ) は必ずしも必要はありません package 内に位置させることが それらが使用するシンボルテーブルの. あなたはサブルーチンを定義出来ます その package の外で 明示的に修飾することで サブルーチンの名前を:


package main;
sub Some_package::foo { ... } # &foo defined in Some_package ( &foo は定義されます Some_package で )



This is just a shorthand for a typeglob assignment at compile time:


これはただの省略形です タイプグロブを割り当てるための コンパイル時に:


BEGIN { *Some_package::foo = sub { ... } }



and is not the same as writing:


それと 同じではありません 書くことと:


{
package Some_package;
sub foo { ... }
}



In the first two versions, the body of the subroutine is lexically in the main package, not in Some_package. So something like this:


最初の 2 つのバージョンでは, サブルーチンのボディは 辞書的に ( lexically ) main package 内にあります, Some_package 内ではなく. なので このようなものは:


package main;

$Some_package::name = "fred";
$main::name = "barney";

sub Some_package::foo {
print "in ", __PACKAGE__, ": \$name is '$name'\n";
}

Some_package::foo();



prints:


出力します:


in main:: $name is 'barney'



rather than:


ではなく:


is Some_package: $name is 'fred'



This also has implications for the use of the SUPER:: qualifier (see perlobj).


これはまた意味を含みます SUPER:: 修飾子を利用するための ( 参照してください perlobj を )


BEGIN, UNITCHECK, CHECK, INIT, END



Five specially named code blocks are executed at the beginning and at the end of a running Perl program. These are the BEGIN, UNITCHECK, CHECK, INIT, and END blocks.


5 つの特別に名付けられたコードブロックは 実行されます Perl プログラムの開始と終了で. これらは BEGIN, UNITCHECK, CHECK, INIT, それと END ブロックです.

These code blocks can be prefixed with sub 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 more than one of these code blocks in a program, and they will get all executed at the appropriate moment. So you can't execute any of these code blocks by name.


これらのコードブロックは sub を前置出来ます 与えるために サブルーチンの体裁を ( もっとも これは 良いスタイルとみなされてはいません ). ひとつ注意するべきです これらのコードブロックは実際には存在しません 名前付きのサブルーチンとしては ( その体裁にもかかわらず ). これを与えたものは あなたは持てるという事実があります これらのコードブロックをひとつ以上 プログラム内で, それと それらは得ます すべての実行を 適切な時点で. なので あなたは実行出来ません これらのどのコードブロックも 名前で.

A BEGIN 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 BEGIN blocks within a file (or eval'ed string); they will execute in order of definition. Because a BEGIN 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 BEGIN has run, it is immediately undefined and any code it used is returned to Perl's memory pool.


BEGIN コードブロックは実行されます 可能な限り早く, つまり, それが完全に定義された時点で, ファイル ( または文字列 ) が含む残りが解析される前であっても. あなたは持つことも出来ます 複数の BEGIN ブロックを ファイル ( または eval される文字列 ) 内で; それらは実行されます 定義された順序で. なぜなら BEGIN コードブロックは実行されるので 即座に, それは引き入れることも出来ます サブルーチンの宣言に それと 他のファイルからは 時間内で 見えます コンパイルと実行時の残りに. 一度 BEGIN が実行されると, それは即座に未定義になり それを利用するすべてのコードは返されます Perl のメモリプールに.

An END 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 exec, or being blown out of the water by a signal--you have to trap that yourself (if you can).) You may have multiple END blocks within a file--they will execute in reverse order of definition; that is: last in, first out (LIFO). END blocks are not executed when you run perl with the -c switch, or if compilation fails.


END コードブロックは実行されます 可能な限り遅く, つまり, perl がプログラムの実行を終了した後 それと インタプリタが exit を始める直前に, もしそれが die() 関数の結果としての exit だったとしても. ( しかし もし exec を介して他のプログラムに変身 ( morphing ) したり, シグナルによって吹き飛ばされた場合は そうではありません -- あなたはトラップしなければなりません あなた自身で ( もし出来るなら ). ) あなたは持てます 複数の END ブロックを ファイル内で -- それらは実行されます 定義の逆順で; つまり: 後入れ, 先出しです ( last in, first out ( LIFO ) ). END ブロックは実行されません あなたが perl を -c スイッチ付きで実行したり, または コンパイルが失敗した場合.

Note that END code blocks are not executed at the end of a string eval(): if any END code blocks are created in a string eval(), they will be executed just as any other END code block of that package in LIFO order just before the interpreter is being exited.


注意して下さい END コードブロックは実行されません 文字列 eval() の最後では: もし任意の END コードブロックが作成された場合 文字列 eval() 内で, それらは 実行されます その他の その package の END コードブロックと同じく LIFO 順で インタプリタが exit する直前に.

Inside an END code block, $? contains the value that the program is going to pass to exit(). You can modify $? to change the exit value of the program. Beware of changing $? by accident (e.g. by running something via system).


END コードブロックの内側では, $? は値を含みます プログラムが exit() に渡す. あなたは出来ます $? を修正して変更することが プログラムの exit の値を.

Inside of a END block, the value of ${^GLOBAL_PHASE} will be "END".


END ブロックの内側では, ${^GLOBAL_PHASE} の値は "END" になります.

UNITCHECK, CHECK and INIT code blocks are useful to catch the transition between the compilation phase and the execution phase of the main program.


UNITCHECK, CHECK それと INIT コードブロックはキャッチするのに便利です main プログラムのコンパイルフェーズと実行フェーズの間の推移 ( transition ) を

UNITCHECK blocks are run just after the unit which defined them has been compiled. The main program file and each module it loads are compilation units, as are string evals, run-time code compiled using the (?{ }) construct in a regex, calls to do FILE, require FILE, and code after the -e switch on the command line.


UNITCHECK ブロックは直後に実行します 定義されたユニットがコンパイルされた. main プログラムファイルとロードした各モジュールがコンパイルユニットです, 文字列 eval, 正規表現内で構築した ?{} を利用してコンパイルされた 実行コード ( run-time code ), 呼び出し do FILE, require FILE, それと コマンドライン上の -e スイッチの後のコードも 同じく.

BEGIN and UNITCHECK blocks are not directly related to the phase of the interpreter. They can be created and executed during any phase.


BEGIN と UNITCHECK ブロックは直接関係しません インタプリタのフェーズには. これらは作成されて実行されます 任意のフェーズの間で.

CHECK code blocks are run just after the initial Perl compile phase ends and before the run time begins, in LIFO order. CHECK code blocks are used in the Perl compiler suite to save the compiled state of the program.


CHECK コードブロックは実行します 初期の Perl コンパイルフェーズが終了した直後 それと実行時間が始まる直前に, LIFO 順で. CHECK コードブロックは 利用されます Perl のコンパイラスイートが保存するために プログラムのコンパイルされた状態を.

Inside of a CHECK block, the value of ${^GLOBAL_PHASE} will be "CHECK".


CHECK ブロックの内側では, ${^GLOBAL_PHASE} の値は "CHECK" になります.

INIT blocks are run just before the Perl runtime begins execution, in "first in, first out" (FIFO) order.


INIT ブロックは実行します Perl ランタイムが実行を始める直前に, "先入れ, 先出し" ( first in, first out ( FIFO ) ) 順で.

Inside of an INIT block, the value of ${^GLOBAL_PHASE} will be "INIT".


INIT ブロックの内側では, ${^GLOBAL_PHASE} の値は "INIT" になります.

The CHECK and INIT blocks in code compiled by require, string do, or string eval will not be executed if they occur after the end of the main compilation phase; that can be a problem in mod_perl and other persistent environments which use those functions to load code at runtime.


CHECK と INIT ブロックは コンパイルされたコード内の require, 文字列 do, または文字列 eval によって 実行されません もし それらがあった場合 main のコンパイルフェーズの終わりの後に; それは問題になるかもしれません mod_perl それと 他の永続的な環境で 実行時に読み込んでそれらのファンクションを利用する.

When you use the -n and -p switches to Perl, BEGIN and END work just as they do in awk, as a degenerate case. Both BEGIN and CHECK blocks are run when you use the -c switch for a compile-only syntax check, although your main code is not.


あなたが利用したとき -n と -p スイッチを Perl に, BEGIN と END は動作します それらが動くように awk で, 退化したケースとして. BEGIN と CHECK ブロック両方は 実行されます あなたが利用した時に -c スイッチを コンパイルのみのシンタックスチェックのために, けれどもあなたの main コードはちがいます.

The begincheck program makes it all clear, eventually:


begincheck プログラムは これをすべてクリアにします, 最終的に:


#!/usr/bin/perl

# begincheck

print "10. Ordinary code runs at runtime. (普通のコードは runtime で実行)\n";

END { print "16. So this is the end of the tale. (そういうわけでこれがお話しの終わり) \n" }
INIT { print " 7. INIT blocks run FIFO just before runtime. (INIT ブロックは runtime の直前に実行)\n" }
UNITCHECK {
print " 4. And therefore before any CHECK blocks. (したがって すべての CHECK ブロックより前) \n"
}
CHECK{ print " 6. So this is the sixth line. (だからこれは 6 行目)\n" }

print "11. It runs in order, of course. (順序よく実行, もちろん)\n";

BEGIN{ print " 1. BEGIN blocks run FIFO during compilation. (BEGIN ブロックはコンパイルの間に FIFO で実行)\n" }
END { print "15. Read perlmod for the rest of the story. (物語の残りのために perlmod を読む)\n" }
CHECK{ print " 5. CHECK blocks run LIFO after all compilation. (CHECK ブロックはコンパイルの後に LIFO で実行)\n" }
INIT { print " 8. Run this again, using Perl's -c switch. (Perl のスイッチ -c を利用してもう一度実行)\n" }

print "12. This is anti-obfuscated code. (これはアンチ難読化コード)\n";

END { print "14. END blocks run LIFO at quitting time. (END ブックは退出時間に LIFO で実行)\n" }
BEGIN{ print " 2. So this line comes out second. (なのでこの行は 2 番目に出てくる)\n" }
UNITCHECK {
print " 3. UNITCHECK blocks run LIFO after each file is compiled. (UNITCHECK ブロックは各ファイルのコンパイル後に LIFO で実行)\n"
}
INIT { print " 9. You'll see the difference right away. (あなたはすぐに違いを見る)\n" }

print "13. It only _looks_ like it should be confusing. (それは混乱させるようにしか見えない)\n";

__END__




Perl のクラス



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).


特別なクラス構文はありません Perl には, しかし package は振る舞うことが出来ます クラスとして もしそれが提供するなら メソッドとして振る舞うサブルーチンを. そのような package は また派生させることも出来ます メソッドの一部を 他のクラス ( package ) から リストすることで 他の package 名 ( 複数可 ) を グローバルな @ISA 配列内で ( これはグローバル package でなければなりません, レキシカルではなく).

For more on this, see perlootut and perlobj.


これのより多くについては, 参照してください perlootutperlobj を.


Perl のモジュール



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.


モジュールは ただの関連するファンクションのセットです ライブラリファイル内の, i.e., Perl package です ファイルと同じ名前の. それは特別にデザインされます 再利用出来るように 外部のモジュールやプログラムから. それは出来ます エクスポートを提供するメカニズムによって そのシンボルの一部を 任意の package が利用するシンボルテーブルの中に それを利用して, または それはクラスの定義として機能し セマンティクスを利用可能にします 暗黙的にそのクラスとオブジェクトのメソッド呼び出しを通して, 明示的に何かをエクスポートすることなく. または それは出来ます 両方とも少しずつ.

For example, to start a traditional, non-OO module called Some::Module, create a file called Some/Module.pm and start with this template:


例えば, トラディショナルに始めるには, 非オブジェクト指向 ( non-OO ) モジュールを Some::Module と呼ばれる, ファイルを作成します Some/Module.pm という それと このテンプレートで始めます:


package Some::Module; # assumes Some/Module.pm (Some/Module.pm と仮定する)

use strict;
use warnings;

BEGIN {
require Exporter;

# set the version for version checking
# (バージョンチェックのためにバージョンをセット
our $VERSION = 1.00;

# Inherit from Exporter to export functions and variables
# (エクスポートするファンクションと変数に Exporter から継承する)
our @ISA = qw(Exporter);

# Functions and variables which are exported by default
# (デフォルトでエクスポートされるファンクションと変数)
our @EXPORT = qw(func1 func2);

# Functions and variables which can be optionally exported
# (オプションでエクスポート出来るファンクションと変数)
our @EXPORT_OK = qw($Var1 %Hashit func3);
}

# exported package globals go here
# (packeage グローバルでエクスポートされるのはここに)
our $Var1 = '';
our $Hashit = ();

# non-exported package globals go here
# (packeage グローバルでエクスポートされないのはここに)
our @more = ();
our $stuff = '';

# file-private lexicals go here, before any functions which use them
# (ファイルにプライベートなレキシカルはここ, それらを使うすべてのファンクションの前に)
my $priv_var = '';
my %secret_hash = ();

# here's a file-private function as a closure,
# callable as $priv_func->();
# (ここはファイルにプライベートなクロージャとしてのファンクションを,
# $priv_func->(); として呼ばれる)
my $priv_func = sub {
...
};

# make all your functions, whether exported or not;
# remember to put something interesting in the {} stubs
# (あなたのすべてのファンクションを作る, エクスポートするしないに関わらず;
# {} スタブに興味深い何かをを置くことを忘れない)
sub func1 { ... }
sub func2 { ... }

# this one isn't exported, but could be called directly
# as Some::Module::func3()
# (これはエクスポートしないが,
# Some::Module::func3() として直接呼ばれる)
sub func3 { ... }

# module clean-up code here (global destructor)
# (モジュールをクリーンアップするコードはここ (グローバルデストラクタ))
END { ... }

# don't forget to return a true value from the file
# (ファイルから 真 の値を返すことを忘れない)
1;




Then go on to declare and use your variables in functions without any qualifications. See Exporter and the perlmodlib for details on mechanics and style issues in module creation.


それから 進みます 宣言と利用に あなたのファンクション内の変数の なんの修飾もせずに. 参照してください Exporter と the perlmodlib を モジュール作成のメカニックとスタイルの問題の詳細のために.

Perl modules are included into your program by saying


Perl モジュールは含まれます あなたのプログラムに 言うことで


use Module;



or


use Module LIST;



This is exactly equivalent to


これはまったく等価です


BEGIN { require 'Module.pm'; 'Module'->import; }



or


BEGIN { require 'Module.pm'; 'Module'->import( LIST ); }



As a special case


特殊なケースとして


use Module ();



is exactly equivalent to


は まったく等価です


BEGIN { require 'Module.pm'; }



All Perl module files have the extension .pm. The use operator assumes this so you don't have to spell out "Module.pm" in quotes. This also helps to differentiate new modules from old .pl and .ph files. Module names are also capitalized unless they're functioning as pragmas; pragmas are in effect compiler directives, and are sometimes called "pragmatic modules" (or even "pragmata" if you're a classicist).


すべての Perl モジュールのファイルは持ちます 拡張子 .pm を. use 演算子は これを仮定するので 書き出す必要はありません 引用符で囲んで "Module.pm" と. これはまた役立ちます 区別するのに 新しいモジュールを 古い .pl と .ph ファイルから. モジュール名はまた 大文字で始められます ( capitalized ) それらがプラグマとして機能しないなら; プラグマは実質的にコンパイラ指示子です, それと ときおり呼ばれます "プラグマティックモジュール" と ( あるいは "プラグマタ" と もしあなたが古典主義者なら ).

The two statements:


この 2 つの構文は:


require SomeModule;
require "SomeModule.pm";



differ from each other in two ways. In the first case, any double colons in the module name, such as Some::Module, are translated into your system's directory separator, usually "/". The second case does not, and would have to be specified literally. The other difference is that seeing the first require clues in the compiler that uses of indirect object notation involving "SomeModule", as in $ob = purge SomeModule, are method calls, not function calls. (Yes, this really can make a difference.)


互いに異なります 2 つの方法で. 最初のケースでは, すべてのダブルコロンは モジュール名の, Some::Module のような, 翻訳されます あなたのシステムのディレクトリセパレータに, 通常は "/" です. 次のケースはそうしません, それと 指定しなければなりません 文字通りに. 他の違いは 最初の require は手がかりを見ることです コンパイラで 間接オブジェクト記法の利用の "SomeModule" を含む, $ob = purge SomeModule などの場合, はメソッド呼び出しです, ファンクションの呼び出しではなく. ( はい, これは本当に違いになります. )

Because the use statement implies a BEGIN block, the importing of semantics happens as soon as the use 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 require instead of use. With require you can get into this problem:


use 構文は BEGIN ブロックを含むので, セマンティクスのインポートは起こります use 構文がコンパイルされるとすぐ, ファイルの残りがコンパイルされる前に. このようにして 機能することが出来ます プラグマメカニズムとして, それと また こういうことです モジュールはサブルーチンを宣言することも出来ます それは その後見えます リストまたは単項演算子として 現在のファイルの残りの部分から. これは動きません もしあなたが require を利用した場合は use の代わりに. require では あなたはこの問題に巻き込まれます.


require Cwd; # make Cwd:: accessible
$here = Cwd::getcwd();

use Cwd; # import names from Cwd;
$here = getcwd();

require Cwd; # make Cwd:: accessible
$here = getcwd(); # oops! no main::getcwd()



In general, use Module () is recommended over require Module, 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 use each other, and each also called a function from that other module. In that case, it's easy to use require instead.


一般的には, use Module() は推奨されます require Module よりも, なぜなら それは決定するので モジュールが利用出来るかを コンパイル時に, あなたのプログラムの実行の途中ではなく. 例外になるでしょう もし 2 つのモジュールがそれぞれ利用をトライした場合は お互いに, それと それぞれがまたファンクションを呼び出した 他方のモジュールから. この場合, それは簡単です 利用します 代わりに require を.

Perl packages may be nested inside other package names, so we can have package names containing ::. 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, Text::Soundex, then its definition is actually found in the library file Text/Soundex.pm.


Perl package は 他の package 名の中にネストすることも出来ます, なので 私たちは package 名を持てます :: を含む. しかし もし私たちが利用した場合 その package 名を 直接ファイル名として それは扱いにくく または いくつかのシステムでありえない名前になります. したがって, もしモジュール名が, 言った場合, Text::Soundex と, その後 その定義は 実際には発見されます ライブラリファイル Text/Soundex.pm で.

Perl modules always have a .pm file, but there may also be dynamically linked executables (often ending in .so) or autoloaded subroutine definitions (often ending in .al) associated with the module. If so, these will be entirely transparent to the user of the module. It is the responsibility of the .pm 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 use POSIX to get it all.


Perl モジュールはいつも .pm ファイルです, しかし 動的にリンクされた実行ファイル ( 大抵 .so でおわる ) または オートロードされるサブルーチンの定義 (大抵 .al でおわる ) があるかもしれません モジュールに関連付けられた. もしそうなら, それらは 完全に透明になります モジュールのユーザに. それは .pm ファイルの責任です ロードします ( またはオートロードを用意する ) すべての追加機能を. 例えば, POSIX モジュールでは 両方発生しますが 動的ロードとオートロードが, ユーザは言えます use POSIX とだけ 全てを得るために.


モジュールをスレッドセーフにする



Perl supports a type of threads called interpreter threads (ithreads). These threads can be used explicitly and implicitly.


Perl はサポートします スレッドのタイプを インタプリタスレッド ( iスレッド ) と呼ばれる. これらのスレッドは利用出来ます 明示的に それと 暗黙的に.

Ithreads work by cloning the data tree so that no data is shared between different threads. These threads can be used by using the threads 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.8.0 has support for the CLONE special subroutine. In CLONE you can do whatever you need to do, like for example handle the cloning of non-Perl data, if necessary. CLONE 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.


iスレッドは 動作します データツリーをクローンすることで なので データはシェアされません 異なるスレッドの間で. これらのスレッドは利用されます スレッドモジュールを利用して または win32 の fork() ( 仮の fork() サポート ) を行うことによって. スレッドがクローンされたとき すべての Perl データがクローンされます, けれども 非 Perl データは自動的にはクローンされません. Perl の 5.8.0 以降は サポートします CLONE という特別なサブルーチンを. CLONE では あなたは何でも出来ます あなたが必要とすることを, 例えば 非 Perl データのクローン操作のような, もし必要なら. CLONE は一度呼ばれます クラスメソッドとして すべての package の それが定義された ( または継承された それが ). それは呼ばれます 新しいスレッドのコンテキストで, なのですべての変更は新しいエリアでされます. 現在の CLONE は呼ばれます 暗黙の第 1 引数 ( the invocant ) の package 名の他にパラメータはなしで, しかし コードは仮定してはいけません これが変更されないままだと, 将来的には 余分なパラメータが渡されるだろうとして より多くの情報を与えるための クローンの状態に関する.

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().


もし あなたが すべてのオブジェクトの CLONE を望む場合は あなたは必要です それらの package 毎の記録を取ることが. これはシンプルに行えます ハッシュ それと Scalar::Util::weaken() を利用して.

Perl after 5.8.7 has support for the CLONE_SKIP special subroutine. Like CLONE, CLONE_SKIP 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. For example: if in the parent there are two references to a single blessed hash, then in the child there will be two references to a single undefined scalar value instead. This provides a simple mechanism for making a module threadsafe; just add sub CLONE_SKIP { 1 } at the top of the class, and DESTROY() will 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.


Perl 5.8.7 以降はサポートします 特別なサブルーチン CLONE_SKIP. CLONE 同様, CLONE_SKIP は呼び出されます package 毎に 1 度 ; しかしながら, それは呼び出されます クローンがスタートする前に, それと 親スレッドのコンテキストで. もしそれが返すなら 真 の値を, その後 そのクラスのオブジェクトはクローンされません; というより, それらはコピーされます bless されていない, 未定義値として. 例えば: もし親で 1 つのブレスされたハッシュへの 2 つのリファレンスがある場合, その後 子では 1 つの未定義のスカラ値への 2 つのリファレンスがあります 代わりに. これは提供します シンプルなメカニズムを モジュールをスレッドセーフにするための; sub CLONE_SKIP { 1 } を追加するだけで クラスのトップに, それと DESTROY() は 今や呼ばれるだけになります オブジェクト毎に 1 度. もちろん, もし 子スレッドが必要とするなら オブジェクトの利用を, その後は より洗練されたアプローチが必要になります.

Like CLONE, CLONE_SKIP 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 0 or 1 value.


CLONE と同様に, CLONE_SKIP は現在呼ばれます 暗黙の第 1 引数 ( the invocant ) の package 名のほかにパラメータはなしで, とはいえ それは変更されるかもしれません. 同じく, 将来の拡張しても良いように, 戻り値は 単一の値 0 か 1 にしたほうがよいはずです.


SEE ALSO



See perlmodlib for general style issues related to building Perl modules and classes, as well as descriptions of the standard library and CPAN, Exporter for how Perl's standard import/export mechanism works, perlootut and perlobj for in-depth information on creating classes, perlobj for a hard-core reference document on objects, perlsub for an explanation of functions and scoping, and perlxstut and perlguts for more information on writing extension modules.


参照してください perlmodlib を 関連する一般的なスタイルの問題のために Perl モジュールとクラスの構築, それから 標準ライブラリの説明のために, Exporter を どのように Perl の標準 import/export メカニズムが動くか, perlootutperlobj を クラス作成に関する深い情報のために, perlobj を オブジェクトに関するハードコアなリファレンスのドキュメントのために, perlsub を ファンクションとスコープの説明のために, それと perlxstutperlguts を 拡張モジュールの記述に関するより多くの情報のために.


NEXT



次回は、今回確認した Perl の package に関する情報を出来るだけまとめる予定です。


参考情報は書籍「 続・初めての Perl 改訂版 」, 「 Effective Perl 第 2 版 」を中心に perldoc, Wikipedia および各 Web サイト。それと詳しい先輩。

目次 - Perl Index


























同じカテゴリー(Perl)の記事
 Perl mp2 翻訳 Web コンテンツ圧縮の FAQ (d228) (2023-10-11 23:49)
 Perl mp2 翻訳 既知のブラウザのバグの回避策をいくつか (d227) (2023-05-26 15:41)
 Perl mp2 翻訳 Perl と Apache でのキュートなトリック (d226) (2023-05-19 17:05)
 Perl mp2 翻訳 テンプレートシステムの選択 (d225) (2022-08-15 22:23)
 Perl mp2 翻訳 大規模 E コマースサイトの構築 (d224) (2022-06-15 20:43)
 Perl mp2 翻訳 チュートリアル (d223) (2022-06-15 20:42)

Llama
リャマ
TI-DA
てぃーだブログ
プロフィール
セラ (perlackline)
セラ (perlackline)
QRコード
QRCODE
オーナーへメッセージ

PAGE TOP ▲