perltie > 5.10.0 との差分

perltie 5.10.0 と 5.30.0 の差分

11
22=encoding euc-jp
33
44=head1 NAME
55X<tie>
66
77=begin original
88
99perltie - how to hide an object class in a simple variable
1010
1111=end original
1212
1313perltie - オブジェクトクラスを単純な変数に隠す方法
1414
1515=head1 SYNOPSIS
1616
1717 tie VARIABLE, CLASSNAME, LIST
1818
1919 $object = tied VARIABLE
2020
2121 untie VARIABLE
2222
2323=head1 DESCRIPTION
2424
2525=begin original
2626
2727Prior to release 5.0 of Perl, a programmer could use dbmopen()
2828to connect an on-disk database in the standard Unix dbm(3x)
2929format magically to a %HASH in their program. However, their Perl was either
3030built with one particular dbm library or another, but not both, and
3131you couldn't extend this mechanism to other packages or types of variables.
3232
3333=end original
3434
35355.0 より前の Perl では、プログラマは dbmopen() を使ってディスクにある
3636標準 UNIX dbm(3x) フォーマットのデータベースをプログラム中の %HASH と
3737結び付けることができました。
3838しかしながら、Perl は特定の dbm ライブラリか別のものを使って
39ビルドすることができたものの、両方一度にはできませんでした
39ビルドすることができたものの、両方一度にはできませんでした; そして、この
40そして、この仕組みを他のパッケージや変数の型に拡張することは
40仕組みを他のパッケージや変数の型に拡張することはできなかったのです。
41できなかったのです。
4241
4342=begin original
4443
4544Now you can.
4645
4746=end original
4847
4948今はできます。
5049
5150=begin original
5251
5352The tie() function binds a variable to a class (package) that will provide
5453the implementation for access methods for that variable. Once this magic
5554has been performed, accessing a tied variable automatically triggers
5655method calls in the proper class. The complexity of the class is
5756hidden behind magic methods calls. The method names are in ALL CAPS,
5857which is a convention that Perl uses to indicate that they're called
5958implicitly rather than explicitly--just like the BEGIN() and END()
6059functions.
6160
6261=end original
6362
6463tie() 関数は変数と、その変数に対するアクセスメソッドの実装を提供する
6564クラス(パッケージ)とを結び付けます。
6665この魔法が一度働けば、tie された変数は自動的に適切なクラスにある
6766メソッド呼び出しを実行します。
6867クラスのすべての複雑性はメソッド呼び出しに隠されます。
6968それらのメソッドの名前は、BEGIN() や END() と同様に(そのメソッドを) Perl が
7069こっそりと呼び出すことを示すための規約に従って全て大文字です。
7170
7271=begin original
7372
7473In the tie() call, C<VARIABLE> is the name of the variable to be
7574enchanted. C<CLASSNAME> is the name of a class implementing objects of
7675the correct type. Any additional arguments in the C<LIST> are passed to
7776the appropriate constructor method for that class--meaning TIESCALAR(),
7877TIEARRAY(), TIEHASH(), or TIEHANDLE(). (Typically these are arguments
7978such as might be passed to the dbminit() function of C.) The object
8079returned by the "new" method is also returned by the tie() function,
8180which would be useful if you wanted to access other methods in
8281C<CLASSNAME>. (You don't actually have to return a reference to a right
8382"type" (e.g., HASH or C<CLASSNAME>) so long as it's a properly blessed
8483object.) You can also retrieve a reference to the underlying object
8584using the tied() function.
8685
8786=end original
8887
8988tie() コールの中で、C<VARIABLE> は魔法を掛けられる変数の名前です。
9089C<CLASSNAME> は正しい型のオブジェクトを実装するクラスの名前です。
9190C<LIST> にあるその他の引数はクラスの適切なコンストラクタメソッド
9291TIESCALAR()、TIEARRAY()、TIEHASH()、TIEHANDLE() のいずれかに
93渡されます(典型的にはこれらの引数は C の dbminit() 関数に渡すのと
92渡されます
94同じものです)
93(典型的にはこれらの引数は C の dbminit() 関数に渡すのと同じものです。)
9594"new" メソッドから返されたオブジェクトは同様に関数 tie() からも
96返されます
95返されます; これはあなたが C<CLASSNAME> の中の別のメソッドで
97これはあなたが C<CLASSNAME> の中の別のメソッドでアクセスしたいというときに
96アクセスしたいというときに便利でしょう。
98便利でしょう(あなたは実際には正しい「型」(HASH か C<CLASSNAME>) の
97(あなたは実際には正しい「型」(HASH か C<CLASSNAME>) の参照を、それが適切な
99参照を、それが適切な bless されたオブジェクトであるということから
98bless されたオブジェクトであるということから返す必要はありません。)
100返す必要はありません)。
10199また、関数 tied() を使って、基礎となるオブジェクトへのリファレンスを
102100取得することができます。
103101
104102=begin original
105103
106104Unlike dbmopen(), the tie() function will not C<use> or C<require> a module
107105for you--you need to do that explicitly yourself.
108106
109107=end original
110108
111109dbmopen() とは異なり、tie() はモジュールを C<use> したり C<require> したり
112することはありません
110することはありません--あなたが、自分自身でそれを明示的に
113あなたが、自分自身でそれを明示的に行わなければなりません。
111行わなければなりません。
114112
115113=head2 Tying Scalars
116114X<scalar, tying>
117115
118116(スカラを tie する)
119117
120118=begin original
121119
122120A class implementing a tied scalar should define the following methods:
123121TIESCALAR, FETCH, STORE, and possibly UNTIE and/or DESTROY.
124122
125123=end original
126124
127125tie されたスカラを実装するクラスは、TIESCALAR, FETCH, STORE,
128126そして可能であれば UNTIE や DESTROY といったメソッドを定義しておくべきです。
129127
130128=begin original
131129
132130Let's look at each in turn, using as an example a tie class for
133131scalars that allows the user to do something like:
134132
135133=end original
136134
137135以下のような操作を、ユーザーに許しているスカラに対してクラスを
138136tie する例を使って順に見て行きましょう。
139137
140138 tie $his_speed, 'Nice', getppid();
141139 tie $my_speed, 'Nice', $$;
142140
143141=begin original
144142
145143And now whenever either of those variables is accessed, its current
146144system priority is retrieved and returned. If those variables are set,
147145then the process's priority is changed!
148146
149147=end original
150148
151149こうした後ではこれらの変数のいずれかがアクセスされたときには、カレントの
152150システム優先順位が取得されたり返されたりします。
153151もし変数に代入が行われれば、プロセスの優先順位は変更されます!
154152
155153=begin original
156154
157155We'll use Jarkko Hietaniemi <F<jhi@iki.fi>>'s BSD::Resource class (not
158156included) to access the PRIO_PROCESS, PRIO_MIN, and PRIO_MAX constants
159157from your system, as well as the getpriority() and setpriority() system
160158calls. Here's the preamble of the class.
161159
162160=end original
163161
164162システムの PRIO_PROCESS, PRIO_MIN, PRIO_MAX といった定数に
165163アクセスするために Jarkko Hietaniemi <F<jhi@iki.fi>> の
166164BSD::Resource クラスを使います。
167165以下はこのクラスの前置きです。
168166
169167 package Nice;
170168 use Carp;
171169 use BSD::Resource;
172170 use strict;
173171 $Nice::DEBUG = 0 unless defined $Nice::DEBUG;
174172
175173=over 4
176174
177175=item TIESCALAR classname, LIST
178176X<TIESCALAR>
179177
180178=begin original
181179
182180This is the constructor for the class. That means it is
183181expected to return a blessed reference to a new scalar
184182(probably anonymous) that it's creating. For example:
185183
186184=end original
187185
188これはクラスのためのコンストラクタです。
186これはこのクラスのコンストラクタです。
189187その役割は作成された新たな(おそらくは無名の)スカラへの bless された
190188参照を返すことです。
191たとえば
189えば:
192190
193 sub TIESCALAR {
191 sub TIESCALAR {
194 my $class = shift;
192 my $class = shift;
195 my $pid = shift || $$; # 0 means me
193 my $pid = shift || $$; # 0 means me
196194
197 if ($pid !~ /^\d+$/) {
195 if ($pid !~ /^\d+$/) {
198 carp "Nice::Tie::Scalar got non-numeric pid $pid" if $^W;
196 carp "Nice::Tie::Scalar got non-numeric pid $pid" if $^W;
199 return undef;
197 return undef;
200 }
198 }
201199
202 unless (kill 0, $pid) { # EPERM or ERSCH, no doubt
200 unless (kill 0, $pid) { # EPERM or ERSCH, no doubt
203 carp "Nice::Tie::Scalar got bad pid $pid: $!" if $^W;
201 carp "Nice::Tie::Scalar got bad pid $pid: $!" if $^W;
204 return undef;
202 return undef;
205 }
203 }
206204
207 return bless \$pid, $class;
205 return bless \$pid, $class;
208 }
206 }
209207
210208=begin original
211209
212210This tie class has chosen to return an error rather than raising an
213211exception if its constructor should fail. While this is how dbmopen() works,
214212other classes may well not wish to be so forgiving. It checks the global
215213variable C<$^W> to see whether to emit a bit of noise anyway.
216214
217215=end original
218216
219217このtie クラスでは、コンストラクタが失敗したときに例外を起こすのではなく
220218エラーを返すことを選択しました。
221219dbmopen() が動作している間に、他のクラスは例外が起きることを
222220好まないかもしれないからです。
223221グローバル変数 C<$^W> でエラーメッセージを出すかどうかを検査しています。
224222
225223=item FETCH this
226224X<FETCH>
227225
228226=begin original
229227
230228This method will be triggered every time the tied variable is accessed
231229(read). It takes no arguments beyond its self reference, which is the
232230object representing the scalar we're dealing with. Because in this case
233231we're using just a SCALAR ref for the tied scalar object, a simple $$self
234232allows the method to get at the real value stored there. In our example
235233below, that real value is the process ID to which we've tied our variable.
236234
237235=end original
238236
239237このメソッドは tie された変数がアクセス(読み出し)される度に起動されます。
240238これは自分のリファレンス、つまり私たちが扱おうとしている
241239スカラを表現するオブジェクトの他に引数は取りません。
242240この場合、単に SCALAR の参照をtieされたスカラオブジェクトとして
243241使うので、単純な $$self がそこに格納されている実際の値を取得する
244242メソッドとなります。
245243以下に示した例では、実際の値は変数に tie されたプロセス ID です。
246244
247245 sub FETCH {
248246 my $self = shift;
249247 confess "wrong type" unless ref $self;
250248 croak "usage error" if @_;
251249 my $nicety;
252250 local($!) = 0;
253251 $nicety = getpriority(PRIO_PROCESS, $$self);
254252 if ($!) { croak "getpriority failed: $!" }
255253 return $nicety;
256254 }
257255
258256=begin original
259257
260258This time we've decided to blow up (raise an exception) if the renice
261259fails--there's no place for us to return an error otherwise, and it's
262260probably the right thing to do.
263261
264262=end original
265263
266ここでは、renice に失敗した場合には例外を引き起こすようにしました
264ここでは、renice に失敗した場合には例外を引き起こすようにしました--
267265エラーを返すための場所がなく、例外を引き起こすことがおそらく妥当です。
268266
269267=item STORE this, value
270268X<STORE>
271269
272270=begin original
273271
274272This method will be triggered every time the tied variable is set
275273(assigned). Beyond its self reference, it also expects one (and only one)
276argument--the new value the user is trying to assign. Don't worry about
274argument: the new value the user is trying to assign. Don't worry about
277returning a value from STORE -- the semantic of assignment returning the
275returning a value from STORE; the semantic of assignment returning the
278276assigned value is implemented with FETCH.
279277
280278=end original
281279
282280このメソッドは tie された変数に代入される度毎に起動されます。
283281自分の参照のほか、ただ一つの引数としてユーザーが代入しようとする
284282新しい値を取ります。
285STORE から返される値は気にしないで下さい --
283STORE から返される値は気にしないで下さい;
286284代入された値を返す代入の動作は FETCH で実装されています。
287285
288 sub STORE {
286 sub STORE {
289 my $self = shift;
287 my $self = shift;
290 confess "wrong type" unless ref $self;
288 confess "wrong type" unless ref $self;
291 my $new_nicety = shift;
289 my $new_nicety = shift;
292 croak "usage error" if @_;
290 croak "usage error" if @_;
293291
294 if ($new_nicety < PRIO_MIN) {
292 if ($new_nicety < PRIO_MIN) {
295 carp sprintf
293 carp sprintf
296 "WARNING: priority %d less than minimum system priority %d",
294 "WARNING: priority %d less than minimum system priority %d",
297 $new_nicety, PRIO_MIN if $^W;
295 $new_nicety, PRIO_MIN if $^W;
298 $new_nicety = PRIO_MIN;
296 $new_nicety = PRIO_MIN;
299 }
297 }
300298
301 if ($new_nicety > PRIO_MAX) {
299 if ($new_nicety > PRIO_MAX) {
302 carp sprintf
300 carp sprintf
303 "WARNING: priority %d greater than maximum system priority %d",
301 "WARNING: priority %d greater than maximum system priority %d",
304 $new_nicety, PRIO_MAX if $^W;
302 $new_nicety, PRIO_MAX if $^W;
305 $new_nicety = PRIO_MAX;
303 $new_nicety = PRIO_MAX;
306 }
304 }
307305
308 unless (defined setpriority(PRIO_PROCESS, $$self, $new_nicety)) {
306 unless (defined setpriority(PRIO_PROCESS,
309 confess "setpriority failed: $!";
307 $$self,
310 }
308 $new_nicety))
311 }
309 {
310 confess "setpriority failed: $!";
311 }
312 }
312313
313314=item UNTIE this
314315X<UNTIE>
315316
316317=begin original
317318
318319This method will be triggered when the C<untie> occurs. This can be useful
319320if the class needs to know when no further calls will be made. (Except DESTROY
320321of course.) See L<The C<untie> Gotcha> below for more details.
321322
322323=end original
323324
324325このメソッドは、C<untie> が発生すると起動されます。
325326これは、クラスが、もはや呼び出されなくなるのはいつかを知る必要がある場合に
326327便利です。
327328(もちろん DESTROY を除いてです。)
328329さらなる詳細については後述する L<The C<untie> Gotcha> を参照してください。
329330
330331=item DESTROY this
331332X<DESTROY>
332333
333334=begin original
334335
335336This method will be triggered when the tied variable needs to be destructed.
336337As with other object classes, such a method is seldom necessary, because Perl
337338deallocates its moribund object's memory for you automatically--this isn't
338339C++, you know. We'll use a DESTROY method here for debugging purposes only.
339340
340341=end original
341342
342このメソッドは tie された変数を破棄する必要があるときに起動されます。
343このメソッドは tie された変数を破棄する必要があるときに呼び出されます。
343他のオブジェクトクラスと同じように、このようなメソッドは
344他のオブジェクトクラスと同じように、このようなメソッドはほとんど
344ほとんど必要ありません
345必要ありません; それは、Perl は消滅しかかったオブジェクトのメモリを自動的に
345れは、Perl消滅しかかったオブジェクトメモリを自動的に
346解放するからです--これは C++ でないです; いいですね?
346解放するからです。
347これは C++ ではないのです。
348いいですね?。
349347私たちはここでは DESTROY メソッドをデバッグのためだけに使います。
350348
351349 sub DESTROY {
352350 my $self = shift;
353351 confess "wrong type" unless ref $self;
354352 carp "[ Nice::DESTROY pid $$self ]" if $Nice::DEBUG;
355353 }
356354
357355=back
358356
359357=begin original
360358
361359That's about all there is to it. Actually, it's more than all there
362360is to it, because we've done a few nice things here for the sake
363361of completeness, robustness, and general aesthetics. Simpler
364362TIESCALAR classes are certainly possible.
365363
366364=end original
367365
368366これがすべきことの全てです。
369実際のところ、それよりも多くのことがあります
367実際のところ、それよりも多くのことがあります; ですから、私たちはここで
370ですから、私たはここでちょっとした完全性、堅牢性、一般的な美しさと
368ちょっとした完全性、堅牢性、一般的な美しさというものを込めました。
371いうものを込めました。
372369もっと簡単な TIESCALAR クラスを作ることも可能です。
373370
374371=head2 Tying Arrays
375372X<array, tying>
376373
377374(配列を tie する)
378375
379376=begin original
380377
381378A class implementing a tied ordinary array should define the following
382methods: TIEARRAY, FETCH, STORE, FETCHSIZE, STORESIZE and perhaps UNTIE and/or DESTROY.
379methods: TIEARRAY, FETCH, STORE, FETCHSIZE, STORESIZE, CLEAR
380and perhaps UNTIE and/or DESTROY.
383381
384382=end original
385383
386tie された配列を実装するクラスは TIEARRAY, FETCH, STORE, FETCHSIZE,
384tie された配列を実装するクラスは TIEARRAY, FETCH, STORE, FETCHSIZE, CLEAR,
387385STORESIZE、そしておそらく UNTIE や DESTROY といったメソッドを
388386実装すべきでしょう。
389387
390388=begin original
391389
392390FETCHSIZE and STORESIZE are used to provide C<$#array> and
393391equivalent C<scalar(@array)> access.
394392
395393=end original
396394
397395FETCHSIZE と STORESIZE は C<$#array> と
398396C<scalar(@array)> アクセスに等価なものを提供します。
399397
400398=begin original
401399
402400The methods POP, PUSH, SHIFT, UNSHIFT, SPLICE, DELETE, and EXISTS are
403401required if the perl operator with the corresponding (but lowercase) name
404402is to operate on the tied array. The B<Tie::Array> class can be used as a
405403base class to implement the first five of these in terms of the basic
406404methods above. The default implementations of DELETE and EXISTS in
407405B<Tie::Array> simply C<croak>.
408406
409407=end original
410408
411409POP, PUSH, SHIFT, UNSHIFT, SPLICE, DELETE, EXIST といったメソッドは
412410同名の perl の演算子(ただし小文字)が tie された配列に対して
413411操作を行うときに必要となります。
414412B<Tie::Array> クラスは、これらのうち、最初の 5 つの基本的なメソッドを
415413実装するための基底クラスとして使用できます。
416414B<Tie::Array> での DELETE と EXISTS のデフォルトの実装は
417415単なる C<croak> です。
418416
419417=begin original
420418
421419In addition EXTEND will be called when perl would have pre-extended
422420allocation in a real array.
423421
424422=end original
425423
426424それに加え、EXTEND は perl が実際の配列中であらかじめ
427425拡張するようなときに呼び出されます。
428426
429427=begin original
430428
431429For this discussion, we'll implement an array whose elements are a fixed
432430size at creation. If you try to create an element larger than the fixed
433431size, you'll take an exception. For example:
434432
435433=end original
436434
437435ここでの説明のため、要素数が生成時に固定されたサイズである配列を実装します。
438436固定サイズを越えた要素を作ろうとすると、例外が発生します。
439437例えば:
440438
441439 use FixedElem_Array;
442440 tie @array, 'FixedElem_Array', 3;
443441 $array[0] = 'cat'; # ok.
444442 $array[1] = 'dogs'; # exception, length('dogs') > 3.
445443
446444=begin original
447445
448446The preamble code for the class is as follows:
449447
450448=end original
451449
452450このクラスに対する 前置きコードは以下の通りです。
453451
454452 package FixedElem_Array;
455453 use Carp;
456454 use strict;
457455
458456=over 4
459457
460458=item TIEARRAY classname, LIST
461459X<TIEARRAY>
462460
463461=begin original
464462
465463This is the constructor for the class. That means it is expected to
466464return a blessed reference through which the new array (probably an
467465anonymous ARRAY ref) will be accessed.
468466
469467=end original
470468
471これはクラスのためのコンストラクタです。
469これはこのクラスのコンストラクタです。
472470その役割は作成された新たな(おそらくは無名の配列の参照)配列への
473471bless された参照を返すことです。
474472
475473=begin original
476474
477475In our example, just to show you that you don't I<really> have to return an
478476ARRAY reference, we'll choose a HASH reference to represent our object.
479477A HASH works out well as a generic record type: the C<{ELEMSIZE}> field will
480478store the maximum element size allowed, and the C<{ARRAY}> field will hold the
481479true ARRAY ref. If someone outside the class tries to dereference the
482480object returned (doubtless thinking it an ARRAY ref), they'll blow up.
483481This just goes to show you that you should respect an object's privacy.
484482
485483=end original
486484
487485私たちの例では、あなたにあなたが I<実際には> ARRAY のリファレンスを
488486返さなくてもよいということを示すためだけに、使用するオブジェクトを
489487表わす HASH の参照を選びました。
490HASH は汎用的なレコード型と同じように働きます
488HASH は汎用的なレコード型と同じように働きます: C<{ELEMSIZE}> フィールドは
491C<{ELEMSIZE}> フィールドは許される最大の要素の数を格納し、
489許される最大の要素の数を格納し、C<{ARRAY}> フィールドは本物の ARRAY の
492C<{ARRAY}> フィールドは本物の ARRAY のリファレンスを保持します。
490リファレンスを保持します。
493491誰かがクラスの外側で返されたオブジェクトのデリファレンスを試みた場合
494492(それが ARRAY のリファレンスであると疑いなく考えて)、それは失敗します。
495493これはあなたがオブジェクトのプライバシーを尊重すべきであるという
496494ことなのです。
497495
498496 sub TIEARRAY {
499497 my $class = shift;
500498 my $elemsize = shift;
501499 if ( @_ || $elemsize =~ /\D/ ) {
502500 croak "usage: tie ARRAY, '" . __PACKAGE__ . "', elem_size";
503501 }
504502 return bless {
505503 ELEMSIZE => $elemsize,
506504 ARRAY => [],
507505 }, $class;
508506 }
509507
510508=item FETCH this, index
511509X<FETCH>
512510
513511=begin original
514512
515513This method will be triggered every time an individual element the tied array
516514is accessed (read). It takes one argument beyond its self reference: the
517515index whose value we're trying to fetch.
518516
519517=end original
520518
521519このメソッドは tie された配列の個々の要素がアクセス(読み出し)される毎に
522520起動されます。
523521これは自分の参照のほかに、一つの引数、フェッチしようとする値の
524522インデックスをとります。
525523
526524 sub FETCH {
527525 my $self = shift;
528526 my $index = shift;
529527 return $self->{ARRAY}->[$index];
530528 }
531529
532530=begin original
533531
534532If a negative array index is used to read from an array, the index
535533will be translated to a positive one internally by calling FETCHSIZE
536534before being passed to FETCH. You may disable this feature by
537535assigning a true value to the variable C<$NEGATIVE_INDICES> in the
538536tied array class.
539537
540538=end original
541539
542540配列からの読み込みに負数の添え字が使われると、添え字は
543541FETCH に渡される前に FETCHSIZE を呼び出すことで正の数に変換されます。
544542tie された配列クラスの C<$NEGATIVE_INDICES> に真の値を代入することで
545543この機能を無効にできます。
546544
547545=begin original
548546
549547As you may have noticed, the name of the FETCH method (et al.) is the same
550548for all accesses, even though the constructors differ in names (TIESCALAR
551549vs TIEARRAY). While in theory you could have the same class servicing
552550several tied types, in practice this becomes cumbersome, and it's easiest
553551to keep them at simply one tie type per class.
554552
555553=end original
556554
557555すでに気がついたかもしれませんが、FETCH メソッド(など)の名前は全ての
558556アクセスについて、たとえコンストラクタが別の名前であった
559557(TIESCALAR と TIEARRAY)としても同じ名前になっています。
560558理論的には、幾つかの tie されたクラスをサービスする同じクラスを
561559持つこともできるでしょうが、実際にはこれは厄介なものになり、
562560単にクラスあたり一つの状態にするのが最も簡単です。
563561
564562=item STORE this, index, value
565563X<STORE>
566564
567565=begin original
568566
569567This method will be triggered every time an element in the tied array is set
570568(written). It takes two arguments beyond its self reference: the index at
571569which we're trying to store something and the value we're trying to put
572570there.
573571
574572=end original
575573
576574このメソッドは、tie された配列にある要素に対する書き込みがある度毎に
577575起動されます。
578576これは自分の参照のほかに、何かを格納しようとする場所の添え字と、
579577格納しようとしている値という二つの引数を取ります。
580578
581579=begin original
582580
583581In our example, C<undef> is really C<$self-E<gt>{ELEMSIZE}> number of
584582spaces so we have a little more work to do here:
585583
586584=end original
587585
588586この例では、C<undef> は実際は C<$self-E<gt>{ELEMSIZE}> 個の空白なので、
589587ここでもう少し作業が必要です:
590588
591 sub STORE {
589 sub STORE {
592 my $self = shift;
590 my $self = shift;
593 my( $index, $value ) = @_;
591 my( $index, $value ) = @_;
594 if ( length $value > $self->{ELEMSIZE} ) {
592 if ( length $value > $self->{ELEMSIZE} ) {
595 croak "length of $value is greater than $self->{ELEMSIZE}";
593 croak "length of $value is greater than $self->{ELEMSIZE}";
596 }
594 }
597 # fill in the blanks
595 # fill in the blanks
598 $self->EXTEND( $index ) if $index > $self->FETCHSIZE();
596 $self->EXTEND( $index ) if $index > $self->FETCHSIZE();
599 # right justify to keep element size for smaller elements
597 # right justify to keep element size for smaller elements
600 $self->{ARRAY}->[$index] = sprintf "%$self->{ELEMSIZE}s", $value;
598 $self->{ARRAY}->[$index] = sprintf "%$self->{ELEMSIZE}s", $value;
601 }
599 }
602600
603601=begin original
604602
605603Negative indexes are treated the same as with FETCH.
606604
607605=end original
608606
609607インデックスの値が負数の場合、FETCH と同様に扱われます。
610608
611609=item FETCHSIZE this
612610X<FETCHSIZE>
613611
614612=begin original
615613
616614Returns the total number of items in the tied array associated with
617615object I<this>. (Equivalent to C<scalar(@array)>). For example:
618616
619617=end original
620618
621619オブジェクト I<this> と結び付けられた tie された配列の合計要素数を返します。
622620(C<scalar(@array)> と等価です)。
623621例えば:
624622
625623 sub FETCHSIZE {
626624 my $self = shift;
627625 return scalar @{$self->{ARRAY}};
628626 }
629627
630628=item STORESIZE this, count
631629X<STORESIZE>
632630
633631=begin original
634632
635633Sets the total number of items in the tied array associated with
636634object I<this> to be I<count>. If this makes the array larger then
637635class's mapping of C<undef> should be returned for new positions.
638636If the array becomes smaller then entries beyond count should be
639637deleted.
640638
641639=end original
642640
643641オブジェクト I<this> に結び付けられた tie された配列のアイテムの合計数を
644642I<count> にセットします。
645643もし配列がより大きくなるなら、新しい位置ではクラスのマッピングは
646644C<undef> を返すべきです。
647645もし配列がより小さくなるなら、count を超えたエントリは削除されるべきです。
648646
649647=begin original
650648
651649In our example, 'undef' is really an element containing
652650C<$self-E<gt>{ELEMSIZE}> number of spaces. Observe:
653651
654652=end original
655653
656654この例では、'undef' というのは実際には C<$self-E<gt>{ELEMSIZE}> 個の空白を
657655含む要素です。
658656これを見てください:
659657
660658 sub STORESIZE {
661659 my $self = shift;
662660 my $count = shift;
663661 if ( $count > $self->FETCHSIZE() ) {
664662 foreach ( $count - $self->FETCHSIZE() .. $count ) {
665663 $self->STORE( $_, '' );
666664 }
667665 } elsif ( $count < $self->FETCHSIZE() ) {
668666 foreach ( 0 .. $self->FETCHSIZE() - $count - 2 ) {
669667 $self->POP();
670668 }
671669 }
672670 }
673671
674672=item EXTEND this, count
675673X<EXTEND>
676674
677675=begin original
678676
679677Informative call that array is likely to grow to have I<count> entries.
680678Can be used to optimize allocation. This method need do nothing.
681679
682680=end original
683681
684682配列が、I<count> エントリに大きくなりそうだということを通知する
685683呼び出しです。
686684割り当ての最適化に使えます。
687685このメソッドで何かをしなければならないということはありません。
688686
689687=begin original
690688
691689In our example, we want to make sure there are no blank (C<undef>)
692690entries, so C<EXTEND> will make use of C<STORESIZE> to fill elements
693691as needed:
694692
695693=end original
696694
697695例では、空白 (C<undef>) のエントリがないことを確実にしたいので、
698696C<EXTEND> は必要に応じて要素を埋めるために C<STORESIZE> を使います:
699697
700698 sub EXTEND {
701699 my $self = shift;
702700 my $count = shift;
703701 $self->STORESIZE( $count );
704702 }
705703
706704=item EXISTS this, key
707705X<EXISTS>
708706
709707=begin original
710708
711709Verify that the element at index I<key> exists in the tied array I<this>.
712710
713711=end original
714712
715713tie された配列 I<this> にインデックスが I<key> である要素が存在するかを
716714検証します。
717715
718716=begin original
719717
720718In our example, we will determine that if an element consists of
721719C<$self-E<gt>{ELEMSIZE}> spaces only, it does not exist:
722720
723721=end original
724722
725723この例では、要素が C<$self-E<gt>{ELEMSIZE}> 個の空白のみで構成されていれば、
726724これは存在しません:
727725
728 sub EXISTS {
726 sub EXISTS {
729 my $self = shift;
727 my $self = shift;
730 my $index = shift;
728 my $index = shift;
731 return 0 if ! defined $self->{ARRAY}->[$index] ||
729 return 0 if ! defined $self->{ARRAY}->[$index] ||
732 $self->{ARRAY}->[$index] eq ' ' x $self->{ELEMSIZE};
730 $self->{ARRAY}->[$index] eq ' ' x $self->{ELEMSIZE};
733 return 1;
731 return 1;
734 }
732 }
735733
736734=item DELETE this, key
737735X<DELETE>
738736
739737=begin original
740738
741739Delete the element at index I<key> from the tied array I<this>.
742740
743741=end original
744742
745743インデックス I<key> の要素を tie された配列 I<this> から削除します。
746744
747745=begin original
748746
749747In our example, a deleted item is C<$self-E<gt>{ELEMSIZE}> spaces:
750748
751749=end original
752750
753751この例では、削除された要素は C<$self-E<gt>{ELEMSIZE}> 個の空白です:
754752
755753 sub DELETE {
756754 my $self = shift;
757755 my $index = shift;
758756 return $self->STORE( $index, '' );
759757 }
760758
761759=item CLEAR this
762760X<CLEAR>
763761
764762=begin original
765763
766764Clear (remove, delete, ...) all values from the tied array associated with
767765object I<this>. For example:
768766
769767=end original
770768
771769オブジェクト I<this> に関連付けられた tie された配列から全ての値を
772770削除します。
773771例えば:
774772
775773 sub CLEAR {
776774 my $self = shift;
777775 return $self->{ARRAY} = [];
778776 }
779777
780778=item PUSH this, LIST
781779X<PUSH>
782780
783781=begin original
784782
785783Append elements of I<LIST> to the array. For example:
786784
787785=end original
788786
789787I<LIST> の要素を配列に追加します。
790788例えば:
791789
792790 sub PUSH {
793791 my $self = shift;
794792 my @list = @_;
795793 my $last = $self->FETCHSIZE();
796794 $self->STORE( $last + $_, $list[$_] ) foreach 0 .. $#list;
797795 return $self->FETCHSIZE();
798796 }
799797
800798=item POP this
801799X<POP>
802800
803801=begin original
804802
805803Remove last element of the array and return it. For example:
806804
807805=end original
808806
809807配列の最後の要素を取り除いてそれを返します。
810808例えば:
811809
812810 sub POP {
813811 my $self = shift;
814812 return pop @{$self->{ARRAY}};
815813 }
816814
817815=item SHIFT this
818816X<SHIFT>
819817
820818=begin original
821819
822820Remove the first element of the array (shifting other elements down)
823821and return it. For example:
824822
825823=end original
826824
827825配列の最初の要素を取り除いて(残りの要素はシフトします)、その要素を返します。
828826例えば:
829827
830828 sub SHIFT {
831829 my $self = shift;
832830 return shift @{$self->{ARRAY}};
833831 }
834832
835833=item UNSHIFT this, LIST
836834X<UNSHIFT>
837835
838836=begin original
839837
840838Insert LIST elements at the beginning of the array, moving existing elements
841839up to make room. For example:
842840
843841=end original
844842
845843LIST 要素を配列の先頭に挿入し、すでにある要素は場所を空けるために
846844移動します。
847845例えば:
848846
849847 sub UNSHIFT {
850848 my $self = shift;
851849 my @list = @_;
852850 my $size = scalar( @list );
853851 # make room for our list
854852 @{$self->{ARRAY}}[ $size .. $#{$self->{ARRAY}} + $size ]
855853 = @{$self->{ARRAY}};
856854 $self->STORE( $_, $list[$_] ) foreach 0 .. $#list;
857855 }
858856
859857=item SPLICE this, offset, length, LIST
860858X<SPLICE>
861859
862860=begin original
863861
864862Perform the equivalent of C<splice> on the array.
865863
866864=end original
867865
868866配列に対する C<splice> と等価に振る舞います。
869867
870868=begin original
871869
872870I<offset> is optional and defaults to zero, negative values count back
873871from the end of the array.
874872
875873=end original
876874
877875I<offset> はオプションでデフォルトは 0 です; 負数は配列の最後からの
878876位置を示します。
879877
880878=begin original
881879
882880I<length> is optional and defaults to rest of the array.
883881
884882=end original
885883
886884I<length> はオプションで、デフォルトは配列の残りです。
887885
888886=begin original
889887
890888I<LIST> may be empty.
891889
892890=end original
893891
894892I<LIST> は空かもしれません。
895893
896894=begin original
897895
898896Returns a list of the original I<length> elements at I<offset>.
899897
900898=end original
901899
902900元の、I<offset> の位置から I<length> 要素分のリストを返します。
903901
904902=begin original
905903
906904In our example, we'll use a little shortcut if there is a I<LIST>:
907905
908906=end original
909907
910908この例では、I<LIST> がある場合は少し近道をします:
911909
912910 sub SPLICE {
913911 my $self = shift;
914912 my $offset = shift || 0;
915913 my $length = shift || $self->FETCHSIZE() - $offset;
916914 my @list = ();
917915 if ( @_ ) {
918916 tie @list, __PACKAGE__, $self->{ELEMSIZE};
919917 @list = @_;
920918 }
921919 return splice @{$self->{ARRAY}}, $offset, $length, @list;
922920 }
923921
924922=item UNTIE this
925923X<UNTIE>
926924
927925=begin original
928926
929927Will be called when C<untie> happens. (See L<The C<untie> Gotcha> below.)
930928
931929=end original
932930
933931C<untie> が起きると呼び出されます。
934932(後述する L<The C<untie> Gotcha> を参照してください。)
935933
936934=item DESTROY this
937935X<DESTROY>
938936
939937=begin original
940938
941939This method will be triggered when the tied variable needs to be destructed.
942940As with the scalar tie class, this is almost never needed in a
943941language that does its own garbage collection, so this time we'll
944942just leave it out.
945943
946944=end original
947945
948946このメソッドは tie された変数を破棄する必要があるときに呼び出されます。
949947スカラを tie したクラスと同様、このメソッドはガベージコレクションを
950言語自体が行っているのでほとんど必要ありません
948言語自体が行っているのでほとんど必要ありません; ですから、今回はこのまま
951ですから、今回はこのまま放っておきます。
949放っておきます。
952950
953951=back
954952
955953=head2 Tying Hashes
956954X<hash, tying>
957955
958956(ハッシュを tie する)
959957
960958=begin original
961959
962960Hashes were the first Perl data type to be tied (see dbmopen()). A class
963961implementing a tied hash should define the following methods: TIEHASH is
964962the constructor. FETCH and STORE access the key and value pairs. EXISTS
965963reports whether a key is present in the hash, and DELETE deletes one.
966964CLEAR empties the hash by deleting all the key and value pairs. FIRSTKEY
967965and NEXTKEY implement the keys() and each() functions to iterate over all
968966the keys. SCALAR is triggered when the tied hash is evaluated in scalar
969context. UNTIE is called when C<untie> happens, and DESTROY is called when
967context, and in 5.28 onwards, by C<keys> in boolean context. UNTIE is
970the tied variable is garbage collected.
968called when C<untie> happens, and DESTROY is called when the tied variable
969is garbage collected.
971970
972971=end original
973972
974973ハッシュは tie される最初の Perl データ型でした(dbmopen() を参照)。
975tie されたハッシュを実装するクラスは、以下のメソッドを定義すべきです
974tie されたハッシュを実装するクラスは、以下のメソッドを定義すべきです:
976975TIEHASH はコンストラクタです。
977976FETCH と STORE はキーと値のペアにアクセスします。
978977EXIST はキーがハッシュにあるかどうかを報告し、DELETE はキーを削除します。
979978CLEAR はすべてのキーと値のペアを削除することによりハッシュを空にします。
980979FIRSTKEY と NEXTKEY は全てのキーを反復するための関数 keys() と each() を
981980実装します。
982SCALAR は tie されたハッシュがスカラコンテキストで評価されたとき
981SCALAR は tie されたハッシュがスカラコンテキストで評価されたとき
982また 5.28 以降では、真偽値コンテキストで C<keys> が評価されたときに
983983呼び出されます。
984984UNTIE は C<untie> が起きたときに呼び出され、DESTROY は tie された変数が
985985ガーベジコレクションされるときに呼び出されます。
986986
987987=begin original
988988
989989If this seems like a lot, then feel free to inherit from merely the
990990standard Tie::StdHash module for most of your methods, redefining only the
991991interesting ones. See L<Tie::Hash> for details.
992992
993993=end original
994994
995995もしこれがたくさんありすぎると感じられるのなら、標準の Tie::StdHash
996996モジュールを単純に継承し、再定義を必要とするものだけを自分で
997997実装することもできます。
998998詳しくは L<Tie::Hash> を参照してください。
999999
10001000=begin original
10011001
10021002Remember that Perl distinguishes between a key not existing in the hash,
10031003and the key existing in the hash but having a corresponding value of
10041004C<undef>. The two possibilities can be tested with the C<exists()> and
10051005C<defined()> functions.
10061006
10071007=end original
10081008
10091009Perl がハッシュに存在していないキーと、ハッシュに存在しているけれども
10101010C<undef> という値を持っているキーとを明確に区別しているということを
10111011忘れないでください。
10121012これら二つの可能性は、C<exists()> と
10131013C<defined()> という関数を使って検査できます。
10141014
10151015=begin original
10161016
10171017Here's an example of a somewhat interesting tied hash class: it gives you
10181018a hash representing a particular user's dot files. You index into the hash
10191019with the name of the file (minus the dot) and you get back that dot file's
10201020contents. For example:
10211021
10221022=end original
10231023
1024次の例は tie されたハッシュクラスを使ったものです
1024次の例は tie されたハッシュクラスを使ったものです: この例では特定の
1025この例では特定のユーザーのドットファイルを表わすハッシュを提供します。
1025ユーザーのドットファイルを表わすハッシュを提供します。
10261026あなたはハッシュをファイルの名前(からドットを取り除いたもの)によって
10271027添え字付けを行い、そのドットファイルの内容を取得します。
10281028例えば:
10291029
10301030 use DotFiles;
10311031 tie %dot, 'DotFiles';
10321032 if ( $dot{profile} =~ /MANPATH/ ||
10331033 $dot{login} =~ /MANPATH/ ||
10341034 $dot{cshrc} =~ /MANPATH/ )
10351035 {
10361036 print "you seem to set your MANPATH\n";
10371037 }
10381038
10391039=begin original
10401040
10411041Or here's another sample of using our tied class:
10421042
10431043=end original
10441044
10451045tie されたクラスを使ったもう一つの例です。
10461046
10471047 tie %him, 'DotFiles', 'daemon';
10481048 foreach $f ( keys %him ) {
10491049 printf "daemon dot file %s is size %d\n",
10501050 $f, length $him{$f};
10511051 }
10521052
10531053=begin original
10541054
10551055In our tied hash DotFiles example, we use a regular
10561056hash for the object containing several important
10571057fields, of which only the C<{LIST}> field will be what the
10581058user thinks of as the real hash.
10591059
10601060=end original
10611061
10621062この DotFiles という tie されたハッシュでは、私たちは C<{LIST}>
10631063フィールドのみをユーザーが本当のハッシュであると考えるであろう幾つかの
10641064重要なフィールドを持ったオブジェクトのために、通常のハッシュを
10651065使いました。
10661066
10671067=over 5
10681068
10691069=item USER
10701070
10711071=begin original
10721072
10731073whose dot files this object represents
10741074
10751075=end original
10761076
10771077このオブジェクトが表わしているドットファイルの所有者
10781078
10791079=item HOME
10801080
10811081=begin original
10821082
10831083where those dot files live
10841084
10851085=end original
10861086
10871087ドットファイルがある場所
10881088
10891089=item CLOBBER
10901090
10911091=begin original
10921092
10931093whether we should try to change or remove those dot files
10941094
10951095=end original
10961096
10971097これらのドットファイルを変更したり削除することをしようとすべきか
10981098を表わすフラグ
10991099
11001100=item LIST
11011101
11021102=begin original
11031103
11041104the hash of dot file names and content mappings
11051105
11061106=end original
11071107
11081108ドットファイルの名前と内容のマッピングをしたハッシュ
11091109
11101110=back
11111111
11121112=begin original
11131113
11141114Here's the start of F<Dotfiles.pm>:
11151115
11161116=end original
11171117
11181118次は F<Dotfiles.pm> の先頭です:
11191119
11201120 package DotFiles;
11211121 use Carp;
11221122 sub whowasi { (caller(1))[3] . '()' }
11231123 my $DEBUG = 0;
11241124 sub debug { $DEBUG = @_ ? shift : 1 }
11251125
11261126=begin original
11271127
11281128For our example, we want to be able to emit debugging info to help in tracing
11291129during development. We keep also one convenience function around
11301130internally to help print out warnings; whowasi() returns the function name
11311131that calls it.
11321132
11331133=end original
11341134
11351135この例では、私たちは開発の間トレースがしやすいようにデバッグ情報を
11361136出力できるようにしたいと考えました。
1137同様に、警告を出力するのを助ける一つの便利な内部関数を残しました
1137同様に、警告を出力するのを助ける一つの便利な内部関数を残しました;
11381138whowasi() は呼び出した関数の名前を返します。
11391139
11401140=begin original
11411141
11421142Here are the methods for the DotFiles tied hash.
11431143
11441144=end original
11451145
11461146以下は、DotoFiles に tie されたハッシュのためのメソッドです。
11471147
11481148=over 4
11491149
11501150=item TIEHASH classname, LIST
11511151X<TIEHASH>
11521152
11531153=begin original
11541154
11551155This is the constructor for the class. That means it is expected to
11561156return a blessed reference through which the new object (probably but not
11571157necessarily an anonymous hash) will be accessed.
11581158
11591159=end original
11601160
1161これはクラスに対するコンストラクタです。
1161これはこのクラスコンストラクタです。
11621162その役割は、アクセスされる(おそらくは無名のハッシュ、
11631163ただしそうする必要はない)オブジェクトへの bless された参照を返すことです。
11641164
11651165=begin original
11661166
11671167Here's the constructor:
11681168
11691169=end original
11701170
11711171コンストラクタの例です。
11721172
11731173 sub TIEHASH {
11741174 my $self = shift;
11751175 my $user = shift || $>;
11761176 my $dotdir = shift || '';
11771177 croak "usage: @{[&whowasi]} [USER [DOTDIR]]" if @_;
11781178 $user = getpwuid($user) if $user =~ /^\d+$/;
11791179 my $dir = (getpwnam($user))[7]
11801180 || croak "@{[&whowasi]}: no user $user";
11811181 $dir .= "/$dotdir" if $dotdir;
11821182
11831183 my $node = {
11841184 USER => $user,
11851185 HOME => $dir,
11861186 LIST => {},
11871187 CLOBBER => 0,
11881188 };
11891189
11901190 opendir(DIR, $dir)
11911191 || croak "@{[&whowasi]}: can't opendir $dir: $!";
11921192 foreach $dot ( grep /^\./ && -f "$dir/$_", readdir(DIR)) {
11931193 $dot =~ s/^\.//;
11941194 $node->{LIST}{$dot} = undef;
11951195 }
11961196 closedir DIR;
11971197 return bless $node, $self;
11981198 }
11991199
12001200=begin original
12011201
12021202It's probably worth mentioning that if you're going to filetest the
12031203return values out of a readdir, you'd better prepend the directory
12041204in question. Otherwise, because we didn't chdir() there, it would
12051205have been testing the wrong file.
12061206
12071207=end original
12081208
12091209readdir が返した値をつかってファイルテストをしようという場合、
12101210問い合わせにディレクトリを付加すべきでしょう。
12111211そうしなければ、chdir() をしていないので間違ったファイルを
12121212テストしてしまうこととなります。
12131213
12141214=item FETCH this, key
12151215X<FETCH>
12161216
12171217=begin original
12181218
12191219This method will be triggered every time an element in the tied hash is
12201220accessed (read). It takes one argument beyond its self reference: the key
12211221whose value we're trying to fetch.
12221222
12231223=end original
12241224
12251225このメソッドは tie されたハッシュがアクセス(読み出し)される度毎に
12261226呼び出されます。
12271227これは自分の参照のほかに、フェッチしようとしている値に対するキーを、
12281228ただ一つの引数としてとります。
12291229
12301230=begin original
12311231
12321232Here's the fetch for our DotFiles example.
12331233
12341234=end original
12351235
12361236以下に示すのは、私たちの DotFiles サンプルのためのフェッチです。
12371237
12381238 sub FETCH {
12391239 carp &whowasi if $DEBUG;
12401240 my $self = shift;
12411241 my $dot = shift;
12421242 my $dir = $self->{HOME};
12431243 my $file = "$dir/.$dot";
12441244
12451245 unless (exists $self->{LIST}->{$dot} || -f $file) {
12461246 carp "@{[&whowasi]}: no $dot file" if $DEBUG;
12471247 return undef;
12481248 }
12491249
12501250 if (defined $self->{LIST}->{$dot}) {
12511251 return $self->{LIST}->{$dot};
12521252 } else {
12531253 return $self->{LIST}->{$dot} = `cat $dir/.$dot`;
12541254 }
12551255 }
12561256
12571257=begin original
12581258
12591259It was easy to write by having it call the Unix cat(1) command, but it
12601260would probably be more portable to open the file manually (and somewhat
12611261more efficient). Of course, because dot files are a Unixy concept, we're
12621262not that concerned.
12631263
12641264=end original
12651265
12661266UNIX の cat(1) コマンドを呼んでいるので記述するのは簡単でしたが、
12671267ファイルを自分でオープンすることによってよりポータブル(かつ、より高効率)に
12681268できます。
12691269もちろん、ドットファイルは UNIX 的なコンセプトですから、
12701270私たちは気にしませんでした。
12711271
12721272=item STORE this, key, value
12731273X<STORE>
12741274
12751275=begin original
12761276
12771277This method will be triggered every time an element in the tied hash is set
12781278(written). It takes two arguments beyond its self reference: the index at
12791279which we're trying to store something, and the value we're trying to put
12801280there.
12811281
12821282=end original
12831283
12841284このメソッドは tie されたハッシュの要素がセット(書き込み)される度に
12851285呼び出されます。
12861286これは自分の参照の他に二つの引数、何かを格納しようとする場所の添え字と、
12871287格納しようとする値をとります。
12881288
12891289=begin original
12901290
12911291Here in our DotFiles example, we'll be careful not to let
12921292them try to overwrite the file unless they've called the clobber()
12931293method on the original object reference returned by tie().
12941294
12951295=end original
12961296
1297以下は DotFiles のサンプルです
1297以下は DotFiles のサンプルです; tie() で返されたオブジェクトの
1298tie() で返されたオブジェクトのリファレンス上で clobber() メソッドが
1298リファレンス上で clobber() メソッドが呼び出されない限り、ファイルを
1299呼び出されない限り、ファイルを上書きしないようにしています。
1299上書きしないようにしています。
13001300
13011301 sub STORE {
13021302 carp &whowasi if $DEBUG;
13031303 my $self = shift;
13041304 my $dot = shift;
13051305 my $value = shift;
13061306 my $file = $self->{HOME} . "/.$dot";
13071307 my $user = $self->{USER};
13081308
13091309 croak "@{[&whowasi]}: $file not clobberable"
13101310 unless $self->{CLOBBER};
13111311
1312 open(F, "> $file") || croak "can't open $file: $!";
1312 open(my $f, '>', $file) || croak "can't open $file: $!";
1313 print F $value;
1313 print $f $value;
1314 close(F);
1314 close($f);
13151315 }
13161316
13171317=begin original
13181318
13191319If they wanted to clobber something, they might say:
13201320
13211321=end original
13221322
13231323もし何かを変更したいというのであれば、このようにします。
13241324
13251325 $ob = tie %daemon_dots, 'daemon';
13261326 $ob->clobber(1);
13271327 $daemon_dots{signature} = "A true daemon\n";
13281328
13291329=begin original
13301330
13311331Another way to lay hands on a reference to the underlying object is to
13321332use the tied() function, so they might alternately have set clobber
13331333using:
13341334
13351335=end original
13361336
13371337基礎をなすオブジェクトへの参照を扱うもう一つの方法は tied() 関数を
13381338使うことで、これによって clobber を以下の様に使ってセットできます。
13391339
13401340 tie %daemon_dots, 'daemon';
13411341 tied(%daemon_dots)->clobber(1);
13421342
13431343=begin original
13441344
13451345The clobber method is simply:
13461346
13471347=end original
13481348
13491349clobber メソッドは単純です。
13501350
13511351 sub clobber {
13521352 my $self = shift;
13531353 $self->{CLOBBER} = @_ ? shift : 1;
13541354 }
13551355
13561356=item DELETE this, key
13571357X<DELETE>
13581358
13591359=begin original
13601360
13611361This method is triggered when we remove an element from the hash,
13621362typically by using the delete() function. Again, we'll
13631363be careful to check whether they really want to clobber files.
13641364
13651365=end original
13661366
13671367このメソッドはハッシュから要素を取り除くとき、典型的には delete() 関数を
13681368使ったときに呼び出されます。
13691369繰り返しますが、本当にファイルを clobber したいのかを注意深く検査しています。
13701370
1371 sub DELETE {
1371 sub DELETE {
1372 carp &whowasi if $DEBUG;
1372 carp &whowasi if $DEBUG;
13731373
1374 my $self = shift;
1374 my $self = shift;
1375 my $dot = shift;
1375 my $dot = shift;
1376 my $file = $self->{HOME} . "/.$dot";
1376 my $file = $self->{HOME} . "/.$dot";
1377 croak "@{[&whowasi]}: won't remove file $file"
1377 croak "@{[&whowasi]}: won't remove file $file"
1378 unless $self->{CLOBBER};
1378 unless $self->{CLOBBER};
1379 delete $self->{LIST}->{$dot};
1379 delete $self->{LIST}->{$dot};
1380 my $success = unlink($file);
1380 my $success = unlink($file);
1381 carp "@{[&whowasi]}: can't unlink $file: $!" unless $success;
1381 carp "@{[&whowasi]}: can't unlink $file: $!" unless $success;
1382 $success;
1382 $success;
1383 }
1383 }
13841384
13851385=begin original
13861386
13871387The value returned by DELETE becomes the return value of the call
13881388to delete(). If you want to emulate the normal behavior of delete(),
13891389you should return whatever FETCH would have returned for this key.
13901390In this example, we have chosen instead to return a value which tells
13911391the caller whether the file was successfully deleted.
13921392
13931393=end original
13941394
13951395DELETE の 返す値は delete() の戻り値から来ています。
13961396もしあなたが通常の delete() の動作をまねしたいというのであれば、
13971397FETCH がこのキーに対して返すであろう値を返すべきでしょう。
13981398この例では、戻り値としてファイルの削除に成功したかどうかを
13991399返すことを選択しました。
14001400
14011401=item CLEAR this
14021402X<CLEAR>
14031403
14041404=begin original
14051405
14061406This method is triggered when the whole hash is to be cleared, usually by
14071407assigning the empty list to it.
14081408
14091409=end original
14101410
14111411このメソッドはハッシュ全体が消去されるとき、通常は空リストが代入されたときに
14121412呼び出されます。
14131413
14141414=begin original
14151415
14161416In our example, that would remove all the user's dot files! It's such a
14171417dangerous thing that they'll have to set CLOBBER to something higher than
141814181 to make it happen.
14191419
14201420=end original
14211421
14221422私たちの例では、これはユーザーのすべてのドットファイルを
14231423削除してしまいます!
14241424これはとても危険なことで、実際に削除するには CLOBBER に 1 を超える値を
14251425セットすることが必要となります。
14261426
1427 sub CLEAR {
1427 sub CLEAR {
1428 carp &whowasi if $DEBUG;
1428 carp &whowasi if $DEBUG;
1429 my $self = shift;
1429 my $self = shift;
1430 croak "@{[&whowasi]}: won't remove all dot files for $self->{USER}"
1430 croak "@{[&whowasi]}: won't remove all dot files for $self->{USER}"
1431 unless $self->{CLOBBER} > 1;
1431 unless $self->{CLOBBER} > 1;
1432 my $dot;
1432 my $dot;
1433 foreach $dot ( keys %{$self->{LIST}}) {
1433 foreach $dot ( keys %{$self->{LIST}}) {
1434 $self->DELETE($dot);
1434 $self->DELETE($dot);
1435 }
1435 }
1436 }
1436 }
14371437
14381438=item EXISTS this, key
14391439X<EXISTS>
14401440
14411441=begin original
14421442
14431443This method is triggered when the user uses the exists() function
14441444on a particular hash. In our example, we'll look at the C<{LIST}>
14451445hash element for this:
14461446
14471447=end original
14481448
14491449このメソッドは特定のハッシュにおいて、exists() 関数が使われたときに
14501450呼び出されます。
14511451私たちの例では、このためにハッシュ要素 C<{LIST}> を参照します。
14521452
14531453 sub EXISTS {
14541454 carp &whowasi if $DEBUG;
14551455 my $self = shift;
14561456 my $dot = shift;
14571457 return exists $self->{LIST}->{$dot};
14581458 }
14591459
14601460=item FIRSTKEY this
14611461X<FIRSTKEY>
14621462
14631463=begin original
14641464
14651465This method will be triggered when the user is going
1466to iterate through the hash, such as via a keys() or each()
1466to iterate through the hash, such as via a keys(), values(), or each() call.
1467call.
14681467
14691468=end original
14701469
1471このメソッドは keys() each() を呼び出すのと同様に、ハッシュを通じた
1470このメソッドは keys(), values(), each() を呼び出すのと同様に、ハッシュを
1472反復をユーザーが行おうとするときに呼び出されます。
1471通じた反復をユーザーが行おうとするときに呼び出されます。
14731472
14741473 sub FIRSTKEY {
14751474 carp &whowasi if $DEBUG;
14761475 my $self = shift;
1477 my $a = keys %{$self->{LIST}}; # reset each() iterator
1476 my $a = keys %{$self->{LIST}}; # reset each() iterator
14781477 each %{$self->{LIST}}
14791478 }
14801479
1480=begin original
1481
1482FIRSTKEY is always called in scalar context and it should just
1483return the first key. values(), and each() in list context,
1484will call FETCH for the returned keys.
1485
1486=end original
1487
1488FIRSTKEY は常にスカラコンテキストで呼び出され、単に最初のキーを
1489返すべきです。
1490values() と each() はリストコンテキストでは返された値に対して FETCH を
1491呼び出します。
1492
14811493=item NEXTKEY this, lastkey
14821494X<NEXTKEY>
14831495
14841496=begin original
14851497
1486This method gets triggered during a keys() or each() iteration. It has a
1498This method gets triggered during a keys(), values(), or each() iteration. It has a
14871499second argument which is the last key that had been accessed. This is
1488useful if you're carrying about ordering or calling the iterator from more
1500useful if you're caring about ordering or calling the iterator from more
14891501than one sequence, or not really storing things in a hash anywhere.
14901502
14911503=end original
14921504
1493このメソッドは keys() または each() 反復の間に呼び出されます。
1505このメソッドは keys(), values(), each() 反復の間に呼び出されます。
14941506二番目の引数として、最後にアクセスしたキーをとります。
14951507これは、あなたが順番に取り出すとか、二度以上反復子を呼び出したり、
14961508あるいは実際にはハッシュのどこにも格納されていないものであるときに
14971509便利です。
14981510
14991511=begin original
15001512
1513NEXTKEY is always called in scalar context and it should just
1514return the next key. values(), and each() in list context,
1515will call FETCH for the returned keys.
1516
1517=end original
1518
1519NEXTKEY は常にスカラコンテキストで呼び出され、単に次のキーを
1520返すべきです。
1521values() と each() はリストコンテキストでは返された値に対して FETCH を
1522呼び出します。
1523
1524=begin original
1525
15011526For our example, we're using a real hash so we'll do just the simple
15021527thing, but we'll have to go through the LIST field indirectly.
15031528
15041529=end original
15051530
1506私たちの例では本当のハッシュを使うので、やることは簡単です
1531私たちの例では本当のハッシュを使うので、やることは簡単です; しかし、
1507しかし、LIST フィールドを間接的に扱わなければなりません。
1532LIST フィールドを間接的に扱わなければなりません。
15081533
15091534 sub NEXTKEY {
15101535 carp &whowasi if $DEBUG;
15111536 my $self = shift;
15121537 return each %{ $self->{LIST} }
15131538 }
15141539
15151540=item SCALAR this
15161541X<SCALAR>
15171542
15181543=begin original
15191544
1520This is called when the hash is evaluated in scalar context. In order
1545This is called when the hash is evaluated in scalar context, and in 5.28
1521to mimic the behaviour of untied hashes, this method should return a
1546onwards, by C<keys> in boolean context. In order to mimic the behaviour of
1522false value when the tied hash is considered empty. If this method does
1547untied hashes, this method must return a value which when used as boolean,
1548indicates whether the tied hash is considered empty. If this method does
15231549not exist, perl will make some educated guesses and return true when
15241550the hash is inside an iteration. If this isn't the case, FIRSTKEY is
15251551called, and the result will be a false value if FIRSTKEY returns the empty
15261552list, true otherwise.
15271553
15281554=end original
15291555
1530これはハッシュがスカラコンテキストで評価されたときに呼出されます。
1556これはハッシュがスカラコンテキストで評価されたとき、およ
1531tie されていないハッシュの振る舞いを似るために、tie されたハッシュが空
15575.28 以降は偽値コンテキストの C<keys> で評価されたときに
1532考えらる場合は、このメソッドは偽の値を返すべきです。
1558呼び出さす。
1559tie されていないハッシュの振る舞いを真似るために、
1560真偽値として使われるときに、tie されたハッシュが空と
1561考えられるかどうかを示す値を返さなければなりません。
15331562このメソッドが存在しない場合、perl はいくらかの教育された推測を行い、
15341563ハッシュが反復中である場合は真を返します。
15351564もしそうでない場合は、FIRSTKEY が呼び出され、これが空リストを返した場合は
15361565偽の値を返し、さもなければ真の値を返します。
15371566
15381567=begin original
15391568
15401569However, you should B<not> blindly rely on perl always doing the right
15411570thing. Particularly, perl will mistakenly return true when you clear the
15421571hash by repeatedly calling DELETE until it is empty. You are therefore
15431572advised to supply your own SCALAR method when you want to be absolutely
15441573sure that your hash behaves nicely in scalar context.
15451574
15461575=end original
15471576
15481577しかし、perl が常に正しいことを行うと盲目的に信頼しては B<いけません>。
15491578特に、ハッシュが空になるまで繰り返し DELETE を呼び出すことでハッシュを
15501579クリアした場合、perl は間違って真を返します。
15511580従って、ハッシュがスカラコンテキストでもうまく振舞うことを完全に確実に
15521581したい場合は、独自の SCALAR メソッドを作ることを勧めます。
15531582
15541583=begin original
15551584
15561585In our example we can just call C<scalar> on the underlying hash
15571586referenced by C<$self-E<gt>{LIST}>:
15581587
15591588=end original
15601589
15611590この例では、C<$self-E<gt>{LIST}> でリファレンスされている、元となる
15621591ハッシュで C<scalar> を呼び出しています:
15631592
15641593 sub SCALAR {
15651594 carp &whowasi if $DEBUG;
15661595 my $self = shift;
15671596 return scalar %{ $self->{LIST} }
15681597 }
15691598
1599=begin original
1600
1601NOTE: In perl 5.25 the behavior of scalar %hash on an untied hash changed
1602to return the count of keys. Prior to this it returned a string containing
1603information about the bucket setup of the hash. See
1604L<Hash::Util/bucket_ratio> for a backwards compatibility path.
1605
1606=end original
1607
1608注意: perl 5.25 以降、
1609tie されていないハッシュに関する scalar %hash の振る舞いは、
1610キーの数を返すように変更されました。
1611これ以前は、ハッシュのバケツ設定に関する情報を含む文字列を返していました。
1612後方互換性のためには L<Hash::Util/bucket_ratio> を参照してください。
1613
15701614=item UNTIE this
15711615X<UNTIE>
15721616
15731617=begin original
15741618
15751619This is called when C<untie> occurs. See L<The C<untie> Gotcha> below.
15761620
15771621=end original
15781622
15791623これは C<untie> が発生した時に呼び出されます。
1580以下の L<The C<untie> Gotcha> を参照してください。
1624後述する L<The C<untie> Gotcha> を参照してください。
15811625
15821626=item DESTROY this
15831627X<DESTROY>
15841628
15851629=begin original
15861630
15871631This method is triggered when a tied hash is about to go out of
15881632scope. You don't really need it unless you're trying to add debugging
15891633or have auxiliary state to clean up. Here's a very simple function:
15901634
15911635=end original
15921636
1593このメソッドは tie されたハッシュがスコープの外に出るときに
1637このメソッドは tie されたハッシュがスコープの外に出るときに呼び出されます。
1594呼び出されます。
15951638実際には、デバッグ情報を足そうとするとか、後始末のための
15961639補助的な情報を持っていなければ、必要になりません。
1640以下はとても単純な関数です:
15971641
15981642 sub DESTROY {
15991643 carp &whowasi if $DEBUG;
16001644 }
16011645
16021646=back
16031647
16041648=begin original
16051649
16061650Note that functions such as keys() and values() may return huge lists
16071651when used on large objects, like DBM files. You may prefer to use the
16081652each() function to iterate over such. Example:
16091653
16101654=end original
16111655
16121656keys() や values() といった関数は、DBM ファイルのような大きなオブジェクトに
16131657対して使ったときに大きなリストを返す可能性があるということに
16141658注意してください。
16151659そういったものに対して繰り返しの処理を行うには、each() を使うのが
16161660良いでしょう。
16171661例:
16181662
16191663 # print out history file offsets
16201664 use NDBM_File;
16211665 tie(%HIST, 'NDBM_File', '/usr/lib/news/history', 1, 0);
16221666 while (($key,$val) = each %HIST) {
16231667 print $key, ' = ', unpack('L',$val), "\n";
16241668 }
16251669 untie(%HIST);
16261670
16271671=head2 Tying FileHandles
16281672X<filehandle, tying>
16291673
16301674(ファイルハンドルを tie する)
16311675
16321676=begin original
16331677
16341678This is partially implemented now.
16351679
16361680=end original
16371681
16381682これは現時点ではまだ部分的にしか実装されていません。
16391683
16401684=begin original
16411685
16421686A class implementing a tied filehandle should define the following
16431687methods: TIEHANDLE, at least one of PRINT, PRINTF, WRITE, READLINE, GETC,
16441688READ, and possibly CLOSE, UNTIE and DESTROY. The class can also provide: BINMODE,
16451689OPEN, EOF, FILENO, SEEK, TELL - if the corresponding perl operators are
16461690used on the handle.
16471691
16481692=end original
16491693
1650tie されたファイルハンドルを実装するクラスは以下のメソッドを定義すべきです
1694tie されたファイルハンドルを実装するクラスは以下のメソッドを定義すべきです:
16511695TIEHANDLE と、PRINT, PRINTF, WRITE, READLINE, GETC, READ の
16521696中の少なくともいずれか一つ、そして可能であればCLOSE, UNTIE, DESTROY。
16531697また、クラスは以下のものも提供できます: BINMODE,
16541698OPEN, EOF, FILENO, SEEK, TELL - もし対応する perl の演算子がハンドルで
16551699つかわれるならです。
16561700
16571701=begin original
16581702
16591703When STDERR is tied, its PRINT method will be called to issue warnings
16601704and error messages. This feature is temporarily disabled during the call,
16611705which means you can use C<warn()> inside PRINT without starting a recursive
16621706loop. And just like C<__WARN__> and C<__DIE__> handlers, STDERR's PRINT
16631707method may be called to report parser errors, so the caveats mentioned under
16641708L<perlvar/%SIG> apply.
16651709
16661710=end original
16671711
16681712STDERR が tie されると、その PRINT メソッドが、警告とエラーのメッセージを
16691713出力するために呼び出されます。
16701714この機能は呼び出しの最中には一時的に無効にされているので、再帰ループを
16711715作ることなく PRINT の内部で C<warn()> を使えることを意味します。
16721716また、C<__WARN__> や C<__DIE__> のハンドラと同様に、STDERR の
16731717PRINT メソッドはパーサーエラーの報告に呼び出されるので、L<perlvar/%SIG> で
16741718言及した問題点が適用されます。
16751719
16761720=begin original
16771721
16781722All of this is especially useful when perl is embedded in some other
16791723program, where output to STDOUT and STDERR may have to be redirected
16801724in some special way. See nvi and the Apache module for examples.
16811725
16821726=end original
16831727
16841728これら全ては perl が他のプログラムに埋め込まれていて、
16851729STDOUT や STDERR で出力する場所はなんらかの特殊なやり方でリダイレクトする
16861730必要があるときに特に便利です。
16871731実際の例は nvi や Apache モジュールを参照してください。
16881732
16891733=begin original
16901734
1735When tying a handle, the first argument to C<tie> should begin with an
1736asterisk. So, if you are tying STDOUT, use C<*STDOUT>. If you have
1737assigned it to a scalar variable, say C<$handle>, use C<*$handle>.
1738C<tie $handle> ties the scalar variable C<$handle>, not the handle inside
1739it.
1740
1741=end original
1742
1743ハンドルを tie するとき、C<tie> への最初の引数はアスタリスクで始まります。
1744それで、STDOUT を tie するときは、C<*STDOUT> を使います。
1745これを、例えば C<$handle> というスカラ変数に代入するときは、C<*$handle> を
1746使います。
1747C<tie $handle> はスカラ変数 C<$handle> の内部にあるハンドルではなく、スカラ
1748自身を tie します。
1749
1750=begin original
1751
16911752In our example we're going to create a shouting handle.
16921753
16931754=end original
16941755
16951756私たちの例では、叫ぶハンドルを生成します。
16961757
16971758 package Shout;
16981759
16991760=over 4
17001761
17011762=item TIEHANDLE classname, LIST
17021763X<TIEHANDLE>
17031764
17041765=begin original
17051766
17061767This is the constructor for the class. That means it is expected to
17071768return a blessed reference of some sort. The reference can be used to
17081769hold some internal information.
17091770
17101771=end original
17111772
17121773これはこのクラスのコンストラクタです。
17131774その働きはなにかの bless されたリファレンスを返すことです。
17141775そのリファレンスは内部情報を保持するために使うことができます。
17151776
17161777 sub TIEHANDLE { print "<shout>\n"; my $i; bless \$i, shift }
17171778
17181779=item WRITE this, LIST
17191780X<WRITE>
17201781
17211782=begin original
17221783
17231784This method will be called when the handle is written to via the
17241785C<syswrite> function.
17251786
17261787=end original
17271788
17281789このメソッドは C<syswrite> 関数を通じてハンドルが書き出されるときに
17291790呼び出されます。
17301791
1731 sub WRITE {
1792 sub WRITE {
1732 $r = shift;
1793 $r = shift;
1733 my($buf,$len,$offset) = @_;
1794 my($buf,$len,$offset) = @_;
1734 print "WRITE called, \$buf=$buf, \$len=$len, \$offset=$offset";
1795 print "WRITE called, \$buf=$buf, \$len=$len, \$offset=$offset";
1735 }
1796 }
17361797
17371798=item PRINT this, LIST
17381799X<PRINT>
17391800
17401801=begin original
17411802
17421803This method will be triggered every time the tied handle is printed to
1743with the C<print()> function.
1804with the C<print()> or C<say()> functions. Beyond its self reference
1744Beyond its self reference it also expects the list that was passed to
1805it also expects the list that was passed to the print function.
1745the print function.
17461806
17471807=end original
17481808
1749このメソッドは tie されたハンドルに C<print> 関数を使って出力される
1809このメソッドは tie されたハンドルに C<print> 関数または C<say()> 関数
1750度に呼び出されます。
1810使って出力される度に呼び出されます。
17511811このメソッドは自分の参照のほか、print 関数に渡すリストを受け取ります。
17521812
1753 sub PRINT { $r = shift; $$r++; print join($,,map(uc($_),@_)),$\ }
1813 sub PRINT { $r = shift; $$r++; print join($,,map(uc($_),@_)),$\ }
17541814
1815=begin original
1816
1817C<say()> acts just like C<print()> except $\ will be localized to C<\n> so
1818you need do nothing special to handle C<say()> in C<PRINT()>.
1819
1820=end original
1821
1822C<say()> は C<print()> と同様に動作しますが、$\ は C<\n> に
1823ローカル化されるので C<PRINT()> の中で C<say()> を扱うために何も特別な
1824ことをする必要はありません。
1825
17551826=item PRINTF this, LIST
17561827X<PRINTF>
17571828
17581829=begin original
17591830
17601831This method will be triggered every time the tied handle is printed to
17611832with the C<printf()> function.
17621833Beyond its self reference it also expects the format and list that was
17631834passed to the printf function.
17641835
17651836=end original
17661837
17671838このメソッドは tie されたハンドルに C<printf> 関数を使って
17681839出力される度に呼び出されます。
17691840このメソッドは自分の参照のほか、printf 関数に渡すリストを受け取ります。
17701841
17711842 sub PRINTF {
17721843 shift;
17731844 my $fmt = shift;
17741845 print sprintf($fmt, @_);
17751846 }
17761847
17771848=item READ this, LIST
17781849X<READ>
17791850
17801851=begin original
17811852
17821853This method will be called when the handle is read from via the C<read>
17831854or C<sysread> functions.
17841855
17851856=end original
17861857
17871858このメソッドはハンドルが C<read> や C<sysread> といった関数を通じて
17881859読まれたときに呼び出されます。
17891860
1790 sub READ {
1861 sub READ {
1791 my $self = shift;
1862 my $self = shift;
1792 my $bufref = \$_[0];
1863 my $bufref = \$_[0];
1793 my(undef,$len,$offset) = @_;
1864 my(undef,$len,$offset) = @_;
1794 print "READ called, \$buf=$bufref, \$len=$len, \$offset=$offset";
1865 print "READ called, \$buf=$bufref, \$len=$len, \$offset=$offset";
1795 # add to $$bufref, set $len to number of characters read
1866 # add to $$bufref, set $len to number of characters read
1796 $len;
1867 $len;
1797 }
1868 }
17981869
17991870=item READLINE this
18001871X<READLINE>
18011872
18021873=begin original
18031874
1804This method will be called when the handle is read from via <HANDLE>.
1875This method is called when the handle is read via C<E<lt>HANDLEE<gt>>
1805The method should return undef when there is no more data.
1876or C<readline HANDLE>.
18061877
18071878=end original
18081879
1809このメソッドは <HANDLE> を通してハンドルが読まれたときに呼び出されます。
1880このメソッドは C<E<lt>HANDLEE<gt>> または C<readline HANDLE> を通して
1810このメソッはもうデータない場合は undef を返します。
1881ハン読まれたとき呼び出されます。
18111882
1812 sub READLINE { $r = shift; "READLINE called $$r times\n"; }
1883=begin original
18131884
1885As per L<C<readline>|perlfunc/readline>, in scalar context it should return
1886the next line, or C<undef> for no more data. In list context it should
1887return all remaining lines, or an empty list for no more data. The strings
1888returned should include the input record separator C<$/> (see L<perlvar>),
1889unless it is C<undef> (which means "slurp" mode).
1890
1891=end original
1892
1893L<C<readline>|perlfunc/readline> のように、スカラコンテキストでは次の行を
1894返すか、もうデータが無いときには C<undef> を返します。
1895リストコンテキストでは残り全ての行を返すか、もうデータが無いときには
1896空リストを返します。
1897返された文字列は入力レコードセパレータ C<$/> (L<perlvar> 参照) を
1898含んでいます(C<undef> の場合 (「吸い込み」(slurp) モード) を除きます)。
1899
1900 sub READLINE {
1901 my $r = shift;
1902 if (wantarray) {
1903 return ("all remaining\n",
1904 "lines up\n",
1905 "to eof\n");
1906 } else {
1907 return "READLINE called " . ++$$r . " times\n";
1908 }
1909 }
1910
18141911=item GETC this
18151912X<GETC>
18161913
18171914=begin original
18181915
18191916This method will be called when the C<getc> function is called.
18201917
18211918=end original
18221919
18231920このメソッドは関数 C<getc> が呼ばれたときに呼び出されます。
18241921
18251922 sub GETC { print "Don't GETC, Get Perl"; return "a"; }
18261923
1924=item EOF this
1925X<EOF>
1926
1927=begin original
1928
1929This method will be called when the C<eof> function is called.
1930
1931=end original
1932
1933このメソッドは、C<eof> 関数が呼び出されたときに呼び出されます。
1934
1935=begin original
1936
1937Starting with Perl 5.12, an additional integer parameter will be passed. It
1938will be zero if C<eof> is called without parameter; C<1> if C<eof> is given
1939a filehandle as a parameter, e.g. C<eof(FH)>; and C<2> in the very special
1940case that the tied filehandle is C<ARGV> and C<eof> is called with an empty
1941parameter list, e.g. C<eof()>.
1942
1943=end original
1944
1945Perl 5.12 から、追加の整数引数が渡されます。
1946これは、C<eof> が引数なしで呼び出されたら 0 です; C<eof(FH)> のように、
1947C<eof> がファイルハンドルを引数として呼び出されたら C<1> です;
1948tie されたファイルハンドルが C<ARGV> で、C<eof()> のように、C<eof> が
1949空リストを引数として呼び出されるというとても特殊な場合は C<2> です。
1950
1951 sub EOF { not length $stringbuf }
1952
18271953=item CLOSE this
18281954X<CLOSE>
18291955
18301956=begin original
18311957
18321958This method will be called when the handle is closed via the C<close>
18331959function.
18341960
18351961=end original
18361962
18371963このメソッドは、C<close> 関数を通してハンドルがクローズされるときに
18381964呼び出されます。
18391965
18401966 sub CLOSE { print "CLOSE called.\n" }
18411967
18421968=item UNTIE this
18431969X<UNTIE>
18441970
18451971=begin original
18461972
18471973As with the other types of ties, this method will be called when C<untie> happens.
18481974It may be appropriate to "auto CLOSE" when this occurs. See
18491975L<The C<untie> Gotcha> below.
18501976
18511977=end original
18521978
18531979その他の種類の tie と同様に、このメソッドは C<untie> が起きたときに
18541980呼び出されます。
18551981これが起きたときに、「自動 CLOSE」を行うのに適切です。
18561982後述する L<The C<untie> Gotcha> を参照してください。
18571983
18581984=item DESTROY this
18591985X<DESTROY>
18601986
18611987=begin original
18621988
18631989As with the other types of ties, this method will be called when the
18641990tied handle is about to be destroyed. This is useful for debugging and
18651991possibly cleaning up.
18661992
18671993=end original
18681994
18691995他の型に対する tie と同様に、このメソッドは tie されたハンドルが
18701996破棄されるときに呼び出されます。
18711997これはデバッグや後始末をするのに便利です。
18721998
18731999 sub DESTROY { print "</shout>\n" }
18742000
18752001=back
18762002
18772003=begin original
18782004
18792005Here's how to use our little example:
18802006
18812007=end original
18822008
18832009以下は私たちのサンプルをどのように使うかの例です。
18842010
18852011 tie(*FOO,'Shout');
18862012 print FOO "hello\n";
18872013 $a = 4; $b = 6;
18882014 print FOO $a, " plus ", $b, " equals ", $a + $b, "\n";
18892015 print <FOO>;
18902016
18912017=head2 UNTIE this
18922018X<UNTIE>
18932019
18942020=begin original
18952021
18962022You can define for all tie types an UNTIE method that will be called
18972023at untie(). See L<The C<untie> Gotcha> below.
18982024
18992025=end original
19002026
19012027全ての型に対する tie について、untie() で呼び出される UNTIE メソッドを
19022028定義できます。
1903以下の L<The C<untie> Gotcha> を参照してください。
2029後述する L<The C<untie> Gotcha> を参照してください。
19042030
19052031=head2 The C<untie> Gotcha
19062032X<untie>
19072033
19082034(C<untie> のコツ)
19092035
19102036=begin original
19112037
19122038If you intend making use of the object returned from either tie() or
19132039tied(), and if the tie's target class defines a destructor, there is a
19142040subtle gotcha you I<must> guard against.
19152041
19162042=end original
19172043
19182044tie() や tied() が返したオブジェクトを使おうとするならば、また、
19192045その tie されているターゲットクラスがデストラクタを
19202046定義しているのであれば、あなたが I<しなければならない>
19212047微妙なコツがあります。
19222048
19232049=begin original
19242050
19252051As setup, consider this (admittedly rather contrived) example of a
19262052tie; all it does is use a file to keep a log of the values assigned to
19272053a scalar.
19282054
19292055=end original
19302056
1931セットアップとして、以下の tie の例を考えてみましょう
2057セットアップとして、以下の tie の例を考えてみましょう; これはファイルを
1932これはファイルを使って、スカラに代入された値を記録し続けるというものです。
2058使って、スカラに代入された値を記録し続けるというものです。
19332059
19342060 package Remember;
19352061
19362062 use strict;
19372063 use warnings;
19382064 use IO::File;
19392065
19402066 sub TIESCALAR {
19412067 my $class = shift;
19422068 my $filename = shift;
19432069 my $handle = IO::File->new( "> $filename" )
19442070 or die "Cannot open $filename: $!\n";
19452071
19462072 print $handle "The Start\n";
19472073 bless {FH => $handle, Value => 0}, $class;
19482074 }
19492075
19502076 sub FETCH {
19512077 my $self = shift;
19522078 return $self->{Value};
19532079 }
19542080
19552081 sub STORE {
19562082 my $self = shift;
19572083 my $value = shift;
19582084 my $handle = $self->{FH};
19592085 print $handle "$value\n";
19602086 $self->{Value} = $value;
19612087 }
19622088
19632089 sub DESTROY {
19642090 my $self = shift;
19652091 my $handle = $self->{FH};
19662092 print $handle "The End\n";
19672093 close $handle;
19682094 }
19692095
19702096 1;
19712097
19722098=begin original
19732099
19742100Here is an example that makes use of this tie:
19752101
19762102=end original
19772103
19782104次に挙げるのは、この tie を使った例です。
19792105
19802106 use strict;
19812107 use Remember;
19822108
19832109 my $fred;
19842110 tie $fred, 'Remember', 'myfile.txt';
19852111 $fred = 1;
19862112 $fred = 4;
19872113 $fred = 5;
19882114 untie $fred;
19892115 system "cat myfile.txt";
19902116
19912117=begin original
19922118
19932119This is the output when it is executed:
19942120
19952121=end original
19962122
19972123これを実行したときの出力は次のようになります。
19982124
19992125 The Start
20002126 1
20012127 4
20022128 5
20032129 The End
20042130
20052131=begin original
20062132
20072133So far so good. Those of you who have been paying attention will have
20082134spotted that the tied object hasn't been used so far. So lets add an
20092135extra method to the Remember class to allow comments to be included in
2010the file -- say, something like this:
2136the file; say, something like this:
20112137
20122138=end original
20132139
20142140まずまずですね。
20152141注意深い人は tie されたオブジェクトがここでは使われていないことを
20162142指摘するでしょう。
20172143そこで、Remember クラスにファイルがコメントを含むことを
2018できるようにするメソッドを追加しましょう -- そう、このような:
2144できるようにするメソッドを追加しましょう; そう、このような:
20192145
20202146 sub comment {
20212147 my $self = shift;
20222148 my $text = shift;
20232149 my $handle = $self->{FH};
20242150 print $handle $text, "\n";
20252151 }
20262152
20272153=begin original
20282154
20292155And here is the previous example modified to use the C<comment> method
20302156(which requires the tied object):
20312157
20322158=end original
20332159
20342160次の例は、前の例を C<comment> メソッド(tie されたオブジェクトを
20352161必要とします)を使うために変更したものです。
20362162
20372163 use strict;
20382164 use Remember;
20392165
20402166 my ($fred, $x);
20412167 $x = tie $fred, 'Remember', 'myfile.txt';
20422168 $fred = 1;
20432169 $fred = 4;
20442170 comment $x "changing...";
20452171 $fred = 5;
20462172 untie $fred;
20472173 system "cat myfile.txt";
20482174
20492175=begin original
20502176
20512177When this code is executed there is no output. Here's why:
20522178
20532179=end original
20542180
20552181このコードを実行したとき、なにも出力されません。
20562182その理由はこうです。
20572183
20582184=begin original
20592185
20602186When a variable is tied, it is associated with the object which is the
20612187return value of the TIESCALAR, TIEARRAY, or TIEHASH function. This
20622188object normally has only one reference, namely, the implicit reference
20632189from the tied variable. When untie() is called, that reference is
20642190destroyed. Then, as in the first example above, the object's
20652191destructor (DESTROY) is called, which is normal for objects that have
20662192no more valid references; and thus the file is closed.
20672193
20682194=end original
20692195
20702196変数が tie されたとき、それは TIESCALAR, TIEARRAY, TIEHASH といった
20712197関数のいずれかの返した値であるオブジェクトに結び付けられます。
20722198このオブジェクトは、通常はただ一つのリファレンス、すなわち tie され
20732199た変数からの暗黙のリファレンスだけを持っています。
20742200untie() が呼ばれたとき、このリファレンスは破棄されます。
20752201したがって、最初の例にあったように、オブジェクトのデストラクタ (DESTROY) が
20762202呼び出されてオブジェクトはもはや正当なリファレンスを持たないようになり、
20772203さらにファイルがクローズされます。
20782204
20792205=begin original
20802206
20812207In the second example, however, we have stored another reference to
20822208the tied object in $x. That means that when untie() gets called
20832209there will still be a valid reference to the object in existence, so
20842210the destructor is not called at that time, and thus the file is not
20852211closed. The reason there is no output is because the file buffers
20862212have not been flushed to disk.
20872213
20882214=end original
20892215
20902216しかしながら二番目の例においては、私たちはもう一つの tie された
20912217オブジェクトへのリファレンスを $x の中に格納しました。
20922218これは untie() されたときに、存在するオブジェクトに対する正当な
2093リファレンスがまだ存在しているということです
2219リファレンスがまだ存在しているということです; このためデストラクタは
2094このためデストラクタはその時には呼び出されません。
2220その時には呼び出されません; そしてファイルはクローズされないのです
2095そしてファイルはクローズされないのです。
20962221何の出力も無かった理由は、ファイルバッファがディスクに
20972222フラッシュされていなかったからです。
20982223
20992224=begin original
21002225
21012226Now that you know what the problem is, what can you do to avoid it?
21022227Prior to the introduction of the optional UNTIE method the only way
21032228was the good old C<-w> flag. Which will spot any instances where you call
21042229untie() and there are still valid references to the tied object. If
21052230the second script above this near the top C<use warnings 'untie'>
21062231or was run with the C<-w> flag, Perl prints this
21072232warning message:
21082233
21092234=end original
21102235
2111さて、あなたはもうこれが問題であることがわかったでしょう
2236さて、あなたはもうこれが問題であることがわかったでしょう;
21122237では、これを避けるにはどうすればいいでしょうか?
21132238省略可能な UNTIE メソッドが導入される前は、唯一の方法は
21142239古き良き C<-w> オプションだけです。
21152240これははあなたが untie() を呼んだそのときに、(untie() の対象となっている)
21162241tie されたオブジェクトに対する正当なリファレンスがまだ存在している場合には
21172242それを指摘してくれます。
21182243もし二番目のスクリプトを先頭の方に C<use warnings 'untie'> を付けるか、
21192244C<-w> オプションをつけた状態で実行していれば、
21202245Perl は次のような警告メッセージを出力します。
21212246
21222247 untie attempted while 1 inner references still exist
21232248
21242249=begin original
21252250
21262251To get the script to work properly and silence the warning make sure
21272252there are no valid references to the tied object I<before> untie() is
21282253called:
21292254
21302255=end original
21312256
21322257スクリプトを正しく動作させ、警告を黙らせるには tie されたオブジェクトが
21332258untie() を呼び出すより I<前に> 正当なリファレンスをなくすようにします。
21342259
21352260 undef $x;
21362261 untie $fred;
21372262
21382263=begin original
21392264
21402265Now that UNTIE exists the class designer can decide which parts of the
21412266class functionality are really associated with C<untie> and which with
21422267the object being destroyed. What makes sense for a given class depends
21432268on whether the inner references are being kept so that non-tie-related
21442269methods can be called on the object. But in most cases it probably makes
21452270sense to move the functionality that would have been in DESTROY to the UNTIE
21462271method.
21472272
21482273=end original
21492274
21502275今や UNTIE が存在するので、クラスデザイナーはクラス機能のどの部分が
21512276本当に C<untie> に関連付けられ、どの部分がオブジェクトが破壊されたときに
21522277関連付けられるかを決定できます。
21532278与えられたクラスについてどんな意味があるかは内部のリファレンスが
21542279維持されているかどうかに依存しているので、tie に関係ないメソッドは
21552280オブジェクトで呼び出しできます。
21562281しかし、ほとんどの場合、DESTROY にある機能を UNTIE メソッドに移すのが
21572282意味のあることでしょう。
21582283
21592284=begin original
21602285
21612286If the UNTIE method exists then the warning above does not occur. Instead the
21622287UNTIE method is passed the count of "extra" references and can issue its own
21632288warning if appropriate. e.g. to replicate the no UNTIE case this method can
21642289be used:
21652290
21662291=end original
21672292
21682293もし UNTIE メソッドが存在するなら、上記の警告は起こりません。
21692294代わりに UNTIE メソッドは「追加の」リファレンスの数が渡され、もし適切なら
2170自身の警告を出力できます; 例えば、UNTIE がない場合を複製するには、
2295自身の警告を出力できます
2171このメソッドが使えます:
2296例えば、UNTIE がない場合を複製するには、このメソッドが使えます:
21722297
2173 sub UNTIE
2298 sub UNTIE
2174 {
2299 {
2175 my ($obj,$count) = @_;
2300 my ($obj,$count) = @_;
2176 carp "untie attempted while $count inner references still exist" if $count;
2301 carp "untie attempted while $count inner references still exist"
2177 }
2302 if $count;
2303 }
21782304
21792305=head1 SEE ALSO
21802306
21812307=begin original
21822308
21832309See L<DB_File> or L<Config> for some interesting tie() implementations.
21842310A good starting point for many tie() implementations is with one of the
21852311modules L<Tie::Scalar>, L<Tie::Array>, L<Tie::Hash>, or L<Tie::Handle>.
21862312
21872313=end original
21882314
21892315興味深い幾つかの tie() の実装については L<DB_File> や L<Config> を
21902316参照してください。
21912317多くの tie() 実装のためのよい開始点は、モジュール L<Tie::Scalar>,
21922318L<Tie::Array>, L<Tie::Hash>, L<Tie::Handle> のいずれかです。
21932319
21942320=head1 BUGS
21952321
21962322=begin original
21972323
2198The bucket usage information provided by C<scalar(%hash)> is not
2324The normal return provided by C<scalar(%hash)> is not
21992325available. What this means is that using %tied_hash in boolean
22002326context doesn't work right (currently this always tests false,
22012327regardless of whether the hash is empty or hash elements).
2328[ This paragraph needs review in light of changes in 5.25 ]
22022329
22032330=end original
22042331
2205C<scalar(%hash)> で提供されるバケツ使用情報は利用できません。
2332C<scalar(%hash)> で提供される通常の返り値は利用できません。
22062333これが意味することは、真偽値コンテキストで %tied_hash を使っても正しく
22072334動作しないということです(現在のところ、ハッシュが空かハッシュ要素かに
22082335関わらず、このテストは常に偽となります)。
2336[ This paragraph needs review in light of changes in 5.25 ]
22092337
22102338=begin original
22112339
22122340Localizing tied arrays or hashes does not work. After exiting the
22132341scope the arrays or the hashes are not restored.
22142342
22152343=end original
22162344
22172345配列やハッシュのローカル化は動作しません。
22182346スコープの終了後、配列やハッシュの値は元に戻りません。
22192347
22202348=begin original
22212349
22222350Counting the number of entries in a hash via C<scalar(keys(%hash))>
22232351or C<scalar(values(%hash)>) is inefficient since it needs to iterate
22242352through all the entries with FIRSTKEY/NEXTKEY.
22252353
22262354=end original
22272355
22282356C<scalar(keys(%hash))> や C<scalar(values(%hash))> を使ってハッシュ内の
22292357エントリの数を数えることは非効率的です; 全てのエントリに対して
22302358FIRSTKEY/NEXTKEY を使って反復する必要があるからです。
22312359
22322360=begin original
22332361
22342362Tied hash/array slices cause multiple FETCH/STORE pairs, there are no
22352363tie methods for slice operations.
22362364
22372365=end original
22382366
22392367tie されたハッシュや配列のスライスは複数回の FETCH/STORE の組を引き起こします;
22402368スライス操作のための tie メソッドはありません。
22412369
22422370=begin original
22432371
22442372You cannot easily tie a multilevel data structure (such as a hash of
22452373hashes) to a dbm file. The first problem is that all but GDBM and
22462374Berkeley DB have size limitations, but beyond that, you also have problems
2247with how references are to be represented on disk. One experimental
2375with how references are to be represented on disk. One
22482376module that does attempt to address this need is DBM::Deep. Check your
22492377nearest CPAN site as described in L<perlmodlib> for source code. Note
22502378that despite its name, DBM::Deep does not use dbm. Another earlier attempt
22512379at solving the problem is MLDBM, which is also available on the CPAN, but
22522380which has some fairly serious limitations.
22532381
22542382=end original
22552383
22562384(ハッシュのハッシュのような)複数レベルのデータ構造を dbm ファイルに
22572385tie することは簡単にはできません。
22582386問題は、GDBM と Berkeley DB はサイズに制限があり、それを超えることが
22592387できないということで、また、ディスク上にあるものを参照する方法についても
22602388問題があります。
2261これを解決しようとしている実験的なモジュールの一つに、
2389これを解決しようとしているモジュールの一つに、DBM::Deep というものが
2262DBM::Deep というものがあります。
2390あります。
22632391ソースコードは L<perlmodlib> にあるように、
22642392あなたのお近くの CPAN サイトを確かめてください。
22652393その名前にも関わらず、DBM::Deep は DBM を使わないことに注意してください。
22662394問題を解決するためのもう一つの初期の試みは MLDBM で、これも CPAN から
22672395利用可能ですが、かなり重大な制限があります。
22682396
22692397=begin original
22702398
22712399Tied filehandles are still incomplete. sysopen(), truncate(),
22722400flock(), fcntl(), stat() and -X can't currently be trapped.
22732401
22742402=end original
22752403
22762404ファイルハンドルの tie はまだ不完全です。
22772405現在のところ、sysopen(), truncate(), flock(), fcntl(), stat(), -X は
22782406トラップできません。
22792407
22802408=head1 AUTHOR
22812409
22822410Tom Christiansen
22832411
22842412TIEHANDLE by Sven Verdoolaege <F<skimo@dns.ufsia.ac.be>> and Doug MacEachern <F<dougm@osf.org>>
22852413
22862414UNTIE by Nick Ing-Simmons <F<nick@ing-simmons.net>>
22872415
22882416SCALAR by Tassilo von Parseval <F<tassilo.von.parseval@rwth-aachen.de>>
22892417
22902418Tying Arrays by Casey West <F<casey@geeknest.com>>
22912419
22922420=begin meta
22932421
22942422Translate: KIMURA Koichi
2295Update: Kentaro Shirakata <argrath@ub32.org>
2423Update: SHIRAKATA Kentaro <argrath@ub32.org> (5.8.8-)
2424Status: completed
22962425
22972426=end meta