{
    "content": [
        {
            "type": "text",
            "text": "# perltie (perldoc)\n\n**Summary:** perltie - how to hide an object class in a simple variable\n\n**Synopsis:** tie VARIABLE, CLASSNAME, LIST\n$object = tied VARIABLE\nuntie VARIABLE\n\n## Section Outline\n\n- **NAME** (2 lines)\n- **SYNOPSIS** (6 lines)\n- **DESCRIPTION** (19 lines) — 6 subsections\n  - tie (7 lines)\n  - Tying Scalars (124 lines)\n  - Tying Arrays (255 lines)\n  - Tying Hashes (60 lines)\n  - whowasi (252 lines)\n  - Tying FileHandles (271 lines)\n- **SEE ALSO** (1 lines) — 1 subsections\n  - tie (2 lines)\n- **BUGS** (25 lines)\n- **AUTHOR** (10 lines)\n\n## Full Content\n\n### NAME\n\nperltie - how to hide an object class in a simple variable\n\n### SYNOPSIS\n\ntie VARIABLE, CLASSNAME, LIST\n\n$object = tied VARIABLE\n\nuntie VARIABLE\n\n### DESCRIPTION\n\nPrior to release 5.0 of Perl, a programmer could use dbmopen() to connect an on-disk database in\nthe standard Unix dbm(3x) format magically to a %HASH in their program. However, their Perl was\neither built with one particular dbm library or another, but not both, and you couldn't extend\nthis 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 class is\nhidden behind magic methods calls. The method names are in ALL CAPS, which is a convention that\nPerl uses to indicate that they're called implicitly rather than explicitly--just like the\nBEGIN() and END() functions.\n\nIn the tie() call, \"VARIABLE\" is the name of the variable to be enchanted. \"CLASSNAME\" is the\nname of a class implementing objects of the correct type. Any additional arguments in the \"LIST\"\nare passed to the appropriate constructor method for that class--meaning TIESCALAR(),\nTIEARRAY(), TIEHASH(), or TIEHANDLE(). (Typically these are arguments such as might be passed to\nthe dbminit() function of C.) The object returned by the \"new\" method is also returned by the\n\n#### tie\n\ndon't actually have to return a reference to a right \"type\" (e.g., HASH or \"CLASSNAME\") so long\nas it's a properly blessed object.) You can also retrieve a reference to the underlying object\nusing the tied() function.\n\nUnlike dbmopen(), the tie() function will not \"use\" or \"require\" a module for you--you need to\ndo that explicitly yourself.\n\n#### Tying Scalars\n\nA class implementing a tied scalar should define the following methods: TIESCALAR, FETCH, STORE,\nand 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 to\ndo 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 retrieved\nand 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 wish\nto be so forgiving. It checks the global variable $^W to see whether to emit a bit of noise\nanyway.\n\nFETCH this\nThis method will be triggered every time the tied variable is accessed (read). It takes no\narguments 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 object,\na simple $$self allows the method to get at the real value stored there. In our example\nbelow, 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 assignment\nreturning 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 needs\nto know when no further calls will be made. (Except DESTROY of course.) See \"The \"untie\"\nGotcha\" below for more details.\n\nDESTROY this\nThis method will be triggered when the tied variable needs to be destructed. As with other\nobject classes, such a method is seldom necessary, because Perl deallocates its moribund\nobject's memory for you automatically--this isn't C++, you know. We'll use a DESTROY method\nhere 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 done\na few nice things here for the sake of completeness, robustness, and general aesthetics. Simpler\nTIESCALAR classes are certainly possible.\n\n#### Tying Arrays\n\nA class implementing a tied ordinary array should define the following methods: TIEARRAY, FETCH,\nSTORE, 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 simply\n\"croak\".\n\nIn addition EXTEND will be called when perl would have pre-extended allocation in a real array.\n\nFor this discussion, we'll implement an array whose elements are a fixed size at creation. If\nyou try to create an element larger than the fixed size, you'll take an exception. For example:\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 generic\nrecord type: the \"{ELEMSIZE}\" field will store the maximum element size allowed, and the\n\"{ARRAY}\" field will hold the true ARRAY ref. If someone outside the class tries to\ndereference the object returned (doubtless thinking it an ARRAY ref), they'll blow up. This\njust 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 trying\nto 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 a\npositive one internally by calling FETCHSIZE before being passed to FETCH. You may disable\nthis feature by assigning a true value to the variable $NEGATIVEINDICES in the tied array\nclass.\n\nAs you may have noticed, the name of the FETCH method (et al.) is the same for all accesses,\neven though the constructors differ in names (TIESCALAR vs TIEARRAY). While in theory you\ncould have the same class servicing several tied types, in practice this becomes cumbersome,\nand 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). It\ntakes two arguments beyond its self reference: the index at which we're trying to store\nsomething 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 little\nmore 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\n*count*. If this makes the array larger then class's mapping of \"undef\" should be returned\nfor new positions. 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. This\nmethod is only relevant to tied array implementations where there is the possibility of\nhaving 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 to\ntime call EXTEND without wanting to actually change the array size directly. Any tied array\nshould function correctly if this method is a no-op, even if perhaps they might not be as\nefficient 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}\" spaces\nonly, 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\n*offset* is optional and defaults to zero, negative values count back from the end of the\narray.\n\n*length* is optional and defaults to rest of the array.\n\n*LIST* 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\n#### Tying Hashes\n\nHashes 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 the\nkey and value pairs. EXISTS reports whether a key is present in the hash, and DELETE deletes\none. CLEAR empties the hash by deleting all the key and value pairs. FIRSTKEY and NEXTKEY\nimplement the keys() and each() functions to iterate over all the keys. SCALAR is triggered when\nthe tied hash is evaluated in scalar context, and in 5.28 onwards, by \"keys\" in boolean context.\nUNTIE is called when \"untie\" happens, and DESTROY is called when the tied variable is garbage\ncollected.\n\nIf this seems like a lot, then feel free to inherit from merely the standard Tie::StdHash module\nfor most of your methods, redefining only the interesting ones. See Tie::Hash for details.\n\nRemember that Perl distinguishes between a key not existing in the hash, and the key existing in\nthe hash but having a corresponding value of \"undef\". The two possibilities can be tested with\nthe \"exists()\" and \"defined()\" functions.\n\nHere's an example of a somewhat interesting tied hash class: it gives you a hash representing a\nparticular user's dot files. You index into the hash with the name of the file (minus the dot)\nand 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 real\nhash.\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 warnings;\n\n#### whowasi\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) will\nbe 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 a\nreaddir, 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). It\ntakes one argument beyond its self reference: the key whose value we're trying to fetch.\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, because\ndot 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). It\ntakes two arguments beyond its self reference: the index at which we're trying to store\nsomething, 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 want\nto emulate the normal behavior of delete(), you should return whatever FETCH would have\nreturned for this key. In this example, we have chosen instead to return a value which tells\nthe 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 that\nthey'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. In\nour 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 second\nargument which is the last key that had been accessed. This is useful if you're caring about\nordering or calling the iterator from more than one sequence, or not really storing things\nin a hash anywhere.\n\nNEXTKEY is always called in scalar context and it should just return the next key. values(),\nand 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 have\nto 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 of\nyour 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 \"keys\"\nin boolean context. In order to mimic the behaviour of untied hashes, this method must\nreturn a value which when used as boolean, indicates whether the tied hash is considered\nempty. If this method does not exist, perl will make some educated guesses and return true\nwhen the hash is inside an iteration. If this isn't the case, FIRSTKEY is called, and the\nresult will be a false value if FIRSTKEY returns the empty list, true otherwise.\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 until\nit is empty. You are therefore advised to supply your own SCALAR method when you want to be\nabsolutely 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 need\nit unless you're trying to add debugging or have auxiliary state to clean up. Here's a very\nsimple 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\n#### Tying FileHandles\n\nThis is partially implemented now.\n\nA class implementing a tied filehandle should define the following methods: TIEHANDLE, at least\none of PRINT, PRINTF, WRITE, READLINE, GETC, READ, and possibly CLOSE, UNTIE and DESTROY. The\nclass can also provide: BINMODE, OPEN, EOF, FILENO, SEEK, TELL - if the corresponding perl\noperators are used on the handle.\n\nWhen STDERR is tied, its PRINT method will be called to issue warnings and error messages. This\nfeature is temporarily disabled during the call, which means you can use \"warn()\" inside PRINT\nwithout starting a recursive loop. And just like \"WARN\" and \"DIE\" handlers, STDERR's\nPRINT method may be called to report parser errors, so the caveats mentioned under \"%SIG\" in\nperlvar 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 module\nfor examples.\n\nWhen tying a handle, the first argument to \"tie\" should begin with an asterisk. So, if you are\ntying STDOUT, use *STDOUT. If you have assigned it to a scalar variable, say $handle, use\n*$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()\" or\n\"say()\" functions. Beyond its self reference it also expects the list that was passed to the\nprint 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 nothing\nspecial to handle \"say()\" in \"PRINT()\".\n\nPRINTF this, LIST\nThis method will be triggered every time the tied handle is printed to with the \"printf()\"\nfunction. Beyond its self reference it also expects the format and list that was passed to\nthe 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 more\ndata. In list context it should return all remaining lines, or an empty list for no more\ndata. The strings returned should include the input record separator $/ (see perlvar),\nunless 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 if\n\"eof\" is called without parameter; 1 if \"eof\" is given a filehandle as a parameter, e.g.\n\"eof(FH)\"; and 2 in the very special case that the tied filehandle is \"ARGV\" and \"eof\" is\ncalled 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 be\nappropriate 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 to\nbe 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\nUNTIE this\nYou can define for all tie types an UNTIE method that will be called at untie(). See \"The\n\"untie\" Gotcha\" below.\n\nThe \"untie\" Gotcha\nIf 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 tied\nobject):\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, namely,\nthe implicit reference from the tied variable. When untie() is called, that reference is\ndestroyed. Then, as in the first example above, the object's destructor (DESTROY) is called,\nwhich is normal for objects that have no more valid references; and thus the file is closed.\n\nIn the second example, however, we have stored another reference to the tied object in $x. That\nmeans that when untie() gets called there will still be a valid reference to the object in\nexistence, so the destructor is not called at that time, and thus the file is not closed. The\nreason 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 introduction of\nthe optional UNTIE method the only way was the good old \"-w\" flag. Which will spot any instances\nwhere you call untie() and there are still valid references to the tied object. If the second\nscript above this near the top \"use warnings 'untie'\" or was run with the \"-w\" flag, Perl prints\nthis 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 are\nreally associated with \"untie\" and which with the object being destroyed. What makes sense for a\ngiven class depends on whether the inner references are being kept so that non-tie-related\nmethods can be called on the object. But in most cases it probably makes sense to move the\nfunctionality 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\n### SEE ALSO\n\nSee DBFile or Config for some interesting tie() implementations. A good starting point for many\n\n#### tie\n\nTie::Handle.\n\n### BUGS\n\nThe normal return provided by \"scalar(%hash)\" is not available. What this means is that using\n%tiedhash in boolean context doesn't work right (currently this always tests false, regardless\nof whether the hash is empty or hash elements). [ This paragraph needs review in light of\nchanges in 5.25 ]\n\nLocalizing tied arrays or hashes does not work. After exiting the scope the arrays or the hashes\nare not restored.\n\nCounting the number of entries in a hash via \"scalar(keys(%hash))\" or \"scalar(values(%hash)\") is\ninefficient 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. The\nfirst problem is that all but GDBM and Berkeley DB have size limitations, but beyond that, you\nalso have problems with how references are to be represented on disk. One module that does\nattempt to address this need is DBM::Deep. Check your nearest CPAN site as described in\nperlmodlib for source code. Note that despite its name, DBM::Deep does not use dbm. Another\nearlier attempt at solving the problem is MLDBM, which is also available on the CPAN, but which\nhas some fairly serious limitations.\n\nTied filehandles are still incomplete. sysopen(), truncate(), flock(), fcntl(), stat() and -X\ncan't currently be trapped.\n\n### AUTHOR\n\nTom 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"
        }
    ],
    "structuredContent": {
        "command": "perltie",
        "section": "",
        "mode": "perldoc",
        "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": 19,
                "subsections": [
                    {
                        "name": "tie",
                        "lines": 7
                    },
                    {
                        "name": "Tying Scalars",
                        "lines": 124
                    },
                    {
                        "name": "Tying Arrays",
                        "lines": 255
                    },
                    {
                        "name": "Tying Hashes",
                        "lines": 60
                    },
                    {
                        "name": "whowasi",
                        "lines": 252
                    },
                    {
                        "name": "Tying FileHandles",
                        "lines": 271
                    }
                ]
            },
            {
                "name": "SEE ALSO",
                "lines": 1,
                "subsections": [
                    {
                        "name": "tie",
                        "lines": 2
                    }
                ]
            },
            {
                "name": "BUGS",
                "lines": 25,
                "subsections": []
            },
            {
                "name": "AUTHOR",
                "lines": 10,
                "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 in\nthe standard Unix dbm(3x) format magically to a %HASH in their program. However, their Perl was\neither built with one particular dbm library or another, but not both, and you couldn't extend\nthis 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 class is\nhidden behind magic methods calls. The method names are in ALL CAPS, which is a convention that\nPerl uses to indicate that they're called implicitly rather than explicitly--just like the\nBEGIN() and END() functions.\n\nIn the tie() call, \"VARIABLE\" is the name of the variable to be enchanted. \"CLASSNAME\" is the\nname of a class implementing objects of the correct type. Any additional arguments in the \"LIST\"\nare passed to the appropriate constructor method for that class--meaning TIESCALAR(),\nTIEARRAY(), TIEHASH(), or TIEHANDLE(). (Typically these are arguments such as might be passed to\nthe dbminit() function of C.) The object returned by the \"new\" method is also returned by the",
                "subsections": [
                    {
                        "name": "tie",
                        "content": "don't actually have to return a reference to a right \"type\" (e.g., HASH or \"CLASSNAME\") so long\nas it's a properly blessed object.) You can also retrieve a reference to the underlying object\nusing the tied() function.\n\nUnlike dbmopen(), the tie() function will not \"use\" or \"require\" a module for you--you need to\ndo that explicitly yourself.\n"
                    },
                    {
                        "name": "Tying Scalars",
                        "content": "A class implementing a tied scalar should define the following methods: TIESCALAR, FETCH, STORE,\nand 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 to\ndo 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 retrieved\nand 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 wish\nto be so forgiving. It checks the global variable $^W to see whether to emit a bit of noise\nanyway.\n\nFETCH this\nThis method will be triggered every time the tied variable is accessed (read). It takes no\narguments 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 object,\na simple $$self allows the method to get at the real value stored there. In our example\nbelow, 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 assignment\nreturning 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 needs\nto know when no further calls will be made. (Except DESTROY of course.) See \"The \"untie\"\nGotcha\" below for more details.\n\nDESTROY this\nThis method will be triggered when the tied variable needs to be destructed. As with other\nobject classes, such a method is seldom necessary, because Perl deallocates its moribund\nobject's memory for you automatically--this isn't C++, you know. We'll use a DESTROY method\nhere 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 done\na few nice things here for the sake of completeness, robustness, and general aesthetics. Simpler\nTIESCALAR classes are certainly possible.\n"
                    },
                    {
                        "name": "Tying Arrays",
                        "content": "A class implementing a tied ordinary array should define the following methods: TIEARRAY, FETCH,\nSTORE, 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 simply\n\"croak\".\n\nIn addition EXTEND will be called when perl would have pre-extended allocation in a real array.\n\nFor this discussion, we'll implement an array whose elements are a fixed size at creation. If\nyou try to create an element larger than the fixed size, you'll take an exception. For example:\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 generic\nrecord type: the \"{ELEMSIZE}\" field will store the maximum element size allowed, and the\n\"{ARRAY}\" field will hold the true ARRAY ref. If someone outside the class tries to\ndereference the object returned (doubtless thinking it an ARRAY ref), they'll blow up. This\njust 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 trying\nto 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 a\npositive one internally by calling FETCHSIZE before being passed to FETCH. You may disable\nthis feature by assigning a true value to the variable $NEGATIVEINDICES in the tied array\nclass.\n\nAs you may have noticed, the name of the FETCH method (et al.) is the same for all accesses,\neven though the constructors differ in names (TIESCALAR vs TIEARRAY). While in theory you\ncould have the same class servicing several tied types, in practice this becomes cumbersome,\nand 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). It\ntakes two arguments beyond its self reference: the index at which we're trying to store\nsomething 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 little\nmore 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\n*count*. If this makes the array larger then class's mapping of \"undef\" should be returned\nfor new positions. 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. This\nmethod is only relevant to tied array implementations where there is the possibility of\nhaving 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 to\ntime call EXTEND without wanting to actually change the array size directly. Any tied array\nshould function correctly if this method is a no-op, even if perhaps they might not be as\nefficient 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}\" spaces\nonly, 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\n*offset* is optional and defaults to zero, negative values count back from the end of the\narray.\n\n*length* is optional and defaults to rest of the array.\n\n*LIST* 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 the\nkey and value pairs. EXISTS reports whether a key is present in the hash, and DELETE deletes\none. CLEAR empties the hash by deleting all the key and value pairs. FIRSTKEY and NEXTKEY\nimplement the keys() and each() functions to iterate over all the keys. SCALAR is triggered when\nthe tied hash is evaluated in scalar context, and in 5.28 onwards, by \"keys\" in boolean context.\nUNTIE is called when \"untie\" happens, and DESTROY is called when the tied variable is garbage\ncollected.\n\nIf this seems like a lot, then feel free to inherit from merely the standard Tie::StdHash module\nfor most of your methods, redefining only the interesting ones. See Tie::Hash for details.\n\nRemember that Perl distinguishes between a key not existing in the hash, and the key existing in\nthe hash but having a corresponding value of \"undef\". The two possibilities can be tested with\nthe \"exists()\" and \"defined()\" functions.\n\nHere's an example of a somewhat interesting tied hash class: it gives you a hash representing a\nparticular user's dot files. You index into the hash with the name of the file (minus the dot)\nand 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 real\nhash.\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 warnings;"
                    },
                    {
                        "name": "whowasi",
                        "content": "Here 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) will\nbe 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 a\nreaddir, 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). It\ntakes one argument beyond its self reference: the key whose value we're trying to fetch.\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, because\ndot 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). It\ntakes two arguments beyond its self reference: the index at which we're trying to store\nsomething, 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 want\nto emulate the normal behavior of delete(), you should return whatever FETCH would have\nreturned for this key. In this example, we have chosen instead to return a value which tells\nthe 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 that\nthey'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. In\nour 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 second\nargument which is the last key that had been accessed. This is useful if you're caring about\nordering or calling the iterator from more than one sequence, or not really storing things\nin a hash anywhere.\n\nNEXTKEY is always called in scalar context and it should just return the next key. values(),\nand 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 have\nto 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 of\nyour 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 \"keys\"\nin boolean context. In order to mimic the behaviour of untied hashes, this method must\nreturn a value which when used as boolean, indicates whether the tied hash is considered\nempty. If this method does not exist, perl will make some educated guesses and return true\nwhen the hash is inside an iteration. If this isn't the case, FIRSTKEY is called, and the\nresult will be a false value if FIRSTKEY returns the empty list, true otherwise.\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 until\nit is empty. You are therefore advised to supply your own SCALAR method when you want to be\nabsolutely 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 need\nit unless you're trying to add debugging or have auxiliary state to clean up. Here's a very\nsimple 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 least\none of PRINT, PRINTF, WRITE, READLINE, GETC, READ, and possibly CLOSE, UNTIE and DESTROY. The\nclass can also provide: BINMODE, OPEN, EOF, FILENO, SEEK, TELL - if the corresponding perl\noperators are used on the handle.\n\nWhen STDERR is tied, its PRINT method will be called to issue warnings and error messages. This\nfeature is temporarily disabled during the call, which means you can use \"warn()\" inside PRINT\nwithout starting a recursive loop. And just like \"WARN\" and \"DIE\" handlers, STDERR's\nPRINT method may be called to report parser errors, so the caveats mentioned under \"%SIG\" in\nperlvar 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 module\nfor examples.\n\nWhen tying a handle, the first argument to \"tie\" should begin with an asterisk. So, if you are\ntying STDOUT, use *STDOUT. If you have assigned it to a scalar variable, say $handle, use\n*$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()\" or\n\"say()\" functions. Beyond its self reference it also expects the list that was passed to the\nprint 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 nothing\nspecial to handle \"say()\" in \"PRINT()\".\n\nPRINTF this, LIST\nThis method will be triggered every time the tied handle is printed to with the \"printf()\"\nfunction. Beyond its self reference it also expects the format and list that was passed to\nthe 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 more\ndata. In list context it should return all remaining lines, or an empty list for no more\ndata. The strings returned should include the input record separator $/ (see perlvar),\nunless 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 if\n\"eof\" is called without parameter; 1 if \"eof\" is given a filehandle as a parameter, e.g.\n\"eof(FH)\"; and 2 in the very special case that the tied filehandle is \"ARGV\" and \"eof\" is\ncalled 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 be\nappropriate 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 to\nbe 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\nUNTIE this\nYou can define for all tie types an UNTIE method that will be called at untie(). See \"The\n\"untie\" Gotcha\" below.\n\nThe \"untie\" Gotcha\nIf 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 tied\nobject):\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, namely,\nthe implicit reference from the tied variable. When untie() is called, that reference is\ndestroyed. Then, as in the first example above, the object's destructor (DESTROY) is called,\nwhich is normal for objects that have no more valid references; and thus the file is closed.\n\nIn the second example, however, we have stored another reference to the tied object in $x. That\nmeans that when untie() gets called there will still be a valid reference to the object in\nexistence, so the destructor is not called at that time, and thus the file is not closed. The\nreason 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 introduction of\nthe optional UNTIE method the only way was the good old \"-w\" flag. Which will spot any instances\nwhere you call untie() and there are still valid references to the tied object. If the second\nscript above this near the top \"use warnings 'untie'\" or was run with the \"-w\" flag, Perl prints\nthis 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 are\nreally associated with \"untie\" and which with the object being destroyed. What makes sense for a\ngiven class depends on whether the inner references are being kept so that non-tie-related\nmethods can be called on the object. But in most cases it probably makes sense to move the\nfunctionality 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 many",
                "subsections": [
                    {
                        "name": "tie",
                        "content": "Tie::Handle.\n"
                    }
                ]
            },
            "BUGS": {
                "content": "The normal return provided by \"scalar(%hash)\" is not available. What this means is that using\n%tiedhash in boolean context doesn't work right (currently this always tests false, regardless\nof whether the hash is empty or hash elements). [ This paragraph needs review in light of\nchanges in 5.25 ]\n\nLocalizing tied arrays or hashes does not work. After exiting the scope the arrays or the hashes\nare not restored.\n\nCounting the number of entries in a hash via \"scalar(keys(%hash))\" or \"scalar(values(%hash)\") is\ninefficient 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. The\nfirst problem is that all but GDBM and Berkeley DB have size limitations, but beyond that, you\nalso have problems with how references are to be represented on disk. One module that does\nattempt to address this need is DBM::Deep. Check your nearest CPAN site as described in\nperlmodlib for source code. Note that despite its name, DBM::Deep does not use dbm. Another\nearlier attempt at solving the problem is MLDBM, which is also available on the CPAN, but which\nhas some fairly serious limitations.\n\nTied filehandles are still incomplete. sysopen(), truncate(), flock(), fcntl(), stat() and -X\ncan'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",
                "subsections": []
            }
        }
    }
}