{
    "mode": "info",
    "parameter": "Hash::Util::FieldHash",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/info/Hash%3A%3AUtil%3A%3AFieldHash/json",
    "generated": "2026-07-05T13:27:47Z",
    "synopsis": "### Create fieldhashes\nuse Hash::Util qw(fieldhash fieldhashes);\n# Create a single field hash\nfieldhash my %foo;\n# Create three at once...\nfieldhashes \\ my(%foo, %bar, %baz);\n# ...or any number\nfieldhashes @hashrefs;\n### Create an idhash and register it for garbage collection\nuse Hash::Util::FieldHash qw(idhash register);\nidhash my %name;\nmy $object = \\ do { my $o };\n# register the idhash for garbage collection with $object\nregister($object, \\ %name);\n# the following entry will be deleted when $object goes out of scope\n$name{$object} = 'John Doe';\n### Register an ordinary hash for garbage collection\nuse Hash::Util::FieldHash qw(id register);\nmy %name;\nmy $object = \\ do { my $o };\n# register the hash %name for garbage collection of $object's id\nregister $object, \\ %name;\n# the following entry will be deleted when $object goes out of scope\n$name{id $object} = 'John Doe';",
    "sections": {
        "Hash::Util::FieldHash(3Perl)Programmers Reference Hash::Util::FieldHash(3perl)": {
            "content": "",
            "subsections": []
        },
        "NAME": {
            "content": "Hash::Util::FieldHash - Support for Inside-Out Classes\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "### Create fieldhashes\nuse Hash::Util qw(fieldhash fieldhashes);\n\n# Create a single field hash\nfieldhash my %foo;\n\n# Create three at once...\nfieldhashes \\ my(%foo, %bar, %baz);\n# ...or any number\nfieldhashes @hashrefs;\n\n### Create an idhash and register it for garbage collection\nuse Hash::Util::FieldHash qw(idhash register);\nidhash my %name;\nmy $object = \\ do { my $o };\n# register the idhash for garbage collection with $object\nregister($object, \\ %name);\n# the following entry will be deleted when $object goes out of scope\n$name{$object} = 'John Doe';\n\n### Register an ordinary hash for garbage collection\nuse Hash::Util::FieldHash qw(id register);\nmy %name;\nmy $object = \\ do { my $o };\n# register the hash %name for garbage collection of $object's id\nregister $object, \\ %name;\n# the following entry will be deleted when $object goes out of scope\n$name{id $object} = 'John Doe';\n",
            "subsections": []
        },
        "FUNCTIONS": {
            "content": "\"Hash::Util::FieldHash\" offers a number of functions in support of \"The\nInside-out Technique\" of class construction.\n\nid\nid($obj)\n\nReturns the reference address of a reference $obj.  If $obj is not\na reference, returns $obj.\n\nThis function is a stand-in replacement for Scalar::Util::refaddr,\nthat is, it returns the reference address of its argument as a\nnumeric value.  The only difference is that \"refaddr()\" returns\n\"undef\" when given a non-reference while \"id()\" returns its\nargument unchanged.\n\n\"id()\" also uses a caching technique that makes it faster when the\nid of an object is requested often, but slower if it is needed only\nonce or twice.\n\nid2obj\n$obj = id2obj($id)\n\nIf $id is the id of a registered object (see \"register\"), returns\nthe object, otherwise an undefined value.  For registered objects\nthis is the inverse function of \"id()\".\n\nregister\nregister($obj)\nregister($obj, @hashrefs)\n\nIn the first form, registers an object to work with for the\nfunction \"id2obj()\".  In the second form, it additionally marks\nthe given hashrefs down for garbage collection.  This means that\nwhen the object goes out of scope, any entries in the given hashes\nunder the key of \"id($obj)\" will be deleted from the hashes.\n\nIt is a fatal error to register a non-reference $obj.  Any non-\nhashrefs among the following arguments are silently ignored.\n\nIt is not an error to register the same object multiple times with\nvarying sets of hashrefs.  Any hashrefs that are not registered yet\nwill be added, others ignored.\n\nRegistry also implies thread support.  When a new thread is\ncreated, all references are replaced with new ones, including all\nobjects.  If a hash uses the reference address of an object as a\nkey, that connection would be broken.  With a registered object,\nits id will be updated in all hashes registered with it.\n\nidhash\nidhash my %hash\n\nMakes an idhash from the argument, which must be a hash.\n\nAn idhash works like a normal hash, except that it stringifies a\nreference used as a key differently.  A reference is stringified as\nif the \"id()\" function had been invoked on it, that is, its\nreference address in decimal is used as the key.\n\nidhashes\nidhashes \\ my(%hash, %gnash, %trash)\nidhashes \\ @hashrefs\n\nCreates many idhashes from its hashref arguments.  Returns those\narguments that could be converted or their number in scalar\ncontext.\n\nfieldhash\nfieldhash %hash;\n\nCreates a single fieldhash.  The argument must be a hash.  Returns\na reference to the given hash if successful, otherwise nothing.\n\nA fieldhash is, in short, an idhash with auto-registry.  When an\nobject (or, indeed, any reference) is used as a fieldhash key, the\nfieldhash is automatically registered for garbage collection with\nthe object, as if \"register $obj, \\ %fieldhash\" had been called.\n\nfieldhashes\nfieldhashes @hashrefs;\n\nCreates any number of field hashes.  Arguments must be hash\nreferences.  Returns the converted hashrefs in list context, their\nnumber in scalar context.\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "A word on terminology:  I shall use the term field for a scalar piece\nof data that a class associates with an object.  Other terms that have\nbeen used for this concept are \"object variable\", \"(object) property\",\n\"(object) attribute\" and more.  Especially \"attribute\" has some\ncurrency among Perl programmer, but that clashes with the \"attributes\"\npragma.  The term \"field\" also has some currency in this sense and\ndoesn't seem to conflict with other Perl terminology.\n\nIn Perl, an object is a blessed reference.  The standard way of\nassociating data with an object is to store the data inside the\nobject's body, that is, the piece of data pointed to by the reference.\n\nIn consequence, if two or more classes want to access an object they\nmust agree on the type of reference and also on the organization of\ndata within the object body.  Failure to agree on the type results in\nimmediate death when the wrong method tries to access an object.\nFailure to agree on data organization may lead to one class trampling\nover the data of another.\n\nThis object model leads to a tight coupling between subclasses.  If one\nclass wants to inherit from another (and both classes access object\ndata), the classes must agree about implementation details.\nInheritance can only be used among classes that are maintained\ntogether, in a single source or not.\n\nIn particular, it is not possible to write general-purpose classes in\nthis technique, classes that can advertise themselves as \"Put me on\nyour @ISA list and use my methods\".  If the other class has different\nideas about how the object body is used, there is trouble.\n\nFor reference \"Namehash\" in \"Example 1\" shows the standard\nimplementation of a simple class \"Name\" in the well-known hash based\nway.  It also demonstrates the predictable failure to construct a\ncommon subclass \"NamedFile\" of \"Name\" and the class \"IO::File\" (whose\nobjects must be globrefs).\n\nThus, techniques are of interest that store object data not in the\nobject body but some other place.\n\nThe Inside-out Technique\nWith inside-out classes, each class declares a (typically lexical) hash\nfor each field it wants to use.  The reference address of an object is\nused as the hash key.  By definition, the reference address is unique\nto each object so this guarantees a place for each field that is\nprivate to the class and unique to each object.  See \"Nameid\" in\n\"Example 1\" for a simple example.\n\nIn comparison to the standard implementation where the object is a hash\nand the fields correspond to hash keys, here the fields correspond to\nhashes, and the object determines the hash key.  Thus the hashes appear\nto be turned inside out.\n\nThe body of an object is never examined by an inside-out class, only\nits reference address is used.  This allows for the body of an actual\nobject to be anything at all while the object methods of the class\nstill work as designed.  This is a key feature of inside-out classes.\n\nProblems of Inside-out\nInside-out classes give us freedom of inheritance, but as usual there\nis a price.\n\nMost obviously, there is the necessity of retrieving the reference\naddress of an object for each data access.  It's a minor inconvenience,\nbut it does clutter the code.\n\nMore important (and less obvious) is the necessity of garbage\ncollection.  When a normal object dies, anything stored in the object\nbody is garbage-collected by perl.  With inside-out objects, Perl knows\nnothing about the data stored in field hashes by a class, but these\nmust be deleted when the object goes out of scope.  Thus the class must\nprovide a \"DESTROY\" method to take care of that.\n\nIn the presence of multiple classes it can be non-trivial to make sure\nthat every relevant destructor is called for every object.  Perl calls\nthe first one it finds on the inheritance tree (if any) and that's it.\n\nA related issue is thread-safety.  When a new thread is created, the\nPerl interpreter is cloned, which implies that all reference addresses\nin use will be replaced with new ones.  Thus, if a class tries to\naccess a field of a cloned object its (cloned) data will still be\nstored under the now invalid reference address of the original in the\nparent thread.  A general \"CLONE\" method must be provided to re-\nestablish the association.\n\nSolutions\n\"Hash::Util::FieldHash\" addresses these issues on several levels.\n\nThe \"id()\" function is provided in addition to the existing\n\"Scalar::Util::refaddr()\".  Besides its short name it can be a little\nfaster under some circumstances (and a bit slower under others).\nBenchmark if it matters.  The working of \"id()\" also allows the use of\nthe class name as a generic object as described further down.\n\nThe \"id()\" function is incorporated in id hashes in the sense that it\nis called automatically on every key that is used with the hash.  No\nexplicit call is necessary.\n\nThe problems of garbage collection and thread safety are both addressed\nby the function \"register()\".  It registers an object together with any\nnumber of hashes.  Registry means that when the object dies, an entry\nin any of the hashes under the reference address of this object will be\ndeleted.  This guarantees garbage collection in these hashes.  It also\nmeans that on thread cloning the object's entries in registered hashes\nwill be replaced with updated entries whose key is the cloned object's\nreference address.  Thus the object-data association becomes thread-\nsafe.\n\nObject registry is best done when the object is initialized for use\nwith a class.  That way, garbage collection and thread safety are\nestablished for every object and every field that is initialized.\n\nFinally, field hashes incorporate all these functions in one package.\nBesides automatically calling the \"id()\" function on every object used\nas a key, the object is registered with the field hash on first use.\nClasses based on field hashes are fully garbage-collected and thread\nsafe without further measures.\n\nMore Problems\nAnother problem that occurs with inside-out classes is serialization.\nSince the object data is not in its usual place, standard routines like\n\"Storable::freeze()\", \"Storable::thaw()\" and \"Data::Dumper::Dumper()\"\ncan't deal with it on their own.  Both \"Data::Dumper\" and \"Storable\"\nprovide the necessary hooks to make things work, but the functions or\nmethods used by the hooks must be provided by each inside-out class.\n\nA general solution to the serialization problem would require another\nlevel of registry, one that associates classes and fields.  So far, the\nfunctions of \"Hash::Util::FieldHash\" are unaware of any classes, which\nI consider a feature.  Therefore \"Hash::Util::FieldHash\" doesn't\naddress the serialization problems.\n\nThe Generic Object\nClasses based on the \"id()\" function (and hence classes based on\n\"idhash()\" and \"fieldhash()\") show a peculiar behavior in that the\nclass name can be used like an object.  Specifically, methods that set\nor read data associated with an object continue to work as class\nmethods, just as if the class name were an object, distinct from all\nother objects, with its own data.  This object may be called the\ngeneric object of the class.\n\nThis works because field hashes respond to keys that are not references\nlike a normal hash would and use the string offered as the hash key.\nThus, if a method is called as a class method, the field hash is\npresented with the class name instead of an object and blithely uses it\nas a key.  Since the keys of real objects are decimal numbers, there is\nno conflict and the slot in the field hash can be used like any other.\nThe \"id()\" function behaves correspondingly with respect to non-\nreference arguments.\n\nTwo possible uses (besides ignoring the property) come to mind.  A\nsingleton class could be implemented this using the generic object.  If\nnecessary, an \"init()\" method could die or ignore calls with actual\nobjects (references), so only the generic object will ever exist.\n\nAnother use of the generic object would be as a template.  It is a\nconvenient place to store class-specific defaults for various fields to\nbe used in actual object initialization.\n\nUsually, the feature can be entirely ignored.  Calling object methods\nas class methods normally leads to an error and isn't used routinely\nanywhere.  It may be a problem that this error isn't indicated by a\nclass with a generic object.\n\nHow to use Field Hashes\nTraditionally, the definition of an inside-out class contains a bare\nblock inside which a number of lexical hashes are declared and the\nbasic accessor methods defined, usually through\n\"Scalar::Util::refaddr\".  Further methods may be defined outside this\nblock.  There has to be a DESTROY method and, for thread support, a\nCLONE method.\n\nWhen field hashes are used, the basic structure remains the same.  Each\nlexical hash will be made a field hash.  The call to \"refaddr\" can be\nomitted from the accessor methods.  DESTROY and CLONE methods are not\nnecessary.\n\nIf you have an existing inside-out class, simply making all hashes\nfield hashes with no other change should make no difference.  Through\nthe calls to \"refaddr\" or equivalent, the field hashes never get to see\na reference and work like normal hashes.  Your DESTROY (and CLONE)\nmethods are still needed.\n\nTo make the field hashes kick in, it is easiest to redefine \"refaddr\"\nas\n\nsub refaddr { shift }\n\ninstead of importing it from \"Scalar::Util\".  It should now be possible\nto disable DESTROY and CLONE.  Note that while it isn't disabled,\nDESTROY will be called before the garbage collection of field hashes,\nso it will be invoked with a functional object and will continue to\nfunction.\n\nIt is not desirable to import the functions \"fieldhash\" and/or\n\"fieldhashes\" into every class that is going to use them.  They are\nonly used once to set up the class.  When the class is up and running,\nthese functions serve no more purpose.\n\nIf there are only a few field hashes to declare, it is simplest to\n\nuse Hash::Util::FieldHash;\n\nearly and call the functions qualified:\n\nHash::Util::FieldHash::fieldhash my %foo;\n\nOtherwise, import the functions into a convenient package like \"HUF\"\nor, more general, \"Aux\"\n\n{\npackage Aux;\nuse Hash::Util::FieldHash ':all';\n}\n\nand call\n\nAux::fieldhash my %foo;\n\nas needed.\n\nGarbage-Collected Hashes\nGarbage collection in a field hash means that entries will\n\"spontaneously\" disappear when the object that created them disappears.\nThat must be borne in mind, especially when looping over a field hash.\nIf anything you do inside the loop could cause an object to go out of\nscope, a random key may be deleted from the hash you are looping over.\nThat can throw the loop iterator, so it's best to cache a consistent\nsnapshot of the keys and/or values and loop over that.  You will still\nhave to check that a cached entry still exists when you get to it.\n\nGarbage collection can be confusing when keys are created in a field\nhash from normal scalars as well as references.  Once a reference is\nused with a field hash, the entry will be collected, even if it was\nlater overwritten with a plain scalar key (every positive integer is a\ncandidate).  This is true even if the original entry was deleted in the\nmeantime.  In fact, deletion from a field hash, and also a test for\nexistence constitute use in this sense and create a liability to delete\nthe entry when the reference goes out of scope.  If you happen to\ncreate an entry with an identical key from a string or integer, that\nwill be collected instead.  Thus, mixed use of references and plain\nscalars as field hash keys is not entirely supported.\n",
            "subsections": []
        },
        "EXAMPLES": {
            "content": "The examples show a very simple class that implements a name,\nconsisting of a first and last name (no middle initial).  The name\nclass has four methods:\n\no   \"init()\"\n\nAn object method that initializes the first and last name to its\ntwo arguments. If called as a class method, \"init()\" creates an\nobject in the given class and initializes that.\n\no   \"first()\"\n\nRetrieve the first name\n\no   \"last()\"\n\nRetrieve the last name\n\no   \"name()\"\n\nRetrieve the full name, the first and last name joined by a blank.\n\nThe examples show this class implemented with different levels of\nsupport by \"Hash::Util::FieldHash\".  All supported combinations are\nshown.  The difference between implementations is often quite small.\nThe implementations are:\n\no   \"Namehash\"\n\nA conventional (not inside-out) implementation where an object is a\nhash that stores the field values, without support by\n\"Hash::Util::FieldHash\".  This implementation doesn't allow\narbitrary inheritance.\n\no   \"Nameid\"\n\nInside-out implementation based on the \"id()\" function.  It needs a\n\"DESTROY\" method.  For thread support a \"CLONE\" method (not shown)\nwould also be needed.  Instead of \"Hash::Util::FieldHash::id()\" the\nfunction \"Scalar::Util::refaddr\" could be used with very little\nfunctional difference.  This is the basic pattern of an inside-out\nclass.\n\no   \"Nameidhash\"\n\nIdhash-based inside-out implementation.  Like \"Nameid\" it needs a\n\"DESTROY\" method and would need \"CLONE\" for thread support.\n\no   \"Nameidreg\"\n\nInside-out implementation based on the \"id()\" function with\nexplicit object registry.  No destructor is needed and objects are\nthread safe.\n\no   \"Nameidhashreg\"\n\nIdhash-based inside-out implementation with explicit object\nregistry.  No destructor is needed and objects are thread safe.\n\no   \"Namefieldhash\"\n\nFieldHash-based inside-out implementation.  Object registry happens\nautomatically.  No destructor is needed and objects are thread\nsafe.\n\nThese examples are realized in the code below, which could be copied to\na file Example.pm.\n\nExample 1\nuse strict; use warnings;\n\n{\npackage Namehash;  # standard implementation: the\n# object is a hash\nsub init {\nmy $obj = shift;\nmy ($first, $last) = @;\n# create an object if called as class method\n$obj = bless {}, $obj unless ref $obj;\n$obj->{ first} = $first;\n$obj->{ last} = $last;\n$obj;\n}\n\nsub first { shift()->{ first} }\nsub last { shift()->{ last} }\n\nsub name {\nmy $n = shift;\njoin ' ' => $n->first, $n->last;\n}\n\n}\n\n{\npackage Nameid;\nuse Hash::Util::FieldHash qw(id);\n\nmy (%first, %last);\n\nsub init {\nmy $obj = shift;\nmy ($first, $last) = @;\n# create an object if called as class method\n$obj = bless \\ my $o, $obj unless ref $obj;\n$first{ id $obj} = $first;\n$last{ id $obj} = $last;\n$obj;\n}\n\nsub first { $first{ id shift()} }\nsub last { $last{ id shift()} }\n\nsub name {\nmy $n = shift;\njoin ' ' => $n->first, $n->last;\n}\n\nsub DESTROY {\nmy $id = id shift;\ndelete $first{ $id};\ndelete $last{ $id};\n}\n\n}\n\n{\npackage Nameidhash;\nuse Hash::Util::FieldHash;\n\nHash::Util::FieldHash::idhashes( \\ my (%first, %last) );\n\nsub init {\nmy $obj = shift;\nmy ($first, $last) = @;\n# create an object if called as class method\n$obj = bless \\ my $o, $obj unless ref $obj;\n$first{ $obj} = $first;\n$last{ $obj} = $last;\n$obj;\n}\n\nsub first { $first{ shift()} }\nsub last { $last{ shift()} }\n\nsub name {\nmy $n = shift;\njoin ' ' => $n->first, $n->last;\n}\n\nsub DESTROY {\nmy $n = shift;\ndelete $first{ $n};\ndelete $last{ $n};\n}\n\n}\n\n{\npackage Nameidreg;\nuse Hash::Util::FieldHash qw(id register);\n\nmy (%first, %last);\n\nsub init {\nmy $obj = shift;\nmy ($first, $last) = @;\n# create an object if called as class method\n$obj = bless \\ my $o, $obj unless ref $obj;\nregister( $obj, \\ (%first, %last) );\n$first{ id $obj} = $first;\n$last{ id $obj} = $last;\n$obj;\n}\n\nsub first { $first{ id shift()} }\nsub last { $last{ id shift()} }\n\nsub name {\nmy $n = shift;\njoin ' ' => $n->first, $n->last;\n}\n}\n\n{\npackage Nameidhashreg;\nuse Hash::Util::FieldHash qw(register);\n\nHash::Util::FieldHash::idhashes \\ my (%first, %last);\n\nsub init {\nmy $obj = shift;\nmy ($first, $last) = @;\n# create an object if called as class method\n$obj = bless \\ my $o, $obj unless ref $obj;\nregister( $obj, \\ (%first, %last) );\n$first{ $obj} = $first;\n$last{ $obj} = $last;\n$obj;\n}\n\nsub first { $first{ shift()} }\nsub last { $last{ shift()} }\n\nsub name {\nmy $n = shift;\njoin ' ' => $n->first, $n->last;\n}\n}\n\n{\npackage Namefieldhash;\nuse Hash::Util::FieldHash;\n\nHash::Util::FieldHash::fieldhashes \\ my (%first, %last);\n\nsub init {\nmy $obj = shift;\nmy ($first, $last) = @;\n# create an object if called as class method\n$obj = bless \\ my $o, $obj unless ref $obj;\n$first{ $obj} = $first;\n$last{ $obj} = $last;\n$obj;\n}\n\nsub first { $first{ shift()} }\nsub last { $last{ shift()} }\n\nsub name {\nmy $n = shift;\njoin ' ' => $n->first, $n->last;\n}\n}\n\n1;\n\nTo exercise the various implementations the script below can be used.\n\nIt sets up a class \"Name\" that is a mirror of one of the implementation\nclasses \"Namehash\", \"Nameid\", ..., \"Namefieldhash\".  That determines\nwhich implementation is run.\n\nThe script first verifies the function of the \"Name\" class.\n\nIn the second step, the free inheritability of the implementation (or\nlack thereof) is demonstrated.  For this purpose it constructs a class\ncalled \"NamedFile\" which is a common subclass of \"Name\" and the\nstandard class \"IO::File\".  This puts inheritability to the test\nbecause objects of \"IO::File\" must be globrefs.  Objects of \"NamedFile\"\nshould behave like a file opened for reading and also support the\n\"name()\" method.  This class juncture works with exception of the\n\"Namehash\" implementation, where object initialization fails because\nof the incompatibility of object bodies.\n\nExample 2\nuse strict; use warnings; $| = 1;\n\nuse Example;\n\n{\npackage Name;\nuse parent 'Nameid';  # define here which implementation to run\n}\n\n# Verify that the base package works\nmy $n = Name->init(qw(Albert Einstein));\nprint $n->name, \"\\n\";\nprint \"\\n\";\n\n# Create a named file handle (See definition below)\nmy $nf = NamedFile->init(qw(/tmp/x Filomena File));\n# use as a file handle...\nfor ( 1 .. 3 ) {\nmy $l = <$nf>;\nprint \"line $: $l\";\n}\n# ...and as a Name object\nprint \"...brought to you by \", $nf->name, \"\\n\";\nexit;\n\n# Definition of NamedFile\npackage NamedFile;\nuse parent 'Name';\nuse parent 'IO::File';\n\nsub init {\nmy $obj = shift;\nmy ($file, $first, $last) = @;\n$obj = $obj->IO::File::new() unless ref $obj;\n$obj->open($file) or die \"Can't read '$file': $!\";\n$obj->Name::init($first, $last);\n}\nEND\n",
            "subsections": []
        },
        "GUTS": {
            "content": "To make \"Hash::Util::FieldHash\" work, there were two changes to perl\nitself.  \"PERLMAGICuvar\" was made available for hashes, and weak\nreferences now call uvar \"get\" magic after a weakref has been cleared.\nThe first feature is used to make field hashes intercept their keys\nupon access.  The second one triggers garbage collection.\n\nThe \"PERLMAGICuvar\" interface for hashes\n\"PERLMAGICuvar\" get magic is called from \"hvfetchcommon\" and\n\"hvdeletecommon\" through the function \"hvmagicuvarxkey\", which\ndefines the interface.  The call happens for hashes with \"uvar\" magic\nif the \"ufuncs\" structure has equal values in the \"ufval\" and \"ufset\"\nfields.  Hashes are unaffected if (and as long as) these fields hold\ndifferent values.\n\nUpon the call, the \"mgobj\" field will hold the hash key to be\naccessed.  Upon return, the \"SV*\" value in \"mgobj\" will be used in\nplace of the original key in the hash access.  The integer index value\nin the first parameter will be the \"action\" value from\n\"hvfetchcommon\", or -1 if the call is from \"hvdeletecommon\".\n\nThis is a template for a function suitable for the \"ufval\" field in a\n\"ufuncs\" structure for this call.  The \"ufset\" and \"ufindex\" fields\nare irrelevant.\n\nIV watchkey(pTHX IV action, SV* field) {\nMAGIC* mg = mgfind(field, PERLMAGICuvar);\nSV* keysv = mg->mgobj;\n/* Do whatever you need to.  If you decide to\nsupply a different key newkey, return it like this\n*/\nsv2mortal(newkey);\nmg->mgobj = newkey;\nreturn 0;\n}\n\nWeakrefs call uvar magic\nWhen a weak reference is stored in an \"SV\" that has \"uvar\" magic, \"set\"\nmagic is called after the reference has gone stale.  This hook can be\nused to trigger further garbage-collection activities associated with\nthe referenced object.\n\nHow field hashes work\nThe three features of key hashes, key replacement, thread support, and\ngarbage collection are supported by a data structure called the object\nregistry.  This is a private hash where every object is stored.  An\n\"object\" in this sense is any reference (blessed or unblessed) that has\nbeen used as a field hash key.\n\nThe object registry keeps track of references that have been used as\nfield hash keys.  The keys are generated from the reference address\nlike in a field hash (though the registry isn't a field hash).  Each\nvalue is a weak copy of the original reference, stored in an \"SV\" that\nis itself magical (\"PERLMAGICuvar\" again).  The magical structure\nholds a list (another hash, really) of field hashes that the reference\nhas been used with.  When the weakref becomes stale, the magic is\nactivated and uses the list to delete the reference from all field\nhashes it has been used with.  After that, the entry is removed from\nthe object registry itself.  Implicitly, that frees the magic structure\nand the storage it has been using.\n\nWhenever a reference is used as a field hash key, the object registry\nis checked and a new entry is made if necessary.  The field hash is\nthen added to the list of fields this reference has used.\n\nThe object registry is also used to repair a field hash after thread\ncloning.  Here, the entire object registry is processed.  For every\nreference found there, the field hashes it has used are visited and the\nentry is updated.\n\nInternal function Hash::Util::FieldHash::fieldhash\n# test if %hash is a field hash\nmy $result = fieldhash \\ %hash, 0;\n\n# make %hash a field hash\nmy $result = fieldhash \\ %hash, 1;\n\n\"fieldhash\" is the internal function used to create field hashes.  It\ntakes two arguments, a hashref and a mode.  If the mode is boolean\nfalse, the hash is not changed but tested if it is a field hash.  If\nthe hash isn't a field hash the return value is boolean false.  If it\nis, the return value indicates the mode of field hash.  When called\nwith a boolean true mode, it turns the given hash into a field hash of\nthis mode, returning the mode of the created field hash.  \"fieldhash\"\ndoes not erase the given hash.\n\nCurrently there is only one type of field hash, and only the boolean\nvalue of the mode makes a difference, but that may change.\n",
            "subsections": []
        },
        "AUTHOR": {
            "content": "Anno Siegel (ANNO) wrote the xs code and the changes in perl proper\nJerry Hedden (JDHEDDEN) made it faster\n",
            "subsections": []
        },
        "COPYRIGHT AND LICENSE": {
            "content": "Copyright (C) 2006-2007 by (Anno Siegel)\n\nThis library is free software; you can redistribute it and/or modify it\nunder the same terms as Perl itself, either Perl version 5.8.7 or, at\nyour option, any later version of Perl 5 you may have available.\n\nperl v5.34.0                      2026-06-23      Hash::Util::FieldHash(3perl)",
            "subsections": []
        }
    },
    "summary": "Hash::Util::FieldHash - Support for Inside-Out Classes",
    "flags": [],
    "examples": [
        "The examples show a very simple class that implements a name,",
        "consisting of a first and last name (no middle initial).  The name",
        "class has four methods:",
        "o   \"init()\"",
        "An object method that initializes the first and last name to its",
        "two arguments. If called as a class method, \"init()\" creates an",
        "object in the given class and initializes that.",
        "o   \"first()\"",
        "Retrieve the first name",
        "o   \"last()\"",
        "Retrieve the last name",
        "o   \"name()\"",
        "Retrieve the full name, the first and last name joined by a blank.",
        "The examples show this class implemented with different levels of",
        "support by \"Hash::Util::FieldHash\".  All supported combinations are",
        "shown.  The difference between implementations is often quite small.",
        "The implementations are:",
        "o   \"Namehash\"",
        "A conventional (not inside-out) implementation where an object is a",
        "hash that stores the field values, without support by",
        "\"Hash::Util::FieldHash\".  This implementation doesn't allow",
        "arbitrary inheritance.",
        "o   \"Nameid\"",
        "Inside-out implementation based on the \"id()\" function.  It needs a",
        "\"DESTROY\" method.  For thread support a \"CLONE\" method (not shown)",
        "would also be needed.  Instead of \"Hash::Util::FieldHash::id()\" the",
        "function \"Scalar::Util::refaddr\" could be used with very little",
        "functional difference.  This is the basic pattern of an inside-out",
        "class.",
        "o   \"Nameidhash\"",
        "Idhash-based inside-out implementation.  Like \"Nameid\" it needs a",
        "\"DESTROY\" method and would need \"CLONE\" for thread support.",
        "o   \"Nameidreg\"",
        "Inside-out implementation based on the \"id()\" function with",
        "explicit object registry.  No destructor is needed and objects are",
        "thread safe.",
        "o   \"Nameidhashreg\"",
        "Idhash-based inside-out implementation with explicit object",
        "registry.  No destructor is needed and objects are thread safe.",
        "o   \"Namefieldhash\"",
        "FieldHash-based inside-out implementation.  Object registry happens",
        "automatically.  No destructor is needed and objects are thread",
        "safe.",
        "These examples are realized in the code below, which could be copied to",
        "a file Example.pm.",
        "Example 1",
        "use strict; use warnings;",
        "package Namehash;  # standard implementation: the",
        "# object is a hash",
        "sub init {",
        "my $obj = shift;",
        "my ($first, $last) = @;",
        "# create an object if called as class method",
        "$obj = bless {}, $obj unless ref $obj;",
        "$obj->{ first} = $first;",
        "$obj->{ last} = $last;",
        "$obj;",
        "sub first { shift()->{ first} }",
        "sub last { shift()->{ last} }",
        "sub name {",
        "my $n = shift;",
        "join ' ' => $n->first, $n->last;",
        "package Nameid;",
        "use Hash::Util::FieldHash qw(id);",
        "my (%first, %last);",
        "sub init {",
        "my $obj = shift;",
        "my ($first, $last) = @;",
        "# create an object if called as class method",
        "$obj = bless \\ my $o, $obj unless ref $obj;",
        "$first{ id $obj} = $first;",
        "$last{ id $obj} = $last;",
        "$obj;",
        "sub first { $first{ id shift()} }",
        "sub last { $last{ id shift()} }",
        "sub name {",
        "my $n = shift;",
        "join ' ' => $n->first, $n->last;",
        "sub DESTROY {",
        "my $id = id shift;",
        "delete $first{ $id};",
        "delete $last{ $id};",
        "package Nameidhash;",
        "use Hash::Util::FieldHash;",
        "Hash::Util::FieldHash::idhashes( \\ my (%first, %last) );",
        "sub init {",
        "my $obj = shift;",
        "my ($first, $last) = @;",
        "# create an object if called as class method",
        "$obj = bless \\ my $o, $obj unless ref $obj;",
        "$first{ $obj} = $first;",
        "$last{ $obj} = $last;",
        "$obj;",
        "sub first { $first{ shift()} }",
        "sub last { $last{ shift()} }",
        "sub name {",
        "my $n = shift;",
        "join ' ' => $n->first, $n->last;",
        "sub DESTROY {",
        "my $n = shift;",
        "delete $first{ $n};",
        "delete $last{ $n};",
        "package Nameidreg;",
        "use Hash::Util::FieldHash qw(id register);",
        "my (%first, %last);",
        "sub init {",
        "my $obj = shift;",
        "my ($first, $last) = @;",
        "# create an object if called as class method",
        "$obj = bless \\ my $o, $obj unless ref $obj;",
        "register( $obj, \\ (%first, %last) );",
        "$first{ id $obj} = $first;",
        "$last{ id $obj} = $last;",
        "$obj;",
        "sub first { $first{ id shift()} }",
        "sub last { $last{ id shift()} }",
        "sub name {",
        "my $n = shift;",
        "join ' ' => $n->first, $n->last;",
        "package Nameidhashreg;",
        "use Hash::Util::FieldHash qw(register);",
        "Hash::Util::FieldHash::idhashes \\ my (%first, %last);",
        "sub init {",
        "my $obj = shift;",
        "my ($first, $last) = @;",
        "# create an object if called as class method",
        "$obj = bless \\ my $o, $obj unless ref $obj;",
        "register( $obj, \\ (%first, %last) );",
        "$first{ $obj} = $first;",
        "$last{ $obj} = $last;",
        "$obj;",
        "sub first { $first{ shift()} }",
        "sub last { $last{ shift()} }",
        "sub name {",
        "my $n = shift;",
        "join ' ' => $n->first, $n->last;",
        "package Namefieldhash;",
        "use Hash::Util::FieldHash;",
        "Hash::Util::FieldHash::fieldhashes \\ my (%first, %last);",
        "sub init {",
        "my $obj = shift;",
        "my ($first, $last) = @;",
        "# create an object if called as class method",
        "$obj = bless \\ my $o, $obj unless ref $obj;",
        "$first{ $obj} = $first;",
        "$last{ $obj} = $last;",
        "$obj;",
        "sub first { $first{ shift()} }",
        "sub last { $last{ shift()} }",
        "sub name {",
        "my $n = shift;",
        "join ' ' => $n->first, $n->last;",
        "1;",
        "To exercise the various implementations the script below can be used.",
        "It sets up a class \"Name\" that is a mirror of one of the implementation",
        "classes \"Namehash\", \"Nameid\", ..., \"Namefieldhash\".  That determines",
        "which implementation is run.",
        "The script first verifies the function of the \"Name\" class.",
        "In the second step, the free inheritability of the implementation (or",
        "lack thereof) is demonstrated.  For this purpose it constructs a class",
        "called \"NamedFile\" which is a common subclass of \"Name\" and the",
        "standard class \"IO::File\".  This puts inheritability to the test",
        "because objects of \"IO::File\" must be globrefs.  Objects of \"NamedFile\"",
        "should behave like a file opened for reading and also support the",
        "\"name()\" method.  This class juncture works with exception of the",
        "\"Namehash\" implementation, where object initialization fails because",
        "of the incompatibility of object bodies.",
        "Example 2",
        "use strict; use warnings; $| = 1;",
        "use Example;",
        "package Name;",
        "use parent 'Nameid';  # define here which implementation to run",
        "# Verify that the base package works",
        "my $n = Name->init(qw(Albert Einstein));",
        "print $n->name, \"\\n\";",
        "print \"\\n\";",
        "# Create a named file handle (See definition below)",
        "my $nf = NamedFile->init(qw(/tmp/x Filomena File));",
        "# use as a file handle...",
        "for ( 1 .. 3 ) {",
        "my $l = <$nf>;",
        "print \"line $: $l\";",
        "# ...and as a Name object",
        "print \"...brought to you by \", $nf->name, \"\\n\";",
        "exit;",
        "# Definition of NamedFile",
        "package NamedFile;",
        "use parent 'Name';",
        "use parent 'IO::File';",
        "sub init {",
        "my $obj = shift;",
        "my ($file, $first, $last) = @;",
        "$obj = $obj->IO::File::new() unless ref $obj;",
        "$obj->open($file) or die \"Can't read '$file': $!\";",
        "$obj->Name::init($first, $last);",
        "END"
    ],
    "see_also": []
}