{
    "mode": "perldoc",
    "parameter": "Hash::Util",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/Hash%3A%3AUtil/json",
    "generated": "2026-06-03T03:35:13Z",
    "synopsis": "# Restricted hashes\nuse Hash::Util qw(\nfieldhash fieldhashes\nallkeys\nlockkeys unlockkeys\nlockvalue unlockvalue\nlockhash unlockhash\nlockkeysplus\nhashlocked hashunlocked\nhashreflocked hashrefunlocked\nhiddenkeys legalkeys\nlockrefkeys unlockrefkeys\nlockrefvalue unlockrefvalue\nlockhashref unlockhashref\nlockrefkeysplus\nhiddenrefkeys legalrefkeys\nhashseed hashvalue hvstore\nbucketstats bucketinfo bucketarray\nlockhashrecurse unlockhashrecurse\nlockhashrefrecurse unlockhashrefrecurse\nhashtraversalmask\n);\n%hash = (foo => 42, bar => 23);\n# Ways to restrict a hash\nlockkeys(%hash);\nlockkeys(%hash, @keyset);\nlockkeysplus(%hash, @additionalkeys);\n# Ways to inspect the properties of a restricted hash\nmy @legal = legalkeys(%hash);\nmy @hidden = hiddenkeys(%hash);\nmy $ref = allkeys(%hash,@keys,@hidden);\nmy $islocked = hashlocked(%hash);\n# Remove restrictions on the hash\nunlockkeys(%hash);\n# Lock individual values in a hash\nlockvalue  (%hash, 'foo');\nunlockvalue(%hash, 'foo');\n# Ways to change the restrictions on both keys and values\nlockhash  (%hash);\nunlockhash(%hash);\nmy $hashesarerandomised = hashseed() !~ /^\\0+$/;\nmy $inthashvalue = hashvalue( 'string' );\nmy $mask= hashtraversalmask(%hash);\nhashtraversalmask(%hash,1234);",
    "sections": {
        "NAME": {
            "content": "Hash::Util - A selection of general-utility hash subroutines\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "# Restricted hashes\n\nuse Hash::Util qw(\nfieldhash fieldhashes\n\nallkeys\nlockkeys unlockkeys\nlockvalue unlockvalue\nlockhash unlockhash\nlockkeysplus\nhashlocked hashunlocked\nhashreflocked hashrefunlocked\nhiddenkeys legalkeys\n\nlockrefkeys unlockrefkeys\nlockrefvalue unlockrefvalue\nlockhashref unlockhashref\nlockrefkeysplus\nhiddenrefkeys legalrefkeys\n\nhashseed hashvalue hvstore\nbucketstats bucketinfo bucketarray\nlockhashrecurse unlockhashrecurse\nlockhashrefrecurse unlockhashrefrecurse\n\nhashtraversalmask\n);\n\n%hash = (foo => 42, bar => 23);\n# Ways to restrict a hash\nlockkeys(%hash);\nlockkeys(%hash, @keyset);\nlockkeysplus(%hash, @additionalkeys);\n\n# Ways to inspect the properties of a restricted hash\nmy @legal = legalkeys(%hash);\nmy @hidden = hiddenkeys(%hash);\nmy $ref = allkeys(%hash,@keys,@hidden);\nmy $islocked = hashlocked(%hash);\n\n# Remove restrictions on the hash\nunlockkeys(%hash);\n\n# Lock individual values in a hash\nlockvalue  (%hash, 'foo');\nunlockvalue(%hash, 'foo');\n\n# Ways to change the restrictions on both keys and values\nlockhash  (%hash);\nunlockhash(%hash);\n\nmy $hashesarerandomised = hashseed() !~ /^\\0+$/;\n\nmy $inthashvalue = hashvalue( 'string' );\n\nmy $mask= hashtraversalmask(%hash);\n\nhashtraversalmask(%hash,1234);\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "\"Hash::Util\" and \"Hash::Util::FieldHash\" contain special functions for manipulating hashes that\ndon't really warrant a keyword.\n\n\"Hash::Util\" contains a set of functions that support restricted hashes. These are described in\nthis document. \"Hash::Util::FieldHash\" contains an (unrelated) set of functions that support the\nuse of hashes in *inside-out classes*, described in Hash::Util::FieldHash.\n\nBy default \"Hash::Util\" does not export anything.\n",
            "subsections": [
                {
                    "name": "Restricted hashes",
                    "content": "5.8.0 introduces the ability to restrict a hash to a certain set of keys. No keys outside of\nthis set can be added. It also introduces the ability to lock an individual key so it cannot be\ndeleted and the ability to ensure that an individual value cannot be changed.\n\nThis is intended to largely replace the deprecated pseudo-hashes.\n\nlockkeys\nunlockkeys\nlockkeys(%hash);\nlockkeys(%hash, @keys);\n\nRestricts the given %hash's set of keys to @keys. If @keys is not given it restricts it to\nits current keyset. No more keys can be added. delete() and exists() will still work, but\nwill not alter the set of allowed keys. Note: the current implementation prevents the hash\nfrom being bless()ed while it is in a locked state. Any attempt to do so will raise an\nexception. Of course you can still bless() the hash before you call lockkeys() so this\nshouldn't be a problem.\n\nunlockkeys(%hash);\n\nRemoves the restriction on the %hash's keyset.\n\nNote that if any of the values of the hash have been locked they will not be unlocked after\nthis sub executes.\n\nBoth routines return a reference to the hash operated on.\n\nlockkeysplus\nlockkeysplus(%hash,@additionalkeys)\n\nSimilar to \"lockkeys()\", with the difference being that the optional key list specifies\nkeys that may or may not be already in the hash. Essentially this is an easier way to say\n\nlockkeys(%hash,@additionalkeys,keys %hash);\n\nReturns a reference to %hash\n\nlockvalue\nunlockvalue\nlockvalue  (%hash, $key);\nunlockvalue(%hash, $key);\n\nLocks and unlocks the value for an individual key of a hash. The value of a locked key\ncannot be changed.\n\nUnless %hash has already been locked the key/value could be deleted regardless of this\nsetting.\n\nReturns a reference to the %hash.\n\nlockhash\nunlockhash\nlockhash(%hash);\n\nlockhash() locks an entire hash, making all keys and values read-only. No value can be\nchanged, no keys can be added or deleted.\n\nunlockhash(%hash);\n\nunlockhash() does the opposite of lockhash(). All keys and values are made writable. All\nvalues can be changed and keys can be added and deleted.\n\nReturns a reference to the %hash.\n\nlockhashrecurse\nunlockhashrecurse\nlockhashrecurse(%hash);\n\nlockhash() locks an entire hash and any hashes it references recursively, making all keys\nand values read-only. No value can be changed, no keys can be added or deleted.\n\nThis method only recurses into hashes that are referenced by another hash. Thus a Hash of\nHashes (HoH) will all be restricted, but a Hash of Arrays of Hashes (HoAoH) will only have\nthe top hash restricted.\n\nunlockhashrecurse(%hash);\n\nunlockhashrecurse() does the opposite of lockhashrecurse(). All keys and values are made\nwritable. All values can be changed and keys can be added and deleted. Identical recursion\nrestrictions apply as to lockhashrecurse().\n\nReturns a reference to the %hash.\n\nhashreflocked\nhashlocked\nhashreflocked(\\%hash) and print \"Hash is locked!\\n\";\nhashlocked(%hash) and print \"Hash is locked!\\n\";\n\nReturns true if the hash and its keys are locked.\n\nhashrefunlocked\nhashunlocked\nhashrefunlocked(\\%hash) and print \"Hash is unlocked!\\n\";\nhashunlocked(%hash) and print \"Hash is unlocked!\\n\";\n\nReturns true if the hash and its keys are unlocked.\n\nlegalkeys\nmy @keys = legalkeys(%hash);\n\nReturns the list of the keys that are legal in a restricted hash. In the case of an\nunrestricted hash this is identical to calling keys(%hash).\n\nhiddenkeys\nmy @keys = hiddenkeys(%hash);\n\nReturns the list of the keys that are legal in a restricted hash but do not have a value\nassociated to them. Thus if 'foo' is a \"hidden\" key of the %hash it will return false for\nboth \"defined\" and \"exists\" tests.\n\nIn the case of an unrestricted hash this will return an empty list.\n\nNOTE this is an experimental feature that is heavily dependent on the current implementation\nof restricted hashes. Should the implementation change, this routine may become meaningless,\nin which case it will return an empty list.\n\nallkeys\nallkeys(%hash,@keys,@hidden);\n\nPopulates the arrays @keys with the all the keys that would pass an \"exists\" tests, and\npopulates @hidden with the remaining legal keys that have not been utilized.\n\nReturns a reference to the hash.\n\nIn the case of an unrestricted hash this will be equivalent to\n\n$ref = do {\n@keys = keys %hash;\n@hidden = ();\n\\%hash\n};\n\nNOTE this is an experimental feature that is heavily dependent on the current implementation\nof restricted hashes. Should the implementation change this routine may become meaningless\nin which case it will behave identically to how it would behave on an unrestricted hash.\n\nhashseed\nmy $hashseed = hashseed();\n\nhashseed() returns the seed bytes used to randomise hash ordering.\n\nNote that the hash seed is sensitive information: by knowing it one can craft a\ndenial-of-service attack against Perl code, even remotely, see \"Algorithmic Complexity\nAttacks\" in perlsec for more information. Do not disclose the hash seed to people who don't\nneed to know it. See also \"PERLHASHSEEDDEBUG\" in perlrun.\n\nPrior to Perl 5.17.6 this function returned a UV, it now returns a string, which may be of\nnearly any size as determined by the hash function your Perl has been built with. Possible\nsizes may be but are not limited to 4 bytes (for most hash algorithms) and 16 bytes (for\nsiphash).\n\nhashvalue\nmy $hashvalue = hashvalue($string);\n\nhashvalue() returns the current perl's internal hash value for a given string.\n\nReturns a 32 bit integer representing the hash value of the string passed in. This value is\nonly reliable for the lifetime of the process. It may be different depending on invocation,\nenvironment variables, perl version, architectures, and build options.\n\nNote that the hash value of a given string is sensitive information: by knowing it one can\ndeduce the hash seed which in turn can allow one to craft a denial-of-service attack against\nPerl code, even remotely, see \"Algorithmic Complexity Attacks\" in perlsec for more\ninformation. Do not disclose the hash value of a string to people who don't need to know it.\nSee also \"PERLHASHSEEDDEBUG\" in perlrun.\n\nbucketinfo\nReturn a set of basic information about a hash.\n\nmy ($keys, $buckets, $used, @lengthcounts)= bucketinfo($hash);\n\nFields are as follows:\n\n0: Number of keys in the hash\n1: Number of buckets in the hash\n2: Number of used buckets in the hash\nrest : list of counts, Kth element is the number of buckets\nwith K keys in it.\n\nSee also bucketstats() and bucketarray().\n\nbucketstats\nReturns a list of statistics about a hash.\n\nmy ($keys, $buckets, $used, $quality, $utilizationratio,\n$collisionpct, $mean, $stddev, @lengthcounts)\n= bucketstats($hashref);\n\nFields are as follows:\n\n0: Number of keys in the hash\n1: Number of buckets in the hash\n2: Number of used buckets in the hash\n3: Hash Quality Score\n4: Percent of buckets used\n5: Percent of keys which are in collision\n6: Mean bucket length of occupied buckets\n7: Standard Deviation of bucket lengths of occupied buckets\nrest : list of counts, Kth element is the number of buckets\nwith K keys in it.\n\nSee also bucketinfo() and bucketarray().\n\nNote that Hash Quality Score would be 1 for an ideal hash, numbers close to and below 1\nindicate good hashing, and number significantly above indicate a poor score. In practice it\nshould be around 0.95 to 1.05. It is defined as:\n\n$score= sum( $count[$length] * ($length * ($length + 1) / 2) )\n/\n( ( $keys / 2 * $buckets ) *\n( $keys + ( 2 * $buckets ) - 1 ) )\n\nThe formula is from the Red Dragon book (reformulated to use the data available) and is\ndocumented at <http://www.strchr.com/hashfunctions>\n\nbucketarray\nmy $array= bucketarray(\\%hash);\n\nReturns a packed representation of the bucket array associated with a hash. Each element of\nthe array is either an integer K, in which case it represents K empty buckets, or a\nreference to another array which contains the keys that are in that bucket.\n\nNote that the information returned by bucketarray is sensitive information: by knowing it\none can directly attack perl's hash function which in turn may allow one to craft a\ndenial-of-service attack against Perl code, even remotely, see \"Algorithmic Complexity\nAttacks\" in perlsec for more information. Do not disclose the output of this function to\npeople who don't need to know it. See also \"PERLHASHSEEDDEBUG\" in perlrun. This function\nis provided strictly for debugging and diagnostics purposes only, it is hard to imagine a\nreason why it would be used in production code.\n\nbucketstatsformatted\nprint bucketstatsformatted($hashref);\n\nReturn a formatted report of the information returned by bucketstats(). An example report\nlooks like this:\n\nKeys: 50 Buckets: 33/64 Quality-Score: 1.01 (Good)\nUtilized Buckets: 51.56% Optimal: 78.12% Keys In Collision: 34.00%\nChain Length - mean: 1.52 stddev: 0.66\nBuckets 64          [0000000000000000000000000000000111111111111111111122222222222333]\nLen   0 Pct:  48.44 [###############################]\nLen   1 Pct:  29.69 [###################]\nLen   2 Pct:  17.19 [###########]\nLen   3 Pct:   4.69 [###]\nKeys    50          [11111111111111111111111111111111122222222222222333]\nPos   1 Pct:  66.00 [#################################]\nPos   2 Pct:  28.00 [##############]\nPos   3 Pct:   6.00 [###]\n\nThe first set of stats gives some summary statistical information, including the quality\nscore translated into \"Good\", \"Poor\" and \"Bad\", (score<=1.05, score<=1.2, score>1.2). See\nthe documentation in bucketstats() for more details.\n\nThe two sets of barcharts give stats and a visual indication of performance of the hash.\n\nThe first gives data on bucket chain lengths and provides insight on how much work a fetch\n*miss* will take. In this case we have to inspect every item in a bucket before we can be\nsure the item is not in the list. The performance for an insert is equivalent to this case,\nas is a delete where the item is not in the hash.\n\nThe second gives data on how many keys are at each depth in the chain, and gives an idea of\nhow much work a fetch *hit* will take. The performance for an update or delete of an item in\nthe hash is equivalent to this case.\n\nNote that these statistics are summary only. Actual performance will depend on real hit/miss\nratios accessing the hash. If you are concerned by hit ratios you are recommended to\n\"oversize\" your hash by using something like:\n\nkeys(%hash)= keys(%hash) << $k;\n\nWith $k chosen carefully, and likely to be a small number like 1 or 2. In theory the larger\nthe bucket array the less chance of collision.\n\nhvstore\nmy $sv = 0;\nhvstore(%hash,$key,$sv) or die \"Failed to alias!\";\n$hash{$key} = 1;\nprint $sv; # prints 1\n\nStores an alias to a variable in a hash instead of copying the value.\n\nhashtraversalmask\nAs of Perl 5.18 every hash has its own hash traversal order, and this order changes every\ntime a new element is inserted into the hash. This functionality is provided by maintaining\nan unsigned integer mask (U32) which is xor'ed with the actual bucket id during a traversal\nof the hash buckets using keys(), values() or each().\n\nYou can use this subroutine to get and set the traversal mask for a specific hash. Setting\nthe mask ensures that a given hash will produce the same key order. Note that this does not\nguarantee that two hashes will produce the same key order for the same hash seed and\ntraversal mask, items that collide into one bucket may have different orders regardless of\nthis setting.\n\nbucketratio\nThis function behaves the same way that scalar(%hash) behaved prior to Perl 5.25.\nSpecifically if the hash is tied, then it calls the SCALAR tied hash method, if untied then\nif the hash is empty it return 0, otherwise it returns a string containing the number of\nused buckets in the hash, followed by a slash, followed by the total number of buckets in\nthe hash.\n\nmy %hash=(\"foo\"=>1);\nprint Hash::Util::bucketratio(%hash); # prints \"1/8\"\n\nusedbuckets\nThis function returns the count of used buckets in the hash. It is expensive to calculate\nand the value is NOT cached, so avoid use of this function in production code.\n\nnumbuckets\nThis function returns the total number of buckets the hash holds, or would hold if the array\nwere created. (When a hash is freshly created the array may not be allocated even though\nthis value will be non-zero.)\n"
                },
                {
                    "name": "Operating on references to hashes.",
                    "content": "Most subroutines documented in this module have equivalent versions that operate on references\nto hashes instead of native hashes. The following is a list of these subs. They are identical\nexcept in name and in that instead of taking a %hash they take a $hashref, and additionally are\nnot prototyped.\n\nlockrefkeys\nunlockrefkeys\nlockrefkeysplus\nlockrefvalue\nunlockrefvalue\nlockhashref\nunlockhashref\nlockhashrefrecurse\nunlockhashrefrecurse\nhashrefunlocked\nlegalrefkeys\nhiddenrefkeys\n"
                }
            ]
        },
        "CAVEATS": {
            "content": "Note that the trapping of the restricted operations is not atomic: for example\n\neval { %hash = (illegalkey => 1) }\n\nleaves the %hash empty rather than with its original contents.\n",
            "subsections": []
        },
        "BUGS": {
            "content": "The interface exposed by this module is very close to the current implementation of restricted\nhashes. Over time it is expected that this behavior will be extended and the interface\nabstracted further.\n",
            "subsections": []
        },
        "AUTHOR": {
            "content": "Michael G Schwern <schwern@pobox.com> on top of code by Nick Ing-Simmons and Jeffrey Friedl.\n",
            "subsections": [
                {
                    "name": "hv_store",
                    "content": "Additional code by Yves Orton.\n"
                }
            ]
        },
        "SEE ALSO": {
            "content": "Scalar::Util, List::Util and \"Algorithmic Complexity Attacks\" in perlsec.\n\nHash::Util::FieldHash.\n",
            "subsections": []
        }
    },
    "summary": "Hash::Util - A selection of general-utility hash subroutines",
    "flags": [],
    "examples": [],
    "see_also": []
}