{
    "content": [
        {
            "type": "text",
            "text": "# perltie (man)\n\n## NAME\n\nperltie - how to hide an object class in a simple variable\n\n## SYNOPSIS\n\ntie VARIABLE, CLASSNAME, LIST\n$object = tied VARIABLE\nuntie VARIABLE\n\n## DESCRIPTION\n\nPrior to release 5.0 of Perl, a programmer could use dbmopen() to connect an on-disk database\nin the standard Unix dbm(3x) format magically to a %HASH in their program.  However, their\nPerl was either built with one particular dbm library or another, but not both, and you\ncouldn't extend this mechanism to other packages or types of variables.\n\n## Sections\n\n- **NAME**\n- **SYNOPSIS**\n- **DESCRIPTION** (6 subsections)\n- **SEE ALSO**\n- **BUGS**\n- **AUTHOR**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "perltie",
        "section": "",
        "mode": "man",
        "summary": "perltie - how to hide an object class in a simple variable",
        "synopsis": "tie VARIABLE, CLASSNAME, LIST\n$object = tied VARIABLE\nuntie VARIABLE",
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "SYNOPSIS",
                "lines": 6,
                "subsections": []
            },
            {
                "name": "DESCRIPTION",
                "lines": 27,
                "subsections": [
                    {
                        "name": "Tying Scalars",
                        "lines": 124
                    },
                    {
                        "name": "Tying Arrays",
                        "lines": 257
                    },
                    {
                        "name": "Tying Hashes",
                        "lines": 317
                    },
                    {
                        "name": "Tying FileHandles",
                        "lines": 131
                    },
                    {
                        "name": "UNTIE this",
                        "lines": 3
                    },
                    {
                        "name": "The \"untie\" Gotcha",
                        "lines": 136
                    }
                ]
            },
            {
                "name": "SEE ALSO",
                "lines": 4,
                "subsections": []
            },
            {
                "name": "BUGS",
                "lines": 25,
                "subsections": []
            },
            {
                "name": "AUTHOR",
                "lines": 13,
                "subsections": []
            }
        ],
        "sections": {
            "NAME": {
                "content": "perltie - how to hide an object class in a simple variable\n",
                "subsections": []
            },
            "SYNOPSIS": {
                "content": "tie VARIABLE, CLASSNAME, LIST\n\n$object = tied VARIABLE\n\nuntie VARIABLE\n",
                "subsections": []
            },
            "DESCRIPTION": {
                "content": "Prior to release 5.0 of Perl, a programmer could use dbmopen() to connect an on-disk database\nin the standard Unix dbm(3x) format magically to a %HASH in their program.  However, their\nPerl was either built with one particular dbm library or another, but not both, and you\ncouldn't extend this mechanism to other packages or types of variables.\n\nNow you can.\n\nThe tie() function binds a variable to a class (package) that will provide the implementation\nfor access methods for that variable.  Once this magic has been performed, accessing a tied\nvariable automatically triggers method calls in the proper class.  The complexity of the\nclass is hidden behind magic methods calls.  The method names are in ALL CAPS, which is a\nconvention that Perl uses to indicate that they're called implicitly rather than\nexplicitly--just like the BEGIN() and END() functions.\n\nIn the tie() call, \"VARIABLE\" is the name of the variable to be enchanted.  \"CLASSNAME\" is\nthe name of a class implementing objects of the correct type.  Any additional arguments in\nthe \"LIST\" are passed to the appropriate constructor method for that class--meaning\nTIESCALAR(), TIEARRAY(), TIEHASH(), or TIEHANDLE().  (Typically these are arguments such as\nmight be passed to the dbminit() function of C.) The object returned by the \"new\" method is\nalso returned by the tie() function, which would be useful if you wanted to access other\nmethods in \"CLASSNAME\". (You don't actually have to return a reference to a right \"type\"\n(e.g., HASH or \"CLASSNAME\") so long as it's a properly blessed object.)  You can also\nretrieve a reference to the underlying object using the tied() function.\n\nUnlike dbmopen(), the tie() function will not \"use\" or \"require\" a module for you--you need\nto do that explicitly yourself.\n",
                "subsections": [
                    {
                        "name": "Tying Scalars",
                        "content": "A class implementing a tied scalar should define the following methods: TIESCALAR, FETCH,\nSTORE, and possibly UNTIE and/or DESTROY.\n\nLet's look at each in turn, using as an example a tie class for scalars that allows the user\nto do something like:\n\ntie $hisspeed, 'Nice', getppid();\ntie $myspeed,  'Nice', $$;\n\nAnd now whenever either of those variables is accessed, its current system priority is\nretrieved and returned.  If those variables are set, then the process's priority is changed!\n\nWe'll use Jarkko Hietaniemi <jhi@iki.fi>'s BSD::Resource class (not included) to access the\nPRIOPROCESS, PRIOMIN, and PRIOMAX constants from your system, as well as the getpriority()\nand setpriority() system calls.  Here's the preamble of the class.\n\npackage Nice;\nuse Carp;\nuse BSD::Resource;\nuse strict;\n$Nice::DEBUG = 0 unless defined $Nice::DEBUG;\n\nTIESCALAR classname, LIST\nThis is the constructor for the class.  That means it is expected to return a blessed\nreference to a new scalar (probably anonymous) that it's creating.  For example:\n\nsub TIESCALAR {\nmy $class = shift;\nmy $pid = shift || $$; # 0 means me\n\nif ($pid !~ /^\\d+$/) {\ncarp \"Nice::Tie::Scalar got non-numeric pid $pid\" if $^W;\nreturn undef;\n}\n\nunless (kill 0, $pid) { # EPERM or ERSCH, no doubt\ncarp \"Nice::Tie::Scalar got bad pid $pid: $!\" if $^W;\nreturn undef;\n}\n\nreturn bless \\$pid, $class;\n}\n\nThis tie class has chosen to return an error rather than raising an exception if its\nconstructor should fail.  While this is how dbmopen() works, other classes may well not\nwish to be so forgiving.  It checks the global variable $^W to see whether to emit a bit\nof noise anyway.\n\nFETCH this\nThis method will be triggered every time the tied variable is accessed (read).  It takes\nno arguments beyond its self reference, which is the object representing the scalar we're\ndealing with.  Because in this case we're using just a SCALAR ref for the tied scalar\nobject, a simple $$self allows the method to get at the real value stored there.  In our\nexample below, that real value is the process ID to which we've tied our variable.\n\nsub FETCH {\nmy $self = shift;\nconfess \"wrong type\" unless ref $self;\ncroak \"usage error\" if @;\nmy $nicety;\nlocal($!) = 0;\n$nicety = getpriority(PRIOPROCESS, $$self);\nif ($!) { croak \"getpriority failed: $!\" }\nreturn $nicety;\n}\n\nThis time we've decided to blow up (raise an exception) if the renice fails--there's no\nplace for us to return an error otherwise, and it's probably the right thing to do.\n\nSTORE this, value\nThis method will be triggered every time the tied variable is set (assigned).  Beyond its\nself reference, it also expects one (and only one) argument: the new value the user is\ntrying to assign. Don't worry about returning a value from STORE; the semantic of\nassignment returning the assigned value is implemented with FETCH.\n\nsub STORE {\nmy $self = shift;\nconfess \"wrong type\" unless ref $self;\nmy $newnicety = shift;\ncroak \"usage error\" if @;\n\nif ($newnicety < PRIOMIN) {\ncarp sprintf\n\"WARNING: priority %d less than minimum system priority %d\",\n$newnicety, PRIOMIN if $^W;\n$newnicety = PRIOMIN;\n}\n\nif ($newnicety > PRIOMAX) {\ncarp sprintf\n\"WARNING: priority %d greater than maximum system priority %d\",\n$newnicety, PRIOMAX if $^W;\n$newnicety = PRIOMAX;\n}\n\nunless (defined setpriority(PRIOPROCESS,\n$$self,\n$newnicety))\n{\nconfess \"setpriority failed: $!\";\n}\n}\n\nUNTIE this\nThis method will be triggered when the \"untie\" occurs. This can be useful if the class\nneeds to know when no further calls will be made. (Except DESTROY of course.) See \"The\n\"untie\" Gotcha\" below for more details.\n\nDESTROY this\nThis method will be triggered when the tied variable needs to be destructed.  As with\nother object classes, such a method is seldom necessary, because Perl deallocates its\nmoribund object's memory for you automatically--this isn't C++, you know.  We'll use a\nDESTROY method here for debugging purposes only.\n\nsub DESTROY {\nmy $self = shift;\nconfess \"wrong type\" unless ref $self;\ncarp \"[ Nice::DESTROY pid $$self ]\" if $Nice::DEBUG;\n}\n\nThat's about all there is to it.  Actually, it's more than all there is to it, because we've\ndone a few nice things here for the sake of completeness, robustness, and general aesthetics.\nSimpler TIESCALAR classes are certainly possible.\n"
                    },
                    {
                        "name": "Tying Arrays",
                        "content": "A class implementing a tied ordinary array should define the following methods: TIEARRAY,\nFETCH, STORE, FETCHSIZE, STORESIZE, CLEAR and perhaps UNTIE and/or DESTROY.\n\nFETCHSIZE and STORESIZE are used to provide $#array and equivalent \"scalar(@array)\" access.\n\nThe methods POP, PUSH, SHIFT, UNSHIFT, SPLICE, DELETE, and EXISTS are required if the perl\noperator with the corresponding (but lowercase) name is to operate on the tied array. The\nTie::Array class can be used as a base class to implement the first five of these in terms of\nthe basic methods above.  The default implementations of DELETE and EXISTS in Tie::Array\nsimply \"croak\".\n\nIn addition EXTEND will be called when perl would have pre-extended allocation in a real\narray.\n\nFor this discussion, we'll implement an array whose elements are a fixed size at creation.\nIf you try to create an element larger than the fixed size, you'll take an exception.  For\nexample:\n\nuse FixedElemArray;\ntie @array, 'FixedElemArray', 3;\n$array[0] = 'cat';  # ok.\n$array[1] = 'dogs'; # exception, length('dogs') > 3.\n\nThe preamble code for the class is as follows:\n\npackage FixedElemArray;\nuse Carp;\nuse strict;\n\nTIEARRAY classname, LIST\nThis is the constructor for the class.  That means it is expected to return a blessed\nreference through which the new array (probably an anonymous ARRAY ref) will be accessed.\n\nIn our example, just to show you that you don't really have to return an ARRAY reference,\nwe'll choose a HASH reference to represent our object.  A HASH works out well as a\ngeneric record type: the \"{ELEMSIZE}\" field will store the maximum element size allowed,\nand the \"{ARRAY}\" field will hold the true ARRAY ref.  If someone outside the class tries\nto dereference the object returned (doubtless thinking it an ARRAY ref), they'll blow up.\nThis just goes to show you that you should respect an object's privacy.\n\nsub TIEARRAY {\nmy $class    = shift;\nmy $elemsize = shift;\nif ( @ || $elemsize =~ /\\D/ ) {\ncroak \"usage: tie ARRAY, '\" . PACKAGE . \"', elemsize\";\n}\nreturn bless {\nELEMSIZE => $elemsize,\nARRAY    => [],\n}, $class;\n}\n\nFETCH this, index\nThis method will be triggered every time an individual element the tied array is accessed\n(read).  It takes one argument beyond its self reference: the index whose value we're\ntrying to fetch.\n\nsub FETCH {\nmy $self  = shift;\nmy $index = shift;\nreturn $self->{ARRAY}->[$index];\n}\n\nIf a negative array index is used to read from an array, the index will be translated to\na positive one internally by calling FETCHSIZE before being passed to FETCH.  You may\ndisable this feature by assigning a true value to the variable $NEGATIVEINDICES in the\ntied array class.\n\nAs you may have noticed, the name of the FETCH method (et al.) is the same for all\naccesses, even though the constructors differ in names (TIESCALAR vs TIEARRAY).  While in\ntheory you could have the same class servicing several tied types, in practice this\nbecomes cumbersome, and it's easiest to keep them at simply one tie type per class.\n\nSTORE this, index, value\nThis method will be triggered every time an element in the tied array is set (written).\nIt takes two arguments beyond its self reference: the index at which we're trying to\nstore something and the value we're trying to put there.\n\nIn our example, \"undef\" is really \"$self->{ELEMSIZE}\" number of spaces so we have a\nlittle more work to do here:\n\nsub STORE {\nmy $self = shift;\nmy( $index, $value ) = @;\nif ( length $value > $self->{ELEMSIZE} ) {\ncroak \"length of $value is greater than $self->{ELEMSIZE}\";\n}\n# fill in the blanks\n$self->STORESIZE( $index ) if $index > $self->FETCHSIZE();\n# right justify to keep element size for smaller elements\n$self->{ARRAY}->[$index] = sprintf \"%$self->{ELEMSIZE}s\", $value;\n}\n\nNegative indexes are treated the same as with FETCH.\n\nFETCHSIZE this\nReturns the total number of items in the tied array associated with object this.\n(Equivalent to \"scalar(@array)\").  For example:\n\nsub FETCHSIZE {\nmy $self = shift;\nreturn scalar $self->{ARRAY}->@*;\n}\n\nSTORESIZE this, count\nSets the total number of items in the tied array associated with object this to be count.\nIf this makes the array larger then class's mapping of \"undef\" should be returned for new\npositions.  If the array becomes smaller then entries beyond count should be deleted.\n\nIn our example, 'undef' is really an element containing \"$self->{ELEMSIZE}\" number of\nspaces.  Observe:\n\nsub STORESIZE {\nmy $self  = shift;\nmy $count = shift;\nif ( $count > $self->FETCHSIZE() ) {\nforeach ( $count - $self->FETCHSIZE() .. $count ) {\n$self->STORE( $, '' );\n}\n} elsif ( $count < $self->FETCHSIZE() ) {\nforeach ( 0 .. $self->FETCHSIZE() - $count - 2 ) {\n$self->POP();\n}\n}\n}\n\nEXTEND this, count\nInformative call that array is likely to grow to have count entries.  Can be used to\noptimize allocation. This method need do nothing.\n\nIn our example there is no reason to implement this method, so we leave it as a no-op.\nThis method is only relevant to tied array implementations where there is the possibility\nof having the allocated size of the array be larger than is visible to a perl programmer\ninspecting the size of the array. Many tied array implementations will have no reason to\nimplement it.\n\nsub EXTEND {\nmy $self  = shift;\nmy $count = shift;\n# nothing to see here, move along.\n}\n\nNOTE: It is generally an error to make this equivalent to STORESIZE.  Perl may from time\nto time call EXTEND without wanting to actually change the array size directly. Any tied\narray should function correctly if this method is a no-op, even if perhaps they might not\nbe as efficient as they would if this method was implemented.\n\nEXISTS this, key\nVerify that the element at index key exists in the tied array this.\n\nIn our example, we will determine that if an element consists of \"$self->{ELEMSIZE}\"\nspaces only, it does not exist:\n\nsub EXISTS {\nmy $self  = shift;\nmy $index = shift;\nreturn 0 if ! defined $self->{ARRAY}->[$index] ||\n$self->{ARRAY}->[$index] eq ' ' x $self->{ELEMSIZE};\nreturn 1;\n}\n\nDELETE this, key\nDelete the element at index key from the tied array this.\n\nIn our example, a deleted item is \"$self->{ELEMSIZE}\" spaces:\n\nsub DELETE {\nmy $self  = shift;\nmy $index = shift;\nreturn $self->STORE( $index, '' );\n}\n\nCLEAR this\nClear (remove, delete, ...) all values from the tied array associated with object this.\nFor example:\n\nsub CLEAR {\nmy $self = shift;\nreturn $self->{ARRAY} = [];\n}\n\nPUSH this, LIST\nAppend elements of LIST to the array.  For example:\n\nsub PUSH {\nmy $self = shift;\nmy @list = @;\nmy $last = $self->FETCHSIZE();\n$self->STORE( $last + $, $list[$] ) foreach 0 .. $#list;\nreturn $self->FETCHSIZE();\n}\n\nPOP this\nRemove last element of the array and return it.  For example:\n\nsub POP {\nmy $self = shift;\nreturn pop $self->{ARRAY}->@*;\n}\n\nSHIFT this\nRemove the first element of the array (shifting other elements down) and return it.  For\nexample:\n\nsub SHIFT {\nmy $self = shift;\nreturn shift $self->{ARRAY}->@*;\n}\n\nUNSHIFT this, LIST\nInsert LIST elements at the beginning of the array, moving existing elements up to make\nroom.  For example:\n\nsub UNSHIFT {\nmy $self = shift;\nmy @list = @;\nmy $size = scalar( @list );\n# make room for our list\n$self->{ARRAY}[ $size .. $self->{ARRAY}->$#* + $size ]->@*\n= $self->{ARRAY}->@*\n$self->STORE( $, $list[$] ) foreach 0 .. $#list;\n}\n\nSPLICE this, offset, length, LIST\nPerform the equivalent of \"splice\" on the array.\n\noffset is optional and defaults to zero, negative values count back from the end of the\narray.\n\nlength is optional and defaults to rest of the array.\n\nLIST may be empty.\n\nReturns a list of the original length elements at offset.\n\nIn our example, we'll use a little shortcut if there is a LIST:\n\nsub SPLICE {\nmy $self   = shift;\nmy $offset = shift || 0;\nmy $length = shift || $self->FETCHSIZE() - $offset;\nmy @list   = ();\nif ( @ ) {\ntie @list, PACKAGE, $self->{ELEMSIZE};\n@list   = @;\n}\nreturn splice $self->{ARRAY}->@*, $offset, $length, @list;\n}\n\nUNTIE this\nWill be called when \"untie\" happens. (See \"The \"untie\" Gotcha\" below.)\n\nDESTROY this\nThis method will be triggered when the tied variable needs to be destructed.  As with the\nscalar tie class, this is almost never needed in a language that does its own garbage\ncollection, so this time we'll just leave it out.\n"
                    },
                    {
                        "name": "Tying Hashes",
                        "content": "Hashes were the first Perl data type to be tied (see dbmopen()).  A class implementing a tied\nhash should define the following methods: TIEHASH is the constructor.  FETCH and STORE access\nthe key and value pairs.  EXISTS reports whether a key is present in the hash, and DELETE\ndeletes one.  CLEAR empties the hash by deleting all the key and value pairs.  FIRSTKEY and\nNEXTKEY implement the keys() and each() functions to iterate over all the keys. SCALAR is\ntriggered when the tied hash is evaluated in scalar context, and in 5.28 onwards, by \"keys\"\nin boolean context. UNTIE is called when \"untie\" happens, and DESTROY is called when the tied\nvariable is garbage collected.\n\nIf this seems like a lot, then feel free to inherit from merely the standard Tie::StdHash\nmodule for most of your methods, redefining only the interesting ones.  See Tie::Hash for\ndetails.\n\nRemember that Perl distinguishes between a key not existing in the hash, and the key existing\nin the hash but having a corresponding value of \"undef\".  The two possibilities can be tested\nwith the \"exists()\" and \"defined()\" functions.\n\nHere's an example of a somewhat interesting tied hash class:  it gives you a hash\nrepresenting a particular user's dot files.  You index into the hash with the name of the\nfile (minus the dot) and you get back that dot file's contents.  For example:\n\nuse DotFiles;\ntie %dot, 'DotFiles';\nif ( $dot{profile} =~ /MANPATH/ ||\n$dot{login}   =~ /MANPATH/ ||\n$dot{cshrc}   =~ /MANPATH/    )\n{\nprint \"you seem to set your MANPATH\\n\";\n}\n\nOr here's another sample of using our tied class:\n\ntie %him, 'DotFiles', 'daemon';\nforeach $f ( keys %him ) {\nprintf \"daemon dot file %s is size %d\\n\",\n$f, length $him{$f};\n}\n\nIn our tied hash DotFiles example, we use a regular hash for the object containing several\nimportant fields, of which only the \"{LIST}\" field will be what the user thinks of as the\nreal hash.\n\nUSER whose dot files this object represents\n\nHOME where those dot files live\n\nCLOBBER\nwhether we should try to change or remove those dot files\n\nLIST the hash of dot file names and content mappings\n\nHere's the start of Dotfiles.pm:\n\npackage DotFiles;\nuse Carp;\nsub whowasi { (caller(1))[3] . '()' }\nmy $DEBUG = 0;\nsub debug { $DEBUG = @ ? shift : 1 }\n\nFor our example, we want to be able to emit debugging info to help in tracing during\ndevelopment.  We keep also one convenience function around internally to help print out\nwarnings; whowasi() returns the function name that calls it.\n\nHere are the methods for the DotFiles tied hash.\n\nTIEHASH classname, LIST\nThis is the constructor for the class.  That means it is expected to return a blessed\nreference through which the new object (probably but not necessarily an anonymous hash)\nwill be accessed.\n\nHere's the constructor:\n\nsub TIEHASH {\nmy $self = shift;\nmy $user = shift || $>;\nmy $dotdir = shift || '';\ncroak \"usage: @{[&whowasi]} [USER [DOTDIR]]\" if @;\n$user = getpwuid($user) if $user =~ /^\\d+$/;\nmy $dir = (getpwnam($user))[7]\n|| croak \"@{[&whowasi]}: no user $user\";\n$dir .= \"/$dotdir\" if $dotdir;\n\nmy $node = {\nUSER    => $user,\nHOME    => $dir,\nLIST    => {},\nCLOBBER => 0,\n};\n\nopendir(DIR, $dir)\n|| croak \"@{[&whowasi]}: can't opendir $dir: $!\";\nforeach $dot ( grep /^\\./ && -f \"$dir/$\", readdir(DIR)) {\n$dot =~ s/^\\.//;\n$node->{LIST}{$dot} = undef;\n}\nclosedir DIR;\nreturn bless $node, $self;\n}\n\nIt's probably worth mentioning that if you're going to filetest the return values out of\na readdir, you'd better prepend the directory in question.  Otherwise, because we didn't\nchdir() there, it would have been testing the wrong file.\n\nFETCH this, key\nThis method will be triggered every time an element in the tied hash is accessed (read).\nIt takes one argument beyond its self reference: the key whose value we're trying to\nfetch.\n\nHere's the fetch for our DotFiles example.\n\nsub FETCH {\ncarp &whowasi if $DEBUG;\nmy $self = shift;\nmy $dot = shift;\nmy $dir = $self->{HOME};\nmy $file = \"$dir/.$dot\";\n\nunless (exists $self->{LIST}->{$dot} || -f $file) {\ncarp \"@{[&whowasi]}: no $dot file\" if $DEBUG;\nreturn undef;\n}\n\nif (defined $self->{LIST}->{$dot}) {\nreturn $self->{LIST}->{$dot};\n} else {\nreturn $self->{LIST}->{$dot} = `cat $dir/.$dot`;\n}\n}\n\nIt was easy to write by having it call the Unix cat(1) command, but it would probably be\nmore portable to open the file manually (and somewhat more efficient).  Of course,\nbecause dot files are a Unixy concept, we're not that concerned.\n\nSTORE this, key, value\nThis method will be triggered every time an element in the tied hash is set (written).\nIt takes two arguments beyond its self reference: the index at which we're trying to\nstore something, and the value we're trying to put there.\n\nHere in our DotFiles example, we'll be careful not to let them try to overwrite the file\nunless they've called the clobber() method on the original object reference returned by\ntie().\n\nsub STORE {\ncarp &whowasi if $DEBUG;\nmy $self = shift;\nmy $dot = shift;\nmy $value = shift;\nmy $file = $self->{HOME} . \"/.$dot\";\nmy $user = $self->{USER};\n\ncroak \"@{[&whowasi]}: $file not clobberable\"\nunless $self->{CLOBBER};\n\nopen(my $f, '>', $file) || croak \"can't open $file: $!\";\nprint $f $value;\nclose($f);\n}\n\nIf they wanted to clobber something, they might say:\n\n$ob = tie %daemondots, 'daemon';\n$ob->clobber(1);\n$daemondots{signature} = \"A true daemon\\n\";\n\nAnother way to lay hands on a reference to the underlying object is to use the tied()\nfunction, so they might alternately have set clobber using:\n\ntie %daemondots, 'daemon';\ntied(%daemondots)->clobber(1);\n\nThe clobber method is simply:\n\nsub clobber {\nmy $self = shift;\n$self->{CLOBBER} = @ ? shift : 1;\n}\n\nDELETE this, key\nThis method is triggered when we remove an element from the hash, typically by using the\ndelete() function.  Again, we'll be careful to check whether they really want to clobber\nfiles.\n\nsub DELETE   {\ncarp &whowasi if $DEBUG;\n\nmy $self = shift;\nmy $dot = shift;\nmy $file = $self->{HOME} . \"/.$dot\";\ncroak \"@{[&whowasi]}: won't remove file $file\"\nunless $self->{CLOBBER};\ndelete $self->{LIST}->{$dot};\nmy $success = unlink($file);\ncarp \"@{[&whowasi]}: can't unlink $file: $!\" unless $success;\n$success;\n}\n\nThe value returned by DELETE becomes the return value of the call to delete().  If you\nwant to emulate the normal behavior of delete(), you should return whatever FETCH would\nhave returned for this key.  In this example, we have chosen instead to return a value\nwhich tells the caller whether the file was successfully deleted.\n\nCLEAR this\nThis method is triggered when the whole hash is to be cleared, usually by assigning the\nempty list to it.\n\nIn our example, that would remove all the user's dot files!  It's such a dangerous thing\nthat they'll have to set CLOBBER to something higher than 1 to make it happen.\n\nsub CLEAR    {\ncarp &whowasi if $DEBUG;\nmy $self = shift;\ncroak \"@{[&whowasi]}: won't remove all dot files for $self->{USER}\"\nunless $self->{CLOBBER} > 1;\nmy $dot;\nforeach $dot ( keys $self->{LIST}->%* ) {\n$self->DELETE($dot);\n}\n}\n\nEXISTS this, key\nThis method is triggered when the user uses the exists() function on a particular hash.\nIn our example, we'll look at the \"{LIST}\" hash element for this:\n\nsub EXISTS   {\ncarp &whowasi if $DEBUG;\nmy $self = shift;\nmy $dot = shift;\nreturn exists $self->{LIST}->{$dot};\n}\n\nFIRSTKEY this\nThis method will be triggered when the user is going to iterate through the hash, such as\nvia a keys(), values(), or each() call.\n\nsub FIRSTKEY {\ncarp &whowasi if $DEBUG;\nmy $self = shift;\nmy $a = keys $self->{LIST}->%*;  # reset each() iterator\neach $self->{LIST}->%*\n}\n\nFIRSTKEY is always called in scalar context and it should just return the first key.\nvalues(), and each() in list context, will call FETCH for the returned keys.\n\nNEXTKEY this, lastkey\nThis method gets triggered during a keys(), values(), or each() iteration.  It has a\nsecond argument which is the last key that had been accessed.  This is useful if you're\ncaring about ordering or calling the iterator from more than one sequence, or not really\nstoring things in a hash anywhere.\n\nNEXTKEY is always called in scalar context and it should just return the next key.\nvalues(), and each() in list context, will call FETCH for the returned keys.\n\nFor our example, we're using a real hash so we'll do just the simple thing, but we'll\nhave to go through the LIST field indirectly.\n\nsub NEXTKEY  {\ncarp &whowasi if $DEBUG;\nmy $self = shift;\nreturn each $self->{LIST}->%*\n}\n\nIf the object underlying your tied hash isn't a real hash and you don't have \"each\"\navailable, then you should return \"undef\" or the empty list once you've reached the end\nof your list of keys. See \"each's own documentation\" for more details.\n\nSCALAR this\nThis is called when the hash is evaluated in scalar context, and in 5.28 onwards, by\n\"keys\" in boolean context. In order to mimic the behaviour of untied hashes, this method\nmust return a value which when used as boolean, indicates whether the tied hash is\nconsidered empty. If this method does not exist, perl will make some educated guesses and\nreturn true when the hash is inside an iteration. If this isn't the case, FIRSTKEY is\ncalled, and the result will be a false value if FIRSTKEY returns the empty list, true\notherwise.\n\nHowever, you should not blindly rely on perl always doing the right thing. Particularly,\nperl will mistakenly return true when you clear the hash by repeatedly calling DELETE\nuntil it is empty. You are therefore advised to supply your own SCALAR method when you\nwant to be absolutely sure that your hash behaves nicely in scalar context.\n\nIn our example we can just call \"scalar\" on the underlying hash referenced by\n\"$self->{LIST}\":\n\nsub SCALAR {\ncarp &whowasi if $DEBUG;\nmy $self = shift;\nreturn scalar $self->{LIST}->%*\n}\n\nNOTE: In perl 5.25 the behavior of scalar %hash on an untied hash changed to return the\ncount of keys. Prior to this it returned a string containing information about the bucket\nsetup of the hash. See \"bucketratio\" in Hash::Util for a backwards compatibility path.\n\nUNTIE this\nThis is called when \"untie\" occurs.  See \"The \"untie\" Gotcha\" below.\n\nDESTROY this\nThis method is triggered when a tied hash is about to go out of scope.  You don't really\nneed it unless you're trying to add debugging or have auxiliary state to clean up.\nHere's a very simple function:\n\nsub DESTROY  {\ncarp &whowasi if $DEBUG;\n}\n\nNote that functions such as keys() and values() may return huge lists when used on large\nobjects, like DBM files.  You may prefer to use the each() function to iterate over such.\nExample:\n\n# print out history file offsets\nuse NDBMFile;\ntie(%HIST, 'NDBMFile', '/usr/lib/news/history', 1, 0);\nwhile (($key,$val) = each %HIST) {\nprint $key, ' = ', unpack('L',$val), \"\\n\";\n}\nuntie(%HIST);\n"
                    },
                    {
                        "name": "Tying FileHandles",
                        "content": "This is partially implemented now.\n\nA class implementing a tied filehandle should define the following methods: TIEHANDLE, at\nleast one of PRINT, PRINTF, WRITE, READLINE, GETC, READ, and possibly CLOSE, UNTIE and\nDESTROY.  The class can also provide: BINMODE, OPEN, EOF, FILENO, SEEK, TELL - if the\ncorresponding perl operators are used on the handle.\n\nWhen STDERR is tied, its PRINT method will be called to issue warnings and error messages.\nThis feature is temporarily disabled during the call, which means you can use \"warn()\" inside\nPRINT without starting a recursive loop.  And just like \"WARN\" and \"DIE\" handlers,\nSTDERR's PRINT method may be called to report parser errors, so the caveats mentioned under\n\"%SIG\" in perlvar apply.\n\nAll of this is especially useful when perl is embedded in some other program, where output to\nSTDOUT and STDERR may have to be redirected in some special way.  See nvi and the Apache\nmodule for examples.\n\nWhen tying a handle, the first argument to \"tie\" should begin with an asterisk.  So, if you\nare tying STDOUT, use *STDOUT.  If you have assigned it to a scalar variable, say $handle,\nuse *$handle.  \"tie $handle\" ties the scalar variable $handle, not the handle inside it.\n\nIn our example we're going to create a shouting handle.\n\npackage Shout;\n\nTIEHANDLE classname, LIST\nThis is the constructor for the class.  That means it is expected to return a blessed\nreference of some sort. The reference can be used to hold some internal information.\n\nsub TIEHANDLE { print \"<shout>\\n\"; my $i; bless \\$i, shift }\n\nWRITE this, LIST\nThis method will be called when the handle is written to via the \"syswrite\" function.\n\nsub WRITE {\n$r = shift;\nmy($buf,$len,$offset) = @;\nprint \"WRITE called, \\$buf=$buf, \\$len=$len, \\$offset=$offset\";\n}\n\nPRINT this, LIST\nThis method will be triggered every time the tied handle is printed to with the \"print()\"\nor \"say()\" functions.  Beyond its self reference it also expects the list that was passed\nto the print function.\n\nsub PRINT { $r = shift; $$r++; print join($,,map(uc($),@)),$\\ }\n\n\"say()\" acts just like \"print()\" except $\\ will be localized to \"\\n\" so you need do\nnothing special to handle \"say()\" in \"PRINT()\".\n\nPRINTF this, LIST\nThis method will be triggered every time the tied handle is printed to with the\n\"printf()\" function.  Beyond its self reference it also expects the format and list that\nwas passed to the printf function.\n\nsub PRINTF {\nshift;\nmy $fmt = shift;\nprint sprintf($fmt, @);\n}\n\nREAD this, LIST\nThis method will be called when the handle is read from via the \"read\" or \"sysread\"\nfunctions.\n\nsub READ {\nmy $self = shift;\nmy $bufref = \\$[0];\nmy(undef,$len,$offset) = @;\nprint \"READ called, \\$buf=$bufref, \\$len=$len, \\$offset=$offset\";\n# add to $$bufref, set $len to number of characters read\n$len;\n}\n\nREADLINE this\nThis method is called when the handle is read via \"<HANDLE>\" or \"readline HANDLE\".\n\nAs per \"readline\", in scalar context it should return the next line, or \"undef\" for no\nmore data.  In list context it should return all remaining lines, or an empty list for no\nmore data.  The strings returned should include the input record separator $/ (see\nperlvar), unless it is \"undef\" (which means \"slurp\" mode).\n\nsub READLINE {\nmy $r = shift;\nif (wantarray) {\nreturn (\"all remaining\\n\",\n\"lines up\\n\",\n\"to eof\\n\");\n} else {\nreturn \"READLINE called \" . ++$$r . \" times\\n\";\n}\n}\n\nGETC this\nThis method will be called when the \"getc\" function is called.\n\nsub GETC { print \"Don't GETC, Get Perl\"; return \"a\"; }\n\nEOF this\nThis method will be called when the \"eof\" function is called.\n\nStarting with Perl 5.12, an additional integer parameter will be passed.  It will be zero\nif \"eof\" is called without parameter; 1 if \"eof\" is given a filehandle as a parameter,\ne.g. \"eof(FH)\"; and 2 in the very special case that the tied filehandle is \"ARGV\" and\n\"eof\" is called with an empty parameter list, e.g. \"eof()\".\n\nsub EOF { not length $stringbuf }\n\nCLOSE this\nThis method will be called when the handle is closed via the \"close\" function.\n\nsub CLOSE { print \"CLOSE called.\\n\" }\n\nUNTIE this\nAs with the other types of ties, this method will be called when \"untie\" happens.  It may\nbe appropriate to \"auto CLOSE\" when this occurs.  See \"The \"untie\" Gotcha\" below.\n\nDESTROY this\nAs with the other types of ties, this method will be called when the tied handle is about\nto be destroyed. This is useful for debugging and possibly cleaning up.\n\nsub DESTROY { print \"</shout>\\n\" }\n\nHere's how to use our little example:\n\ntie(*FOO,'Shout');\nprint FOO \"hello\\n\";\n$a = 4; $b = 6;\nprint FOO $a, \" plus \", $b, \" equals \", $a + $b, \"\\n\";\nprint <FOO>;\n"
                    },
                    {
                        "name": "UNTIE this",
                        "content": "You can define for all tie types an UNTIE method that will be called at untie().  See \"The\n\"untie\" Gotcha\" below.\n"
                    },
                    {
                        "name": "The \"untie\" Gotcha",
                        "content": "If you intend making use of the object returned from either tie() or tied(), and if the tie's\ntarget class defines a destructor, there is a subtle gotcha you must guard against.\n\nAs setup, consider this (admittedly rather contrived) example of a tie; all it does is use a\nfile to keep a log of the values assigned to a scalar.\n\npackage Remember;\n\nuse strict;\nuse warnings;\nuse IO::File;\n\nsub TIESCALAR {\nmy $class = shift;\nmy $filename = shift;\nmy $handle = IO::File->new( \"> $filename\" )\nor die \"Cannot open $filename: $!\\n\";\n\nprint $handle \"The Start\\n\";\nbless {FH => $handle, Value => 0}, $class;\n}\n\nsub FETCH {\nmy $self = shift;\nreturn $self->{Value};\n}\n\nsub STORE {\nmy $self = shift;\nmy $value = shift;\nmy $handle = $self->{FH};\nprint $handle \"$value\\n\";\n$self->{Value} = $value;\n}\n\nsub DESTROY {\nmy $self = shift;\nmy $handle = $self->{FH};\nprint $handle \"The End\\n\";\nclose $handle;\n}\n\n1;\n\nHere is an example that makes use of this tie:\n\nuse strict;\nuse Remember;\n\nmy $fred;\ntie $fred, 'Remember', 'myfile.txt';\n$fred = 1;\n$fred = 4;\n$fred = 5;\nuntie $fred;\nsystem \"cat myfile.txt\";\n\nThis is the output when it is executed:\n\nThe Start\n1\n4\n5\nThe End\n\nSo far so good.  Those of you who have been paying attention will have spotted that the tied\nobject hasn't been used so far.  So lets add an extra method to the Remember class to allow\ncomments to be included in the file; say, something like this:\n\nsub comment {\nmy $self = shift;\nmy $text = shift;\nmy $handle = $self->{FH};\nprint $handle $text, \"\\n\";\n}\n\nAnd here is the previous example modified to use the \"comment\" method (which requires the\ntied object):\n\nuse strict;\nuse Remember;\n\nmy ($fred, $x);\n$x = tie $fred, 'Remember', 'myfile.txt';\n$fred = 1;\n$fred = 4;\ncomment $x \"changing...\";\n$fred = 5;\nuntie $fred;\nsystem \"cat myfile.txt\";\n\nWhen this code is executed there is no output.  Here's why:\n\nWhen a variable is tied, it is associated with the object which is the return value of the\nTIESCALAR, TIEARRAY, or TIEHASH function.  This object normally has only one reference,\nnamely, the implicit reference from the tied variable.  When untie() is called, that\nreference is destroyed.  Then, as in the first example above, the object's destructor\n(DESTROY) is called, which is normal for objects that have no more valid references; and thus\nthe file is closed.\n\nIn the second example, however, we have stored another reference to the tied object in $x.\nThat means that when untie() gets called there will still be a valid reference to the object\nin existence, so the destructor is not called at that time, and thus the file is not closed.\nThe reason there is no output is because the file buffers have not been flushed to disk.\n\nNow that you know what the problem is, what can you do to avoid it?  Prior to the\nintroduction of the optional UNTIE method the only way was the good old \"-w\" flag. Which will\nspot any instances where you call untie() and there are still valid references to the tied\nobject.  If the second script above this near the top \"use warnings 'untie'\" or was run with\nthe \"-w\" flag, Perl prints this warning message:\n\nuntie attempted while 1 inner references still exist\n\nTo get the script to work properly and silence the warning make sure there are no valid\nreferences to the tied object before untie() is called:\n\nundef $x;\nuntie $fred;\n\nNow that UNTIE exists the class designer can decide which parts of the class functionality\nare really associated with \"untie\" and which with the object being destroyed. What makes\nsense for a given class depends on whether the inner references are being kept so that non-\ntie-related methods can be called on the object. But in most cases it probably makes sense to\nmove the functionality that would have been in DESTROY to the UNTIE method.\n\nIf the UNTIE method exists then the warning above does not occur. Instead the UNTIE method is\npassed the count of \"extra\" references and can issue its own warning if appropriate. e.g. to\nreplicate the no UNTIE case this method can be used:\n\nsub UNTIE\n{\nmy ($obj,$count) = @;\ncarp \"untie attempted while $count inner references still exist\"\nif $count;\n}\n"
                    }
                ]
            },
            "SEE ALSO": {
                "content": "See DBFile or Config for some interesting tie() implementations.  A good starting point for\nmany tie() implementations is with one of the modules Tie::Scalar, Tie::Array, Tie::Hash, or\nTie::Handle.\n",
                "subsections": []
            },
            "BUGS": {
                "content": "The normal return provided by \"scalar(%hash)\" is not available.  What this means is that\nusing %tiedhash in boolean context doesn't work right (currently this always tests false,\nregardless of whether the hash is empty or hash elements).  [ This paragraph needs review in\nlight of changes in 5.25 ]\n\nLocalizing tied arrays or hashes does not work.  After exiting the scope the arrays or the\nhashes are not restored.\n\nCounting the number of entries in a hash via \"scalar(keys(%hash))\" or \"scalar(values(%hash)\")\nis inefficient since it needs to iterate through all the entries with FIRSTKEY/NEXTKEY.\n\nTied hash/array slices cause multiple FETCH/STORE pairs, there are no tie methods for slice\noperations.\n\nYou cannot easily tie a multilevel data structure (such as a hash of hashes) to a dbm file.\nThe first problem is that all but GDBM and Berkeley DB have size limitations, but beyond\nthat, you also have problems with how references are to be represented on disk.  One module\nthat does attempt to address this need is DBM::Deep.  Check your nearest CPAN site as\ndescribed in perlmodlib for source code.  Note that despite its name, DBM::Deep does not use\ndbm.  Another earlier attempt at solving the problem is MLDBM, which is also available on the\nCPAN, but which has some fairly serious limitations.\n\nTied filehandles are still incomplete.  sysopen(), truncate(), flock(), fcntl(), stat() and\n-X can't currently be trapped.\n",
                "subsections": []
            },
            "AUTHOR": {
                "content": "Tom Christiansen\n\nTIEHANDLE by Sven Verdoolaege <skimo@dns.ufsia.ac.be> and Doug MacEachern <dougm@osf.org>\n\nUNTIE by Nick Ing-Simmons <nick@ing-simmons.net>\n\nSCALAR by Tassilo von Parseval <tassilo.von.parseval@rwth-aachen.de>\n\nTying Arrays by Casey West <casey@geeknest.com>\n\n\n\nperl v5.34.0                                 2025-07-25                                   PERLTIE(1)",
                "subsections": []
            }
        }
    }
}