{
    "mode": "perldoc",
    "parameter": "Hash::Ordered",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/Hash%3A%3AOrdered/json",
    "generated": "2026-10-09T04:14:12Z",
    "synopsis": "use Hash::Ordered;\nmy $oh = Hash::Ordered->new( a => 1 );\n$oh->get( 'a' );\n$oh->set( 'a' => 2 );\n$oh->exists( 'a' );\n$val = $oh->delete( 'a' );\n@keys  = $oh->keys;\n@vals  = $oh->values;\n@pairs = $oh->aslist\n$oh->push( c => 3, d => 4 );\n$oh->unshift( e => 5, f => 6 );\n( $k, $v ) = $oh->pop;\n( $k, $v ) = $oh->shift;\n$iter = $oh->iterator;\nwhile( ( $k, $v ) = $iter->() ) { ... }\n$copy     = $oh->clone;\n$subset   = $oh->clone( qw/c d/ );\n$reversed = $oh->clone( reverse $oh->keys );\n@valueslice = $oh->values(  qw/c f/ ); # qw/3 6/\n@pairsslice = $oh->aslist( qw/f e/ ); # qw/f 6 e 5/\n$oh->postinc( 'a' );          # like $oh{a}++\n$oh->add( 'a', 5 );           # like $oh{a} += 5\n$oh->concat( 'a', 'hello' );  # like $oh{a} .= 'hello'\n$oh->orequals( 'g', '23' );  # like $oh{g} ||= 23\n$oh->dorequals( 'g', '23' ); # like $oh{g} //= 23",
    "sections": {
        "NAME": {
            "content": "Hash::Ordered - A fast, pure-Perl ordered hash class\n",
            "subsections": []
        },
        "VERSION": {
            "content": "version 0.014\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "use Hash::Ordered;\n\nmy $oh = Hash::Ordered->new( a => 1 );\n\n$oh->get( 'a' );\n$oh->set( 'a' => 2 );\n\n$oh->exists( 'a' );\n$val = $oh->delete( 'a' );\n\n@keys  = $oh->keys;\n@vals  = $oh->values;\n@pairs = $oh->aslist\n\n$oh->push( c => 3, d => 4 );\n$oh->unshift( e => 5, f => 6 );\n\n( $k, $v ) = $oh->pop;\n( $k, $v ) = $oh->shift;\n\n$iter = $oh->iterator;\nwhile( ( $k, $v ) = $iter->() ) { ... }\n\n$copy     = $oh->clone;\n$subset   = $oh->clone( qw/c d/ );\n$reversed = $oh->clone( reverse $oh->keys );\n\n@valueslice = $oh->values(  qw/c f/ ); # qw/3 6/\n@pairsslice = $oh->aslist( qw/f e/ ); # qw/f 6 e 5/\n\n$oh->postinc( 'a' );          # like $oh{a}++\n$oh->add( 'a', 5 );           # like $oh{a} += 5\n$oh->concat( 'a', 'hello' );  # like $oh{a} .= 'hello'\n$oh->orequals( 'g', '23' );  # like $oh{g} ||= 23\n$oh->dorequals( 'g', '23' ); # like $oh{g} //= 23\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "This module implements an ordered hash, meaning that it associates keys with values like a Perl\nhash, but keeps the keys in a consistent order. Because it is implemented as an object and\nmanipulated with method calls, it is much slower than a Perl hash. This is the cost of keeping\norder.\n\nHowever, compared to other ordered hash implementations, Hash::Ordered is optimized for getting\nand setting individual elements and is generally faster at most other tasks as well. For\nspecific details, see Hash::Ordered::Benchmarks.\n",
            "subsections": []
        },
        "METHODS": {
            "content": "new\n$oh = Hash::Ordered->new;\n$oh = Hash::Ordered->new( @pairs );\n\nConstructs an object, with an optional list of key-value pairs.\n\nThe position of a key corresponds to the first occurrence in the list, but the value will be\nupdated if the key is seen more than once.\n\nCurrent API available since 0.009.\n\nclone\n$oh2 = $oh->clone;\n$oh2 = $oh->clone( @keys );\n\nCreates a shallow copy of an ordered hash object. If no arguments are given, it produces an\nexact copy. If a list of keys is given, the new object includes only those keys in the given\norder. Keys that aren't in the original will have the value \"undef\".\n\nkeys\n@keys = $oh->keys;\n$size = $oh->keys;\n\nIn list context, returns the ordered list of keys. In scalar context, returns the number of\nelements.\n\nCurrent API available since 0.005.\n\nvalues\n@values = $oh->values;\n@values = $oh->values( @keys );\n\nReturns an ordered list of values. If no arguments are given, returns the ordered values of the\nentire hash. If a list of keys is given, returns values in order corresponding to those keys. If\na key does not exist, \"undef\" will be returned for that value.\n\nIn scalar context, returns the number of elements.\n\nCurrent API available since 0.006.\n\nget\n$value = $oh->get(\"some key\");\n\nReturns the value associated with the key, or \"undef\" if it does not exist in the hash.\n\nset\n$oh->set(\"some key\" => \"some value\");\n\nAssociates a value with a key and returns the value. If the key does not already exist in the\nhash, it will be added at the end.\n\nexists\nif ( $oh->exists(\"some key\") ) { ... }\n\nTest if some key exists in the hash (without creating it).\n\ndelete\n$value = $oh->delete(\"some key\");\n\nRemoves a key-value pair from the hash and returns the value.\n\nclear\n$oh->clear;\n\nRemoves all key-value pairs from the hash. Returns undef in scalar context or an empty list in\nlist context.\n\nCurrent API available since 0.003.\n\npush\n$oh->push( one => 1, two => 2);\n\nAdd a list of key-value pairs to the end of the ordered hash. If a key already exists in the\nhash, it will be deleted and re-inserted at the end with the new value.\n\nReturns the number of keys after the push is complete.\n\npop\n($key, $value) = $oh->pop;\n$value = $oh->pop;\n\nRemoves and returns the last key-value pair in the ordered hash. In scalar context, only the\nvalue is returned. If the hash is empty, the returned key and value will be \"undef\".\n\nunshift\n$oh->unshift( one => 1, two => 2 );\n\nAdds a list of key-value pairs to the beginning of the ordered hash. If a key already exists, it\nwill be deleted and re-inserted at the beginning with the new value.\n\nReturns the number of keys after the unshift is complete.\n\nshift\n($key, $value) = $oh->shift;\n$value = $oh->shift;\n\nRemoves and returns the first key-value pair in the ordered hash. In scalar context, only the\nvalue is returned. If the hash is empty, the returned key and value will be \"undef\".\n\nmerge\n$oh->merge( one => 1, two => 2 );\n\nMerges a list of key-value pairs into the ordered hash. If a key already exists, its value is\nreplaced. Otherwise, the key-value pair is added at the end of the hash.\n\naslist\n@pairs = $oh->aslist;\n@pairs = $oh->aslist( @keys );\n\nReturns an ordered list of key-value pairs. If no arguments are given, all pairs in the hash are\nreturned. If a list of keys is given, the returned list includes only those key-value pairs in\nthe given order. Keys that aren't in the original will have the value \"undef\".\n\niterator\n$iter = $oh->iterator;\n$iter = $oh->iterator( reverse $oh->keys ); # reverse\n\nwhile ( my ($key,$value) = $iter->() ) { ... }\n\nReturns a code reference that returns a single key-value pair (in order) on each invocation, or\nthe empty list if all keys are visited.\n\nIf no arguments are given, the iterator walks the entire hash in order. If a list of keys is\nprovided, the iterator walks the hash in that order. Unknown keys will return \"undef\".\n\nThe list of keys to return is set when the iterator is generator. Keys added later will not be\nreturned. Subsequently deleted keys will return \"undef\" for the value.\n\npreinc\n$oh->preinc($key);      # like ++$hash{$key}\n\nThis method is sugar for incrementing a key without having to call \"set\" and \"get\" explicitly.\nIt returns the new value.\n\nCurrent API available since 0.005.\n\npostinc\n$oh->postinc($key);     # like $hash{$key}++\n\nThis method is sugar for incrementing a key without having to call \"set\" and \"get\" explicitly.\nIt returns the old value.\n\nCurrent API available since 0.005.\n\npredec\n$oh->predec($key);      # like --$hash{$key}\n\nThis method is sugar for decrementing a key without having to call \"set\" and \"get\" explicitly.\nIt returns the new value.\n\nCurrent API available since 0.005.\n\npostdec\n$oh->postdec($key);      # like $hash{$key}--\n\nThis method is sugar for decrementing a key without having to call \"set\" and \"get\" explicitly.\nIt returns the old value.\n\nCurrent API available since 0.005.\n\nadd\n$oh->add($key, $n);     # like $hash{$key} += $n\n\nThis method is sugar for adding a value to a key without having to call \"set\" and \"get\"\nexplicitly. With no value to add, it is treated as \"0\". It returns the new value.\n\nCurrent API available since 0.005.\n\nsubtract\n$oh->subtract($key, $n);  # like $hash{$key} -= $n\n\nThis method is sugar for subtracting a value from a key without having to call \"set\" and \"get\"\nexplicitly. With no value to subtract, it is treated as \"0\". It returns the new value.\n\nCurrent API available since 0.005.\n\nconcat\n$oh->concat($key, $str); # like $hash{$key} .= $str\n\nThis method is sugar for concatenating a string onto the value of a key without having to call\n\"set\" and \"get\" explicitly. It returns the new value. If the value to append is not defined, no\nconcatenation is done and no warning is given.\n\nCurrent API available since 0.005.\n\norequals\n$oh->orequals($key, $str); # like $hash{$key} ||= $str\n\nThis method is sugar for assigning to a key if the existing value is false without having to\ncall \"set\" and \"get\" explicitly. It returns the new value.\n\nCurrent API available since 0.005.\n\ndorequals\n$oh->dorequals($key, $str); # like $hash{$key} //= $str\n\nThis method is sugar for assigning to a key if the existing value is not defined without having\nto call \"set\" and \"get\" explicitly. It returns the new value.\n\nCurrent API available since 0.005.\n",
            "subsections": []
        },
        "OVERLOADING": {
            "content": "",
            "subsections": [
                {
                    "name": "Boolean",
                    "content": "if ( $oh ) { ... }\n\nWhen used in boolean context, a Hash::Ordered object is true if it has any entries and false\notherwise.\n"
                },
                {
                    "name": "String",
                    "content": "say \"$oh\";\n\nWhen used in string context, a Hash::Ordered object stringifies like typical Perl objects. E.g.\n\"Hash::Ordered=ARRAY(0x7f815302cac0)\"\n\nCurrent API available since 0.005.\n"
                },
                {
                    "name": "Numeric",
                    "content": "$count = 0 + $oh;\n\nWhen used in numeric context, a Hash::Ordered object numifies as the decimal representation of\nits memory address, just like typical Perl objects. E.g. 140268162536552\n\nFor the number of keys, call the \"keys\" method in scalar context.\n\nCurrent API available since 0.005.\n"
                },
                {
                    "name": "Fallback",
                    "content": "Other overload methods are derived from these three, if possible.\n"
                }
            ]
        },
        "TIED INTERFACE": {
            "content": "Using \"tie\" is slower than using method calls directly. But for compatibility with libraries\nthat can only take hashes, it's available if you really need it:\n\ntie my %hash, \"Hash::Ordered\", @pairs;\n\nIf you want to access the underlying object for method calls, use \"tied\":\n\ntied( %hash )->unshift( @data );\n\nTied hash API available since 0.005.\n",
            "subsections": []
        },
        "CAVEATS": {
            "content": "",
            "subsections": [
                {
                    "name": "Deletion and order modification with push, pop, etc.",
                    "content": "This can be expensive, as the ordered list of keys has to be updated. For small hashes with no\nmore than 25 keys, keys are found and spliced out with linear search. As an optimization for\nlarger hashes, the first change to the ordered list of keys will construct an index to the list\nof keys. Thereafter, removed keys will be marked with a \"tombstone\" record. Tombstones will be\ngarbage collected whenever the number of tombstones exceeds the number of valid keys.\n\nThese internal implementation details largely shouldn't concern you. The important things to\nnote are:\n\n*   The costs of efficient deletion are deferred until you need it\n\n*   Deleting lots of keys will temporarily appear to leak memory until garbage collection occurs\n"
                }
            ]
        },
        "MOTIVATION": {
            "content": "For a long time, I used Tie::IxHash for ordered hashes, but I grew frustrated with things it\nlacked, like a cheap way to copy an IxHash object or a convenient iterator when not using the\ntied interface. As I looked at its implementation, it seemed more complex than I though it\nneeded, with an extra level of indirection that slows data access.\n\nGiven that frustration, I started experimenting with the simplest thing I thought could work for\nan ordered hash: a hash of key-value pairs and an array with key order.\n\nAs I worked on this, I also started searching for other modules doing similar things. What I\nfound fell broadly into two camps: modules based on tie (even if they offered an OO interface),\nand pure OO modules. They all either lacked features I deemed necessary or else seemed\noverly-complex in either implementation or API.\n\nHash::Ordered attempts to find the sweet spot with simple implementation, reasonably good\nefficiency for most common operations, and a rich, intuitive API.\n\nAfter discussions with Mario Roy about the potential use of Hash::Ordered with MCE, I optimized\ndeletion of larger hashes and provided a tied interface for compatibility. Mario's suggestions\nand feedback about optimization were quite valuable. Thank you, Mario!\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "This section describes other ordered-hash modules I found on CPAN. For benchmarking results, see\nHash::Ordered::Benchmarks.\n",
            "subsections": [
                {
                    "name": "Tie modules",
                    "content": "The following modules offer some sort of tie interface. I don't like ties, in general, because\nof the extra indirection involved over a direct method call. Still, you can make any tied\ninterface into a faster OO one with \"tied\":\n\ntied( %tiedhash )->FETCH($key);\n\nTie::Hash::Indexed is implemented in XS and thus seems promising if pure-Perl isn't a criterion;\nit generally fails tests on Perl 5.18 and above due to the hash randomization change. Despite\nbeing XS, it is slower than Hash::Ordered at everything exception creation and deletion.\n\nTie::IxHash is probably the most well known and includes an OO API. Given the performance\nproblems it has, \"well known\" is the only real reason to use it.\n\nThese other modules below have very specific designs/limitations and I didn't find any of them\nsuitable for general purpose use:\n\n*   Tie::Array::AsHash — array elements split with separator; tie API only\n\n*   Tie::Hash::Array — ordered alphabetically; tie API only\n\n*   Tie::InsertOrderHash — ordered by insertion; tie API only\n\n*   Tie::LLHash — linked-list implementation; quite slow\n\n*   Tie::StoredOrderHash — ordered by last update; tie API only\n"
                },
                {
                    "name": "Other ordered hash modules",
                    "content": "Other modules stick with an object-oriented API, with a wide variety of implementation\napproaches.\n\nArray::AsHash is essentially an inverse implementation from Hash::Ordered. It keeps pairs in an\narray and uses a hash to index into the array. This indirection would already make hash-like\noperations slower, but the specific implementation makes it even worse, with abstractions and\nfunction calls that make getting or setting individual items up to 10x slower than\nHash::Ordered.\n\nHowever, \"Array::AsHash\" takes an arrayref to initialize, which is very fast and can return the\nlist of pairs faster, too. If you mostly create and list out very large ordered hashes and very\nrarely touch individual entries, I think this could be something to very cautiously consider.\n\nThese other modules below have restrictions or particularly complicated implementations (often\nrelying on \"tie\") and thus I didn't think any of them really suitable for use:\n\n*   Array::Assign — arrays with named access; restricted keys\n\n*   Array::OrdHash — overloads array/hash deref and uses internal tied data\n\n*   Data::Pairs — array of key-value hashrefs; allows duplicate keys\n\n*   Data::OMap — array of key-value hashrefs; no duplicate keys\n\n*   Data::XHash — blessed, tied hashref with doubly-linked-list\n"
                }
            ]
        },
        "SUPPORT": {
            "content": "Bugs / Feature Requests\nPlease report any bugs or feature requests through the issue tracker at\n<https://github.com/dagolden/Hash-Ordered/issues>. You will be notified automatically of any\nprogress on your issue.\n",
            "subsections": [
                {
                    "name": "Source Code",
                    "content": "This is open source software. The code repository is available for public review and\ncontribution under the terms of the license.\n\n<https://github.com/dagolden/Hash-Ordered>\n\ngit clone https://github.com/dagolden/Hash-Ordered.git\n"
                }
            ]
        },
        "AUTHOR": {
            "content": "David Golden <dagolden@cpan.org>\n",
            "subsections": []
        },
        "CONTRIBUTORS": {
            "content": "*   Andy Lester <andy@petdance.com>\n\n*   Benct Philip Jonsson <bpjonsson@gmail.com>\n\n*   Mario Roy <marioeroy@gmail.com>\n",
            "subsections": []
        },
        "COPYRIGHT AND LICENSE": {
            "content": "This software is Copyright (c) 2014 by David Golden.\n\nThis is free software, licensed under:\n\nThe Apache License, Version 2.0, January 2004\n",
            "subsections": []
        }
    },
    "summary": "Hash::Ordered - A fast, pure-Perl ordered hash class",
    "flags": [],
    "examples": [],
    "see_also": []
}