{
    "mode": "info",
    "parameter": "Storable",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/info/Storable/json",
    "generated": "2026-07-05T23:42:58Z",
    "synopsis": "use Storable;\nstore \\%table, 'file';\n$hashref = retrieve('file');\nuse Storable qw(nstore storefd nstorefd freeze thaw dclone);\n# Network order\nnstore \\%table, 'file';\n$hashref = retrieve('file');   # There is NO nretrieve()\n# Storing to and retrieving from an already opened file\nstorefd \\@array, \\*STDOUT;\nnstorefd \\%table, \\*STDOUT;\n$aryref = fdretrieve(\\*SOCKET);\n$hashref = fdretrieve(\\*SOCKET);\n# Serializing to memory\n$serialized = freeze \\%table;\n%tableclone = %{ thaw($serialized) };\n# Deep (recursive) cloning\n$cloneref = dclone($ref);\n# Advisory locking\nuse Storable qw(lockstore locknstore lockretrieve)\nlockstore \\%table, 'file';\nlocknstore \\%table, 'file';\n$hashref = lockretrieve('file');",
    "sections": {
        "NAME": {
            "content": "Storable - persistence for Perl data structures\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "use Storable;\nstore \\%table, 'file';\n$hashref = retrieve('file');\n\nuse Storable qw(nstore storefd nstorefd freeze thaw dclone);\n\n# Network order\nnstore \\%table, 'file';\n$hashref = retrieve('file');   # There is NO nretrieve()\n\n# Storing to and retrieving from an already opened file\nstorefd \\@array, \\*STDOUT;\nnstorefd \\%table, \\*STDOUT;\n$aryref = fdretrieve(\\*SOCKET);\n$hashref = fdretrieve(\\*SOCKET);\n\n# Serializing to memory\n$serialized = freeze \\%table;\n%tableclone = %{ thaw($serialized) };\n\n# Deep (recursive) cloning\n$cloneref = dclone($ref);\n\n# Advisory locking\nuse Storable qw(lockstore locknstore lockretrieve)\nlockstore \\%table, 'file';\nlocknstore \\%table, 'file';\n$hashref = lockretrieve('file');\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "The Storable package brings persistence to your Perl data structures\ncontaining SCALAR, ARRAY, HASH or REF objects, i.e. anything that can\nbe conveniently stored to disk and retrieved at a later time.\n\nIt can be used in the regular procedural way by calling \"store\" with a\nreference to the object to be stored, along with the file name where\nthe image should be written.\n\nThe routine returns \"undef\" for I/O problems or other internal error, a\ntrue value otherwise. Serious errors are propagated as a \"die\"\nexception.\n\nTo retrieve data stored to disk, use \"retrieve\" with a file name.  The\nobjects stored into that file are recreated into memory for you, and a\nreference to the root object is returned. In case an I/O error occurs\nwhile reading, \"undef\" is returned instead. Other serious errors are\npropagated via \"die\".\n\nSince storage is performed recursively, you might want to stuff\nreferences to objects that share a lot of common data into a single\narray or hash table, and then store that object. That way, when you\nretrieve back the whole thing, the objects will continue to share what\nthey originally shared.\n\nAt the cost of a slight header overhead, you may store to an already\nopened file descriptor using the \"storefd\" routine, and retrieve from\na file via \"fdretrieve\". Those names aren't imported by default, so\nyou will have to do that explicitly if you need those routines.  The\nfile descriptor you supply must be already opened, for read if you're\ngoing to retrieve and for write if you wish to store.\n\nstorefd(\\%table, *STDOUT) || die \"can't store to stdout\\n\";\n$hashref = fdretrieve(*STDIN);\n\nYou can also store data in network order to allow easy sharing across\nmultiple platforms, or when storing on a socket known to be remotely\nconnected. The routines to call have an initial \"n\" prefix for network,\nas in \"nstore\" and \"nstorefd\". At retrieval time, your data will be\ncorrectly restored so you don't have to know whether you're restoring\nfrom native or network ordered data.  Double values are stored\nstringified to ensure portability as well, at the slight risk of\nloosing some precision in the last decimals.\n\nWhen using \"fdretrieve\", objects are retrieved in sequence, one object\n(i.e. one recursive tree) per associated \"storefd\".\n\nIf you're more from the object-oriented camp, you can inherit from\nStorable and directly store your objects by invoking \"store\" as a\nmethod. The fact that the root of the to-be-stored tree is a blessed\nreference (i.e. an object) is special-cased so that the retrieve does\nnot provide a reference to that object but rather the blessed object\nreference itself. (Otherwise, you'd get a reference to that blessed\nobject).\n",
            "subsections": []
        },
        "MEMORY STORE": {
            "content": "The Storable engine can also store data into a Perl scalar instead, to\nlater retrieve them. This is mainly used to freeze a complex structure\nin some safe compact memory place (where it can possibly be sent to\nanother process via some IPC, since freezing the structure also\nserializes it in effect). Later on, and maybe somewhere else, you can\nthaw the Perl scalar out and recreate the original complex structure in\nmemory.\n\nSurprisingly, the routines to be called are named \"freeze\" and \"thaw\".\nIf you wish to send out the frozen scalar to another machine, use\n\"nfreeze\" instead to get a portable image.\n\nNote that freezing an object structure and immediately thawing it\nactually achieves a deep cloning of that structure:\n\ndclone(.) = thaw(freeze(.))\n\nStorable provides you with a \"dclone\" interface which does not create\nthat intermediary scalar but instead freezes the structure in some\ninternal memory space and then immediately thaws it out.\n",
            "subsections": []
        },
        "ADVISORY LOCKING": {
            "content": "The \"lockstore\" and \"locknstore\" routine are equivalent to \"store\"\nand \"nstore\", except that they get an exclusive lock on the file before\nwriting.  Likewise, \"lockretrieve\" does the same as \"retrieve\", but\nalso gets a shared lock on the file before reading.\n\nAs with any advisory locking scheme, the protection only works if you\nsystematically use \"lockstore\" and \"lockretrieve\".  If one side of\nyour application uses \"store\" whilst the other uses \"lockretrieve\",\nyou will get no protection at all.\n\nThe internal advisory locking is implemented using Perl's flock()\nroutine.  If your system does not support any form of flock(), or if\nyou share your files across NFS, you might wish to use other forms of\nlocking by using modules such as LockFile::Simple which lock a file\nusing a filesystem entry, instead of locking the file descriptor.\n",
            "subsections": []
        },
        "SPEED": {
            "content": "The heart of Storable is written in C for decent speed. Extra low-level\noptimizations have been made when manipulating perl internals, to\nsacrifice encapsulation for the benefit of greater speed.\n",
            "subsections": []
        },
        "CANONICAL REPRESENTATION": {
            "content": "Normally, Storable stores elements of hashes in the order they are\nstored internally by Perl, i.e. pseudo-randomly.  If you set\n$Storable::canonical to some \"TRUE\" value, Storable will store hashes\nwith the elements sorted by their key.  This allows you to compare data\nstructures by comparing their frozen representations (or even the\ncompressed frozen representations), which can be useful for creating\nlookup tables for complicated queries.\n\nCanonical order does not imply network order; those are two orthogonal\nsettings.\n",
            "subsections": []
        },
        "CODE REFERENCES": {
            "content": "Since Storable version 2.05, CODE references may be serialized with the\nhelp of B::Deparse. To enable this feature, set $Storable::Deparse to a\ntrue value. To enable deserialization, $Storable::Eval should be set to\na true value. Be aware that deserialization is done through \"eval\",\nwhich is dangerous if the Storable file contains malicious data. You\ncan set $Storable::Eval to a subroutine reference which would be used\ninstead of \"eval\". See below for an example using a Safe compartment\nfor deserialization of CODE references.\n\nIf $Storable::Deparse and/or $Storable::Eval are set to false values,\nthen the value of $Storable::forgiveme (see below) is respected while\nserializing and deserializing.\n",
            "subsections": []
        },
        "FORWARD COMPATIBILITY": {
            "content": "This release of Storable can be used on a newer version of Perl to\nserialize data which is not supported by earlier Perls.  By default,\nStorable will attempt to do the right thing, by \"croak()\"ing if it\nencounters data that it cannot deserialize.  However, the defaults can\nbe changed as follows:\n\nutf8 data\nPerl 5.6 added support for Unicode characters with code points >\n255, and Perl 5.8 has full support for Unicode characters in hash\nkeys.  Perl internally encodes strings with these characters using\nutf8, and Storable serializes them as utf8.  By default, if an\nolder version of Perl encounters a utf8 value it cannot represent,\nit will \"croak()\".  To change this behaviour so that Storable\ndeserializes utf8 encoded values as the string of bytes\n(effectively dropping the isutf8 flag) set $Storable::droputf8 to\nsome \"TRUE\" value.  This is a form of data loss, because with\n$droputf8 true, it becomes impossible to tell whether the original\ndata was the Unicode string, or a series of bytes that happen to be\nvalid utf8.\n\nrestricted hashes\nPerl 5.8 adds support for restricted hashes, which have keys\nrestricted to a given set, and can have values locked to be read\nonly.  By default, when Storable encounters a restricted hash on a\nperl that doesn't support them, it will deserialize it as a normal\nhash, silently discarding any placeholder keys and leaving the keys\nand all values unlocked.  To make Storable \"croak()\" instead, set\n$Storable::downgraderestricted to a \"FALSE\" value.  To restore the\ndefault set it back to some \"TRUE\" value.\n\nThe cperl PERLPERTURBKEYSTOP hash strategy has a known problem\nwith restricted hashes.\n\nhuge objects\nOn 64bit systems some data structures may exceed the 2G (i.e.\nI32MAX) limit. On 32bit systems also strings between I32 and U32\n(2G-4G).  Since Storable 3.00 (not in perl5 core) we are able to\nstore and retrieve these objects, even if perl5 itself is not able\nto handle them.  These are strings longer then 4G, arrays with more\nthen 2G elements and hashes with more then 2G elements. cperl\nforbids hashes with more than 2G elements, but this fail in cperl\nthen. perl5 itself at least until 5.26 allows it, but cannot\niterate over them.  Note that creating those objects might cause\nout of memory exceptions by the operating system before perl has a\nchance to abort.\n\nfiles from future versions of Storable\nEarlier versions of Storable would immediately croak if they\nencountered a file with a higher internal version number than the\nreading Storable knew about.  Internal version numbers are\nincreased each time new data types (such as restricted hashes) are\nadded to the vocabulary of the file format.  This meant that a\nnewer Storable module had no way of writing a file readable by an\nolder Storable, even if the writer didn't store newer data types.\n\nThis version of Storable will defer croaking until it encounters a\ndata type in the file that it does not recognize.  This means that\nit will continue to read files generated by newer Storable modules\nwhich are careful in what they write out, making it easier to\nupgrade Storable modules in a mixed environment.\n\nThe old behaviour of immediate croaking can be re-instated by\nsetting $Storable::acceptfutureminor to some \"FALSE\" value.\n\nAll these variables have no effect on a newer Perl which supports the\nrelevant feature.\n",
            "subsections": []
        },
        "ERROR REPORTING": {
            "content": "Storable uses the \"exception\" paradigm, in that it does not try to\nworkaround failures: if something bad happens, an exception is\ngenerated from the caller's perspective (see Carp and \"croak()\").  Use\neval {} to trap those exceptions.\n\nWhen Storable croaks, it tries to report the error via the \"logcroak()\"\nroutine from the \"Log::Agent\" package, if it is available.\n\nNormal errors are reported by having store() or retrieve() return\n\"undef\".  Such errors are usually I/O errors (or truncated stream\nerrors at retrieval).\n\nWhen Storable throws the \"Max. recursion depth with nested structures\nexceeded\" error we are already out of stack space. Unfortunately on\nsome earlier perl versions cleaning up a recursive data structure\nrecurses into the free calls, which will lead to stack overflows in the\ncleanup. This data structure is not properly cleaned up then, it will\nonly be destroyed during global destruction.\n",
            "subsections": []
        },
        "WIZARDS ONLY": {
            "content": "Hooks\nAny class may define hooks that will be called during the serialization\nand deserialization process on objects that are instances of that\nclass.  Those hooks can redefine the way serialization is performed\n(and therefore, how the symmetrical deserialization should be\nconducted).\n\nSince we said earlier:\n\ndclone(.) = thaw(freeze(.))\n\neverything we say about hooks should also hold for deep cloning.\nHowever, hooks get to know whether the operation is a mere\nserialization, or a cloning.\n\nTherefore, when serializing hooks are involved,\n\ndclone(.) <> thaw(freeze(.))\n\nWell, you could keep them in sync, but there's no guarantee it will\nalways hold on classes somebody else wrote.  Besides, there is little\nto gain in doing so: a serializing hook could keep only one attribute\nof an object, which is probably not what should happen during a deep\ncloning of that same object.\n\nHere is the hooking interface:\n\n\"STORABLEfreeze\" obj, cloning\nThe serializing hook, called on the object during serialization.\nIt can be inherited, or defined in the class itself, like any other\nmethod.\n\nArguments: obj is the object to serialize, cloning is a flag\nindicating whether we're in a dclone() or a regular serialization\nvia store() or freeze().\n\nReturned value: A LIST \"($serialized, $ref1, $ref2, ...)\" where\n$serialized is the serialized form to be used, and the optional\n$ref1, $ref2, etc... are extra references that you wish to let the\nStorable engine serialize.\n\nAt deserialization time, you will be given back the same LIST, but\nall the extra references will be pointing into the deserialized\nstructure.\n\nThe first time the hook is hit in a serialization flow, you may\nhave it return an empty list.  That will signal the Storable engine\nto further discard that hook for this class and to therefore revert\nto the default serialization of the underlying Perl data.  The hook\nwill again be normally processed in the next serialization.\n\nUnless you know better, serializing hook should always say:\n\nsub STORABLEfreeze {\nmy ($self, $cloning) = @;\nreturn if $cloning;         # Regular default serialization\n....\n}\n\nin order to keep reasonable dclone() semantics.\n\n\"STORABLEthaw\" obj, cloning, serialized, ...\nThe deserializing hook called on the object during deserialization.\nBut wait: if we're deserializing, there's no object yet... right?\n\nWrong: the Storable engine creates an empty one for you.  If you\nknow Eiffel, you can view \"STORABLEthaw\" as an alternate creation\nroutine.\n\nThis means the hook can be inherited like any other method, and\nthat obj is your blessed reference for this particular instance.\n\nThe other arguments should look familiar if you know\n\"STORABLEfreeze\": cloning is true when we're part of a deep clone\noperation, serialized is the serialized string you returned to the\nengine in \"STORABLEfreeze\", and there may be an optional list of\nreferences, in the same order you gave them at serialization time,\npointing to the deserialized objects (which have been processed\ncourtesy of the Storable engine).\n\nWhen the Storable engine does not find any \"STORABLEthaw\" hook\nroutine, it tries to load the class by requiring the package\ndynamically (using the blessed package name), and then re-attempts\nthe lookup.  If at that time the hook cannot be located, the engine\ncroaks.  Note that this mechanism will fail if you define several\nclasses in the same file, but perlmod warned you.\n\nIt is up to you to use this information to populate obj the way you\nwant.\n\nReturned value: none.\n\n\"STORABLEattach\" class, cloning, serialized\nWhile \"STORABLEfreeze\" and \"STORABLEthaw\" are useful for classes\nwhere each instance is independent, this mechanism has difficulty\n(or is incompatible) with objects that exist as common process-\nlevel or system-level resources, such as singleton objects,\ndatabase pools, caches or memoized objects.\n\nThe alternative \"STORABLEattach\" method provides a solution for\nthese shared objects. Instead of \"STORABLEfreeze\" -->\n\"STORABLEthaw\", you implement \"STORABLEfreeze\" -->\n\"STORABLEattach\" instead.\n\nArguments: class is the class we are attaching to, cloning is a\nflag indicating whether we're in a dclone() or a regular de-\nserialization via thaw(), and serialized is the stored string for\nthe resource object.\n\nBecause these resource objects are considered to be owned by the\nentire process/system, and not the \"property\" of whatever is being\nserialized, no references underneath the object should be included\nin the serialized string. Thus, in any class that implements\n\"STORABLEattach\", the \"STORABLEfreeze\" method cannot return any\nreferences, and \"Storable\" will throw an error if \"STORABLEfreeze\"\ntries to return references.\n\nAll information required to \"attach\" back to the shared resource\nobject must be contained only in the \"STORABLEfreeze\" return\nstring.  Otherwise, \"STORABLEfreeze\" behaves as normal for\n\"STORABLEattach\" classes.\n\nBecause \"STORABLEattach\" is passed the class (rather than an\nobject), it also returns the object directly, rather than modifying\nthe passed object.\n\nReturned value: object of type \"class\"\n\nPredicates\nPredicates are not exportable.  They must be called by explicitly\nprefixing them with the Storable package name.\n\n\"Storable::lastopinnetorder\"\nThe \"Storable::lastopinnetorder()\" predicate will tell you\nwhether network order was used in the last store or retrieve\noperation.  If you don't know how to use this, just forget about\nit.\n\n\"Storable::isstoring\"\nReturns true if within a store operation (via STORABLEfreeze\nhook).\n\n\"Storable::isretrieving\"\nReturns true if within a retrieve operation (via STORABLEthaw\nhook).\n\nRecursion\nWith hooks comes the ability to recurse back to the Storable engine.\nIndeed, hooks are regular Perl code, and Storable is convenient when it\ncomes to serializing and deserializing things, so why not use it to\nhandle the serialization string?\n\nThere are a few things you need to know, however:\n\no   From Storable 3.05 to 3.13 we probed for the stack recursion limit\nfor references, arrays and hashes to a maximal depth of\n~1200-35000, otherwise we might fall into a stack-overflow.  On\nJSON::XS this limit is 512 btw.  With references not immediately\nreferencing each other there's no such limit yet, so you might fall\ninto such a stack-overflow segfault.\n\nThis probing and the checks we performed have some limitations:\n\no   the stack size at build time might be different at run time,\neg. the stack size may have been modified with ulimit(1).  If\nit's larger at run time Storable may fail the freeze() or\nthaw() unnecessarily.  If it's larger at build time Storable\nmay segmentation fault when processing a deep structure at run\ntime.\n\no   the stack size might be different in a thread.\n\no   array and hash recursion limits are checked separately against\nthe same recursion depth, a frozen structure with a large\nsequence of nested arrays within many nested hashes may exhaust\nthe processor stack without triggering Storable's recursion\nprotection.\n\nSo these now have simple defaults rather than probing at build-\ntime.\n\nYou can control the maximum array and hash recursion depths by\nmodifying $Storable::recursionlimit and\n$Storable::recursionlimithash respectively.  Either can be set to\n\"-1\" to prevent any depth checks, though this isn't recommended.\n\nIf you want to test what the limits are, the stacksize tool is\nincluded in the \"Storable\" distribution.\n\no   You can create endless loops if the things you serialize via\nfreeze() (for instance) point back to the object we're trying to\nserialize in the hook.\n\no   Shared references among objects will not stay shared: if we're\nserializing the list of object [A, C] where both object A and C\nrefer to the SAME object B, and if there is a serializing hook in A\nthat says freeze(B), then when deserializing, we'll get [A', C']\nwhere A' refers to B', but C' refers to D, a deep clone of B'.  The\ntopology was not preserved.\n\no   The maximal stack recursion limit for your system is returned by\n\"stackdepth()\" and \"stackdepthhash()\". The hash limit is usually\nhalf the size of the array and ref limit, as the Perl hash API is\nnot optimal.\n\nThat's why \"STORABLEfreeze\" lets you provide a list of references to\nserialize.  The engine guarantees that those will be serialized in the\nsame context as the other objects, and therefore that shared objects\nwill stay shared.\n\nIn the above [A, C] example, the \"STORABLEfreeze\" hook could return:\n\n(\"something\", $self->{B})\n\nand the B part would be serialized by the engine.  In \"STORABLEthaw\",\nyou would get back the reference to the B' object, deserialized for\nyou.\n\nTherefore, recursion should normally be avoided, but is nonetheless\nsupported.\n\nDeep Cloning\nThere is a Clone module available on CPAN which implements deep cloning\nnatively, i.e. without freezing to memory and thawing the result.  It\nis aimed to replace Storable's dclone() some day.  However, it does not\ncurrently support Storable hooks to redefine the way deep cloning is\nperformed.\n",
            "subsections": []
        },
        "Storable magic": {
            "content": "Yes, there's a lot of that :-) But more precisely, in UNIX systems\nthere's a utility called \"file\", which recognizes data files based on\ntheir contents (usually their first few bytes).  For this to work, a\ncertain file called magic needs to taught about the signature of the\ndata.  Where that configuration file lives depends on the UNIX flavour;\noften it's something like /usr/share/misc/magic or /etc/magic.  Your\nsystem administrator needs to do the updating of the magic file.  The\nnecessary signature information is output to STDOUT by invoking\nStorable::showfilemagic().  Note that the GNU implementation of the\n\"file\" utility, version 3.38 or later, is expected to contain support\nfor recognising Storable files out-of-the-box, in addition to other\nkinds of Perl files.\n\nYou can also use the following functions to extract the file header\ninformation from Storable images:\n\n$info = Storable::filemagic( $filename )\nIf the given file is a Storable image return a hash describing it.\nIf the file is readable, but not a Storable image return \"undef\".\nIf the file does not exist or is unreadable then croak.\n\nThe hash returned has the following elements:\n\n\"version\"\nThis returns the file format version.  It is a string like\n\"2.7\".\n\nNote that this version number is not the same as the version\nnumber of the Storable module itself.  For instance Storable\nv0.7 create files in format v2.0 and Storable v2.15 create\nfiles in format v2.7.  The file format version number only\nincrement when additional features that would confuse older\nversions of the module are added.\n\nFiles older than v2.0 will have the one of the version numbers\n\"-1\", \"0\" or \"1\".  No minor number was used at that time.\n\n\"versionnv\"\nThis returns the file format version as number.  It is a string\nlike \"2.007\".  This value is suitable for numeric comparisons.\n\nThe constant function \"Storable::BINVERSIONNV\" returns a\ncomparable number that represents the highest file version\nnumber that this version of Storable fully supports (but see\ndiscussion of $Storable::acceptfutureminor above).  The\nconstant \"Storable::BINWRITEVERSIONNV\" function returns what\nfile version is written and might be less than\n\"Storable::BINVERSIONNV\" in some configurations.\n\n\"major\", \"minor\"\nThis also returns the file format version.  If the version is\n\"2.7\" then major would be 2 and minor would be 7.  The minor\nelement is missing for when major is less than 2.\n\n\"hdrsize\"\nThe is the number of bytes that the Storable header occupies.\n\n\"netorder\"\nThis is TRUE if the image store data in network order.  This\nmeans that it was created with nstore() or similar.\n\n\"byteorder\"\nThis is only present when \"netorder\" is FALSE.  It is the\n$Config{byteorder} string of the perl that created this image.\nIt is a string like \"1234\" (32 bit little endian) or \"87654321\"\n(64 bit big endian).  This must match the current perl for the\nimage to be readable by Storable.\n\n\"intsize\", \"longsize\", \"ptrsize\", \"nvsize\"\nThese are only present when \"netorder\" is FALSE. These are the\nsizes of various C datatypes of the perl that created this\nimage.  These must match the current perl for the image to be\nreadable by Storable.\n\nThe \"nvsize\" element is only present for file format v2.2 and\nhigher.\n\n\"file\"\nThe name of the file.\n\n$info = Storable::readmagic( $buffer )\n$info = Storable::readmagic( $buffer, $mustbefile )\nThe $buffer should be a Storable image or the first few bytes of\nit.  If $buffer starts with a Storable header, then a hash\ndescribing the image is returned, otherwise \"undef\" is returned.\n\nThe hash has the same structure as the one returned by\nStorable::filemagic().  The \"file\" element is true if the image is\na file image.\n\nIf the $mustbefile argument is provided and is TRUE, then return\n\"undef\" unless the image looks like it belongs to a file dump.\n\nThe maximum size of a Storable header is currently 21 bytes.  If\nthe provided $buffer is only the first part of a Storable image it\nshould at least be this long to ensure that readmagic() will\nrecognize it as such.\n",
            "subsections": []
        },
        "EXAMPLES": {
            "content": "Here are some code samples showing a possible usage of Storable:\n\nuse Storable qw(store retrieve freeze thaw dclone);\n\n%color = ('Blue' => 0.1, 'Red' => 0.8, 'Black' => 0, 'White' => 1);\n\nstore(\\%color, 'mycolors') or die \"Can't store %a in mycolors!\\n\";\n\n$colref = retrieve('mycolors');\ndie \"Unable to retrieve from mycolors!\\n\" unless defined $colref;\nprintf \"Blue is still %lf\\n\", $colref->{'Blue'};\n\n$colref2 = dclone(\\%color);\n\n$str = freeze(\\%color);\nprintf \"Serialization of %%color is %d bytes long.\\n\", length($str);\n$colref3 = thaw($str);\n\nwhich prints (on my machine):\n\nBlue is still 0.100000\nSerialization of %color is 102 bytes long.\n\nSerialization of CODE references and deserialization in a safe\ncompartment:\n\nuse Storable qw(freeze thaw);\nuse Safe;\nuse strict;\nmy $safe = new Safe;\n# because of opcodes used in \"use strict\":\n$safe->permit(qw(:default require));\nlocal $Storable::Deparse = 1;\nlocal $Storable::Eval = sub { $safe->reval($[0]) };\nmy $serialized = freeze(sub { 42 });\nmy $code = thaw($serialized);\n$code->() == 42;\n",
            "subsections": []
        },
        "SECURITY WARNING": {
            "content": "Do not accept Storable documents from untrusted sources!\n\nSome features of Storable can lead to security vulnerabilities if you\naccept Storable documents from untrusted sources with the default\nflags. Most obviously, the optional (off by default) CODE reference\nserialization feature allows transfer of code to the deserializing\nprocess. Furthermore, any serialized object will cause Storable to\nhelpfully load the module corresponding to the class of the object in\nthe deserializing module.  For manipulated module names, this can load\nalmost arbitrary code.  Finally, the deserialized object's destructors\nwill be invoked when the objects get destroyed in the deserializing\nprocess. Maliciously crafted Storable documents may put such objects in\nthe value of a hash key that is overridden by another key/value pair in\nthe same hash, thus causing immediate destructor execution.\n\nTo disable blessing objects while thawing/retrieving remove the flag\n\"BLESSOK\" = 2 from $Storable::flags or set the 2nd argument for\nthaw/retrieve to 0.\n\nTo disable tieing data while thawing/retrieving remove the flag\n\"TIEOK\" = 4 from $Storable::flags or set the 2nd argument for\nthaw/retrieve to 0.\n\nWith the default setting of $Storable::flags = 6, creating or\ndestroying random objects, even renamed objects can be controlled by an\nattacker.  See CVE-2015-1592 and its metasploit module.\n\nIf your application requires accepting data from untrusted sources, you\nare best off with a less powerful and more-likely safe serialization\nformat and implementation. If your data is sufficiently simple,\nCpanel::JSON::XS, Data::MessagePack or Sereal are the best choices and\noffer maximum interoperability, but note that Sereal is unsafe by\ndefault.\n",
            "subsections": []
        },
        "WARNING": {
            "content": "If you're using references as keys within your hash tables, you're\nbound to be disappointed when retrieving your data. Indeed, Perl\nstringifies references used as hash table keys. If you later wish to\naccess the items via another reference stringification (i.e. using the\nsame reference that was used for the key originally to record the value\ninto the hash table), it will work because both references stringify to\nthe same string.\n\nIt won't work across a sequence of \"store\" and \"retrieve\" operations,\nhowever, because the addresses in the retrieved objects, which are part\nof the stringified references, will probably differ from the original\naddresses. The topology of your structure is preserved, but not hidden\nsemantics like those.\n\nOn platforms where it matters, be sure to call \"binmode()\" on the\ndescriptors that you pass to Storable functions.\n\nStoring data canonically that contains large hashes can be\nsignificantly slower than storing the same data normally, as temporary\narrays to hold the keys for each hash have to be allocated, populated,\nsorted and freed.  Some tests have shown a halving of the speed of\nstoring -- the exact penalty will depend on the complexity of your\ndata.  There is no slowdown on retrieval.\n",
            "subsections": []
        },
        "REGULAR EXPRESSIONS": {
            "content": "Storable now has experimental support for storing regular expressions,\nbut there are significant limitations:\n\no   perl 5.8 or later is required.\n\no   regular expressions with code blocks, ie \"/(?{ ... })/\" or \"/(??{\n... })/\" will throw an exception when thawed.\n\no   regular expression syntax and flags have changed over the history\nof perl, so a regular expression that you freeze in one version of\nperl may fail to thaw or behave differently in another version of\nperl.\n\no   depending on the version of perl, regular expressions can change in\nbehaviour depending on the context, but later perls will bake that\nbehaviour into the regexp.\n\nStorable will throw an exception if a frozen regular expression cannot\nbe thawed.\n",
            "subsections": []
        },
        "BUGS": {
            "content": "You can't store GLOB, FORMLINE, etc.... If you can define semantics for\nthose operations, feel free to enhance Storable so that it can deal\nwith them.\n\nThe store functions will \"croak\" if they run into such references\nunless you set $Storable::forgiveme to some \"TRUE\" value. In that\ncase, the fatal message is converted to a warning and some meaningless\nstring is stored instead.\n\nSetting $Storable::canonical may not yield frozen strings that compare\nequal due to possible stringification of numbers. When the string\nversion of a scalar exists, it is the form stored; therefore, if you\nhappen to use your numbers as strings between two freezing operations\non the same data structures, you will get different results.\n\nWhen storing doubles in network order, their value is stored as text.\nHowever, you should also not expect non-numeric floating-point values\nsuch as infinity and \"not a number\" to pass successfully through a\nnstore()/retrieve() pair.\n\nAs Storable neither knows nor cares about character sets (although it\ndoes know that characters may be more than eight bits wide), any\ndifference in the interpretation of character codes between a host and\na target system is your problem.  In particular, if host and target use\ndifferent code points to represent the characters used in the text\nrepresentation of floating-point numbers, you will not be able be able\nto exchange floating-point data, even with nstore().\n\n\"Storable::droputf8\" is a blunt tool.  There is no facility either to\nreturn all strings as utf8 sequences, or to attempt to convert utf8\ndata back to 8 bit and \"croak()\" if the conversion fails.\n\nPrior to Storable 2.01, no distinction was made between signed and\nunsigned integers on storing.  By default Storable prefers to store a\nscalars string representation (if it has one) so this would only cause\nproblems when storing large unsigned integers that had never been\nconverted to string or floating point.  In other words values that had\nbeen generated by integer operations such as logic ops and then not\nused in any string or arithmetic context before storing.\n\n64 bit data in perl 5.6.0 and 5.6.1\nThis section only applies to you if you have existing data written out\nby Storable 2.02 or earlier on perl 5.6.0 or 5.6.1 on Unix or Linux\nwhich has been configured with 64 bit integer support (not the default)\nIf you got a precompiled perl, rather than running Configure to build\nyour own perl from source, then it almost certainly does not affect\nyou, and you can stop reading now (unless you're curious). If you're\nusing perl on Windows it does not affect you.\n\nStorable writes a file header which contains the sizes of various C\nlanguage types for the C compiler that built Storable (when not writing\nin network order), and will refuse to load files written by a Storable\nnot on the same (or compatible) architecture.  This check and a check\non machine byteorder is needed because the size of various fields in\nthe file are given by the sizes of the C language types, and so files\nwritten on different architectures are incompatible.  This is done for\nincreased speed.  (When writing in network order, all fields are\nwritten out as standard lengths, which allows full interworking, but\ntakes longer to read and write)\n\nPerl 5.6.x introduced the ability to optional configure the perl\ninterpreter to use C's \"long long\" type to allow scalars to store 64\nbit integers on 32 bit systems.  However, due to the way the Perl\nconfiguration system generated the C configuration files on non-Windows\nplatforms, and the way Storable generates its header, nothing in the\nStorable file header reflected whether the perl writing was using 32 or\n64 bit integers, despite the fact that Storable was storing some data\ndifferently in the file.  Hence Storable running on perl with 64 bit\nintegers will read the header from a file written by a 32 bit perl, not\nrealise that the data is actually in a subtly incompatible format, and\nthen go horribly wrong (possibly crashing) if it encountered a stored\ninteger.  This is a design failure.\n\nStorable has now been changed to write out and read in a file header\nwith information about the size of integers.  It's impossible to detect\nwhether an old file being read in was written with 32 or 64 bit\nintegers (they have the same header) so it's impossible to\nautomatically switch to a correct backwards compatibility mode.  Hence\nthis Storable defaults to the new, correct behaviour.\n\nWhat this means is that if you have data written by Storable 1.x\nrunning on perl 5.6.0 or 5.6.1 configured with 64 bit integers on Unix\nor Linux then by default this Storable will refuse to read it, giving\nthe error Byte order is not compatible.  If you have such data then you\nshould set $Storable::interwork5664bit to a true value to make this\nStorable read and write files with the old header.  You should also\nmigrate your data, or any older perl you are communicating with, to\nthis current version of Storable.\n\nIf you don't have data written with specific configuration of perl\ndescribed above, then you do not and should not do anything.  Don't set\nthe flag - not only will Storable on an identically configured perl\nrefuse to load them, but Storable a differently configured perl will\nload them believing them to be correct for it, and then may well fail\nor crash part way through reading them.\n",
            "subsections": []
        },
        "CREDITS": {
            "content": "Thank you to (in chronological order):\n\nJarkko Hietaniemi <jhi@iki.fi>\nUlrich Pfeifer <pfeifer@charly.informatik.uni-dortmund.de>\nBenjamin A. Holzman <bholzman@earthlink.net>\nAndrew Ford <A.Ford@ford-mason.co.uk>\nGisle Aas <gisle@aas.no>\nJeff Gresham <greshamjeffrey@jpmorgan.com>\nMurray Nesbitt <murray@activestate.com>\nMarc Lehmann <pcg@opengroup.org>\nJustin Banks <justinb@wamnet.com>\nJarkko Hietaniemi <jhi@iki.fi> (AGAIN, as perl 5.7.0 Pumpkin!)\nSalvador Ortiz Garcia <sog@msg.com.mx>\nDominic Dunlop <domo@computer.org>\nErik Haugan <erik@solbors.no>\nBenjamin A. Holzman <ben.holzman@grantstreet.com>\nReini Urban <rurban@cpan.org>\nTodd Rinaldo <toddr@cpanel.net>\nAaron Crane <arc@cpan.org>\n\nfor their bug reports, suggestions and contributions.\n\nBenjamin Holzman contributed the tied variable support, Andrew Ford\ncontributed the canonical order for hashes, and Gisle Aas fixed a few\nmisunderstandings of mine regarding the perl internals, and optimized\nthe emission of \"tags\" in the output streams by simply counting the\nobjects instead of tagging them (leading to a binary incompatibility\nfor the Storable image starting at version 0.6--older images are, of\ncourse, still properly understood).  Murray Nesbitt made Storable\nthread-safe.  Marc Lehmann added overloading and references to tied\nitems support.  Benjamin Holzman added a performance improvement for\noverloaded classes; thanks to Grant Street Group for footing the bill.\nReini Urban took over maintenance from p5p, and added security fixes\nand huge object support.\n",
            "subsections": []
        },
        "AUTHOR": {
            "content": "Storable was written by Raphael Manfredi <RaphaelManfredi@pobox.com>\nMaintenance is now done by cperl <http://perl11.org/cperl>\n\nPlease e-mail us with problems, bug fixes, comments and complaints,\nalthough if you have compliments you should send them to Raphael.\nPlease don't e-mail Raphael with problems, as he no longer works on\nStorable, and your message will be delayed while he forwards it to us.\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "Clone.\n\nperl v5.34.0                      2026-06-23                   Storable(3perl)",
            "subsections": []
        }
    },
    "summary": "Storable - persistence for Perl data structures",
    "flags": [],
    "examples": [
        "Here are some code samples showing a possible usage of Storable:",
        "use Storable qw(store retrieve freeze thaw dclone);",
        "%color = ('Blue' => 0.1, 'Red' => 0.8, 'Black' => 0, 'White' => 1);",
        "store(\\%color, 'mycolors') or die \"Can't store %a in mycolors!\\n\";",
        "$colref = retrieve('mycolors');",
        "die \"Unable to retrieve from mycolors!\\n\" unless defined $colref;",
        "printf \"Blue is still %lf\\n\", $colref->{'Blue'};",
        "$colref2 = dclone(\\%color);",
        "$str = freeze(\\%color);",
        "printf \"Serialization of %%color is %d bytes long.\\n\", length($str);",
        "$colref3 = thaw($str);",
        "which prints (on my machine):",
        "Blue is still 0.100000",
        "Serialization of %color is 102 bytes long.",
        "Serialization of CODE references and deserialization in a safe",
        "compartment:",
        "use Storable qw(freeze thaw);",
        "use Safe;",
        "use strict;",
        "my $safe = new Safe;",
        "# because of opcodes used in \"use strict\":",
        "$safe->permit(qw(:default require));",
        "local $Storable::Deparse = 1;",
        "local $Storable::Eval = sub { $safe->reval($[0]) };",
        "my $serialized = freeze(sub { 42 });",
        "my $code = thaw($serialized);",
        "$code->() == 42;"
    ],
    "see_also": []
}