{
    "mode": "perldoc",
    "parameter": "Storable",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/Storable/json",
    "generated": "2026-06-15T14:32:53Z",
    "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 containing SCALAR, ARRAY,\nHASH or REF objects, i.e. anything that can be conveniently stored to disk and retrieved at a\nlater time.\n\nIt can be used in the regular procedural way by calling \"store\" with a reference to the object\nto be stored, along with the file name where the image should be written.\n\nThe routine returns \"undef\" for I/O problems or other internal error, a true value otherwise.\nSerious errors are propagated as a \"die\" exception.\n\nTo retrieve data stored to disk, use \"retrieve\" with a file name. The objects stored into that\nfile are recreated into memory for you, and a *reference* to the root object is returned. In\ncase an I/O error occurs while reading, \"undef\" is returned instead. Other serious errors are\npropagated via \"die\".\n\nSince storage is performed recursively, you might want to stuff references to objects that share\na lot of common data into a single array or hash table, and then store that object. That way,\nwhen you retrieve back the whole thing, the objects will continue to share what they originally\nshared.\n\nAt the cost of a slight header overhead, you may store to an already opened file descriptor\nusing the \"storefd\" routine, and retrieve from a file via \"fdretrieve\". Those names aren't\nimported by default, so you will have to do that explicitly if you need those routines. The file\ndescriptor you supply must be already opened, for read if you're going to retrieve and for write\nif 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 multiple platforms, or\nwhen storing on a socket known to be remotely connected. The routines to call have an initial\n\"n\" prefix for *network*, as in \"nstore\" and \"nstorefd\". At retrieval time, your data will be\ncorrectly restored so you don't have to know whether you're restoring from native or network\nordered data. Double values are stored stringified to ensure portability as well, at the slight\nrisk of loosing some precision in the last decimals.\n\nWhen using \"fdretrieve\", objects are retrieved in sequence, one object (i.e. one recursive\ntree) per associated \"storefd\".\n\nIf you're more from the object-oriented camp, you can inherit from Storable and directly store\nyour objects by invoking \"store\" as a method. The fact that the root of the to-be-stored tree is\na blessed reference (i.e. an object) is special-cased so that the retrieve does not provide a\nreference to that object but rather the blessed object reference itself. (Otherwise, you'd get a\nreference to that blessed object).\n",
            "subsections": []
        },
        "MEMORY STORE": {
            "content": "The Storable engine can also store data into a Perl scalar instead, to later retrieve them. This\nis mainly used to freeze a complex structure in some safe compact memory place (where it can\npossibly be sent to another process via some IPC, since freezing the structure also serializes\nit in effect). Later on, and maybe somewhere else, you can thaw the Perl scalar out and recreate\nthe original complex structure in memory.\n\nSurprisingly, the routines to be called are named \"freeze\" and \"thaw\". If you wish to send out\nthe frozen scalar to another machine, use \"nfreeze\" instead to get a portable image.\n\nNote that freezing an object structure and immediately thawing it actually achieves a deep\ncloning of that structure:\n\ndclone(.) = thaw(freeze(.))\n\nStorable provides you with a \"dclone\" interface which does not create that intermediary scalar\nbut instead freezes the structure in some internal memory space and then immediately thaws it\nout.\n",
            "subsections": []
        },
        "ADVISORY LOCKING": {
            "content": "The \"lockstore\" and \"locknstore\" routine are equivalent to \"store\" and \"nstore\", except that\nthey get an exclusive lock on the file before writing. Likewise, \"lockretrieve\" does the same\nas \"retrieve\", but also gets a shared lock on the file before reading.\n\nAs with any advisory locking scheme, the protection only works if you systematically use\n\"lockstore\" and \"lockretrieve\". If one side of your application uses \"store\" whilst the other\nuses \"lockretrieve\", you will get no protection at all.\n\nThe internal advisory locking is implemented using Perl's flock() routine. If your system does\nnot support any form of flock(), or if you share your files across NFS, you might wish to use\nother forms of locking by using modules such as LockFile::Simple which lock a file using a\nfilesystem 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 optimizations have been\nmade when manipulating perl internals, to sacrifice encapsulation for the benefit of greater\nspeed.\n",
            "subsections": []
        },
        "CANONICAL REPRESENTATION": {
            "content": "Normally, Storable stores elements of hashes in the order they are stored internally by Perl,\ni.e. pseudo-randomly. If you set $Storable::canonical to some \"TRUE\" value, Storable will store\nhashes with the elements sorted by their key. This allows you to compare data structures by\ncomparing their frozen representations (or even the compressed frozen representations), which\ncan be useful for creating lookup tables for complicated queries.\n\nCanonical order does not imply network order; those are two orthogonal settings.\n",
            "subsections": []
        },
        "CODE REFERENCES": {
            "content": "Since Storable version 2.05, CODE references may be serialized with the help of B::Deparse. To\nenable this feature, set $Storable::Deparse to a true value. To enable deserialization,\n$Storable::Eval should be set to a true value. Be aware that deserialization is done through\n\"eval\", which is dangerous if the Storable file contains malicious data. You can set\n$Storable::Eval to a subroutine reference which would be used instead of \"eval\". See below for\nan example using a Safe compartment for deserialization of CODE references.\n\nIf $Storable::Deparse and/or $Storable::Eval are set to false values, then the value of\n$Storable::forgiveme (see below) is respected while serializing and deserializing.\n",
            "subsections": []
        },
        "FORWARD COMPATIBILITY": {
            "content": "This release of Storable can be used on a newer version of Perl to serialize data which is not\nsupported by earlier Perls. By default, Storable will attempt to do the right thing, by\n\"croak()\"ing if it encounters data that it cannot deserialize. However, the defaults can be\nchanged as follows:\n\nutf8 data\nPerl 5.6 added support for Unicode characters with code points > 255, and Perl 5.8 has full\nsupport for Unicode characters in hash keys. Perl internally encodes strings with these\ncharacters using utf8, and Storable serializes them as utf8. By default, if an older version\nof Perl encounters a utf8 value it cannot represent, it will \"croak()\". To change this\nbehaviour so that Storable deserializes utf8 encoded values as the string of bytes\n(effectively dropping the *isutf8* flag) set $Storable::droputf8 to some \"TRUE\" value.\nThis is a form of data loss, because with $droputf8 true, it becomes impossible to tell\nwhether the original data 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 restricted to a given set, and\ncan have values locked to be read only. By default, when Storable encounters a restricted\nhash on a perl that doesn't support them, it will deserialize it as a normal hash, silently\ndiscarding any placeholder keys and leaving the keys and all values unlocked. To make\nStorable \"croak()\" instead, set $Storable::downgraderestricted to a \"FALSE\" value. To\nrestore the default set it back to some \"TRUE\" value.\n\nThe cperl PERLPERTURBKEYSTOP hash strategy has a known problem with restricted hashes.\n\nhuge objects\nOn 64bit systems some data structures may exceed the 2G (i.e. I32MAX) limit. On 32bit\nsystems also strings between I32 and U32 (2G-4G). Since Storable 3.00 (not in perl5 core) we\nare able to store and retrieve these objects, even if perl5 itself is not able to handle\nthem. These are strings longer then 4G, arrays with more then 2G elements and hashes with\nmore then 2G elements. cperl forbids hashes with more than 2G elements, but this fail in\ncperl then. perl5 itself at least until 5.26 allows it, but cannot iterate over them. Note\nthat creating those objects might cause out of memory exceptions by the operating system\nbefore perl has a chance to abort.\n\nfiles from future versions of Storable\nEarlier versions of Storable would immediately croak if they encountered a file with a\nhigher internal version number than the reading Storable knew about. Internal version\nnumbers are increased each time new data types (such as restricted hashes) are added to the\nvocabulary of the file format. This meant that a newer Storable module had no way of writing\na file readable by an older Storable, even if the writer didn't store newer data types.\n\nThis version of Storable will defer croaking until it encounters a data type in the file\nthat it does not recognize. This means that it will continue to read files generated by\nnewer Storable modules which are careful in what they write out, making it easier to upgrade\nStorable modules in a mixed environment.\n\nThe old behaviour of immediate croaking can be re-instated by setting\n$Storable::acceptfutureminor to some \"FALSE\" value.\n\nAll these variables have no effect on a newer Perl which supports the relevant feature.\n",
            "subsections": []
        },
        "ERROR REPORTING": {
            "content": "Storable uses the \"exception\" paradigm, in that it does not try to workaround failures: if\nsomething bad happens, an exception is generated from the caller's perspective (see Carp and\n\"croak()\"). Use eval {} to trap those exceptions.\n\nWhen Storable croaks, it tries to report the error via the \"logcroak()\" routine from the\n\"Log::Agent\" package, if it is available.\n\nNormal errors are reported by having store() or retrieve() return \"undef\". Such errors are\nusually I/O errors (or truncated stream errors at retrieval).\n\nWhen Storable throws the \"Max. recursion depth with nested structures exceeded\" error we are\nalready out of stack space. Unfortunately on some earlier perl versions cleaning up a recursive\ndata structure recurses into the free calls, which will lead to stack overflows in the cleanup.\nThis data structure is not properly cleaned up then, it will only be destroyed during global\ndestruction.\n",
            "subsections": []
        },
        "WIZARDS ONLY": {
            "content": "",
            "subsections": [
                {
                    "name": "Hooks",
                    "content": "Any class may define hooks that will be called during the serialization and deserialization\nprocess on objects that are instances of that class. Those hooks can redefine the way\nserialization is performed (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. However, hooks get to know\nwhether the operation is a mere serialization, 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 always hold on classes\nsomebody else wrote. Besides, there is little to gain in doing so: a serializing hook could keep\nonly one attribute of an object, which is probably not what should happen during a deep cloning\nof that same object.\n\nHere is the hooking interface:\n\n\"STORABLEfreeze\" *obj*, *cloning*\nThe serializing hook, called on the object during serialization. It can be inherited, or\ndefined in the class itself, like any other method.\n\nArguments: *obj* is the object to serialize, *cloning* is a flag indicating whether we're in\na dclone() or a regular serialization via store() or freeze().\n\nReturned value: A LIST \"($serialized, $ref1, $ref2, ...)\" where $serialized is the\nserialized form to be used, and the optional $ref1, $ref2, etc... are extra references that\nyou wish to let the Storable engine serialize.\n\nAt deserialization time, you will be given back the same LIST, but all the extra references\nwill be pointing into the deserialized structure.\n\nThe first time the hook is hit in a serialization flow, you may have it return an empty\nlist. That will signal the Storable engine to further discard that hook for this class and\nto therefore revert to the default serialization of the underlying Perl data. The hook will\nagain 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. But wait: if we're\ndeserializing, there's no object yet... right?\n\nWrong: the Storable engine creates an empty one for you. If you know Eiffel, you can view\n\"STORABLEthaw\" as an alternate creation routine.\n\nThis means the hook can be inherited like any other method, and that *obj* is your blessed\nreference for this particular instance.\n\nThe other arguments should look familiar if you know \"STORABLEfreeze\": *cloning* is true\nwhen we're part of a deep clone operation, *serialized* is the serialized string you\nreturned to the engine in \"STORABLEfreeze\", and there may be an optional list of\nreferences, in the same order you gave them at serialization time, pointing to the\ndeserialized objects (which have been processed courtesy of the Storable engine).\n\nWhen the Storable engine does not find any \"STORABLEthaw\" hook routine, it tries to load\nthe class by requiring the package dynamically (using the blessed package name), and then\nre-attempts the lookup. If at that time the hook cannot be located, the engine croaks. Note\nthat this mechanism will fail if you define several classes in the same file, but perlmod\nwarned you.\n\nIt is up to you to use this information to populate *obj* the way you want.\n\nReturned value: none.\n\n\"STORABLEattach\" *class*, *cloning*, *serialized*\nWhile \"STORABLEfreeze\" and \"STORABLEthaw\" are useful for classes where each instance is\nindependent, this mechanism has difficulty (or is incompatible) with objects that exist as\ncommon process-level or system-level resources, such as singleton objects, database pools,\ncaches or memoized objects.\n\nThe alternative \"STORABLEattach\" method provides a solution for these shared objects.\nInstead of \"STORABLEfreeze\" --> \"STORABLEthaw\", you implement \"STORABLEfreeze\" -->\n\"STORABLEattach\" instead.\n\nArguments: *class* is the class we are attaching to, *cloning* is a flag indicating whether\nwe're in a dclone() or a regular de-serialization via thaw(), and *serialized* is the stored\nstring for the resource object.\n\nBecause these resource objects are considered to be owned by the entire process/system, and\nnot the \"property\" of whatever is being serialized, no references underneath the object\nshould be included in the serialized string. Thus, in any class that implements\n\"STORABLEattach\", the \"STORABLEfreeze\" method cannot return any references, and \"Storable\"\nwill throw an error if \"STORABLEfreeze\" tries to return references.\n\nAll information required to \"attach\" back to the shared resource object must be contained\nonly in the \"STORABLEfreeze\" return string. Otherwise, \"STORABLEfreeze\" behaves as normal\nfor \"STORABLEattach\" classes.\n\nBecause \"STORABLEattach\" is passed the class (rather than an object), it also returns the\nobject directly, rather than modifying the passed object.\n\nReturned value: object of type \"class\"\n"
                },
                {
                    "name": "Predicates",
                    "content": "Predicates are not exportable. They must be called by explicitly prefixing them with the\nStorable package name.\n\n\"Storable::lastopinnetorder\"\nThe \"Storable::lastopinnetorder()\" predicate will tell you whether network order was used\nin the last store or retrieve operation. If you don't know how to use this, just forget\nabout it.\n\n\"Storable::isstoring\"\nReturns true if within a store operation (via STORABLEfreeze hook).\n\n\"Storable::isretrieving\"\nReturns true if within a retrieve operation (via STORABLEthaw hook).\n"
                },
                {
                    "name": "Recursion",
                    "content": "With hooks comes the ability to recurse back to the Storable engine. Indeed, hooks are regular\nPerl code, and Storable is convenient when it comes to serializing and deserializing things, so\nwhy not use it to handle the serialization string?\n\nThere are a few things you need to know, however:\n\n*   From Storable 3.05 to 3.13 we probed for the stack recursion limit for references, arrays\nand hashes to a maximal depth of ~1200-35000, otherwise we might fall into a stack-overflow.\nOn JSON::XS this limit is 512 btw. With references not immediately referencing each other\nthere's no such limit yet, so you might fall into such a stack-overflow segfault.\n\nThis probing and the checks we performed have some limitations:\n\n*   the stack size at build time might be different at run time, eg. the stack size may have\nbeen modified with ulimit(1). If it's larger at run time Storable may fail the freeze()\nor thaw() unnecessarily. If it's larger at build time Storable may segmentation fault\nwhen processing a deep structure at run time.\n\n*   the stack size might be different in a thread.\n\n*   array and hash recursion limits are checked separately against the same recursion depth,\na frozen structure with a large sequence of nested arrays within many nested hashes may\nexhaust the processor stack without triggering Storable's recursion protection.\n\nSo these now have simple defaults rather than probing at build-time.\n\nYou can control the maximum array and hash recursion depths by modifying\n$Storable::recursionlimit and $Storable::recursionlimithash respectively. Either can be\nset to -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 included in the \"Storable\"\ndistribution.\n\n*   You can create endless loops if the things you serialize via freeze() (for instance) point\nback to the object we're trying to serialize in the hook.\n\n*   Shared references among objects will not stay shared: if we're serializing the list of\nobject [A, C] where both object A and C refer to the SAME object B, and if there is a\nserializing hook in A that says freeze(B), then when deserializing, we'll get [A', C'] where\nA' refers to B', but C' refers to D, a deep clone of B'. The topology was not preserved.\n\n*   The maximal stack recursion limit for your system is returned by \"stackdepth()\" and\n\"stackdepthhash()\". The hash limit is usually half the size of the array and ref limit, as\nthe Perl hash API is not optimal.\n\nThat's why \"STORABLEfreeze\" lets you provide a list of references to serialize. The engine\nguarantees that those will be serialized in the same context as the other objects, and therefore\nthat shared objects will 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\", you would get back the\nreference to the B' object, deserialized for you.\n\nTherefore, recursion should normally be avoided, but is nonetheless supported.\n"
                },
                {
                    "name": "Deep Cloning",
                    "content": "There is a Clone module available on CPAN which implements deep cloning natively, i.e. without\nfreezing to memory and thawing the result. It is aimed to replace Storable's dclone() some day.\nHowever, it does not currently support Storable hooks to redefine the way deep cloning is\nperformed.\n"
                }
            ]
        },
        "Storable magic": {
            "content": "Yes, there's a lot of that :-) But more precisely, in UNIX systems there's a utility called\n\"file\", which recognizes data files based on their contents (usually their first few bytes). For\nthis to work, a certain file called magic needs to taught about the *signature* of the data.\nWhere that configuration file lives depends on the UNIX flavour; often it's something like\n/usr/share/misc/magic or /etc/magic. Your system administrator needs to do the updating of the\nmagic file. The necessary signature information is output to STDOUT by invoking\nStorable::showfilemagic(). Note that the GNU implementation of the \"file\" utility, version\n3.38 or later, is expected to contain support for recognising Storable files out-of-the-box, in\naddition to other kinds of Perl files.\n\nYou can also use the following functions to extract the file header information from Storable\nimages:\n\n$info = Storable::filemagic( $filename )\nIf the given file is a Storable image return a hash describing it. If the file is readable,\nbut not a Storable image return \"undef\". If the file does not exist or is unreadable then\ncroak.\n\nThe hash returned has the following elements:\n\n\"version\"\nThis returns the file format version. It is a string like \"2.7\".\n\nNote that this version number is not the same as the version number of the Storable\nmodule itself. For instance Storable v0.7 create files in format v2.0 and Storable v2.15\ncreate files in format v2.7. The file format version number only increment when\nadditional features that would confuse older versions of the module are added.\n\nFiles older than v2.0 will have the one of the version numbers \"-1\", \"0\" or \"1\". No\nminor number was used at that time.\n\n\"versionnv\"\nThis returns the file format version as number. It is a string like \"2.007\". This value\nis suitable for numeric comparisons.\n\nThe constant function \"Storable::BINVERSIONNV\" returns a comparable number that\nrepresents the highest file version number that this version of Storable fully supports\n(but see discussion of $Storable::acceptfutureminor above). The constant\n\"Storable::BINWRITEVERSIONNV\" function returns what file version is written and might\nbe less than \"Storable::BINVERSIONNV\" in some configurations.\n\n\"major\", \"minor\"\nThis also returns the file format version. If the version is \"2.7\" then major would be 2\nand minor would be 7. The minor element 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 means that it was created\nwith nstore() or similar.\n\n\"byteorder\"\nThis is only present when \"netorder\" is FALSE. It is the $Config{byteorder} string of\nthe perl that created this image. It is a string like \"1234\" (32 bit little endian) or\n\"87654321\" (64 bit big endian). This must match the current perl for the image to be\nreadable by Storable.\n\n\"intsize\", \"longsize\", \"ptrsize\", \"nvsize\"\nThese are only present when \"netorder\" is FALSE. These are the sizes of various C\ndatatypes of the perl that created this image. These must match the current perl for the\nimage to be readable by Storable.\n\nThe \"nvsize\" element is only present for file format v2.2 and higher.\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 it. If $buffer starts with\na Storable header, then a hash describing the image is returned, otherwise \"undef\" is\nreturned.\n\nThe hash has the same structure as the one returned by Storable::filemagic(). The \"file\"\nelement is true if the image is a file image.\n\nIf the $mustbefile argument is provided and is TRUE, then return \"undef\" unless the image\nlooks like it belongs to a file dump.\n\nThe maximum size of a Storable header is currently 21 bytes. If the provided $buffer is only\nthe first part of a Storable image it should at least be this long to ensure that\nreadmagic() will recognize 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 compartment:\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 accept Storable documents\nfrom untrusted sources with the default flags. Most obviously, the optional (off by default)\nCODE reference serialization feature allows transfer of code to the deserializing process.\nFurthermore, any serialized object will cause Storable to helpfully load the module\ncorresponding to the class of the object in the deserializing module. For manipulated module\nnames, this can load almost arbitrary code. Finally, the deserialized object's destructors will\nbe invoked when the objects get destroyed in the deserializing process. Maliciously crafted\nStorable documents may put such objects in the value of a hash key that is overridden by another\nkey/value pair in the same hash, thus causing immediate destructor execution.\n\nTo disable blessing objects while thawing/retrieving remove the flag \"BLESSOK\" = 2 from\n$Storable::flags or set the 2nd argument for thaw/retrieve to 0.\n\nTo disable tieing data while thawing/retrieving remove the flag \"TIEOK\" = 4 from\n$Storable::flags or set the 2nd argument for thaw/retrieve to 0.\n\nWith the default setting of $Storable::flags = 6, creating or destroying random objects, even\nrenamed objects can be controlled by an attacker. See CVE-2015-1592 and its metasploit module.\n\nIf your application requires accepting data from untrusted sources, you are best off with a less\npowerful and more-likely safe serialization format and implementation. If your data is\nsufficiently simple, Cpanel::JSON::XS, Data::MessagePack or Sereal are the best choices and\noffer maximum interoperability, but note that Sereal is unsafe by default.\n",
            "subsections": []
        },
        "WARNING": {
            "content": "If you're using references as keys within your hash tables, you're bound to be disappointed when\nretrieving your data. Indeed, Perl stringifies references used as hash table keys. If you later\nwish to access the items via another reference stringification (i.e. using the same reference\nthat was used for the key originally to record the value into the hash table), it will work\nbecause both references stringify to the same string.\n\nIt won't work across a sequence of \"store\" and \"retrieve\" operations, however, because the\naddresses in the retrieved objects, which are part of the stringified references, will probably\ndiffer from the original addresses. 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 descriptors that you pass to\nStorable functions.\n\nStoring data canonically that contains large hashes can be significantly slower than storing the\nsame data normally, as temporary arrays to hold the keys for each hash have to be allocated,\npopulated, sorted and freed. Some tests have shown a halving of the speed of storing -- the\nexact penalty will depend on the complexity of your data. There is no slowdown on retrieval.\n",
            "subsections": []
        },
        "REGULAR EXPRESSIONS": {
            "content": "Storable now has experimental support for storing regular expressions, but there are significant\nlimitations:\n\n*   perl 5.8 or later is required.\n\n*   regular expressions with code blocks, ie \"/(?{ ... })/\" or \"/(??{ ... })/\" will throw an\nexception when thawed.\n\n*   regular expression syntax and flags have changed over the history of perl, so a regular\nexpression that you freeze in one version of perl may fail to thaw or behave differently in\nanother version of perl.\n\n*   depending on the version of perl, regular expressions can change in behaviour depending on\nthe context, but later perls will bake that behaviour into the regexp.\n\nStorable will throw an exception if a frozen regular expression cannot be thawed.\n",
            "subsections": []
        },
        "BUGS": {
            "content": "You can't store GLOB, FORMLINE, etc.... If you can define semantics for those operations, feel\nfree to enhance Storable so that it can deal with them.\n\nThe store functions will \"croak\" if they run into such references unless you set\n$Storable::forgiveme to some \"TRUE\" value. In that case, the fatal message is converted to a\nwarning and some meaningless string is stored instead.\n\nSetting $Storable::canonical may not yield frozen strings that compare equal due to possible\nstringification of numbers. When the string version of a scalar exists, it is the form stored;\ntherefore, if you happen to use your numbers as strings between two freezing operations on the\nsame data structures, you will get different results.\n\nWhen storing doubles in network order, their value is stored as text. However, you should also\nnot expect non-numeric floating-point values such as infinity and \"not a number\" to pass\nsuccessfully through a nstore()/retrieve() pair.\n\nAs Storable neither knows nor cares about character sets (although it does know that characters\nmay be more than eight bits wide), any difference in the interpretation of character codes\nbetween a host and a target system is your problem. In particular, if host and target use\ndifferent code points to represent the characters used in the text representation of\nfloating-point numbers, you will not be able be able to exchange floating-point data, even with",
            "subsections": [
                {
                    "name": "nstore",
                    "content": "\"Storable::droputf8\" is a blunt tool. There is no facility either to return all strings as utf8\nsequences, or to attempt to convert utf8 data back to 8 bit and \"croak()\" if the conversion\nfails.\n\nPrior to Storable 2.01, no distinction was made between signed and unsigned integers on storing.\nBy default Storable prefers to store a scalars string representation (if it has one) so this\nwould only cause problems when storing large unsigned integers that had never been converted to\nstring or floating point. In other words values that had been generated by integer operations\nsuch as logic ops and then not used 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 by Storable 2.02 or\nearlier on perl 5.6.0 or 5.6.1 on Unix or Linux which has been configured with 64 bit integer\nsupport (not the default) If you got a precompiled perl, rather than running Configure to build\nyour own perl from source, then it almost certainly does not affect you, and you can stop\nreading now (unless you're curious). If you're using perl on Windows it does not affect you.\n\nStorable writes a file header which contains the sizes of various C language types for the C\ncompiler that built Storable (when not writing in network order), and will refuse to load files\nwritten by a Storable not on the same (or compatible) architecture. This check and a check on\nmachine byteorder is needed because the size of various fields in the file are given by the\nsizes of the C language types, and so files written on different architectures are incompatible.\nThis is done for increased speed. (When writing in network order, all fields are written out as\nstandard lengths, which allows full interworking, but takes longer to read and write)\n\nPerl 5.6.x introduced the ability to optional configure the perl interpreter to use C's \"long\nlong\" type to allow scalars to store 64 bit integers on 32 bit systems. However, due to the way\nthe Perl configuration system generated the C configuration files on non-Windows platforms, and\nthe way Storable generates its header, nothing in the Storable file header reflected whether the\nperl writing was using 32 or 64 bit integers, despite the fact that Storable was storing some\ndata differently in the file. Hence Storable running on perl with 64 bit integers will read the\nheader from a file written by a 32 bit perl, not realise that the data is actually in a subtly\nincompatible format, and then 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 with information about the\nsize of integers. It's impossible to detect whether an old file being read in was written with\n32 or 64 bit integers (they have the same header) so it's impossible to automatically switch to\na correct backwards compatibility mode. Hence this Storable defaults to the new, correct\nbehaviour.\n\nWhat this means is that if you have data written by Storable 1.x running on perl 5.6.0 or 5.6.1\nconfigured with 64 bit integers on Unix or Linux then by default this Storable will refuse to\nread it, giving the error *Byte order is not compatible*. If you have such data then you should\nset $Storable::interwork5664bit to a true value to make this Storable read and write files\nwith the old header. You should also migrate your data, or any older perl you are communicating\nwith, to this current version of Storable.\n\nIf you don't have data written with specific configuration of perl described above, then you do\nnot and should not do anything. Don't set the flag - not only will Storable on an identically\nconfigured perl refuse to load them, but Storable a differently configured perl will load them\nbelieving them to be correct for it, and then may well fail or crash part way through reading\nthem.\n"
                }
            ]
        },
        "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 contributed the canonical\norder for hashes, and Gisle Aas fixed a few misunderstandings of mine regarding the perl\ninternals, and optimized the emission of \"tags\" in the output streams by simply counting the\nobjects instead of tagging them (leading to a binary incompatibility for the Storable image\nstarting at version 0.6--older images are, of course, still properly understood). Murray Nesbitt\nmade Storable thread-safe. Marc Lehmann added overloading and references to tied items support.\nBenjamin Holzman added a performance improvement for overloaded classes; thanks to Grant Street\nGroup for footing the bill. Reini 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> Maintenance is now done by\ncperl <http://perl11.org/cperl>\n\nPlease e-mail us with problems, bug fixes, comments and complaints, although if you have\ncompliments you should send them to Raphael. Please don't e-mail Raphael with problems, as he no\nlonger works on Storable, and your message will be delayed while he forwards it to us.\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "Clone.\n",
            "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": []
}