⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 storable.pm

📁 视频监控网络部分的协议ddns,的模块的实现代码,请大家大胆指正.
💻 PM
📖 第 1 页 / 共 3 页
字号:
	eval { $self = pretrieve($file) };		# Call C routine	logcroak $@ if $@ =~ s/\.?\n$/,/;	$@ = $da;	return $self;}## thaw## Recreate objects in memory from an existing frozen image created# by freeze.  If the frozen image passed is undef, return undef.#sub thaw {	my ($frozen) = @_;	return undef unless defined $frozen;	my $self;	my $da = $@;							# Could be from exception handler	eval { $self = mretrieve($frozen) };	# Call C routine	logcroak $@ if $@ =~ s/\.?\n$/,/;	$@ = $da;	return $self;}1;__END__=head1 NAMEStorable - persistence for Perl data structures=head1 SYNOPSIS 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() # 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); # Serializing to memory $serialized = freeze \%table; %table_clone = %{ thaw($serialized) }; # Deep (recursive) cloning $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');=head1 DESCRIPTIONThe Storable package brings persistence to your Perl data structurescontaining SCALAR, ARRAY, HASH or REF objects, i.e. anything that can beconveniently stored to disk and retrieved at a later time.It can be used in the regular procedural way by calling C<store> witha reference to the object to be stored, along with the file name wherethe image should be written.The routine returns C<undef> for I/O problems or other internal error,a true value otherwise. Serious errors are propagated as a C<die> exception.To retrieve data stored to disk, use C<retrieve> with a file name.The objects stored into that file are recreated into memory for you,and a I<reference> to the root object is returned. In case an I/O erroroccurs while reading, C<undef> is returned instead. Other seriouserrors are propagated via C<die>.Since storage is performed recursively, you might want to stuff referencesto objects that share a lot of common data into a single array or hashtable, and then store that object. That way, when you retrieve back thewhole thing, the objects will continue to share what they originally shared.At the cost of a slight header overhead, you may store to an alreadyopened file descriptor using the C<store_fd> routine, and retrievefrom a file via C<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 readif you're going to retrieve and for write if you wish to store.	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 acrossmultiple platforms, or when storing on a socket known to be remotelyconnected. The routines to call have an initial C<n> prefix for I<network>,as in C<nstore> and C<nstore_fd>. At retrieval time, your data will becorrectly restored so you don't have to know whether you're restoringfrom native or network ordered data.  Double values are stored stringifiedto ensure portability as well, at the slight risk of loosing some precisionin the last decimals.When using C<fd_retrieve>, objects are retrieved in sequence, oneobject (i.e. one recursive tree) per associated C<store_fd>.If you're more from the object-oriented camp, you can inherit fromStorable and directly store your objects by invoking C<store> asa method. The fact that the root of the to-be-stored tree is ablessed reference (i.e. an object) is special-cased so that theretrieve does not provide a reference to that object but rather theblessed object reference itself. (Otherwise, you'd get a referenceto that blessed object).=head1 MEMORY STOREThe Storable engine can also store data into a Perl scalar instead, tolater retrieve them. This is mainly used to freeze a complex structure insome safe compact memory place (where it can possibly be sent to anotherprocess via some IPC, since freezing the structure also serializes it ineffect). Later on, and maybe somewhere else, you can thaw the Perl scalarout and recreate the original complex structure in memory.Surprisingly, the routines to be called are named C<freeze> and C<thaw>.If you wish to send out the frozen scalar to another machine, useC<nfreeze> instead to get a portable image.Note that freezing an object structure and immediately thawing itactually achieves a deep cloning of that structure:    dclone(.) = thaw(freeze(.))Storable provides you with a C<dclone> interface which does not createthat intermediary scalar but instead freezes the structure in someinternal memory space and then immediately thaws it out.=head1 ADVISORY LOCKINGThe C<lock_store> and C<lock_nstore> routine are equivalent toC<store> and C<nstore>, except that they get an exclusive lock onthe file before writing.  Likewise, C<lock_retrieve> does the sameas C<retrieve>, but also gets a shared lock on the file before reading.As with any advisory locking scheme, the protection only works if yousystematically use C<lock_store> and C<lock_retrieve>.  If one side ofyour application uses C<store> whilst the other uses C<lock_retrieve>,you will get no protection at all.The internal advisory locking is implemented using Perl's flock()routine.  If your system does not support any form of flock(), or ifyou share your files across NFS, you might wish to use other formsof locking by using modules such as LockFile::Simple which lock afile using a filesystem entry, instead of locking the file descriptor.=head1 SPEEDThe heart of Storable is written in C for decent speed. Extra low-leveloptimizations have been made when manipulating perl internals, tosacrifice encapsulation for the benefit of greater speed.=head1 CANONICAL REPRESENTATIONNormally, Storable stores elements of hashes in the order they arestored internally by Perl, i.e. pseudo-randomly.  If you setC<$Storable::canonical> to some C<TRUE> value, Storable will storehashes with the elements sorted by their key.  This allows you tocompare data structures by comparing their frozen representations (oreven the compressed frozen representations), which can be useful forcreating lookup tables for complicated queries.Canonical order does not imply network order; those are two orthogonalsettings.=head1 CODE REFERENCESSince Storable version 2.05, CODE references may be serialized withthe help of L<B::Deparse>. To enable this feature, setC<$Storable::Deparse> to a true value. To enable deserialization,C<$Storable::Eval> should be set to a true value. Be aware thatdeserialization is done through C<eval>, which is dangerous if theStorable file contains malicious data. You can set C<$Storable::Eval>to a subroutine reference which would be used instead of C<eval>. Seebelow for an example using a L<Safe> compartment for deserializationof CODE references.If C<$Storable::Deparse> and/or C<$Storable::Eval> are set to falsevalues, then the value of C<$Storable::forgive_me> (see below) isrespected while serializing and deserializing.=head1 FORWARD COMPATIBILITYThis release of Storable can be used on a newer version of Perl toserialize data which is not supported by earlier Perls.  By default,Storable will attempt to do the right thing, by C<croak()>ing if itencounters data that it cannot deserialize.  However, the defaultscan be changed as follows:=over 4=item utf8 dataPerl 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, andStorable serializes them as utf8.  By default, if an older version ofPerl encounters a utf8 value it cannot represent, it will C<croak()>.To change this behaviour so that Storable deserializes utf8 encodedvalues as the string of bytes (effectively dropping the I<is_utf8> flag)set C<$Storable::drop_utf8> to some C<TRUE> value.  This is a form ofdata loss, because with C<$drop_utf8> true, it becomes impossible to tellwhether the original data was the Unicode string, or a series of bytesthat happen to be valid utf8.=item restricted hashesPerl 5.8 adds support for restricted hashes, which have keysrestricted to a given set, and can have values locked to be read only.By default, when Storable encounters a restricted hash on a perlthat doesn't support them, it will deserialize it as a normal hash,silently discarding any placeholder keys and leaving the keys andall values unlocked.  To make Storable C<croak()> instead, setC<$Storable::downgrade_restricted> to a C<FALSE> value.  To restorethe default set it back to some C<TRUE> value.=item files from future versions of StorableEarlier versions of Storable would immediately croak if they encountereda file with a higher internal version number than the reading Storableknew about.  Internal version numbers are increased each time new datatypes (such as restricted hashes) are added to the vocabulary of the fileformat.  This meant that a newer Storable module had no way of writing afile readable by an older Storable, even if the writer didn't store newerdata types.This version of Storable will defer croaking until it encounters a datatype in the file that it does not recognize.  This means that it willcontinue to read files generated by newer Storable modules which are carefulin what they write out, making it easier to upgrade Storable modules in amixed environment.The old behaviour of immediate croaking can be re-instated by settingC<$Storable::accept_future_minor> to some C<FALSE> value.=backAll these variables have no effect on a newer Perl which supports therelevant feature.=head1 ERROR REPORTINGStorable uses the "exception" paradigm, in that it does not try to workaroundfailures: if something bad happens, an exception is generated from thecaller's perspective (see L<Carp> and C<croak()>).  Use eval {} to trapthose exceptions.When Storable croaks, it tries to report the error via the C<logcroak()>routine from the C<Log::Agent> package, if it is available.Normal errors are reported by having store() or retrieve() return C<undef>.Such errors are usually I/O errors (or truncated stream errors at retrieval).=head1 WIZARDS ONLY=head2 HooksAny class may define hooks that will be called during the serializationand 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).Since we said earlier:    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 alwayshold on classes somebody else wrote.  Besides, there is little to gain indoing so: a serializing hook could keep only one attribute of an object,which is probably not what should happen during a deep cloning of thatsame object.Here is the hooking interface:=over 4=item C<STORABLE_freeze> I<obj>, I<cloning>The serializing hook, called on the object during serialization.  It can beinherited, or defined in the class itself, like any other method.Arguments: I<obj> is the object to serialize, I<cloning> is a flag indicatingwhether we're in a dclone() or a regular serialization via store() or freeze().Returned value: A LIST C<($serialized, $ref1, $ref2, ...)> where $serializedis the serialized form to be used, and the optional $ref1, $ref2, etc... areextra references that you wish to let the Storable engine serialize.At deserialization time, you will be given back the same LIST, but all theextra references will be pointing into the deserialized structure.The B<first time> the hook is hit in a serialization flow, you may have itreturn an empty list.  That will signal the Storable engine to furtherdiscard that hook for this class and to therefore revert to the defaultserialization of the underlying Perl data.  The hook will again be normallyprocessed in the next serialization.Unless you know better, serializing hook should always say:    sub STORABLE_freeze {        my ($self, $cloning) = @_;        return if $cloning;         # Regular default serialization        ....    }in order to keep reasonable dclone() semantics.=item C<STORABLE_thaw> I<obj>, I<cloning>, I<serialized>, ...The deserializing hook called on the object during deserialization.But wait: if we're deserializing, there's no object yet... right?Wrong: the Storable engine creates an empty one for you.  If you know Eiffel,you can view C<STORABLE_thaw> as an alternate creation routine.This means the hook can be inherited like any other method, and thatI<obj> is your blessed reference for this particular instance.The other arguments should look familiar if you know C<STORABLE_freeze>:I<cloning> is true when we're part of a deep clone operation, I<serialized>is the serialized string you returned to the engine in C<STORABLE_freeze>,and there may be an optional list of references, in the same order you gavethem at serialization time, pointing to the deserialized objects (whichhave been processed courtesy of the Storable engine).When the Storable engine does not find any C<STORABLE_thaw> hook routine,it tries to load the class by requiring the package dynamically (usingthe blessed package name), and then re-attempts the lookup.  If at thattime the hook cannot be located, the engine croaks.  Note that this mechanismwill fail if you define several classes in the same file, but L<perlmod>warned you.It is up to you to use this information to populate I<obj> the way you want.Returned value: none.=item C<STORABLE_attach> I<class>, I<cloning>, I<serialized>While C<STORABLE_freeze> and C<STORABLE_thaw> are useful for classes whereeach instance is independent, this mechanism has difficulty (or isincompatible) with objects that exist as common process-level orsystem-level resources, such as singleton objects, database pools, cachesor memoized objects.The alternative C<STORABLE_attach> method provides a solution for theseshared objects. Instead of C<STORABLE_freeze> --E<gt> C<STORABLE_thaw>,you implement C<STORABLE_freeze> --E<gt> C<STORABLE_attach> instead.Arguments: I<class> is the class we are attaching to, I<cloning> is a flagindicating whether we're in a dclone() or a regular de-serialization viathaw(), and I<serialized> is the stored string for the resource object.Because these resource objects are considered to be owned by the entireprocess/system, and not the "property" of whatever is being serialized,no references underneath the object should be included in the serializedstring. Thus, in any class that implements C<STORABLE_attach>, theC<STORABLE_freeze> method cannot return any references, and C<Storable>will throw an error if C<STORABLE_freeze> tries to return references.All information required to "attach" back to the shared resource objectB<must> be contained B<only> in the C<STORABLE_freeze> return string.Otherwise, C<STORABLE_freeze> behaves as normal for C<STORABLE_attach>classes.Because C<STORABLE_attach> is passed the class (rather than an object),it also returns the object directly, rather than modifying the passedobject.Returned value: object of type C<class>=back=head2 PredicatesPredicates are not exportable.  They must be called by explicitly prefixingthem with the Storable package name.=over 4=item C<Storable::last_op_in_netorder>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -