Storable - persistence for Perl data structures
Storable - Perlデータ構造体の永続化
use Storable;
store \%table, 'file';
$hashref = retrieve('file');
use Storable qw(nstore store_fd nstore_fd freeze thaw dclone);
# Network order
nstore \%table, 'file';
$hashref = retrieve('file'); # There is NO nretrieve()
# ネットワーク様式
nstore \%table, 'file';
$hashref = retrieve('file'); # There is NO nretrieve()
# Storing to and retrieving from an already opened file
store_fd \@array, \*STDOUT;
nstore_fd \%table, \*STDOUT;
$aryref = fd_retrieve(\*SOCKET);
$hashref = fd_retrieve(\*SOCKET);
# 既にオープンされているファイルへ格納し、取込ます
store_fd \@array, \*STDOUT;
nstore_fd \%table, \*STDOUT;
$aryref = fd_retrieve(\*SOCKET);
$hashref = fd_retrieve(\*SOCKET);
# Serializing to memory
$serialized = freeze \%table;
%table_clone = %{ thaw($serialized) };
# メモリへのシリアライズ
$serialized = freeze \%table;
%table_clone = %{ thaw($serialized) };
# Deep (recursive) cloning
$cloneref = dclone($ref);
# 深い(再帰的な)複写
$cloneref = dclone($ref);
# Advisory locking
use Storable qw(lock_store lock_nstore lock_retrieve)
lock_store \%table, 'file';
lock_nstore \%table, 'file';
$hashref = lock_retrieve('file');
# アドバイザリ・ロック
use Storable qw(lock_store lock_nstore lock_retrieve)
lock_store \%table, 'file';
lock_nstore \%table, 'file';
$hashref = lock_retrieve('file');
The Storable package brings persistence to your Perl data structures containing SCALAR, ARRAY, HASH or REF objects, i.e. anything that can be conveniently stored to disk and retrieved at a later time.
Storableパッケージは、スカラー(SCALAR)、配列(ARRAY)、ハッシュ(HASH)、 オブジェクトのリファレンス(REF)を持ったPerlのデータ構造体を永続化します。 つまり簡単にディスクに格納し、後で取り込むことを可能にします。
It can be used in the regular procedural way by calling store with a reference to the object to be stored, along with the file name where the image should be written.
格納するオブジェクトへのリファレンスとイメージが書き込まれるファイル名を 指定してstoreを呼び出すという、通常の手続き的な方法で使うことが出来ます。
The routine returns undef for I/O problems or other internal error, a true value otherwise. Serious errors are propagated as a die exception.
そのルーチンはI/O障害や他の内部エラーが発生するとundefを返し、 そうでなければtrueを返します。重大なエラーはdie例外で伝えられます。
To retrieve data stored to disk, use retrieve with a file name. The objects stored into that file are recreated into memory for you, and a reference to the root object is returned. In case an I/O error occurs while reading, undef is returned instead. Other serious errors are propagated via die.
ディスクに格納されたデータを取り込むには、ファイル名を付けてretrieveを 使います。そしてそのファイルに格納されたオブジェクトはメモリ上に再生成されます。 元になるオブジェクトへのリファレンスが返されます。読込の途中で I/Oエラーが発生すると、undefが代わりに返されます。 他の重大なエラーの場合には、エラーがdieを通じて伝えられます。
Since storage is performed recursively, you might want to stuff references to objects that share a lot of common data into a single array or hash table, and then store that object. That way, when you retrieve back the whole thing, the objects will continue to share what they originally shared.
格納が再帰的に行われるので、共通のデータの多くを共有しているオブジェクトへの リファレンスたちを1つの配列またはハッシュテーブルに詰め込んでしまい、 そのオブジェクトを格納したいと思うかもしれません。この方法では、全体を 取り込んだときに、元々共有していたものを引き続き共有します。
At the cost of a slight header overhead, you may store to an already opened file descriptor using the store_fd routine, and retrieve from a file via fd_retrieve. Those names aren't imported by default, so you will have to do that explicitly if you need those routines. The file descriptor you supply must be already opened, for read if you're going to retrieve and for write if you wish to store.
ヘッダにちょっと手をいれると、store_fdルーチンを使って既に開いている ファイル記述子に格納し、fd_retrieveを通じてファイルから取り出すことが できます。それらの名前はデフォルトではインポートされません。そのため、 これらのルーチンが必要であれば、明示的にインポートしなければいけません。 指定するファイル記述子は、取り込むつもりであれば読み込みread)で、 格納するつもりであれば書き込み(write)で、既に開かれていなければなりません。
store_fd(\%table, *STDOUT) || die "can't store to stdout\n";
$hashref = fd_retrieve(*STDIN);
You can also store data in network order to allow easy sharing across multiple platforms, or when storing on a socket known to be remotely connected. The routines to call have an initial n prefix for network, as in nstore and nstore_fd. At retrieval time, your data will be correctly restored so you don't have to know whether you're restoring from native or network ordered data. Double values are stored stringified to ensure portability as well, at the slight risk of loosing some precision in the last decimals.
複数のプラットホームで共有することを簡単にしたり、リモートに接続されている ことが分かっているソケットに格納するときに、ネットワーク様式で格納することも 出来ます。呼び出すルーチンにはnstoreとnstore_fdのように、頭にnetworkを 表すnが付きます。取り込むときはデータが正しく元に戻るので、取り込むのが ネイティブからなのか、ネットワーク様式のデータからなのかを知る必要は ありません。double(倍精度浮動小数点数型)の値も移植性が保証されるように 文字列化されます。ただし最後の桁の精度が若干失われる危険性があります。
When using fd_retrieve, objects are retrieved in sequence, one object (i.e. one recursive tree) per associated store_fd.
retrieve_fdを使うとき、オブジェクトは、対応するstore_fd毎、 1つのオブジェクト(つまり1つの再帰ツリー)を順番に取り込まれます。
If you're more from the object-oriented camp, you can inherit from Storable and directly store your objects by invoking store as a method. The fact that the root of the to-be-stored tree is a blessed reference (i.e. an object) is special-cased so that the retrieve does not provide a reference to that object but rather the blessed object reference itself. (Otherwise, you'd get a reference to that blessed object).
さらにオブジェクト指向陣営寄りであれば、Storableを継承して、 storeをメソッドとして呼び出すことにより、あなたのオブジェクトを 直接格納することができます。格納されるツリーの元がblessされた リファレンス(つまりオブジェクト)であれば、特別なケースになります。 そのため取込は、そのオブジェクトへのリファレンスを提供せず、 blessされたオブジェクト・リファレンスを提供します。 (そうでなければ、そのblessされたオブジェクトへのリファレンスを 取得することにでしょう)
メモリへの格納¶
The Storable engine can also store data into a Perl scalar instead, to later retrieve them. This is mainly used to freeze a complex structure in some safe compact memory place (where it can possibly be sent to another process via some IPC, since freezing the structure also serializes it in effect). Later on, and maybe somewhere else, you can thaw the Perl scalar out and recreate the original complex structure in memory.
Storableエンジンは後から取り込むために、Perlスカラーにデータを格納する こともできます。これは主に複雑な構造体を安全で小さなメモリ空間に 固めるため(freeze)に使われます(構造体を固めると実際にはシリアライズも されるので、他のプロセスにIPCを通じて送ることも潜在的には可能です)。 後で、そして多分どこか別のところで、Perlスカラを解凍(thaw)し、 元の複雑な構造体をメモリ上に再生成することができます。
Surprisingly, the routines to be called are named freeze and thaw. If you wish to send out the frozen scalar to another machine, use nfreeze instead to get a portable image.
驚いたことに、呼ばれるルーチンの名前はfreezeとthawといいます。 もし固めたスカラを他のマシンに送信したければ、代わりにnfreezeを ポータブルなイメージを取得してください。
Note that freezing an object structure and immediately thawing it actually achieves a deep cloning of that structure:
オブジェクト構造を固め、すぐに解凍すると、実際には、その構造を深く 複写することを実現していることに注意して下さい:
dclone(.) = thaw(freeze(.))
Storable provides you with a dclone interface which does not create that intermediary scalar but instead freezes the structure in some internal memory space and then immediately thaws it out.
Storableは、中間のスカラを作成することなく、代わりに内部メモリ空間に 構造を固め、すぐに解凍するdcloneインターフェイスを提供しています。
アドバイザリ・ロック¶
The lock_store and lock_nstore routine are equivalent to store and nstore, except that they get an exclusive lock on the file before writing. Likewise, lock_retrieve does the same as retrieve, but also gets a shared lock on the file before reading.
lock_storeとlock_nstoreはstoreとnstoreと同じです。ただし、 書き込む前に占有ロックを行います。同様にlock_retrieveはretrieveのように 動きます。しかし読み込む前に共有ロックを行います。
As with any advisory locking scheme, the protection only works if you systematically use lock_store and lock_retrieve. If one side of your application uses store whilst the other uses lock_retrieve, you will get no protection at all.
全てのアドバイザリ・ロックのスキームと同じように、保護はあなたが システマティックにlock_storeとlock_retrieveを使うときにだけ機能します。 もし他の部分がlock_retrieveを使っているときに、あなたのアプリケーションの ある部分がstoreを使うと、何も保護されません。
The internal advisory locking is implemented using Perl's flock() routine. If your system does not support any form of flock(), or if you share your files across NFS, you might wish to use other forms of locking by using modules such as LockFile::Simple which lock a file using a filesystem entry, instead of locking the file descriptor.
アドバイザリ・ロックの内部はPerlのflock()ルーチンを使って実装されます。 もしあなたのシステムがflock()のいかなる形式もサポートしていなかったり、 あなたのファイルをNFS越しにファイルを共有しているのであれば、ファイル記述子ではなく ファイルシステムのエントリを使ってロックするLockFile:Simpleのようなモジュールを 使って他の形式のロックを使いたいことでしょう。
スピード¶
The heart of Storable is written in C for decent speed. Extra low-level optimizations have been made when manipulating perl internals, to sacrifice encapsulation for the benefit of greater speed.
スピードを上げるため、Storableの中核部分はCで書かれています。 Perl内部を操作するとき、 よりスピードを上げるためにカプセル化を犠牲にするという、特別な低レベルの最適化がな されています。
規範形式¶
Normally, Storable stores elements of hashes in the order they are stored internally by Perl, i.e. pseudo-randomly. If you set $Storable::canonical to some TRUE value, Storable will store hashes with the elements sorted by their key. This allows you to compare data structures by comparing their frozen representations (or even the compressed frozen representations), which can be useful for creating lookup tables for complicated queries.
通常StorableはハッシュをPerlが内部的に格納している順序で要素を格納します。つまり 疑似ランダムになります。もし$Storable::canonicalをTRUE値に設定すると、 Storableはハッシュをそのキーの順に要素を格納します。これにより、データ構造体を 固められた形式で(または固められ圧縮され形式でさえ)比較することができるように なります。これは複雑な問い合わせのための参照テーブルを作るのに便利でしょう。
Canonical order does not imply network order; those are two orthogonal settings.
規範様式(=Canonical)はネットワーク様式を意味していません。それらはまったく違う設定です。
コード・リファレンス¶
Since Storable version 2.05, CODE references may be serialized with the help of B::Deparse. To enable this feature, set $Storable::Deparse to a true value. To enable deserializazion, $Storable::Eval should be set to a true value. Be aware that deserialization is done through eval, which is dangerous if the Storable file contains malicious data. You can set $Storable::Eval to a subroutine reference which would be used instead of eval. See below for an example using a Safe compartment for deserialization of CODE references.
Storable バージョン 2.05から、コード(CODE)リファレンスがB::Deparseの 助けを借りてシリアライズできます。この機能を有効にするためには、 $Storable::Deparseをtrue値に設定してください。 デシリアライゼーションを有効にするためには、$Storable::Evalがtrue値に 設定されていなければなりません。デシリアライゼーションがevalを通して 行われることに注意してください。もしStorableファイルに悪意のあるデータが 入っていると危険です。$Storable::Evalにevalの代わりに使われる サブルーチン・リファレンスを設定することができます。 コード(CODE)リファレンスのデシリアライゼーションについては、Safe コンポーネントを使っている下記の例をご覧ください。
将来への互換性¶
This release of Storable can be used on a newer version of Perl to serialize data which is not supported by earlier Perls. By default, Storable will attempt to do the right thing, by croak()ing if it encounters data that it cannot deserialize. However, the defaults can be changed as follows:
今回のStorableのリリースでは、Perlのより新しいバージョンで以前のPerlでは サポートされていなかったデータをシリアライズするために使うことができます。 デフォルトではStorableは適切なことをしようとし、デシリアライズできない データにぶつかったらcroak()します。しかしデフォルトは以下のように 変更することができます:
- utf8 data
-
(utf8データ)
Perl 5.6 added support for Unicode characters with code points > 255, and Perl 5.8 has full support for Unicode characters in hash keys. Perl internally encodes strings with these characters using utf8, and Storable serializes them as utf8. By default, if an older version of Perl encounters a utf8 value it cannot represent, it will croak(). To change this behaviour so that Storable deserializes utf8 encoded values as the string of bytes (effectively dropping the is_utf8 flag) set $Storable::drop_utf8 to some TRUE value. This is a form of data loss, because with $drop_utf8 true, it becomes impossible to tell whether the original data was the Unicode string, or a series of bytes that happen to be valid utf8.
Perl 5.6 は255よりも大きなコード値を持つUnicode文字のサポートが加わりました。 そしてPerl5.8では、ハッシュキーでのフルサポートを持ちます。Perlは内部的に、 これらの文字を持つ文字列をutf8を使ってエンコードします。Storableはutf8として、 それらをシリアライズします。デフォルトでは、より古いバージョンがそれが 表すことが出来ないutf8の値にぶつかると、それはcroak()します。Storableが utf8をバイトの文字列としてエンコードされたものとしてデシリアライズするよう、 この動きを変更するためには、$Storable::drop_utf8を何らかのTRUEの値に 設定してください。これはデータが失われることになります。 というのも$drop_utf8がtrueであると、もとのデータがUnicode文字列だったのか、 たまたまutf8として正しいバイトの並びだったのかが分からなくなってしまいます。
- restricted hashes
-
(限定ハッシュ)
Perl 5.8 adds support for restricted hashes, which have keys restricted to a given set, and can have values locked to be read only. By default, when Storable encounters a restricted hash on a perl that doesn't support them, it will deserialize it as a normal hash, silently discarding any placeholder keys and leaving the keys and all values unlocked. To make Storable croak() instead, set $Storable::downgrade_restricted to a FALSE value. To restore the default set it back to some TRUE value.
Perl 5.8は限定ハッシュ(restricted hash) のサポートを追加します。 それは与えられた集合にのみキーが制限され、値を読込のみにロックすることが 出来ます。デフォルトではそれらをサポートしていないperlではStorableが 限定ハッシュにぶつかると、それを通常のハッシュとしてデシリアライズします。 場所を保持するためのキーを全て黙って処分し、キーと値のロックを全て外します。 代わりにStorableにcroak()させるためには、$Storable::downgrade_restrictedを FALSEの値に設定してください。デフォルトの設定に戻すためには何らかのTRUE値に 戻してください。
- files from future versions of Storable
-
(将来のバージョンのStorableからのファイル)
Earlier versions of Storable would immediately croak if they encountered a file with a higher internal version number than the reading Storable knew about. Internal version numbers are increased each time new data types (such as restricted hashes) are added to the vocabulary of the file format. This meant that a newer Storable module had no way of writing a file readable by an older Storable, even if the writer didn't store newer data types.
以前のStorableは、読んでいるStorableが知っているものより高い内部バージョンを 持ったファイルにぶつかるとすぐにcroakしました。内部バージョン番号は新しいデータ型 (限定ハッシュのような)がファイル形式の用語に加えられるたびに上がります。これは より新しいStorableモジュールには、たとえ新しいデータ型を格納しなかったとしても、 古いStorableで読めるようなファイルを書く方法がないことを意味します。
This version of Storable will defer croaking until it encounters a data type in the file that it does not recognize. This means that it will continue to read files generated by newer Storable modules which are careful in what they write out, making it easier to upgrade Storable modules in a mixed environment.
Storableのこのバージョンは、ファイルの中で、それが理解しないデータ型にぶつかるまで croakしないという点で異なります。つまりこれは出力するものに注意を払えば、 新しいStorableモジュールで作られたファイルでも読むことが出来るということです。 これにより混在する環境でStorableをアップグレードすることが簡単になります。
The old behaviour of immediate croaking can be re-instated by setting $Storable::accept_future_minor to some FALSE value.
$Storable::accept_future_minorをFALSE値にすることにより、即座にcroakする というStorableの古い動きに戻すことが出来ます。
All these variables have no effect on a newer Perl which supports the relevant feature.
これらの変数は関連する機能をサポートしている新しいPerlでは何の効果もありません。
エラー・レポート¶
Storable uses the "exception" paradigm, in that it does not try to workaround failures: if something bad happens, an exception is generated from the caller's perspective (see Carp and croak()). Use eval {} to trap those exceptions.
Storableは"例外"パラダイムを使っています。それでは障害を回避しようとはしません: 何かよくないことが発生したら、呼び出した側の視点で例外が発生します (Carpとcroak()をご覧ください)。それらの例外を捕らえるためにはeval{}を 使ってください。
When Storable croaks, it tries to report the error via the logcroak() routine from the Log::Agent package, if it is available.
Storableがcroakするとき、Log::Agentパッケージが利用できるのであれば、 そのlogcroak()ルーチンを経由してエラーを報告しようとします。
Normal errors are reported by having store() or retrieve() return undef. Such errors are usually I/O errors (or truncated stream errors at retrieval).
通常のエラーはstorable()やretrieve()にundefを返すことにより報告されます。 そのようなエラーは通常I/Oのエラー(あるいはretrieveのさいにストリームが 切り捨てられたか)です。
上級者のみ¶
フック¶
Any class may define hooks that will be called during the serialization and deserialization process on objects that are instances of that class. Those hooks can redefine the way serialization is performed (and therefore, how the symmetrical deserialization should be conducted).
全てのクラスで、そのクラスのインスタンスをシリアライズやデシリアライズの 処理の途中で呼ばれるフックを定義することもできます。それらのフックは 実行されるシリアライゼーションを実行する方法を再定義することが出来ます。 (そのため、対になるデシリアライゼーションも、そのように振舞わなければ なりません)
前述の通り:
dclone(.) = thaw(freeze(.))
everything we say about hooks should also hold for deep cloning. However, hooks get to know whether the operation is a mere serialization, or a cloning.
フックについて述べたことはすべて、深いクローン作成にも当てはまります。 しかしフックには、その処理が単なるシリライゼーションなのかクローンなのかが わかります。
Therefore, when serializing hooks are involved,
このため、シリアライズ化のフックが呼び出されるとになります。
dclone(.) <> thaw(freeze(.))
Well, you could keep them in sync, but there's no guarantee it will always hold on classes somebody else wrote. Besides, there is little to gain in doing so: a serializing hook could keep only one attribute of an object, which is probably not what should happen during a deep cloning of that same object.
同期を取ることもできます。しかし誰か他の人が書いたクラスについて常に 当てはまるような保証はありません。さらに、そうすることによって得られるものは あまりありません:シリアライズのフックは、あるオブジェクトの1つの属性を 保持することだけができます。それは、その同じオブジェクトの深い複写の間に起きる こととは多分、違います。
Here is the hooking interface:
以下にフックのインターフェイスを示します:
STORABLE_freeze obj, cloning
-
The serializing hook, called on the object during serialization. It can be inherited, or defined in the class itself, like any other method.
シリアライズ化フック。オブジェクトがシリアライズされるときに呼ばれます。 これは他のメソッドと同様に継承したり、クラスの中で再定義することができます。
Arguments: obj is the object to serialize, cloning is a flag indicating whether we're in a dclone() or a regular serialization via store() or freeze().
引数:objはシリアラズするオブジェクト、cloningはdclone()の中であるか、 store()やfreeze()を経由した通常のシリアライゼーションかを示します。
Returned value: A LIST ($serialized, $ref1, $ref2, ...) where $serialized is the serialized form to be used, and the optional $ref1, $ref2, etc... are extra references that you wish to let the Storable engine serialize.
戻り値:リスト ($serialized, $ref1, $ref2, ...) 。 $serialized は、 使われるシリアライズされた形式、オプションの$ref1、$ref2などは、 Storableエンジンにシリアラズさせたい特別なリファレンスです。
At deserialization time, you will be given back the same LIST, but all the extra references will be pointing into the deserialized structure.
デシリアライゼーションのときには、あなたは同じリスト(LIST)が与えられます。 しかし特別なリファレンスは全てデシリアライズされた構造体を示します。
The first time the hook is hit in a serialization flow, you may have it return an empty list. That will signal the Storable engine to further discard that hook for this class and to therefore revert to the default serialization of the underlying Perl data. The hook will again be normally processed in the next serialization.
最初にフックがシリアライゼーションの流れの中でヒットしたとき、 あなたは空のリストを返すことができます。それはこのクラスのためのフックを、 それから先、捨てらるようStorableエンジンに合図し、このため元になっている Perlデータのデフォルトのシリアライゼーションに戻ります。そのフックは次の シリアライゼーションでは再び通常通り処理されます。
Unless you know better, serializing hook should always say:
よく分からなければ、シリアライズの フックは以下のようにするべきです:
sub STORABLE_freeze {
my ($self, $cloning) = @_;
return if $cloning; # Regular default serialization
....
}
フックによってStorableエンジンに再帰的に戻ってくることが可能になります。 実際、フックは通常のPerlコードです。そしてStorableは、あるものをシリアライズ したりデシリアライズするときに便利です。それならば、シリアライズされた 文字列を扱うために、それを使っていけないなんてことあるんでしょうか?
CPANから、深いクローン作成をネイティブに、つまりメモリ上に固め、 その結果を解凍することがなしに実装する新しいCloneモジュールが利用できます。 それは将来、Storableのdclone()を置き換えることを目標にしています。 しかし、実行される深いクローン作成の方法を再定義するためのStorableフックは、 まだサポートしていません。