{
    "mode": "perldoc",
    "parameter": "hash",
    "section": "-q",
    "url": "https://www.chedong.com/phpMan.php/perldoc/hash/json",
    "generated": "2026-08-09T06:49:19Z",
    "sections": {
        "Found in /usr/share/perl/5.38/pod/perlfaq3.pod": {
            "content": "How can I free an array or hash so my program shrinks?\n(contributed by Michael Carman)\n\nYou usually can't. Memory allocated to lexicals (i.e. my() variables)\ncannot be reclaimed or reused even if they go out of scope. It is\nreserved in case the variables come back into scope. Memory allocated to\nglobal variables can be reused (within your program) by using undef()\nand/or delete().\n\nOn most operating systems, memory allocated to a program can never be\nreturned to the system. That's why long-running programs sometimes re-\nexec themselves. Some operating systems (notably, systems that use",
            "subsections": [
                {
                    "name": "mmap",
                    "content": "is no longer used, but on such systems, perl must be configured and\ncompiled to use the OS's malloc, not perl's.\n\nIn general, memory allocation and de-allocation isn't something you can\nor should be worrying about much in Perl.\n\nSee also \"How can I make my Perl program take less memory?\"\n"
                }
            ]
        },
        "Found in /usr/share/perl/5.38/pod/perlfaq4.pod": {
            "content": "How do I test whether two arrays or hashes are equal?\nThe following code works for single-level arrays. It uses a stringwise\ncomparison, and does not distinguish defined versus undefined empty\nstrings. Modify if you have other needs.\n\n$areequal = comparearrays(\\@frogs, \\@toads);\n\nsub comparearrays {\nmy ($first, $second) = @;\nno warnings;  # silence spurious -w undef complaints\nreturn 0 unless @$first == @$second;\nfor (my $i = 0; $i < @$first; $i++) {\nreturn 0 if $first->[$i] ne $second->[$i];\n}\nreturn 1;\n}\n\nFor multilevel structures, you may wish to use an approach more like\nthis one. It uses the CPAN module FreezeThaw:\n\nuse FreezeThaw qw(cmpStr);\nmy @a = my @b = ( \"this\", \"that\", [ \"more\", \"stuff\" ] );\n\nprintf \"a and b contain %s arrays\\n\",\ncmpStr(\\@a, \\@b) == 0\n? \"the same\"\n: \"different\";\n\nThis approach also works for comparing hashes. Here we'll demonstrate\ntwo different answers:\n\nuse FreezeThaw qw(cmpStr cmpStrHard);\n\nmy %a = my %b = ( \"this\" => \"that\", \"extra\" => [ \"more\", \"stuff\" ] );\n$a{EXTRA} = \\%b;\n$b{EXTRA} = \\%a;\n\nprintf \"a and b contain %s hashes\\n\",\ncmpStr(\\%a, \\%b) == 0 ? \"the same\" : \"different\";\n\nprintf \"a and b contain %s hashes\\n\",\ncmpStrHard(\\%a, \\%b) == 0 ? \"the same\" : \"different\";\n\nThe first reports that both those the hashes contain the same data,\nwhile the second reports that they do not. Which you prefer is left as\nan exercise to the reader.\n\nWhy does defined() return true on empty arrays and hashes?\nThe short story is that you should probably only use defined on scalars\nor functions, not on aggregates (arrays and hashes). See \"defined\" in\nperlfunc in the 5.004 release or later of Perl for more detail.\n\nHow do I process an entire hash?\n(contributed by brian d foy)\n\nThere are a couple of ways that you can process an entire hash. You can\nget a list of keys, then go through each key, or grab a one key-value\npair at a time.\n\nTo go through all of the keys, use the \"keys\" function. This extracts\nall of the keys of the hash and gives them back to you as a list. You\ncan then get the value through the particular key you're processing:\n\nforeach my $key ( keys %hash ) {\nmy $value = $hash{$key}\n...\n}\n\nOnce you have the list of keys, you can process that list before you\nprocess the hash elements. For instance, you can sort the keys so you\ncan process them in lexical order:\n\nforeach my $key ( sort keys %hash ) {\nmy $value = $hash{$key}\n...\n}\n\nOr, you might want to only process some of the items. If you only want\nto deal with the keys that start with \"text:\", you can select just those\nusing \"grep\":\n\nforeach my $key ( grep /^text:/, keys %hash ) {\nmy $value = $hash{$key}\n...\n}\n\nIf the hash is very large, you might not want to create a long list of\nkeys. To save some memory, you can grab one key-value pair at a time\nusing each(), which returns a pair you haven't seen yet:\n\nwhile( my( $key, $value ) = each( %hash ) ) {\n...\n}\n\nThe \"each\" operator returns the pairs in apparently random order, so if\nordering matters to you, you'll have to stick with the \"keys\" method.\n\nThe each() operator can be a bit tricky though. You can't add or delete\nkeys of the hash while you're using it without possibly skipping or\nre-processing some pairs after Perl internally rehashes all of the\nelements. Additionally, a hash has only one iterator, so if you mix\n\"keys\", \"values\", or \"each\" on the same hash, you risk resetting the\niterator and messing up your processing. See the \"each\" entry in\nperlfunc for more details.\n\nHow do I merge two hashes?\n(contributed by brian d foy)\n\nBefore you decide to merge two hashes, you have to decide what to do if\nboth hashes contain keys that are the same and if you want to leave the\noriginal hashes as they were.\n\nIf you want to preserve the original hashes, copy one hash (%hash1) to a\nnew hash (%newhash), then add the keys from the other hash (%hash2 to\nthe new hash. Checking that the key already exists in %newhash gives\nyou a chance to decide what to do with the duplicates:\n\nmy %newhash = %hash1; # make a copy; leave %hash1 alone\n\nforeach my $key2 ( keys %hash2 ) {\nif( exists $newhash{$key2} ) {\nwarn \"Key [$key2] is in both hashes!\";\n# handle the duplicate (perhaps only warning)\n...\nnext;\n}\nelse {\n$newhash{$key2} = $hash2{$key2};\n}\n}\n\nIf you don't want to create a new hash, you can still use this looping\ntechnique; just change the %newhash to %hash1.\n\nforeach my $key2 ( keys %hash2 ) {\nif( exists $hash1{$key2} ) {\nwarn \"Key [$key2] is in both hashes!\";\n# handle the duplicate (perhaps only warning)\n...\nnext;\n}\nelse {\n$hash1{$key2} = $hash2{$key2};\n}\n}\n\nIf you don't care that one hash overwrites keys and values from the\nother, you could just use a hash slice to add one hash to another. In\nthis case, values from %hash2 replace values from %hash1 when they have\nkeys in common:\n\n@hash1{ keys %hash2 } = values %hash2;\n\nWhat happens if I add or remove keys from a hash while iterating over it?\n(contributed by brian d foy)\n\nThe easy answer is \"Don't do that!\"\n\nIf you iterate through the hash with each(), you can delete the key most\nrecently returned without worrying about it. If you delete or add other\nkeys, the iterator may skip or double up on them since perl may\nrearrange the hash table. See the entry for each() in perlfunc.\n\nHow do I look up a hash element by value?\nCreate a reverse hash:\n\nmy %byvalue = reverse %bykey;\nmy $key = $byvalue{$value};\n\nThat's not particularly efficient. It would be more space-efficient to\nuse:\n\nwhile (my ($key, $value) = each %bykey) {\n$byvalue{$value} = $key;\n}\n\nIf your hash could have repeated values, the methods above will only\nfind one of the associated keys. This may or may not worry you. If it\ndoes worry you, you can always reverse the hash into a hash of arrays\ninstead:\n\nwhile (my ($key, $value) = each %bykey) {\npush @{$keylistbyvalue{$value}}, $key;\n}\n\nHow can I know how many entries are in a hash?\n(contributed by brian d foy)\n\nThis is very similar to \"How do I process an entire hash?\", also in\nperlfaq4, but a bit simpler in the common cases.\n\nYou can use the keys() built-in function in scalar context to find out\nhave many entries you have in a hash:\n\nmy $keycount = keys %hash; # must be scalar context!\n\nIf you want to find out how many entries have a defined value, that's a\nbit different. You have to check each value. A \"grep\" is handy:\n\nmy $definedvaluecount = grep { defined } values %hash;\n\nYou can use that same structure to count the entries any way that you\nlike. If you want the count of the keys with vowels in them, you just\ntest for that instead:\n\nmy $vowelcount = grep { /[aeiou]/ } keys %hash;\n\nThe \"grep\" in scalar context returns the count. If you want the list of\nmatching items, just use it in list context instead:\n\nmy @definedvalues = grep { defined } values %hash;\n\nThe keys() function also resets the iterator, which means that you may\nsee strange results if you use this between uses of other hash operators\nsuch as each().\n\nHow do I sort a hash (optionally by value instead of key)?\n(contributed by brian d foy)\n\nTo sort a hash, start with the keys. In this example, we give the list\nof keys to the sort function which then compares them ASCIIbetically\n(which might be affected by your locale settings). The output list has\nthe keys in ASCIIbetical order. Once we have the keys, we can go through\nthem to create a report which lists the keys in ASCIIbetical order.\n\nmy @keys = sort { $a cmp $b } keys %hash;\n\nforeach my $key ( @keys ) {\nprintf \"%-20s %6d\\n\", $key, $hash{$key};\n}\n\nWe could get more fancy in the sort() block though. Instead of comparing\nthe keys, we can compute a value with them and use that value as the\ncomparison.\n\nFor instance, to make our report order case-insensitive, we use \"lc\" to\nlowercase the keys before comparing them:\n\nmy @keys = sort { lc $a cmp lc $b } keys %hash;\n\nNote: if the computation is expensive or the hash has many elements, you\nmay want to look at the Schwartzian Transform to cache the computation\nresults.\n\nIf we want to sort by the hash value instead, we use the hash key to\nlook it up. We still get out a list of keys, but this time they are\nordered by their value.\n\nmy @keys = sort { $hash{$a} <=> $hash{$b} } keys %hash;\n\nFrom there we can get more complex. If the hash values are the same, we\ncan provide a secondary sort on the hash key.\n\nmy @keys = sort {\n$hash{$a} <=> $hash{$b}\nor\n\"\\L$a\" cmp \"\\L$b\"\n} keys %hash;\n\nHow can I always keep my hash sorted?\nYou can look into using the \"DBFile\" module and tie() using the\n$DBBTREE hash bindings as documented in \"In Memory Databases\" in\nDBFile. The Tie::IxHash module from CPAN might also be instructive.\nAlthough this does keep your hash sorted, you might not like the\nslowdown you suffer from the tie interface. Are you sure you need to do\nthis? :)\n\nWhat's the difference between \"delete\" and \"undef\" with hashes?\nHashes contain pairs of scalars: the first is the key, the second is the\nvalue. The key will be coerced to a string, although the value can be\nany kind of scalar: string, number, or reference. If a key $key is\npresent in %hash, exists($hash{$key}) will return true. The value for a\ngiven key can be \"undef\", in which case $hash{$key} will be \"undef\"\nwhile \"exists $hash{$key}\" will return true. This corresponds to ($key,\n\"undef\") being in the hash.\n\nPictures help... Here's the %hash table:\n\nkeys  values\n+------+------+\n|  a   |  3   |\n|  x   |  7   |\n|  d   |  0   |\n|  e   |  2   |\n+------+------+\n\nAnd these conditions hold\n\n$hash{'a'}                       is true\n$hash{'d'}                       is false\ndefined $hash{'d'}               is true\ndefined $hash{'a'}               is true\nexists $hash{'a'}                is true (Perl 5 only)\ngrep ($ eq 'a', keys %hash)     is true\n\nIf you now say\n\nundef $hash{'a'}\n\nyour table now reads:\n\nkeys  values\n+------+------+\n|  a   | undef|\n|  x   |  7   |\n|  d   |  0   |\n|  e   |  2   |\n+------+------+\n\nand these conditions now hold; changes in caps:\n\n$hash{'a'}                       is FALSE\n$hash{'d'}                       is false\ndefined $hash{'d'}               is true\ndefined $hash{'a'}               is FALSE\nexists $hash{'a'}                is true (Perl 5 only)\ngrep ($ eq 'a', keys %hash)     is true\n\nNotice the last two: you have an undef value, but a defined key!\n\nNow, consider this:\n\ndelete $hash{'a'}\n\nyour table now reads:\n\nkeys  values\n+------+------+\n|  x   |  7   |\n|  d   |  0   |\n|  e   |  2   |\n+------+------+\n\nand these conditions now hold; changes in caps:\n\n$hash{'a'}                       is false\n$hash{'d'}                       is false\ndefined $hash{'d'}               is true\ndefined $hash{'a'}               is false\nexists $hash{'a'}                is FALSE (Perl 5 only)\ngrep ($ eq 'a', keys %hash)     is FALSE\n\nSee, the whole entry is gone!\n\nWhy don't my tied hashes make the defined/exists distinction?\nThis depends on the tied hash's implementation of EXISTS(). For example,\nthere isn't the concept of undef with hashes that are tied to DBM*\nfiles. It also means that exists() and defined() do the same thing with\na DBM* file, and what they end up doing is not what they do with\nordinary hashes.\n\nHow can I get the unique keys from two hashes?\nFirst you extract the keys from the hashes into lists, then solve the\n\"removing duplicates\" problem described above. For example:\n\nmy %seen = ();\nfor my $element (keys(%foo), keys(%bar)) {\n$seen{$element}++;\n}\nmy @uniq = keys %seen;\n\nOr more succinctly:\n\nmy @uniq = keys %{{%foo,%bar}};\n\nOr if you really want to save space:\n\nmy %seen = ();\nwhile (defined ($key = each %foo)) {\n$seen{$key}++;\n}\nwhile (defined ($key = each %bar)) {\n$seen{$key}++;\n}\nmy @uniq = keys %seen;\n\nHow can I make my hash remember the order I put elements into it?\nUse the Tie::IxHash from CPAN.\n\nuse Tie::IxHash;\n\ntie my %myhash, 'Tie::IxHash';\n\nfor (my $i=0; $i<20; $i++) {\n$myhash{$i} = 2*$i;\n}\n\nmy @keys = keys %myhash;\n# @keys = (0,1,2,3,...)\n\nWhy does passing a subroutine an undefined element in a hash create it?\n(contributed by brian d foy)\n\nAre you using a really old version of Perl?\n\nNormally, accessing a hash key's value for a nonexistent key will *not*\ncreate the key.\n\nmy %hash  = ();\nmy $value = $hash{ 'foo' };\nprint \"This won't print\\n\" if exists $hash{ 'foo' };\n\nPassing $hash{ 'foo' } to a subroutine used to be a special case,\nthough. Since you could assign directly to $[0], Perl had to be ready\nto make that assignment so it created the hash key ahead of time:\n\nmysub( $hash{ 'foo' } );\nprint \"This will print before 5.004\\n\" if exists $hash{ 'foo' };\n\nsub mysub {\n# $[0] = 'bar'; # create hash key in case you do this\n1;\n}\n\nSince Perl 5.004, however, this situation is a special case and Perl\ncreates the hash key only when you make the assignment:\n\nmysub( $hash{ 'foo' } );\nprint \"This will print, even after 5.004\\n\" if exists $hash{ 'foo' };\n\nsub mysub {\n$[0] = 'bar';\n}\n\nHowever, if you want the old behavior (and think carefully about that\nbecause it's a weird side effect), you can pass a hash slice instead.\nPerl 5.004 didn't make this a special case:\n\nmysub( @hash{ qw/foo/ } );\n\nHow can I make the Perl equivalent of a C structure/C++ class/hash or array of hashes or arrays?\nUsually a hash ref, perhaps like this:\n\n$record = {\nNAME   => \"Jason\",\nEMPNO  => 132,\nTITLE  => \"deputy peon\",\nAGE    => 23,\nSALARY => 37000,\nPALS   => [ \"Norbert\", \"Rhys\", \"Phineas\"],\n};\n\nReferences are documented in perlref and perlreftut. Examples of complex\ndata structures are given in perldsc and perllol. Examples of structures\nand object-oriented classes are in perlootut.\n\nHow can I use a reference as a hash key?\n(contributed by brian d foy and Ben Morrow)\n\nHash keys are strings, so you can't really use a reference as the key.\nWhen you try to do that, perl turns the reference into its stringified\nform (for instance, HASH(0xDEADBEEF)). From there you can't get back the\nreference from the stringified form, at least without doing some extra\nwork on your own.\n\nRemember that the entry in the hash will still be there even if the\nreferenced variable goes out of scope, and that it is entirely possible\nfor Perl to subsequently allocate a different variable at the same\naddress. This will mean a new variable might accidentally be associated\nwith the value for an old.\n\nIf you have Perl 5.10 or later, and you just want to store a value\nagainst the reference for lookup later, you can use the core\nHash::Util::Fieldhash module. This will also handle renaming the keys if\nyou use multiple threads (which causes all variables to be reallocated\nat new addresses, changing their stringification), and\ngarbage-collecting the entries when the referenced variable goes out of\nscope.\n\nIf you actually need to be able to get a real reference back from each\nhash entry, you can use the Tie::RefHash module, which does the required\nwork for you.\n\nHow can I check if a key exists in a multilevel hash?\n(contributed by brian d foy)\n\nThe trick to this problem is avoiding accidental autovivification. If\nyou want to check three keys deep, you might naïvely try this:\n\nmy %hash;\nif( exists $hash{key1}{key2}{key3} ) {\n...;\n}\n\nEven though you started with a completely empty hash, after that call to\n\"exists\" you've created the structure you needed to check for \"key3\":\n\n%hash = (\n'key1' => {\n'key2' => {}\n}\n);\n\nThat's autovivification. You can get around this in a few ways. The\neasiest way is to just turn it off. The lexical \"autovivification\"\npragma is available on CPAN. Now you don't add to the hash:\n\n{\nno autovivification;\nmy %hash;\nif( exists $hash{key1}{key2}{key3} ) {\n...;\n}\n}\n\nThe Data::Diver module on CPAN can do it for you too. Its \"Dive\"\nsubroutine can tell you not only if the keys exist but also get the\nvalue:\n\nuse Data::Diver qw(Dive);\n\nmy @exists = Dive( \\%hash, qw(key1 key2 key3) );\nif(  ! @exists  ) {\n...; # keys do not exist\n}\nelsif(  ! defined $exists[0]  ) {\n...; # keys exist but value is undef\n}\n\nYou can easily do this yourself too by checking each level of the hash\nbefore you move onto the next level. This is essentially what\nData::Diver does for you:\n\nif( checkhash( \\%hash, qw(key1 key2 key3) ) ) {\n...;\n}\n\nsub checkhash {\nmy( $hash, @keys ) = @;\n\nreturn unless @keys;\n\nforeach my $key ( @keys ) {\nreturn unless eval { exists $hash->{$key} };\n$hash = $hash->{$key};\n}\n\nreturn 1;\n}\n\nHow can I prevent addition of unwanted keys into a hash?\nSince version 5.8.0, hashes can be *restricted* to a fixed number of\ngiven keys. Methods for creating and dealing with restricted hashes are\nexported by the Hash::Util module.\n",
            "subsections": []
        },
        "Found in /usr/share/perl/5.38/pod/perlfaq7.pod": {
            "content": "How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?\nYou need to pass references to these objects. See \"Pass by Reference\" in\nperlsub for this particular question, and perlref for information on\nreferences.\n\nPassing Variables and Functions\nRegular variables and functions are quite easy to pass: just pass in\na reference to an existing or anonymous variable or function:\n\nfunc( \\$somescalar );\n\nfunc( \\@somearray  );\nfunc( [ 1 .. 10 ]   );\n\nfunc( \\%somehash   );\nfunc( { this => 10, that => 20 }   );\n\nfunc( \\&somefunc   );\nfunc( sub { $[0]  $[1] }   );\n\nPassing Filehandles\nAs of Perl 5.6, you can represent filehandles with scalar variables\nwhich you treat as any other scalar.\n\nopen my $fh, $filename or die \"Cannot open $filename! $!\";\nfunc( $fh );\n\nsub func {\nmy $passedfh = shift;\n\nmy $line = <$passedfh>;\n}\n\nBefore Perl 5.6, you had to use the *FH or \"\\*FH\" notations. These\nare \"typeglobs\"--see \"Typeglobs and Filehandles\" in perldata and\nespecially \"Pass by Reference\" in perlsub for more information.\n\nPassing Regexes\nHere's an example of how to pass in a string and a regular\nexpression for it to match against. You construct the pattern with\nthe \"qr//\" operator:\n\nsub compare {\nmy ($val1, $regex) = @;\nmy $retval = $val1 =~ /$regex/;\nreturn $retval;\n}\n$match = compare(\"old McDonald\", qr/d.*D/i);\n\nPassing Methods\nTo pass an object method into a subroutine, you can do this:\n\ncallalot(10, $someobj, \"methname\")\nsub callalot {\nmy ($count, $widget, $trick) = @;\nfor (my $i = 0; $i < $count; $i++) {\n$widget->$trick();\n}\n}\n\nOr, you can use a closure to bundle up the object, its method call,\nand arguments:\n\nmy $whatnot = sub { $someobj->obfuscate(@args) };\nfunc($whatnot);\nsub func {\nmy $code = shift;\n&$code();\n}\n\nYou could also investigate the can() method in the UNIVERSAL class\n(part of the standard perl distribution).\n",
            "subsections": []
        }
    },
    "flags": [],
    "examples": [],
    "see_also": []
}