5.38.0

NAME

perltie - how to hide an object class in a simple variable

perltie - オブジェクトクラスを単純な変数に隠す方法

概要

 tie VARIABLE, CLASSNAME, LIST

 $object = tied VARIABLE

 untie VARIABLE

説明

Prior to release 5.0 of Perl, a programmer could use dbmopen() to connect an on-disk database in the standard Unix dbm(3x) format magically to a %HASH in their program. However, their Perl was either built with one particular dbm library or another, but not both, and you couldn't extend this mechanism to other packages or types of variables.

5.0 より前の Perl では、プログラマは dbmopen() を使ってディスクにある 標準 UNIX dbm(3x) フォーマットのデータベースをプログラム中の %HASH と 結び付けることができました。 しかしながら、Perl は特定の dbm ライブラリか別のものを使って ビルドすることができたものの、両方一度にはできませんでした; そして、この 仕組みを他のパッケージや変数の型に拡張することはできなかったのです。

Now you can.

今はできます。

The tie() function binds a variable to a class (package) that will provide the implementation for access methods for that variable. Once this magic has been performed, accessing a tied variable automatically triggers method calls in the proper class. The complexity of the class is hidden behind magic methods calls. The method names are in ALL CAPS, which is a convention that Perl uses to indicate that they're called implicitly rather than explicitly--just like the BEGIN() and END() functions.

tie() 関数は変数と、その変数に対するアクセスメソッドの実装を提供する クラス(パッケージ)とを結び付けます。 この魔法が一度働けば、tie された変数は自動的に適切なクラスにある メソッド呼び出しを実行します。 クラスのすべての複雑性はメソッド呼び出しに隠されます。 それらのメソッドの名前は、BEGIN() や END() と同様に(そのメソッドを) Perl が こっそりと呼び出すことを示すための規約に従って全て大文字です。

In the tie() call, VARIABLE is the name of the variable to be enchanted. CLASSNAME is the name of a class implementing objects of the correct type. Any additional arguments in the LIST are passed to the appropriate constructor method for that class--meaning TIESCALAR(), TIEARRAY(), TIEHASH(), or TIEHANDLE(). (Typically these are arguments such as might be passed to the dbminit() function of C.) The object returned by the "new" method is also returned by the tie() function, which would be useful if you wanted to access other methods in CLASSNAME. (You don't actually have to return a reference to a right "type" (e.g., HASH or CLASSNAME) so long as it's a properly blessed object.) You can also retrieve a reference to the underlying object using the tied() function.

tie() コールの中で、VARIABLE は魔法を掛けられる変数の名前です。 CLASSNAME は正しい型のオブジェクトを実装するクラスの名前です。 LIST にあるその他の引数はクラスの適切なコンストラクタメソッド TIESCALAR()、TIEARRAY()、TIEHASH()、TIEHANDLE() のいずれかに 渡されます。 (典型的にはこれらの引数は C の dbminit() 関数に渡すのと同じものです。) "new" メソッドから返されたオブジェクトは同様に関数 tie() からも 返されます; これはあなたが CLASSNAME の中の別のメソッドで アクセスしたいというときに便利でしょう。 (あなたは実際には正しい「型」(HASH か CLASSNAME) の参照を、それが適切な bless されたオブジェクトであるということから返す必要はありません。) また、関数 tied() を使って、基礎となるオブジェクトへのリファレンスを 取得することができます。

Unlike dbmopen(), the tie() function will not use or require a module for you--you need to do that explicitly yourself.

dbmopen() とは異なり、tie() はモジュールを use したり require したり することはありません--あなたが、自分自身でそれを明示的に 行わなければなりません。

スカラを tie する

A class implementing a tied scalar should define the following methods: TIESCALAR, FETCH, STORE, and possibly UNTIE and/or DESTROY.

tie されたスカラを実装するクラスは、TIESCALAR, FETCH, STORE, そして可能であれば UNTIE や DESTROY といったメソッドを定義しておくべきです。

Let's look at each in turn, using as an example a tie class for scalars that allows the user to do something like:

以下のような操作を、ユーザーに許しているスカラに対してクラスを tie する例を使って順に見て行きましょう。

    tie $his_speed, 'Nice', getppid();
    tie $my_speed,  'Nice', $$;

And now whenever either of those variables is accessed, its current system priority is retrieved and returned. If those variables are set, then the process's priority is changed!

こうした後ではこれらの変数のいずれかがアクセスされたときには、カレントの システム優先順位が取得されたり返されたりします。 もし変数に代入が行われれば、プロセスの優先順位は変更されます!

We'll use Jarkko Hietaniemi <jhi@iki.fi>'s BSD::Resource class (not included) to access the PRIO_PROCESS, PRIO_MIN, and PRIO_MAX constants from your system, as well as the getpriority() and setpriority() system calls. Here's the preamble of the class.

システムの PRIO_PROCESS, PRIO_MIN, PRIO_MAX といった定数に アクセスするために Jarkko Hietaniemi <jhi@iki.fi> の BSD::Resource クラスを使います。 以下はこのクラスの前置きです。

    package Nice;
    use Carp;
    use BSD::Resource;
    use strict;
    $Nice::DEBUG = 0 unless defined $Nice::DEBUG;
TIESCALAR classname, LIST

This is the constructor for the class. That means it is expected to return a blessed reference to a new scalar (probably anonymous) that it's creating. For example:

これはこのクラスのコンストラクタです。 その役割は作成された新たな(おそらくは無名の)スカラへの bless された 参照を返すことです。 例えば:

 sub TIESCALAR {
     my $class = shift;
     my $pid = shift || $$; # 0 means me

     if ($pid !~ /^\d+$/) {
         carp "Nice::Tie::Scalar got non-numeric pid $pid" if $^W;
         return undef;
     }

     unless (kill 0, $pid) { # EPERM or ERSCH, no doubt
         carp "Nice::Tie::Scalar got bad pid $pid: $!" if $^W;
         return undef;
     }

     return bless \$pid, $class;
 }

This tie class has chosen to return an error rather than raising an exception if its constructor should fail. While this is how dbmopen() works, other classes may well not wish to be so forgiving. It checks the global variable $^W to see whether to emit a bit of noise anyway.

このtie クラスでは、コンストラクタが失敗したときに例外を起こすのではなく エラーを返すことを選択しました。 dbmopen() が動作している間に、他のクラスは例外が起きることを 好まないかもしれないからです。 グローバル変数 $^W でエラーメッセージを出すかどうかを検査しています。

FETCH this

This method will be triggered every time the tied variable is accessed (read). It takes no arguments beyond its self reference, which is the object representing the scalar we're dealing with. Because in this case we're using just a SCALAR ref for the tied scalar object, a simple $$self allows the method to get at the real value stored there. In our example below, that real value is the process ID to which we've tied our variable.

このメソッドは tie された変数がアクセス(読み出し)される度に起動されます。 これは自分のリファレンス、つまり私たちが扱おうとしている スカラを表現するオブジェクトの他に引数は取りません。 この場合、単に SCALAR の参照をtieされたスカラオブジェクトとして 使うので、単純な $$self がそこに格納されている実際の値を取得する メソッドとなります。 以下に示した例では、実際の値は変数に tie されたプロセス ID です。

    sub FETCH {
        my $self = shift;
        confess "wrong type" unless ref $self;
        croak "usage error" if @_;
        my $nicety;
        local($!) = 0;
        $nicety = getpriority(PRIO_PROCESS, $$self);
        if ($!) { croak "getpriority failed: $!" }
        return $nicety;
    }

This time we've decided to blow up (raise an exception) if the renice fails--there's no place for us to return an error otherwise, and it's probably the right thing to do.

ここでは、renice に失敗した場合には例外を引き起こすようにしました-- エラーを返すための場所がなく、例外を引き起こすことがおそらく妥当です。

STORE this, value

This method will be triggered every time the tied variable is set (assigned). Beyond its self reference, it also expects one (and only one) argument: the new value the user is trying to assign. Don't worry about returning a value from STORE; the semantic of assignment returning the assigned value is implemented with FETCH.

このメソッドは tie された変数に代入される度毎に起動されます。 自分の参照のほか、ただ一つの引数としてユーザーが代入しようとする 新しい値を取ります。 STORE から返される値は気にしないで下さい; 代入された値を返す代入の動作は FETCH で実装されています。

 sub STORE {
     my $self = shift;
     confess "wrong type" unless ref $self;
     my $new_nicety = shift;
     croak "usage error" if @_;

     if ($new_nicety < PRIO_MIN) {
         carp sprintf
           "WARNING: priority %d less than minimum system priority %d",
               $new_nicety, PRIO_MIN if $^W;
         $new_nicety = PRIO_MIN;
     }

     if ($new_nicety > PRIO_MAX) {
         carp sprintf
           "WARNING: priority %d greater than maximum system priority %d",
               $new_nicety, PRIO_MAX if $^W;
         $new_nicety = PRIO_MAX;
     }

     unless (defined setpriority(PRIO_PROCESS,
                                 $$self,
                                 $new_nicety))
     {
         confess "setpriority failed: $!";
     }
 }
UNTIE this

This method will be triggered when the untie occurs. This can be useful if the class needs to know when no further calls will be made. (Except DESTROY of course.) See "The untie Gotcha" below for more details.

このメソッドは、untie が発生すると起動されます。 これは、クラスが、もはや呼び出されなくなるのはいつかを知る必要がある場合に 便利です。 (もちろん DESTROY を除いてです。) さらなる詳細については後述する "The untie Gotcha" を参照してください。

DESTROY this

This method will be triggered when the tied variable needs to be destructed. As with other object classes, such a method is seldom necessary, because Perl deallocates its moribund object's memory for you automatically--this isn't C++, you know. We'll use a DESTROY method here for debugging purposes only.

このメソッドは tie された変数を破棄する必要があるときに呼び出されます。 他のオブジェクトクラスと同じように、このようなメソッドはほとんど 必要ありません; それは、Perl は消滅しかかったオブジェクトのメモリを自動的に 解放するからです--これは C++ ではないのです; いいですね? 私たちはここでは DESTROY メソッドをデバッグのためだけに使います。

    sub DESTROY {
        my $self = shift;
        confess "wrong type" unless ref $self;
        carp "[ Nice::DESTROY pid $$self ]" if $Nice::DEBUG;
    }

That's about all there is to it. Actually, it's more than all there is to it, because we've done a few nice things here for the sake of completeness, robustness, and general aesthetics. Simpler TIESCALAR classes are certainly possible.

これがすべきことの全てです。 実際のところ、それよりも多くのことがあります; ですから、私たちはここで ちょっとした完全性、堅牢性、一般的な美しさというものを込めました。 もっと簡単な TIESCALAR クラスを作ることも可能です。

配列を tie する

A class implementing a tied ordinary array should define the following methods: TIEARRAY, FETCH, STORE, FETCHSIZE, STORESIZE, CLEAR and perhaps UNTIE and/or DESTROY.

tie された配列を実装するクラスは TIEARRAY, FETCH, STORE, FETCHSIZE, CLEAR, STORESIZE、そしておそらく UNTIE や DESTROY といったメソッドを 実装すべきでしょう。

FETCHSIZE and STORESIZE are used to provide $#array and equivalent scalar(@array) access.

FETCHSIZE と STORESIZE は $#arrayscalar(@array) アクセスに等価なものを提供します。

The methods POP, PUSH, SHIFT, UNSHIFT, SPLICE, DELETE, and EXISTS are required if the perl operator with the corresponding (but lowercase) name is to operate on the tied array. The Tie::Array class can be used as a base class to implement the first five of these in terms of the basic methods above. The default implementations of DELETE and EXISTS in Tie::Array simply croak.

POP, PUSH, SHIFT, UNSHIFT, SPLICE, DELETE, EXIST といったメソッドは 同名の perl の演算子(ただし小文字)が tie された配列に対して 操作を行うときに必要となります。 Tie::Array クラスは、これらのうち、最初の 5 つの基本的なメソッドを 実装するための基底クラスとして使用できます。 Tie::Array での DELETE と EXISTS のデフォルトの実装は 単なる croak です。

In addition EXTEND will be called when perl would have pre-extended allocation in a real array.

それに加え、EXTEND は perl が実際の配列中であらかじめ 拡張するようなときに呼び出されます。

For this discussion, we'll implement an array whose elements are a fixed size at creation. If you try to create an element larger than the fixed size, you'll take an exception. For example:

ここでの説明のため、要素数が生成時に固定されたサイズである配列を実装します。 固定サイズを越えた要素を作ろうとすると、例外が発生します。 例えば:

    use FixedElem_Array;
    tie @array, 'FixedElem_Array', 3;
    $array[0] = 'cat';  # ok.
    $array[1] = 'dogs'; # exception, length('dogs') > 3.

The preamble code for the class is as follows:

このクラスに対する 前置きコードは以下の通りです。

    package FixedElem_Array;
    use Carp;
    use strict;
TIEARRAY classname, LIST

This is the constructor for the class. That means it is expected to return a blessed reference through which the new array (probably an anonymous ARRAY ref) will be accessed.

これはこのクラスのコンストラクタです。 その役割は作成された新たな(おそらくは無名の配列の参照)配列への bless された参照を返すことです。

In our example, just to show you that you don't really have to return an ARRAY reference, we'll choose a HASH reference to represent our object. A HASH works out well as a generic record type: the {ELEMSIZE} field will store the maximum element size allowed, and the {ARRAY} field will hold the true ARRAY ref. If someone outside the class tries to dereference the object returned (doubtless thinking it an ARRAY ref), they'll blow up. This just goes to show you that you should respect an object's privacy.

私たちの例では、あなたにあなたが 実際には ARRAY のリファレンスを 返さなくてもよいということを示すためだけに、使用するオブジェクトを 表わす HASH の参照を選びました。 HASH は汎用的なレコード型と同じように働きます: {ELEMSIZE} フィールドは 許される最大の要素の数を格納し、{ARRAY} フィールドは本物の ARRAY の リファレンスを保持します。 誰かがクラスの外側で返されたオブジェクトのデリファレンスを試みた場合 (それが ARRAY のリファレンスであると疑いなく考えて)、それは失敗します。 これはあなたがオブジェクトのプライバシーを尊重すべきであるという ことなのです。

    sub TIEARRAY {
      my $class    = shift;
      my $elemsize = shift;
      if ( @_ || $elemsize =~ /\D/ ) {
        croak "usage: tie ARRAY, '" . __PACKAGE__ . "', elem_size";
      }
      return bless {
        ELEMSIZE => $elemsize,
        ARRAY    => [],
      }, $class;
    }
FETCH this, index

This method will be triggered every time an individual element the tied array is accessed (read). It takes one argument beyond its self reference: the index whose value we're trying to fetch.

このメソッドは tie された配列の個々の要素がアクセス(読み出し)される毎に 起動されます。 これは自分の参照のほかに、一つの引数、フェッチしようとする値の インデックスをとります。

    sub FETCH {
      my $self  = shift;
      my $index = shift;
      return $self->{ARRAY}->[$index];
    }

If a negative array index is used to read from an array, the index will be translated to a positive one internally by calling FETCHSIZE before being passed to FETCH. You may disable this feature by assigning a true value to the variable $NEGATIVE_INDICES in the tied array class.

配列からの読み込みに負数の添え字が使われると、添え字は FETCH に渡される前に FETCHSIZE を呼び出すことで正の数に変換されます。 tie された配列クラスの $NEGATIVE_INDICES に真の値を代入することで この機能を無効にできます。

As you may have noticed, the name of the FETCH method (et al.) is the same for all accesses, even though the constructors differ in names (TIESCALAR vs TIEARRAY). While in theory you could have the same class servicing several tied types, in practice this becomes cumbersome, and it's easiest to keep them at simply one tie type per class.

すでに気がついたかもしれませんが、FETCH メソッド(など)の名前は全ての アクセスについて、たとえコンストラクタが別の名前であった (TIESCALAR と TIEARRAY)としても同じ名前になっています。 理論的には、幾つかの tie されたクラスをサービスする同じクラスを 持つこともできるでしょうが、実際にはこれは厄介なものになり、 単にクラスあたり一つの状態にするのが最も簡単です。

STORE this, index, value

This method will be triggered every time an element in the tied array is set (written). It takes two arguments beyond its self reference: the index at which we're trying to store something and the value we're trying to put there.

このメソッドは、tie された配列にある要素に対する書き込みがある度毎に 起動されます。 これは自分の参照のほかに、何かを格納しようとする場所の添え字と、 格納しようとしている値という二つの引数を取ります。

In our example, undef is really $self->{ELEMSIZE} number of spaces so we have a little more work to do here:

この例では、undef は実際は $self->{ELEMSIZE} 個の空白なので、 ここでもう少し作業が必要です:

 sub STORE {
   my $self = shift;
   my( $index, $value ) = @_;
   if ( length $value > $self->{ELEMSIZE} ) {
     croak "length of $value is greater than $self->{ELEMSIZE}";
   }
   # fill in the blanks
   $self->STORESIZE( $index ) if $index > $self->FETCHSIZE();
   # right justify to keep element size for smaller elements
   $self->{ARRAY}->[$index] = sprintf "%$self->{ELEMSIZE}s", $value;
 }

Negative indexes are treated the same as with FETCH.

インデックスの値が負数の場合、FETCH と同様に扱われます。

FETCHSIZE this

Returns the total number of items in the tied array associated with object this. (Equivalent to scalar(@array)). For example:

オブジェクト this と結び付けられた tie された配列の合計要素数を返します。 (scalar(@array) と等価です)。 例えば:

    sub FETCHSIZE {
      my $self = shift;
      return scalar $self->{ARRAY}->@*;
    }
STORESIZE this, count

Sets the total number of items in the tied array associated with object this to be count. If this makes the array larger then class's mapping of undef should be returned for new positions. If the array becomes smaller then entries beyond count should be deleted.

オブジェクト this に結び付けられた tie された配列のアイテムの合計数を count にセットします。 もし配列がより大きくなるなら、新しい位置ではクラスのマッピングは undef を返すべきです。 もし配列がより小さくなるなら、count を超えたエントリは削除されるべきです。

In our example, 'undef' is really an element containing $self->{ELEMSIZE} number of spaces. Observe:

この例では、'undef' というのは実際には $self->{ELEMSIZE} 個の空白を 含む要素です。 これを見てください:

    sub STORESIZE {
      my $self  = shift;
      my $count = shift;
      if ( $count > $self->FETCHSIZE() ) {
        foreach ( $count - $self->FETCHSIZE() .. $count ) {
          $self->STORE( $_, '' );
        }
      } elsif ( $count < $self->FETCHSIZE() ) {
        foreach ( 0 .. $self->FETCHSIZE() - $count - 2 ) {
          $self->POP();
        }
      }
    }
EXTEND this, count

Informative call that array is likely to grow to have count entries. Can be used to optimize allocation. This method need do nothing.

配列が、count エントリに大きくなりそうだということを通知する 呼び出しです。 割り当ての最適化に使えます。 このメソッドで何かをしなければならないということはありません。

In our example there is no reason to implement this method, so we leave it as a no-op. This method is only relevant to tied array implementations where there is the possibility of having the allocated size of the array be larger than is visible to a perl programmer inspecting the size of the array. Many tied array implementations will have no reason to implement it.

この例ではこのメソッドを実装する理由はないので、ここでは 何もしないままにします。 このメソッドは、 配列の割り当てサイズが perl プログラマが配列サイズを検査して 見える物よりも大きい可能性がある tie 配列実装にのみ関係があります。 多くの tie 配列実装ではこれを実装する理由はありません。

    sub EXTEND {   
      my $self  = shift;
      my $count = shift;
      # nothing to see here, move along.
    }

NOTE: It is generally an error to make this equivalent to STORESIZE. Perl may from time to time call EXTEND without wanting to actually change the array size directly. Any tied array should function correctly if this method is a no-op, even if perhaps they might not be as efficient as they would if this method was implemented.

注意: これを STORESIZE と等価にするのは一般的に誤りです。 Perl は時々、実際に配列のサイズを直接変更する目的なしに EXTEND を呼び出すことがあります。 tie 配列は、例えおそらくこのメソッドが実装されている場合ほど効率ではない 場合でも、このメソッドがなにもしない場合正しく動作するべきです。

EXISTS this, key

Verify that the element at index key exists in the tied array this.

tie された配列 this にインデックスが key である要素が存在するかを 検証します。

In our example, we will determine that if an element consists of $self->{ELEMSIZE} spaces only, it does not exist:

この例では、要素が $self->{ELEMSIZE} 個の空白のみで構成されていれば、 これは存在しません:

 sub EXISTS {
   my $self  = shift;
   my $index = shift;
   return 0 if ! defined $self->{ARRAY}->[$index] ||
               $self->{ARRAY}->[$index] eq ' ' x $self->{ELEMSIZE};
   return 1;
 }
DELETE this, key

Delete the element at index key from the tied array this.

インデックス key の要素を tie された配列 this から削除します。

In our example, a deleted item is $self->{ELEMSIZE} spaces:

この例では、削除された要素は $self->{ELEMSIZE} 個の空白です:

    sub DELETE {
      my $self  = shift;
      my $index = shift;
      return $self->STORE( $index, '' );
    }
CLEAR this

Clear (remove, delete, ...) all values from the tied array associated with object this. For example:

オブジェクト this に関連付けられた tie された配列から全ての値を 削除します。 例えば:

    sub CLEAR {
      my $self = shift;
      return $self->{ARRAY} = [];
    }
PUSH this, LIST

Append elements of LIST to the array. For example:

LIST の要素を配列に追加します。 例えば:

    sub PUSH {  
      my $self = shift;
      my @list = @_;
      my $last = $self->FETCHSIZE();
      $self->STORE( $last + $_, $list[$_] ) foreach 0 .. $#list;
      return $self->FETCHSIZE();
    }   
POP this

Remove last element of the array and return it. For example:

配列の最後の要素を取り除いてそれを返します。 例えば:

    sub POP {
      my $self = shift;
      return pop $self->{ARRAY}->@*;
    }
SHIFT this

Remove the first element of the array (shifting other elements down) and return it. For example:

配列の最初の要素を取り除いて(残りの要素はシフトします)、その要素を返します。 例えば:

    sub SHIFT {
      my $self = shift;
      return shift $self->{ARRAY}->@*;
    }
UNSHIFT this, LIST

Insert LIST elements at the beginning of the array, moving existing elements up to make room. For example:

LIST 要素を配列の先頭に挿入し、すでにある要素は場所を空けるために 移動します。 例えば:

    sub UNSHIFT {
      my $self = shift;
      my @list = @_;
      my $size = scalar( @list );
      # make room for our list
      $self->{ARRAY}[ $size .. $self->{ARRAY}->$#* + $size ]->@*
       = $self->{ARRAY}->@*
      $self->STORE( $_, $list[$_] ) foreach 0 .. $#list;
    }
SPLICE this, offset, length, LIST

Perform the equivalent of splice on the array.

配列に対する splice と等価に振る舞います。

offset is optional and defaults to zero, negative values count back from the end of the array.

offset はオプションでデフォルトは 0 です; 負数は配列の最後からの 位置を示します。

length is optional and defaults to rest of the array.

length はオプションで、デフォルトは配列の残りです。

LIST may be empty.

LIST は空かもしれません。

Returns a list of the original length elements at offset.

元の、offset の位置から length 要素分のリストを返します。

In our example, we'll use a little shortcut if there is a LIST:

この例では、LIST がある場合は少し近道をします:

    sub SPLICE {
      my $self   = shift;
      my $offset = shift || 0;
      my $length = shift || $self->FETCHSIZE() - $offset;
      my @list   = (); 
      if ( @_ ) {
        tie @list, __PACKAGE__, $self->{ELEMSIZE};
        @list   = @_;
      }
      return splice $self->{ARRAY}->@*, $offset, $length, @list;
    }
UNTIE this

Will be called when untie happens. (See "The untie Gotcha" below.)

untie が起きると呼び出されます。 (後述する "The untie Gotcha" を参照してください。)

DESTROY this

This method will be triggered when the tied variable needs to be destructed. As with the scalar tie class, this is almost never needed in a language that does its own garbage collection, so this time we'll just leave it out.

このメソッドは tie された変数を破棄する必要があるときに呼び出されます。 スカラを tie したクラスと同様、このメソッドはガベージコレクションを 言語自体が行っているのでほとんど必要ありません; ですから、今回はこのまま 放っておきます。

ハッシュを tie する

Hashes were the first Perl data type to be tied (see dbmopen()). A class implementing a tied hash should define the following methods: TIEHASH is the constructor. FETCH and STORE access the key and value pairs. EXISTS reports whether a key is present in the hash, and DELETE deletes one. CLEAR empties the hash by deleting all the key and value pairs. FIRSTKEY and NEXTKEY implement the keys() and each() functions to iterate over all the keys. SCALAR is triggered when the tied hash is evaluated in scalar context, and in 5.28 onwards, by keys in boolean context. UNTIE is called when untie happens, and DESTROY is called when the tied variable is garbage collected.

ハッシュは tie される最初の Perl データ型でした(dbmopen() を参照)。 tie されたハッシュを実装するクラスは、以下のメソッドを定義すべきです: TIEHASH はコンストラクタです。 FETCH と STORE はキーと値のペアにアクセスします。 EXIST はキーがハッシュにあるかどうかを報告し、DELETE はキーを削除します。 CLEAR はすべてのキーと値のペアを削除することによりハッシュを空にします。 FIRSTKEY と NEXTKEY は全てのキーを反復するための関数 keys() と each() を 実装します。 SCALAR は tie されたハッシュがスカラコンテキストで評価されたとき、 また 5.28 以降では、真偽値コンテキストで keys が評価されたときに 呼び出されます。 UNTIE は untie が起きたときに呼び出され、DESTROY は tie された変数が ガーベジコレクションされるときに呼び出されます。

If this seems like a lot, then feel free to inherit from merely the standard Tie::StdHash module for most of your methods, redefining only the interesting ones. See Tie::Hash for details.

もしこれがたくさんありすぎると感じられるのなら、標準の Tie::StdHash モジュールを単純に継承し、再定義を必要とするものだけを自分で 実装することもできます。 詳しくは Tie::Hash を参照してください。

Remember that Perl distinguishes between a key not existing in the hash, and the key existing in the hash but having a corresponding value of undef. The two possibilities can be tested with the exists() and defined() functions.

Perl がハッシュに存在していないキーと、ハッシュに存在しているけれども undef という値を持っているキーとを明確に区別しているということを 忘れないでください。 これら二つの可能性は、exists()defined() という関数を使って検査できます。

Here's an example of a somewhat interesting tied hash class: it gives you a hash representing a particular user's dot files. You index into the hash with the name of the file (minus the dot) and you get back that dot file's contents. For example:

次の例は tie されたハッシュクラスを使ったものです: この例では特定の ユーザーのドットファイルを表わすハッシュを提供します。 あなたはハッシュをファイルの名前(からドットを取り除いたもの)によって 添え字付けを行い、そのドットファイルの内容を取得します。 例えば:

    use DotFiles;
    tie %dot, 'DotFiles';
    if ( $dot{profile} =~ /MANPATH/ ||
         $dot{login}   =~ /MANPATH/ ||
         $dot{cshrc}   =~ /MANPATH/    )
    {
        print "you seem to set your MANPATH\n";
    }

Or here's another sample of using our tied class:

tie されたクラスを使ったもう一つの例です。

    tie %him, 'DotFiles', 'daemon';
    foreach $f ( keys %him ) {
        printf "daemon dot file %s is size %d\n",
            $f, length $him{$f};
    }

In our tied hash DotFiles example, we use a regular hash for the object containing several important fields, of which only the {LIST} field will be what the user thinks of as the real hash.

この DotFiles という tie されたハッシュでは、私たちは {LIST} フィールドのみをユーザーが本当のハッシュであると考えるであろう幾つかの 重要なフィールドを持ったオブジェクトのために、通常のハッシュを 使いました。

USER

whose dot files this object represents

このオブジェクトが表わしているドットファイルの所有者

HOME

where those dot files live

ドットファイルがある場所

CLOBBER

whether we should try to change or remove those dot files

これらのドットファイルを変更したり削除することをしようとすべきか を表わすフラグ

LIST

the hash of dot file names and content mappings

ドットファイルの名前と内容のマッピングをしたハッシュ

Here's the start of Dotfiles.pm:

次は Dotfiles.pm の先頭です:

    package DotFiles;
    use Carp;
    sub whowasi { (caller(1))[3] . '()' }
    my $DEBUG = 0;
    sub debug { $DEBUG = @_ ? shift : 1 }

For our example, we want to be able to emit debugging info to help in tracing during development. We keep also one convenience function around internally to help print out warnings; whowasi() returns the function name that calls it.

この例では、私たちは開発の間トレースがしやすいようにデバッグ情報を 出力できるようにしたいと考えました。 同様に、警告を出力するのを助ける一つの便利な内部関数を残しました; whowasi() は呼び出した関数の名前を返します。

Here are the methods for the DotFiles tied hash.

以下は、DotoFiles に tie されたハッシュのためのメソッドです。

TIEHASH classname, LIST

This is the constructor for the class. That means it is expected to return a blessed reference through which the new object (probably but not necessarily an anonymous hash) will be accessed.

これはこのクラスのコンストラクタです。 その役割は、アクセスされる(おそらくは無名のハッシュ、 ただしそうする必要はない)オブジェクトへの bless された参照を返すことです。

Here's the constructor:

コンストラクタの例です。

    sub TIEHASH {
        my $class = shift;
        my $user = shift || $>;
        my $dotdir = shift || '';
        croak "usage: @{[&whowasi]} [USER [DOTDIR]]" if @_;
        $user = getpwuid($user) if $user =~ /^\d+$/;
        my $dir = (getpwnam($user))[7]
                || croak "@{[&whowasi]}: no user $user";
        $dir .= "/$dotdir" if $dotdir;

        my $node = {
            USER    => $user,
            HOME    => $dir,
            LIST    => {},
            CLOBBER => 0,
        };

        opendir(DIR, $dir)
                || croak "@{[&whowasi]}: can't opendir $dir: $!";
        foreach $dot ( grep /^\./ && -f "$dir/$_", readdir(DIR)) {
            $dot =~ s/^\.//;
            $node->{LIST}{$dot} = undef;
        }
        closedir DIR;
        return bless $node, $class;
    }

It's probably worth mentioning that if you're going to filetest the return values out of a readdir, you'd better prepend the directory in question. Otherwise, because we didn't chdir() there, it would have been testing the wrong file.

readdir が返した値をつかってファイルテストをしようという場合、 問い合わせにディレクトリを付加すべきでしょう。 そうしなければ、chdir() をしていないので間違ったファイルを テストしてしまうこととなります。

FETCH this, key

This method will be triggered every time an element in the tied hash is accessed (read). It takes one argument beyond its self reference: the key whose value we're trying to fetch.

このメソッドは tie されたハッシュがアクセス(読み出し)される度毎に 呼び出されます。 これは自分の参照のほかに、フェッチしようとしている値に対するキーを、 ただ一つの引数としてとります。

Here's the fetch for our DotFiles example.

以下に示すのは、私たちの DotFiles サンプルのためのフェッチです。

    sub FETCH {
        carp &whowasi if $DEBUG;
        my $self = shift;
        my $dot = shift;
        my $dir = $self->{HOME};
        my $file = "$dir/.$dot";

        unless (exists $self->{LIST}->{$dot} || -f $file) {
            carp "@{[&whowasi]}: no $dot file" if $DEBUG;
            return undef;
        }

        if (defined $self->{LIST}->{$dot}) {
            return $self->{LIST}->{$dot};
        } else {
            return $self->{LIST}->{$dot} = `cat $dir/.$dot`;
        }
    }

It was easy to write by having it call the Unix cat(1) command, but it would probably be more portable to open the file manually (and somewhat more efficient). Of course, because dot files are a Unixy concept, we're not that concerned.

UNIX の cat(1) コマンドを呼んでいるので記述するのは簡単でしたが、 ファイルを自分でオープンすることによってよりポータブル(かつ、より高効率)に できます。 もちろん、ドットファイルは UNIX 的なコンセプトですから、 私たちは気にしませんでした。

STORE this, key, value

This method will be triggered every time an element in the tied hash is set (written). It takes two arguments beyond its self reference: the index at which we're trying to store something, and the value we're trying to put there.

このメソッドは tie されたハッシュの要素がセット(書き込み)される度に 呼び出されます。 これは自分の参照の他に二つの引数、何かを格納しようとする場所の添え字と、 格納しようとする値をとります。

Here in our DotFiles example, we'll be careful not to let them try to overwrite the file unless they've called the clobber() method on the original object reference returned by tie().

以下は DotFiles のサンプルです; tie() で返されたオブジェクトの リファレンス上で clobber() メソッドが呼び出されない限り、ファイルを 上書きしないようにしています。

    sub STORE {
        carp &whowasi if $DEBUG;
        my $self = shift;
        my $dot = shift;
        my $value = shift;
        my $file = $self->{HOME} . "/.$dot";
        my $user = $self->{USER};

        croak "@{[&whowasi]}: $file not clobberable"
            unless $self->{CLOBBER};

        open(my $f, '>', $file) || croak "can't open $file: $!";
        print $f $value;
        close($f);
    }

If they wanted to clobber something, they might say:

もし何かを変更したいというのであれば、このようにします。

    $ob = tie %daemon_dots, 'daemon';
    $ob->clobber(1);
    $daemon_dots{signature} = "A true daemon\n";

Another way to lay hands on a reference to the underlying object is to use the tied() function, so they might alternately have set clobber using:

基礎をなすオブジェクトへの参照を扱うもう一つの方法は tied() 関数を 使うことで、これによって clobber を以下の様に使ってセットできます。

    tie %daemon_dots, 'daemon';
    tied(%daemon_dots)->clobber(1);

The clobber method is simply:

clobber メソッドは単純です。

    sub clobber {
        my $self = shift;
        $self->{CLOBBER} = @_ ? shift : 1;
    }
DELETE this, key

This method is triggered when we remove an element from the hash, typically by using the delete() function. Again, we'll be careful to check whether they really want to clobber files.

このメソッドはハッシュから要素を取り除くとき、典型的には delete() 関数を 使ったときに呼び出されます。 繰り返しますが、本当にファイルを clobber したいのかを注意深く検査しています。

 sub DELETE   {
     carp &whowasi if $DEBUG;

     my $self = shift;
     my $dot = shift;
     my $file = $self->{HOME} . "/.$dot";
     croak "@{[&whowasi]}: won't remove file $file"
         unless $self->{CLOBBER};
     delete $self->{LIST}->{$dot};
     my $success = unlink($file);
     carp "@{[&whowasi]}: can't unlink $file: $!" unless $success;
     $success;
 }

The value returned by DELETE becomes the return value of the call to delete(). If you want to emulate the normal behavior of delete(), you should return whatever FETCH would have returned for this key. In this example, we have chosen instead to return a value which tells the caller whether the file was successfully deleted.

DELETE の 返す値は delete() の戻り値から来ています。 もしあなたが通常の delete() の動作をまねしたいというのであれば、 FETCH がこのキーに対して返すであろう値を返すべきでしょう。 この例では、戻り値としてファイルの削除に成功したかどうかを 返すことを選択しました。

CLEAR this

This method is triggered when the whole hash is to be cleared, usually by assigning the empty list to it.

このメソッドはハッシュ全体が消去されるとき、通常は空リストが代入されたときに 呼び出されます。

In our example, that would remove all the user's dot files! It's such a dangerous thing that they'll have to set CLOBBER to something higher than 1 to make it happen.

私たちの例では、これはユーザーのすべてのドットファイルを 削除してしまいます! これはとても危険なことで、実際に削除するには CLOBBER に 1 を超える値を セットすることが必要となります。

 sub CLEAR    {
     carp &whowasi if $DEBUG;
     my $self = shift;
     croak "@{[&whowasi]}: won't remove all dot files for $self->{USER}"
         unless $self->{CLOBBER} > 1;
     my $dot;
     foreach $dot ( keys $self->{LIST}->%* ) {
         $self->DELETE($dot);
     }
 }
EXISTS this, key

This method is triggered when the user uses the exists() function on a particular hash. In our example, we'll look at the {LIST} hash element for this:

このメソッドは特定のハッシュにおいて、exists() 関数が使われたときに 呼び出されます。 私たちの例では、このためにハッシュ要素 {LIST} を参照します。

    sub EXISTS   {
        carp &whowasi if $DEBUG;
        my $self = shift;
        my $dot = shift;
        return exists $self->{LIST}->{$dot};
    }
FIRSTKEY this

This method will be triggered when the user is going to iterate through the hash, such as via a keys(), values(), or each() call.

このメソッドは keys(), values(), each() を呼び出すのと同様に、ハッシュを 通じた反復をユーザーが行おうとするときに呼び出されます。

    sub FIRSTKEY {
        carp &whowasi if $DEBUG;
        my $self = shift;
        my $a = keys $self->{LIST}->%*;  # reset each() iterator
        each $self->{LIST}->%*
    }

FIRSTKEY is always called in scalar context and it should just return the first key. values(), and each() in list context, will call FETCH for the returned keys.

FIRSTKEY は常にスカラコンテキストで呼び出され、単に最初のキーを 返すべきです。 values() と each() はリストコンテキストでは返された値に対して FETCH を 呼び出します。

NEXTKEY this, lastkey

This method gets triggered during a keys(), values(), or each() iteration. It has a second argument which is the last key that had been accessed. This is useful if you're caring about ordering or calling the iterator from more than one sequence, or not really storing things in a hash anywhere.

このメソッドは keys(), values(), each() 反復の間に呼び出されます。 二番目の引数として、最後にアクセスしたキーをとります。 これは、あなたが順番に取り出すとか、二度以上反復子を呼び出したり、 あるいは実際にはハッシュのどこにも格納されていないものであるときに 便利です。

NEXTKEY is always called in scalar context and it should just return the next key. values(), and each() in list context, will call FETCH for the returned keys.

NEXTKEY は常にスカラコンテキストで呼び出され、単に次のキーを 返すべきです。 values() と each() はリストコンテキストでは返された値に対して FETCH を 呼び出します。

For our example, we're using a real hash so we'll do just the simple thing, but we'll have to go through the LIST field indirectly.

私たちの例では本当のハッシュを使うので、やることは簡単です; しかし、 LIST フィールドを間接的に扱わなければなりません。

    sub NEXTKEY  {
        carp &whowasi if $DEBUG;
        my $self = shift;
        return each $self->{LIST}->%*
    }

If the object underlying your tied hash isn't a real hash and you don't have each available, then you should return undef or the empty list once you've reached the end of your list of keys. See each's own documentation for more details.

tie されたハッシュの基になっているオブジェクトが実際のハッシュではなく、 each が利用可能ではない場合、 キーのリストの末尾に到達したら、undef や空リストを返すべきです。 更なる詳細については each's own documentation を 参照してください。

SCALAR this

This is called when the hash is evaluated in scalar context, and in 5.28 onwards, by keys in boolean context. In order to mimic the behaviour of untied hashes, this method must return a value which when used as boolean, indicates whether the tied hash is considered empty. If this method does not exist, perl will make some educated guesses and return true when the hash is inside an iteration. If this isn't the case, FIRSTKEY is called, and the result will be a false value if FIRSTKEY returns the empty list, true otherwise.

これはハッシュがスカラコンテキストで評価されたとき、および 5.28 以降は真偽値コンテキストの keys で評価されたときに 呼び出されます。 tie されていないハッシュの振る舞いを真似るために、 真偽値として使われるときに、tie されたハッシュが空と 考えられるかどうかを示す値を返さなければなりません。 このメソッドが存在しない場合、perl はいくらかの教育された推測を行い、 ハッシュが反復中である場合は真を返します。 もしそうでない場合は、FIRSTKEY が呼び出され、これが空リストを返した場合は 偽の値を返し、さもなければ真の値を返します。

However, you should not blindly rely on perl always doing the right thing. Particularly, perl will mistakenly return true when you clear the hash by repeatedly calling DELETE until it is empty. You are therefore advised to supply your own SCALAR method when you want to be absolutely sure that your hash behaves nicely in scalar context.

しかし、perl が常に正しいことを行うと盲目的に信頼しては いけません。 特に、ハッシュが空になるまで繰り返し DELETE を呼び出すことでハッシュを クリアした場合、perl は間違って真を返します。 従って、ハッシュがスカラコンテキストでもうまく振舞うことを完全に確実に したい場合は、独自の SCALAR メソッドを作ることを勧めます。

In our example we can just call scalar on the underlying hash referenced by $self->{LIST}:

この例では、$self->{LIST} でリファレンスされている、元となる ハッシュで scalar を呼び出しています:

    sub SCALAR {
        carp &whowasi if $DEBUG;
        my $self = shift;
        return scalar $self->{LIST}->%*
    }

NOTE: In perl 5.25 the behavior of scalar %hash on an untied hash changed to return the count of keys. Prior to this it returned a string containing information about the bucket setup of the hash. See "bucket_ratio" in Hash::Util for a backwards compatibility path.

注意: perl 5.25 以降、 tie されていないハッシュに関する scalar %hash の振る舞いは、 キーの数を返すように変更されました。 これ以前は、ハッシュのバケツ設定に関する情報を含む文字列を返していました。 後方互換性のためには "bucket_ratio" in Hash::Util を参照してください。

UNTIE this

This is called when untie occurs. See "The untie Gotcha" below.

これは untie が発生した時に呼び出されます。 後述する "The untie Gotcha" を参照してください。

DESTROY this

This method is triggered when a tied hash is about to go out of scope. You don't really need it unless you're trying to add debugging or have auxiliary state to clean up. Here's a very simple function:

このメソッドは tie されたハッシュがスコープの外に出るときに呼び出されます。 実際には、デバッグ情報を足そうとするとか、後始末のための 補助的な情報を持っていなければ、必要になりません。 以下はとても単純な関数です:

    sub DESTROY  {
        carp &whowasi if $DEBUG;
    }

Note that functions such as keys() and values() may return huge lists when used on large objects, like DBM files. You may prefer to use the each() function to iterate over such. Example:

keys() や values() といった関数は、DBM ファイルのような大きなオブジェクトに 対して使ったときに大きなリストを返す可能性があるということに 注意してください。 そういったものに対して繰り返しの処理を行うには、each() を使うのが 良いでしょう。 例:

    # print out history file offsets
    use NDBM_File;
    tie(%HIST, 'NDBM_File', '/usr/lib/news/history', 1, 0);
    while (($key,$val) = each %HIST) {
        print $key, ' = ', unpack('L',$val), "\n";
    }
    untie(%HIST);

ファイルハンドルを tie する

This is partially implemented now.

これは現時点ではまだ部分的にしか実装されていません。

A class implementing a tied filehandle should define the following methods: TIEHANDLE, at least one of PRINT, PRINTF, WRITE, READLINE, GETC, READ, and possibly CLOSE, UNTIE and DESTROY. The class can also provide: BINMODE, OPEN, EOF, FILENO, SEEK, TELL - if the corresponding perl operators are used on the handle.

tie されたファイルハンドルを実装するクラスは以下のメソッドを定義すべきです: TIEHANDLE と、PRINT, PRINTF, WRITE, READLINE, GETC, READ の 中の少なくともいずれか一つ、そして可能であればCLOSE, UNTIE, DESTROY。 また、クラスは以下のものも提供できます: BINMODE, OPEN, EOF, FILENO, SEEK, TELL - もし対応する perl の演算子がハンドルで つかわれるならです。

When STDERR is tied, its PRINT method will be called to issue warnings and error messages. This feature is temporarily disabled during the call, which means you can use warn() inside PRINT without starting a recursive loop. And just like __WARN__ and __DIE__ handlers, STDERR's PRINT method may be called to report parser errors, so the caveats mentioned under "%SIG" in perlvar apply.

STDERR が tie されると、その PRINT メソッドが、警告とエラーのメッセージを 出力するために呼び出されます。 この機能は呼び出しの最中には一時的に無効にされているので、再帰ループを 作ることなく PRINT の内部で warn() を使えることを意味します。 また、__WARN____DIE__ のハンドラと同様に、STDERR の PRINT メソッドはパーサーエラーの報告に呼び出されるので、"%SIG" in perlvar で 言及した問題点が適用されます。

All of this is especially useful when perl is embedded in some other program, where output to STDOUT and STDERR may have to be redirected in some special way. See nvi and the Apache module for examples.

これら全ては perl が他のプログラムに埋め込まれていて、 STDOUT や STDERR で出力する場所はなんらかの特殊なやり方でリダイレクトする 必要があるときに特に便利です。 実際の例は nvi や Apache モジュールを参照してください。

When tying a handle, the first argument to tie should begin with an asterisk. So, if you are tying STDOUT, use *STDOUT. If you have assigned it to a scalar variable, say $handle, use *$handle. tie $handle ties the scalar variable $handle, not the handle inside it.

ハンドルを tie するとき、tie への最初の引数はアスタリスクで始まります。 それで、STDOUT を tie するときは、*STDOUT を使います。 これを、例えば $handle というスカラ変数に代入するときは、*$handle を 使います。 tie $handle はスカラ変数 $handle の内部にあるハンドルではなく、スカラ 自身を tie します。

In our example we're going to create a shouting handle.

私たちの例では、叫ぶハンドルを生成します。

    package Shout;
TIEHANDLE classname, LIST

This is the constructor for the class. That means it is expected to return a blessed reference of some sort. The reference can be used to hold some internal information.

これはこのクラスのコンストラクタです。 その働きはなにかの bless されたリファレンスを返すことです。 そのリファレンスは内部情報を保持するために使うことができます。

    sub TIEHANDLE { print "<shout>\n"; my $i; bless \$i, shift }
WRITE this, LIST

This method will be called when the handle is written to via the syswrite function.

このメソッドは syswrite 関数を通じてハンドルが書き出されるときに 呼び出されます。

 sub WRITE {
     $r = shift;
     my($buf,$len,$offset) = @_;
     print "WRITE called, \$buf=$buf, \$len=$len, \$offset=$offset";
 }
PRINT this, LIST

This method will be triggered every time the tied handle is printed to with the print() or say() functions. Beyond its self reference it also expects the list that was passed to the print function.

このメソッドは tie されたハンドルに print 関数または say() 関数を 使って出力される度に呼び出されます。 このメソッドは自分の参照のほか、print 関数に渡すリストを受け取ります。

  sub PRINT { $r = shift; $$r++; print join($,,map(uc($_),@_)),$\ }

say() acts just like print() except $\ will be localized to \n so you need do nothing special to handle say() in PRINT().

say()print() と同様に動作しますが、$\ は \n に ローカル化されるので PRINT() の中で say() を扱うために何も特別な ことをする必要はありません。

PRINTF this, LIST

This method will be triggered every time the tied handle is printed to with the printf() function. Beyond its self reference it also expects the format and list that was passed to the printf function.

このメソッドは tie されたハンドルに printf 関数を使って 出力される度に呼び出されます。 このメソッドは自分の参照のほか、printf 関数に渡すリストを受け取ります。

    sub PRINTF {
        shift;
        my $fmt = shift;
        print sprintf($fmt, @_);
    }
READ this, LIST

This method will be called when the handle is read from via the read or sysread functions.

このメソッドはハンドルが readsysread といった関数を通じて 読まれたときに呼び出されます。

 sub READ {
   my $self = shift;
   my $bufref = \$_[0];
   my(undef,$len,$offset) = @_;
   print "READ called, \$buf=$bufref, \$len=$len, \$offset=$offset";
   # add to $$bufref, set $len to number of characters read
   $len;
 }
READLINE this

This method is called when the handle is read via <HANDLE> or readline HANDLE.

このメソッドは <HANDLE> または readline HANDLE を通して ハンドルが読まれたときに呼び出されます。

As per readline, in scalar context it should return the next line, or undef for no more data. In list context it should return all remaining lines, or an empty list for no more data. The strings returned should include the input record separator $/ (see perlvar), unless it is undef (which means "slurp" mode).

readline のように、スカラコンテキストでは次の行を 返すか、もうデータが無いときには undef を返します。 リストコンテキストでは残り全ての行を返すか、もうデータが無いときには 空リストを返します。 返された文字列は入力レコードセパレータ $/ (perlvar 参照) を 含んでいます(undef の場合 (「吸い込み」(slurp) モード) を除きます)。

    sub READLINE {
      my $r = shift;
      if (wantarray) {
        return ("all remaining\n",
                "lines up\n",
                "to eof\n");
      } else {
        return "READLINE called " . ++$$r . " times\n";
      }
    }
GETC this

This method will be called when the getc function is called.

このメソッドは関数 getc が呼ばれたときに呼び出されます。

    sub GETC { print "Don't GETC, Get Perl"; return "a"; }
EOF this

This method will be called when the eof function is called.

このメソッドは、eof 関数が呼び出されたときに呼び出されます。

Starting with Perl 5.12, an additional integer parameter will be passed. It will be zero if eof is called without parameter; 1 if eof is given a filehandle as a parameter, e.g. eof(FH); and 2 in the very special case that the tied filehandle is ARGV and eof is called with an empty parameter list, e.g. eof().

Perl 5.12 から、追加の整数引数が渡されます。 これは、eof が引数なしで呼び出されたら 0 です; eof(FH) のように、 eof がファイルハンドルを引数として呼び出されたら 1 です; tie されたファイルハンドルが ARGV で、eof() のように、eof が 空リストを引数として呼び出されるというとても特殊な場合は 2 です。

    sub EOF { not length $stringbuf }
CLOSE this

This method will be called when the handle is closed via the close function.

このメソッドは、close 関数を通してハンドルがクローズされるときに 呼び出されます。

    sub CLOSE { print "CLOSE called.\n" }
UNTIE this

As with the other types of ties, this method will be called when untie happens. It may be appropriate to "auto CLOSE" when this occurs. See "The untie Gotcha" below.

その他の種類の tie と同様に、このメソッドは untie が起きたときに 呼び出されます。 これが起きたときに、「自動 CLOSE」を行うのに適切です。 後述する "The untie Gotcha" を参照してください。

DESTROY this

As with the other types of ties, this method will be called when the tied handle is about to be destroyed. This is useful for debugging and possibly cleaning up.

他の型に対する tie と同様に、このメソッドは tie されたハンドルが 破棄されるときに呼び出されます。 これはデバッグや後始末をするのに便利です。

    sub DESTROY { print "</shout>\n" }

Here's how to use our little example:

以下は私たちのサンプルをどのように使うかの例です。

    tie(*FOO,'Shout');
    print FOO "hello\n";
    $a = 4; $b = 6;
    print FOO $a, " plus ", $b, " equals ", $a + $b, "\n";
    print <FOO>;

UNTIE this

You can define for all tie types an UNTIE method that will be called at untie(). See "The untie Gotcha" below.

全ての型に対する tie について、untie() で呼び出される UNTIE メソッドを 定義できます。 後述する "The untie Gotcha" を参照してください。

The untie Gotcha

(untie のコツ)

If you intend making use of the object returned from either tie() or tied(), and if the tie's target class defines a destructor, there is a subtle gotcha you must guard against.

tie() や tied() が返したオブジェクトを使おうとするならば、また、 その tie されているターゲットクラスがデストラクタを 定義しているのであれば、あなたが しなければならない 微妙なコツがあります。

As setup, consider this (admittedly rather contrived) example of a tie; all it does is use a file to keep a log of the values assigned to a scalar.

セットアップとして、以下の tie の例を考えてみましょう; これはファイルを 使って、スカラに代入された値を記録し続けるというものです。

    package Remember;

    use v5.36;
    use IO::File;

    sub TIESCALAR {
        my $class = shift;
        my $filename = shift;
        my $handle = IO::File->new( "> $filename" )
                         or die "Cannot open $filename: $!\n";

        print $handle "The Start\n";
        bless {FH => $handle, Value => 0}, $class;
    }

    sub FETCH {
        my $self = shift;
        return $self->{Value};
    }

    sub STORE {
        my $self = shift;
        my $value = shift;
        my $handle = $self->{FH};
        print $handle "$value\n";
        $self->{Value} = $value;
    }

    sub DESTROY {
        my $self = shift;
        my $handle = $self->{FH};
        print $handle "The End\n";
        close $handle;
    }

    1;

Here is an example that makes use of this tie:

次に挙げるのは、この tie を使った例です。

    use strict;
    use Remember;

    my $fred;
    tie $fred, 'Remember', 'myfile.txt';
    $fred = 1;
    $fred = 4;
    $fred = 5;
    untie $fred;
    system "cat myfile.txt";

This is the output when it is executed:

これを実行したときの出力は次のようになります。

    The Start
    1
    4
    5
    The End

So far so good. Those of you who have been paying attention will have spotted that the tied object hasn't been used so far. So lets add an extra method to the Remember class to allow comments to be included in the file; say, something like this:

まずまずですね。 注意深い人は tie されたオブジェクトがここでは使われていないことを 指摘するでしょう。 そこで、Remember クラスにファイルがコメントを含むことを できるようにするメソッドを追加しましょう; そう、このような:

    sub comment {
        my $self = shift;
        my $text = shift;
        my $handle = $self->{FH};
        print $handle $text, "\n";
    }

And here is the previous example modified to use the comment method (which requires the tied object):

次の例は、前の例を comment メソッド(tie されたオブジェクトを 必要とします)を使うために変更したものです。

    use strict;
    use Remember;

    my ($fred, $x);
    $x = tie $fred, 'Remember', 'myfile.txt';
    $fred = 1;
    $fred = 4;
    comment $x "changing...";
    $fred = 5;
    untie $fred;
    system "cat myfile.txt";

When this code is executed there is no output. Here's why:

このコードを実行したとき、なにも出力されません。 その理由はこうです。

When a variable is tied, it is associated with the object which is the return value of the TIESCALAR, TIEARRAY, or TIEHASH function. This object normally has only one reference, namely, the implicit reference from the tied variable. When untie() is called, that reference is destroyed. Then, as in the first example above, the object's destructor (DESTROY) is called, which is normal for objects that have no more valid references; and thus the file is closed.

変数が tie されたとき、それは TIESCALAR, TIEARRAY, TIEHASH といった 関数のいずれかの返した値であるオブジェクトに結び付けられます。 このオブジェクトは、通常はただ一つのリファレンス、すなわち tie され た変数からの暗黙のリファレンスだけを持っています。 untie() が呼ばれたとき、このリファレンスは破棄されます。 したがって、最初の例にあったように、オブジェクトのデストラクタ (DESTROY) が 呼び出されてオブジェクトはもはや正当なリファレンスを持たないようになり、 さらにファイルがクローズされます。

In the second example, however, we have stored another reference to the tied object in $x. That means that when untie() gets called there will still be a valid reference to the object in existence, so the destructor is not called at that time, and thus the file is not closed. The reason there is no output is because the file buffers have not been flushed to disk.

しかしながら二番目の例においては、私たちはもう一つの tie された オブジェクトへのリファレンスを $x の中に格納しました。 これは untie() されたときに、存在するオブジェクトに対する正当な リファレンスがまだ存在しているということです; このためデストラクタは その時には呼び出されません; そしてファイルはクローズされないのです。 何の出力も無かった理由は、ファイルバッファがディスクに フラッシュされていなかったからです。

Now that you know what the problem is, what can you do to avoid it? Prior to the introduction of the optional UNTIE method the only way was the good old -w flag. Which will spot any instances where you call untie() and there are still valid references to the tied object. If the second script above this near the top use warnings 'untie' or was run with the -w flag, Perl prints this warning message:

さて、あなたはもうこれが問題であることがわかったでしょう; では、これを避けるにはどうすればいいでしょうか? 省略可能な UNTIE メソッドが導入される前は、唯一の方法は 古き良き -w オプションだけです。 これははあなたが untie() を呼んだそのときに、(untie() の対象となっている) tie されたオブジェクトに対する正当なリファレンスがまだ存在している場合には それを指摘してくれます。 もし二番目のスクリプトを先頭の方に use warnings 'untie' を付けるか、 -w オプションをつけた状態で実行していれば、 Perl は次のような警告メッセージを出力します。

    untie attempted while 1 inner references still exist

To get the script to work properly and silence the warning make sure there are no valid references to the tied object before untie() is called:

スクリプトを正しく動作させ、警告を黙らせるには tie されたオブジェクトが untie() を呼び出すより 前に 正当なリファレンスをなくすようにします。

    undef $x;
    untie $fred;

Now that UNTIE exists the class designer can decide which parts of the class functionality are really associated with untie and which with the object being destroyed. What makes sense for a given class depends on whether the inner references are being kept so that non-tie-related methods can be called on the object. But in most cases it probably makes sense to move the functionality that would have been in DESTROY to the UNTIE method.

今や UNTIE が存在するので、クラスデザイナーはクラス機能のどの部分が 本当に untie に関連付けられ、どの部分がオブジェクトが破壊されたときに 関連付けられるかを決定できます。 与えられたクラスについてどんな意味があるかは内部のリファレンスが 維持されているかどうかに依存しているので、tie に関係ないメソッドは オブジェクトで呼び出しできます。 しかし、ほとんどの場合、DESTROY にある機能を UNTIE メソッドに移すのが 意味のあることでしょう。

If the UNTIE method exists then the warning above does not occur. Instead the UNTIE method is passed the count of "extra" references and can issue its own warning if appropriate. e.g. to replicate the no UNTIE case this method can be used:

もし UNTIE メソッドが存在するなら、上記の警告は起こりません。 代わりに UNTIE メソッドは「追加の」リファレンスの数が渡され、もし適切なら 自身の警告を出力できます。 例えば、UNTIE がない場合を複製するには、このメソッドが使えます:

 sub UNTIE
 {
  my ($obj,$count) = @_;
  carp "untie attempted while $count inner references still exist"
                                                              if $count;
 }

SEE ALSO

See DB_File or Config for some interesting tie() implementations. A good starting point for many tie() implementations is with one of the modules Tie::Scalar, Tie::Array, Tie::Hash, or Tie::Handle.

興味深い幾つかの tie() の実装については DB_FileConfig を 参照してください。 多くの tie() 実装のためのよい開始点は、モジュール Tie::Scalar, Tie::Array, Tie::Hash, Tie::Handle のいずれかです。

バグ

The normal return provided by scalar(%hash) is not available. What this means is that using %tied_hash in boolean context doesn't work right (currently this always tests false, regardless of whether the hash is empty or hash elements). [ This paragraph needs review in light of changes in 5.25 ]

scalar(%hash) で提供される通常の返り値は利用できません。 これが意味することは、真偽値コンテキストで %tied_hash を使っても正しく 動作しないということです(現在のところ、ハッシュが空かハッシュ要素かに 関わらず、このテストは常に偽となります)。 [ This paragraph needs review in light of changes in 5.25 ]

Localizing tied arrays or hashes does not work. After exiting the scope the arrays or the hashes are not restored.

配列やハッシュのローカル化は動作しません。 スコープの終了後、配列やハッシュの値は元に戻りません。

Counting the number of entries in a hash via scalar(keys(%hash)) or scalar(values(%hash)) is inefficient since it needs to iterate through all the entries with FIRSTKEY/NEXTKEY.

scalar(keys(%hash))scalar(values(%hash)) を使ってハッシュ内の エントリの数を数えることは非効率的です; 全てのエントリに対して FIRSTKEY/NEXTKEY を使って反復する必要があるからです。

Tied hash/array slices cause multiple FETCH/STORE pairs, there are no tie methods for slice operations.

tie されたハッシュや配列のスライスは複数回の FETCH/STORE の組を引き起こします; スライス操作のための tie メソッドはありません。

You cannot easily tie a multilevel data structure (such as a hash of hashes) to a dbm file. The first problem is that all but GDBM and Berkeley DB have size limitations, but beyond that, you also have problems with how references are to be represented on disk. One module that does attempt to address this need is DBM::Deep. Check your nearest CPAN site as described in perlmodlib for source code. Note that despite its name, DBM::Deep does not use dbm. Another earlier attempt at solving the problem is MLDBM, which is also available on the CPAN, but which has some fairly serious limitations.

(ハッシュのハッシュのような)複数レベルのデータ構造を dbm ファイルに tie することは簡単にはできません。 問題は、GDBM と Berkeley DB はサイズに制限があり、それを超えることが できないということで、また、ディスク上にあるものを参照する方法についても 問題があります。 これを解決しようとしているモジュールの一つに、DBM::Deep というものが あります。 ソースコードは perlmodlib にあるように、 あなたのお近くの CPAN サイトを確かめてください。 その名前にも関わらず、DBM::Deep は DBM を使わないことに注意してください。 問題を解決するためのもう一つの初期の試みは MLDBM で、これも CPAN から 利用可能ですが、かなり重大な制限があります。

Tied filehandles are still incomplete. sysopen(), truncate(), flock(), fcntl(), stat() and -X can't currently be trapped.

ファイルハンドルの tie はまだ不完全です。 現在のところ、sysopen(), truncate(), flock(), fcntl(), stat(), -X は トラップできません。

作者

Tom Christiansen

TIEHANDLE by Sven Verdoolaege <skimo@dns.ufsia.ac.be> and Doug MacEachern <dougm@osf.org>

UNTIE by Nick Ing-Simmons <nick@ing-simmons.net>

SCALAR by Tassilo von Parseval <tassilo.von.parseval@rwth-aachen.de>

Tying Arrays by Casey West <casey@geeknest.com>