PERLTIE(1)
πΈ PERLTIE(1) β Perl Programmers Reference Guide πΈ
okay bestie, sit DOWN, because today we're talking about perltie β how to hide an object class in a simple variable. yes that's the actual name and yes it's giving magic trick energy π©β¨
β¨ SYNOPSIS β¨
tie VARIABLE, CLASSNAME, LIST
$object = tied VARIABLE
untie VARIABLE
likeβ¦ that's it. that's the whole vibe. three lines and you're a wizard π
π DESCRIPTION π
so back in the day β and by "the day" I mean prior to release 5.0 of Perl β a programmer could use dbmopen() to connect an on-disk database in the standard Unix dbm(3x) format magically to a %HASH in their program. cute, right? except their Perl was either built with one particular dbm library or another, but not both, and you couldn't extend this mechanism to other packages or types of variables. it's giving locked doors π
now you can. periodt.
The tie() function binds a variable to a class (package) that will provide the implementation for access methods for that variable. once this magic has been performed, accessing a tied variable automatically triggers method calls in the proper class. the complexity of the class is hidden behind magic method calls. the method names are in ALL CAPS, which is a convention Perl uses to indicate that they're called implicitly rather than explicitly β just like the BEGIN() and END() functions. iykyk π«Ά
In the tie() call, VARIABLE is the name of the variable to be enchanted. CLASSNAME is the name of a class implementing objects of the correct type. any additional arguments in the LIST are passed to the appropriate constructor method for that class β meaning TIESCALAR(), TIEARRAY(), TIEHASH(), or TIEHANDLE(). (typically these are arguments such as might be passed to the dbminit() function of C.) the object returned by the new method is also returned by the tie() function, which would be useful if you wanted to access other methods in CLASSNAME. (you don't actually have to return a reference to a right "type" (e.g., HASH or CLASSNAME) so long as it's a properly blessed object.) you can also retrieve a reference to the underlying object using the tied() function.
heads up bestie: unlikedbmopen(), thetie()function will notuseorrequirea module for you β you need to do that explicitly yourself. no hand-holding, she's independent π
π§ Tying Scalars π§
A class implementing a tied scalar should define the following methods: TIESCALAR, FETCH, STORE, and possibly UNTIE and/or DESTROY.
let's look at each in turn, using as an example a tie class for scalars that allows the user to do something like:
tie $his_speed, 'Nice', getppid();
tie $my_speed, 'Nice', $$;
And now whenever either of those variables is accessed, its current system priority is retrieved and returned. If those variables are set, then the process's priority is changed! that's actually so iconic π₯
We'll use Jarkko Hietaniemi <jhi@iki.fi>'s BSD::Resource class (not included) to access the PRIO_PROCESS, PRIO_MIN, and PRIO_MAX constants from your system, as well as the getpriority() and setpriority() system calls. Here's the preamble of the class.
package Nice;
use Carp;
use BSD::Resource;
use strict;
$Nice::DEBUG = 0 unless defined $Nice::DEBUG;
π TIESCALAR classname, LIST π
This is the constructor for the class. That means it is expected to return a blessed reference to a new scalar (probably anonymous) that it's creating. For example:
sub TIESCALAR {
my $class = shift;
my $pid = shift || $$; # 0 means me
if ($pid !~ /^\d+$/) {
carp "Nice::Tie::Scalar got non-numeric pid $pid" if $^W;
return undef;
}
unless (kill 0, $pid) { # EPERM or ERSCH, no doubt
carp "Nice::Tie::Scalar got bad pid $pid: $!" if $^W;
return undef;
}
return bless \$pid, $class;
}
This tie class has chosen to return an error rather than raising an exception if its constructor should fail. While this is how dbmopen() works, other classes may well not wish to be so forgiving. It checks the global variable $^W to see whether to emit a bit of noise anyway. so polite, so gentle, so demure π
π FETCH this π
This method will be triggered every time the tied variable is accessed (read). It takes no arguments beyond its self reference, which is the object representing the scalar we're dealing with. Because in this case we're using just a SCALAR ref for the tied scalar object, a simple $$self allows the method to get at the real value stored there. In our example below, that real value is the process ID to which we've tied our variable.
sub FETCH {
my $self = shift;
confess "wrong type" unless ref $self;
croak "usage error" if @_;
my $nicety;
local($!) = 0;
$nicety = getpriority(PRIO_PROCESS, $$self);
if ($!) { croak "getpriority failed: $!" }
return $nicety;
}
This time we've decided to blow up (raise an exception) if the renice fails β there's no place for us to return an error otherwise, and it's probably the right thing to do. dramatic exit, she said what she said π
β¨ STORE this, value β¨
This method will be triggered every time the tied variable is set (assigned). Beyond its self reference, it also expects one (and only one) argument: the new value the user is trying to assign. Don't worry about returning a value from STORE; the semantic of assignment returning the assigned value is implemented with FETCH. π«Ά
sub STORE {
my $self = shift;
confess "wrong type" unless ref $self;
my $new_nicety = shift;
croak "usage error" if @_;
if ($new_nicety < PRIO_MIN) {
carp sprintf
"WARNING: priority %d less than minimum system priority %d",
$new_nicety, PRIO_MIN if $^W;
$new_nicety = PRIO_MIN;
}
if ($new_nicety > PRIO_MAX) {
carp sprintf
"WARNING: priority %d greater than maximum system priority %d",
$new_nicety, PRIO_MAX if $^W;
$new_nicety = PRIO_MAX;
}
unless (defined setpriority(PRIO_PROCESS,
$$self,
$new_nicety))
{
confess "setpriority failed: $!";
}
}
π¦ UNTIE this π¦
This method will be triggered when the untie occurs. This can be useful if the class needs to know when no further calls will be made. (Except DESTROY of course.) See "The untie Gotcha" below for more details.
π DESTROY this π
This method will be triggered when the tied variable needs to be destructed. As with other object classes, such a method is seldom necessary, because Perl deallocates its moribund object's memory for you automatically β this isn't C++, you know. π We'll use a DESTROY method here for debugging purposes only.
sub DESTROY {
my $self = shift;
confess "wrong type" unless ref $self;
carp "[ Nice::DESTROY pid $$self ]" if $Nice::DEBUG;
}
That's about all there is to it. Actually, it's more than all there is to it, because we've done a few nice things here for the sake of completeness, robustness, and general aesthetics. Simpler TIESCALAR classes are certainly possible. you don't have to be extra, but it IS fun π
π Tying Arrays π
A class implementing a tied ordinary array should define the following methods: TIEARRAY, FETCH, STORE, FETCHSIZE, STORESIZE, CLEAR and perhaps UNTIE and/or DESTROY.
FETCHSIZE and STORESIZE are used to provide $#array and equivalent scalar(@array) access.
The methods POP, PUSH, SHIFT, UNSHIFT, SPLICE, DELETE, and EXISTS are required if the perl operator with the corresponding (but lowercase) name is to operate on the tied array. The Tie::Array class can be used as a base class to implement the first five of these in terms of the basic methods above. The default implementations of DELETE and EXISTS in Tie::Array simply croak. π
In addition EXTEND will be called when perl would have pre-extended allocation in a real array.
For this discussion, we'll implement an array whose elements are a fixed size at creation. If you try to create an element larger than the fixed size, you'll take an exception. For example:
use FixedElem_Array;
tie @array, 'FixedElem_Array', 3;
$array[0] = 'cat'; # ok.
$array[1] = 'dogs'; # exception, length('dogs') > 3.
imagine getting clapped back by your own data structure, couldn't be me π
The preamble code for the class is as follows:
package FixedElem_Array;
use Carp;
use strict;
π TIEARRAY classname, LIST π
This is the constructor for the class. That means it is expected to return a blessed reference through which the new array (probably an anonymous ARRAY ref) will be accessed.
In our example, just to show you that you don't really have to return an ARRAY reference, we'll choose a HASH reference to represent our object. A HASH works out well as a generic record type: the {ELEMSIZE} field will store the maximum element size allowed, and the {ARRAY} field will hold the true ARRAY ref. If someone outside the class tries to dereference the object returned (doubtless thinking it is an ARRAY ref), they'll blow up. This just goes to show you that you should respect an object's privacy. mind your business challenge, difficulty level: impossible π
sub TIEARRAY {
my $class = shift;
my $elemsize = shift;
if ( @_ || $elemsize =~ /\D/ ) {
croak "usage: tie ARRAY, '" . __PACKAGE__ . "', elem_size";
}
return bless {
ELEMSIZE => $elemsize,
ARRAY => [],
}, $class;
}
π FETCH this, index π
This method will be triggered every time an individual element the tied array is accessed (read). It takes one argument beyond its self reference: the index whose value we're trying to fetch.
sub FETCH {
my $self = shift;
my $index = shift;
return $self->{ARRAY}->[$index];
}
If a negative array index is used to read from an array, the index will be translated to a positive one internally by calling FETCHSIZE before being passed to FETCH. You may disable this feature by assigning a true value to the variable $NEGATIVE_INDICES in the tied array class. π₯
As you may have noticed, the name of the FETCH method (et al.) is the same for all accesses, even though the constructors differ in names (TIESCALAR vs TIEARRAY). While in theory you could have the same class servicing several tied types, in practice this becomes cumbersome, and it's easiest to keep them at simply one tie type per class. one class, one vibe, no chaos π¦
STORE this, index, value πΎ
This one fires every single time something gets written into the tied array. It gets two args past its own self reference: the index where we're tryna stash something, and the value we're tryna put there. π«Ά
In our lil example, undef is literally $self->{ELEMSIZE} spaces, so bestie we have a bit more work to do here:
sub STORE {
my $self = shift;
my( $index, $value ) = @_;
if ( length $value > $self->{ELEMSIZE} ) {
croak "length of $value is greater than $self->{ELEMSIZE}";
}
# fill in the blanks
$self->STORESIZE( $index ) if $index > $self->FETCHSIZE();
# right justify to keep element size for smaller elements
$self->{ARRAY}->[$index] = sprintf "%$self->{ELEMSIZE}s", $value;
}
Negative indexes get treated exactly the same as with FETCH. no cap. β¨
FETCHSIZE this π
Hands you back the total number of items in the tied array that belongs to object this. (Same energy as scalar(@array).) Like so:
sub FETCHSIZE {
my $self = shift;
return scalar $self->{ARRAY}->@*;
}
STORESIZE this, count π
Sets the total number of items in the tied array for object this to be count. If that makes the array bigger, then the class's mapping of undef should come back for the new positions. If the array gets smaller, then everything past count should be deleted. bye bestie π
In our example, 'undef' is really an element holding "$self->{ELEMSIZE}" number of spaces. Observe:
sub STORESIZE {
my $self = shift;
my $count = shift;
if ( $count > $self->FETCHSIZE() ) {
foreach ( $count - $self->FETCHSIZE() .. $count ) {
$self->STORE( $_, '' );
}
} elsif ( $count < $self->FETCHSIZE() ) {
foreach ( 0 .. $self->FETCHSIZE() - $count - 2 ) {
$self->POP();
}
}
}
EXTEND this, count π
This is a lil heads-up call that the array is probably gonna grow to have count entries. You can use it to optimize allocation. This method literally doesn't have to do anything. π¦
In our example there's zero reason to implement it, so we leave it as a no-op. This method only matters for tied array implementations where the allocated size of the array might be bigger than what a perl programmer can see when they peek at the array's size. Lots of tied array implementations will have no reason to implement it at all.
sub EXTEND {
my $self = shift;
my $count = shift;
# nothing to see here, move along.
}
β οΈ NOTE: it's generally an error to make this equivalent toSTORESIZE. Perl may callEXTENDfrom time to time without actually wanting to change the array size directly. Any tied array should still work correctly if this method is a no-op β even if it's maybe not as efficient as it'd be if the method was implemented. periodt.
EXISTS this, key π
Verify that the element at index key exists in the tied array this.
In our example, we decide that if an element is made of "$self->{ELEMSIZE}" spaces and nothing else, it does not exist:
sub EXISTS {
my $self = shift;
my $index = shift;
return 0 if ! defined $self->{ARRAY}->[$index] ||
$self->{ARRAY}->[$index] eq ' ' x $self->{ELEMSIZE};
return 1;
}
DELETE this, key ποΈ
Delete the element at index key from the tied array this.
In our example, a deleted item is "$self->{ELEMSIZE}" spaces:
sub DELETE {
my $self = shift;
my $index = shift;
return $self->STORE( $index, '' );
}
CLEAR this π§Ή
Clear (remove, delete, whatever you wanna call it) all the values from the tied array associated with object this. For example:
sub CLEAR {
my $self = shift;
return $self->{ARRAY} = [];
}
PUSH this, LIST β
Append the elements of LIST onto the array. For example:
sub PUSH {
my $self = shift;
my @list = @_;
my $last = $self->FETCHSIZE();
$self->STORE( $last + $_, $list[$_] ) foreach 0 .. $#list;
return $self->FETCHSIZE();
}
POP this β
Remove the last element of the array and hand it back. For example:
sub POP {
my $self = shift;
return pop $self->{ARRAY}->@*;
}
SHIFT this π
Remove the first element of the array (shifting all the other elements down) and return it. For example:
sub SHIFT {
my $self = shift;
return shift $self->{ARRAY}->@*;
}
UNSHIFT this, LIST π
Insert the LIST elements at the beginning of the array, pushing existing elements up to make room. For example:
sub UNSHIFT {
my $self = shift;
my @list = @_;
my $size = scalar( @list );
# make room for our list
$self->{ARRAY}[ $size .. $self->{ARRAY}->$#* + $size ]->@*
= $self->{ARRAY}->@*
$self->STORE( $_, $list[$_] ) foreach 0 .. $#list;
}
SPLICE this, offset, length, LIST βοΈ
Does the equivalent of "splice" on the array. iconic.
- offset is optional and defaults to zero; negative values count back from the end of the array.
- length is optional and defaults to the rest of the array.
- LIST may be empty.
Returns a list of the original length elements at offset.
In our example we take a lil shortcut if there's a LIST:
sub SPLICE {
my $self = shift;
my $offset = shift || 0;
my $length = shift || $self->FETCHSIZE() - $offset;
my @list = ();
if ( @_ ) {
tie @list, __PACKAGE__, $self->{ELEMSIZE};
@list = @_;
}
return splice $self->{ARRAY}->@*, $offset, $length, @list;
}
UNTIE this πͺ’
Gets called when "untie" happens. (Peep "The "untie" Gotcha" down below.)
DESTROY this π
This method fires when the tied variable needs to be destructed. Same as with the scalar tie class, this is almost never needed in a language that does its own garbage collection, so this time we're just gonna leave it out. slay.
πΈ Tying Hashes πΈ
Hashes were the very first Perl data type to be tied (check dbmopen()). A class implementing a tied hash should define these methods: TIEHASH is the constructor. FETCH and STORE access the key and value pairs. EXISTS reports whether a key is present in the hash, and DELETE deletes one. CLEAR empties the hash by deleting all the key and value pairs. FIRSTKEY and NEXTKEY implement the keys() and each() functions to iterate over all the keys. SCALAR is triggered when the tied hash is evaluated in scalar context, and in 5.28 onwards, by "keys" in boolean context. UNTIE is called when "untie" happens, and DESTROY is called when the tied variable gets garbage collected.
If that sounds like a LOT (it is, bestie π), then feel free to inherit from just the standard Tie::StdHash module for most of your methods, and only redefine the interesting ones. See Tie::Hash for the details. π
Remember that Perl distinguishes between a key not existing in the hash, and the key existing but having a corresponding value of "undef". You can test those two possibilities with the exists() and defined() functions. π
Here's an example of a somewhat interesting tied hash class: it gives you a hash representing a particular user's dot files. You index into the hash with the name of the file (minus the dot) and you get back that dot file's contents. For example:
use DotFiles;
tie %dot, 'DotFiles';
if ( $dot{profile} =~ /MANPATH/ ||
$dot{login} =~ /MANPATH/ ||
$dot{cshrc} =~ /MANPATH/ )
{
print "you seem to set your MANPATH\n";
}
Or here's another sample of using our tied class:
tie %him, 'DotFiles', 'daemon';
foreach $f ( keys %him ) {
printf "daemon dot file %s is size %d\n",
$f, length $him{$f};
}
In our tied hash DotFiles example, we use a regular hash for the object holding several important fields, and only the "{LIST}" field is what the user thinks of as the real hash. π«Ά
USERβ whose dot files this object representsHOMEβ where those dot files liveCLOBBERβ whether we should try to change or remove those dot filesLISTβ the hash of dot file names and content mappings
Here's the start of Dotfiles.pm:
package DotFiles;
use Carp;
sub whowasi { (caller(1))[3] . '()' }
my $DEBUG = 0;
sub debug { $DEBUG = @_ ? shift : 1 }
For our example, we wanna be able to emit debugging info to help with tracing during development. We also keep one convenience function around internally to help print out warnings; whowasi() returns the name of the function that calls it. β¨
Here are the methods for the DotFiles tied hash. π
TIEHASH classname, LIST ποΈ
This is the constructor for the class. That means it's expected to return a blessed reference through which the new object (probably, but not necessarily, an anonymous hash) will be accessed.
Here's the constructor:
sub TIEHASH {
my $class = shift;
my $user = shift || $>;
my $dotdir = shift || '';
croak "usage: @{[&whowasi]} [USER [DOTDIR]]" if @_;
$user = getpwuid($user) if $user =~ /^\d+$/;
my $dir = (getpwnam($user))[7]
|| croak "@{[&whowasi]}: no user $user";
$dir .= "/$dotdir" if $dotdir;
my $node = {
USER => $user,
HOME => $dir,
LIST => {},
CLOBBER => 0,
};
opendir(DIR, $dir)
|| croak "@{[&whowasi]}: can't opendir $dir: $!";
foreach $dot ( grep /^\./ && -f "$dir/$_", readdir(DIR)) {
$dot =~ s/^\.//;
$node->{LIST}{$dot} = undef;
}
closedir DIR;
return bless $node, $class;
}
One last thing about readdir before we bounce β if you're gonna filetest the values it hands back, you gotta prepend the directory, bestie. Otherwise, because we didn't chdir() in there, you'd have been testing the wrong file the entire time. π And that's not a cute little bug, that's just wrong.
β¨ FETCH this, key β¨
This one fires every single time someone reads an element out of the tied hash. It takes one argument beyond its self reference: the key whose value we're trying to fetch. Simple. Iconic. π«Ά
Here's the fetch for our DotFiles example:
sub FETCH {
carp &whowasi if $DEBUG;
my $self = shift;
my $dot = shift;
my $dir = $self->{HOME};
my $file = "$dir/.$dot";
unless (exists $self->{LIST}->{$dot} || -f $file) {
carp "@{[&whowasi]}: no $dot file" if $DEBUG;
return undef;
}
if (defined $self->{LIST}->{$dot}) {
return $self->{LIST}->{$dot};
} else {
return $self->{LIST}->{$dot} = `cat $dir/.$dot`;
}
}
It was easy to write by having it call the Unix cat(1) command, but ngl it'd probably be more portable to open the file manually (and lowkey more efficient too). But dot files are a Unixy concept anyway, so likeβ¦ we're not that concerned. π€·ββοΈ
π STORE this, key, value π
This one gets triggered every time an element in the tied hash is set (written). It takes two arguments beyond its self reference: the index at which we're trying to store something, and the value we're trying to put there. Two whole extras, she's doing the most. π
Here in our DotFiles example, we'll be careful not to let them try to overwrite the file unless they've called the clobber() method on the original object reference returned by tie().
sub STORE {
carp &whowasi if $DEBUG;
my $self = shift;
my $dot = shift;
my $value = shift;
my $file = $self->{HOME} . "/.$dot";
my $user = $self->{USER};
croak "@{[&whowasi]}: $file not clobberable"
unless $self->{CLOBBER};
open(my $f, '>', $file) || croak "can't open $file: $!";
print $f $value;
close($f);
}
If they wanted to clobber something, they might say:
$ob = tie %daemon_dots, 'daemon';
$ob->clobber(1);
$daemon_dots{signature} = "A true daemon\n";
Another way to lay hands on a reference to the underlying object is to use the tied() function, so they might alternately have set clobber using:
tie %daemon_dots, 'daemon';
tied(%daemon_dots)->clobber(1);
The clobber method is simply:
sub clobber {
my $self = shift;
$self->{CLOBBER} = @_ ? shift : 1;
}
π¦ DELETE this, key π¦
This method is triggered when we remove an element from the hash, typically by using the delete() function. Again, we'll be careful to check whether they really want to clobber files. Consent first, always. β
sub DELETE {
carp &whowasi if $DEBUG;
my $self = shift;
my $dot = shift;
my $file = $self->{HOME} . "/.$dot";
croak "@{[&whowasi]}: won't remove file $file"
unless $self->{CLOBBER};
delete $self->{LIST}->{$dot};
my $success = unlink($file);
carp "@{[&whowasi]}: can't unlink $file: $!" unless $success;
$success;
}
The value returned by DELETE becomes the return value of the call to delete(). So if you wanna emulate the normal behavior of delete(), you should return whatever FETCH would have returned for this key. In this example though, we chose instead to return a value which tells the caller whether the file was successfully deleted. Different priorities, still valid. πββοΈ
π CLEAR this π
Triggered when the whole hash is about to be cleared, usually by assigning the empty list to it.
In our example, that would remove all the user's dot files!! Not a drill. It's such a dangerous thing that they'll have to set CLOBBER to something higher than 1 to make it happen. The bar is on the floor and also in hell. π
sub CLEAR {
carp &whowasi if $DEBUG;
my $self = shift;
croak "@{[&whowasi]}: won't remove all dot files for $self->{USER}"
unless $self->{CLOBBER} > 1;
my $dot;
foreach $dot ( keys $self->{LIST}->%* ) {
$self->DELETE($dot);
}
}
π EXISTS this, key π
This one gets triggered when the user hits the exists() function on a particular hash. In our example, we'll look at the {LIST} hash element for this:
sub EXISTS {
carp &whowasi if $DEBUG;
my $self = shift;
my $dot = shift;
return exists $self->{LIST}->{$dot};
}
β FIRSTKEY this β
This method will be triggered when the user is about to iterate through the hash, like via a keys(), values(), or each() call. She's the opener. π
sub FIRSTKEY {
carp &whowasi if $DEBUG;
my $self = shift;
my $x = keys $self->{LIST}->%*; # reset each() iterator
each $self->{LIST}->%*
}
FIRSTKEY is always called in scalar context and it should just return the first key. values(), and each() in list context, will call FETCH for the returned keys. So don't get cute and return a list, okay? π
π NEXTKEY this, lastkey π
This method gets triggered during a keys(), values(), or each() iteration. It has a second argument which is the last key that had been accessed. This is useful if you're caring about ordering, or calling the iterator from more than one sequence, or not really storing things in a hash anywhere. Chaos-friendly. πͺοΈ
NEXTKEY is always called in scalar context and it should just return the next key. values(), and each() in list context, will call FETCH for the returned keys.
For our example, we're using a real hash so we'll do just the simple thing, but we'll have to go through the LIST field indirectly.
sub NEXTKEY {
carp &whowasi if $DEBUG;
my $self = shift;
return each $self->{LIST}->%*
}
If the object underlying your tied hash isn't a real hash and you don't have each available, then you should return undef or the empty list once you've reached the end of your list of keys. See each's own documentation for more details. π
π SCALAR this π
This is called when the hash is evaluated in scalar context, and in 5.28 onwards, by keys in boolean context. In order to mimic the behaviour of untied hashes, this method must return a value which, when used as boolean, indicates whether the tied hash is considered empty. If this method does not exist, perl will make some educated guesses and return true when the hash is inside an iteration. If that isn't the case, FIRSTKEY is called, and the result will be a false value if FIRSTKEY returns the empty list, true otherwise.
However, you should not blindly rely on perl always doing the right thing. Particularly, perl will mistakenly return true when you clear the hash by repeatedly callingDELETEuntil it is empty. You are therefore advised to supply your ownSCALARmethod when you want to be absolutely sure that your hash behaves nicely in scalar context. Perl is doing her best but she is guessing. π
In our example we can just call scalar on the underlying hash referenced by $self->{LIST}:
sub SCALAR {
carp &whowasi if $DEBUG;
my $self = shift;
return scalar $self->{LIST}->%*
}
NOTE: In perl 5.25 the behavior ofscalar %hashon an untied hash changed to return the count of keys. Prior to this it returned a string containing information about the bucket setup of the hash. Seebucket_ratioin Hash::Util for a backwards compatibility path.
π§ UNTIE this π§
This is called when untie occurs. See "The untie Gotcha" below. Foreshadowing, bestie. β¨
π DESTROY this π
This method is triggered when a tied hash is about to go out of scope. You don't really need it unless you're trying to add debugging or have auxiliary state to clean up. It's the goodbye-hug method. π« Here's a very simple function:
sub DESTROY {
carp &whowasi if $DEBUG;
}
Note that functions such as keys() and values() may return huge lists when used on large objects, like DBM files. You may prefer to use the each() function to iterate over such. Example:
# print out history file offsets
use NDBM_File;
tie(%HIST, 'NDBM_File', '/usr/lib/news/history', 1, 0);
while (($key,$val) = each %HIST) {
print $key, ' = ', unpack('L',$val), "\n";
}
untie(%HIST);
π¦ Tying FileHandles π¦
This is partially implemented now. Yes, partially. We're being honest up front. π
A class implementing a tied filehandle should define the following methods: TIEHANDLE, at least one of PRINT, PRINTF, WRITE, READLINE, GETC, READ, and possibly CLOSE, UNTIE and DESTROY. The class can also provide: BINMODE, OPEN, EOF, FILENO, SEEK, TELL β if the corresponding perl operators are used on the handle.
When STDERR is tied, its PRINT method will be called to issue warnings and error messages. This feature is temporarily disabled during the call, which means you can use warn() inside PRINT without starting a recursive loop. π And just like __WARN__ and __DIE__ handlers, STDERR's PRINT method may be called to report parser errors, so the caveats mentioned under %SIG in perlvar apply.
All of this is especially useful when perl is embedded in some other program, where output to STDOUT and STDERR may have to be redirected in some special way. See nvi and the Apache module for examples. π
When tying a handle, the first argument to tie should begin with an asterisk. So, if you are tying STDOUT, use *STDOUT. If you have assigned it to a scalar variable, say $handle, use *$handle. And listen: tie $handle ties the scalar variable $handle, not the handle inside it. This trips everyone up, no cap. π
In our example we're going to create a shouting handle.
package Shout;
π’ TIEHANDLE classname, LIST π’
This is the constructor for the class. That means it is expected to return a blessed reference of some sort. The reference can be used to hold some internal information.
sub TIEHANDLE { print "<shout>\n"; my $i; bless \$i, shift }
π£ WRITE this, LIST π£
This method will be called when the handle is written to via the syswrite function.
sub WRITE {
$r = shift;
my($buf,$len,$offset) = @_;
print "WRITE called, \$buf=$buf, \$len=$len, \$offset=$offset";
}
π
PRINT this, LIST
Bestie this one fires every single time the tied handle gets print()-ed or say()-ed at. Beyond its self ref it also wants the whole list that got handed to print. Slay.
sub PRINT { $r = shift; $$r++; print join($,,map(uc($_),@_)),$\ }
And say()? It literally acts just like print() except $\ gets localized to "\n", so you gotta do nothing special to handle say() inside PRINT(). No extra work, periodt. β¨
π¨οΈ PRINTF this, LIST
Triggered whenever the tied handle gets printf()-ed at. Besides its self ref it also expects the format and the list that went into printf. Iconic.
sub PRINTF {
shift;
my $fmt = shift;
print sprintf($fmt, @_);
}
π READ this, LIST
This one gets called when the handle is read from via read or sysread. π«Ά
sub READ {
my $self = shift;
my $bufref = \$_[0];
my(undef,$len,$offset) = @_;
print "READ called, \$buf=$bufref, \$len=$len, \$offset=$offset";
# add to $$bufref, set $len to number of characters read
$len;
}
πΈ READLINE this
Called when the handle gets read via <HANDLE> or readline HANDLE. The way thatβ¦
As per readline: in scalar context it should return the next line, or undef for no more data. In list context it should return all remaining lines, or an empty list for no more data. And the strings it returns should include the input record separator $/ (peep perlvar for that) β unless it's undef, which is the whole "slurp" mode situation. π
sub READLINE {
my $r = shift;
if (wantarray) {
return ("all remaining\n",
"lines up\n",
"to eof\n");
} else {
return "READLINE called " . ++$$r . " times\n";
}
}
π€ GETC this
Called when the getc function gets called. Simple as that.
sub GETC { print "Don't GETC, Get Perl"; return "a"; }
π EOF this
Called when the eof function gets called.
Starting with Perl 5.12, an extra integer parameter gets passed in too. Here's the tea:
- it's
0ifeofis called without a parameter; - it's
1ifeofis given a filehandle as a parameter, likeeof(FH); - and it's
2in the very special case that the tied filehandle isARGVandeofis called with an empty parameter list, likeeof().
sub EOF { not length $stringbuf }
π CLOSE this
Called when the handle gets closed via the close function. Bye bestie π¦
sub CLOSE { print "CLOSE called.\n" }
πͺ’ UNTIE this
Same energy as the other tie types β this one fires when untie happens. It may be appropriate to "auto CLOSE" when that goes down. See "The "untie" Gotcha" below, because that section is important. π
π DESTROY this
Again, just like the other tie types: called when the tied handle is about to be destroyed. Super useful for debugging and possibly cleaning up.
sub DESTROY { print "</shout>\n" }
And here's how to actually use our little example, no cap:
tie(*FOO,'Shout');
print FOO "hello\n";
$x = 4; $y = 6;
print FOO $x, " plus ", $y, " equals ", $x + $y, "\n";
print <FOO>;
β¨ UNTIE this β¨
For all tie types you can define an UNTIE method, and it gets called at untie(). See "The "untie" Gotcha" below. π
π The untie Gotcha
Okay so if you're planning on using the object that comes back from either tie() or tied(), AND the tie's target class defines a destructor, there's a subtle little gotcha you must guard against. Not me warning you early.
As setup, consider this (admittedly kinda contrived) example of a tie; all it does is use a file to keep a log of the values assigned to a scalar.
package Remember;
use v5.36;
use IO::File;
sub TIESCALAR {
my $class = shift;
my $filename = shift;
my $handle = IO::File->new( "> $filename" )
or die "Cannot open $filename: $!\n";
print $handle "The Start\n";
bless {FH => $handle, Value => 0}, $class;
}
sub FETCH {
my $self = shift;
return $self->{Value};
}
sub STORE {
my $self = shift;
my $value = shift;
my $handle = $self->{FH};
print $handle "$value\n";
$self->{Value} = $value;
}
sub DESTROY {
my $self = shift;
my $handle = $self->{FH};
print $handle "The End\n";
close $handle;
}
1;
And here's an example that makes use of this tie:
use strict;
use Remember;
my $fred;
tie $fred, 'Remember', 'myfile.txt';
$fred = 1;
$fred = 4;
$fred = 5;
untie $fred;
system "cat myfile.txt";
This is the output when it's executed:
The Start
1
4
5
The End
So far so good, right? π
Those of you who've been paying attention will have spotted that the tied object hasn't actually been used so far. So let's add an extra method to the Remember class so comments can go in the file; something like this:
sub comment {
my $self = shift;
my $text = shift;
my $handle = $self->{FH};
print $handle $text, "\n";
}
And here's the previous example modified to use the comment method (which requires the tied object):
use strict;
use Remember;
my ($fred, $x);
$x = tie $fred, 'Remember', 'myfile.txt';
$fred = 1;
$fred = 4;
comment $x "changing...";
$fred = 5;
untie $fred;
system "cat myfile.txt";
When this code runs there is no output. Here's why, bestie:
When a variable is tied, it's associated with the object which is the return value of the TIESCALAR, TIEARRAY, or TIEHASH function. That object normally has only one reference β namely the implicit reference from the tied variable. When untie() is called, that reference gets destroyed. Then, like in the first example above, the object's destructor (DESTROY) gets called, which is totally normal for objects with no more valid references β and thus the file is closed.
In the second example, though, we've stored another reference to the tied object in $x. Which means when untie() gets called there's still a valid reference to the object out there in the world, so the destructor does not get called at that time, and thus the file does not get closed. And the reason there's no output is that the file buffers haven't been flushed to disk. π
So now you know what the problem is β what do you do to avoid it? Prior to the introduction of the optional UNTIE method, the only way was the good old -w flag. Which will spot any instances where you call untie() and there are still valid references to the tied object. If the second script above had use warnings 'untie' near the top, or was run with the -w flag, Perl prints this warning message:
untie attempted while 1 inner references still exist
To get the script working properly AND silence that warning, make sure there are no valid references to the tied object before untie() is called:
undef $x;
untie $fred;
Now that UNTIE exists, the class designer gets to decide which parts of the class functionality are really associated with untie and which are associated with the object getting destroyed. What makes sense for a given class depends on whether the inner references are being kept so that non-tie-related methods can be called on the object. But in most cases it probably makes sense to move the functionality that would've been in DESTROY over to the UNTIE method. π§
And if the UNTIE method exists, the warning above does not occur. Instead, the UNTIE method gets passed the count of "extra" references and can issue its own warning if it wants to. Like, to replicate the no-UNTIE case, this method can be used:
sub UNTIE
{
my ($obj,$count) = @_;
carp "untie attempted while $count inner references still exist"
if $count;
}
π SEE ALSO
Go look at DB_File or Config for some genuinely interesting tie() implementations. And a really good starting point for loads of tie() implementations is one of the modules Tie::Scalar, Tie::Array, Tie::Hash, or Tie::Handle. iykyk π«Ά
π BUGS
Okay so the normal return provided by scalar(%hash) is not available. What this means is that using %tied_hash in boolean context doesn't work right (currently this always tests false, regardless of whether the hash is empty or has hash elements). [ This paragraph needs review in light of changes in 5.25 ]
Localizing tied arrays or hashes does not work. After exiting the scope the arrays or the hashes are not restored. π
Counting the number of entries in a hash via scalar(keys(%hash)) or scalar(values(%hash)) is inefficient, since it needs to iterate through all the entries with FIRSTKEY/NEXTKEY. Lowkey expensive fr.
Tied hash/array slices cause multiple FETCH/STORE pairs, and there are no tie methods for slice operations.
You cannot easily tie a multilevel data structure (like a hash of hashes) to a dbm file. First problem: all but GDBM and Berkeley DB have size limitations. But beyond that, you also have problems with how references are to be represented on disk. One module that does attempt to address this need is DBM::Deep. Check your nearest CPAN site as described in perlmodlib for source code. Note that despite its name, DBM::Deep does not use dbm. Another earlier attempt at solving the problem is MLDBM, which is also available on the CPAN, but which has some fairly serious limitations.
Tied filehandles are still incomplete. sysopen(), truncate(), flock(), fcntl(), stat() and -X can't currently be trapped. π
π AUTHOR
Tom Christiansen
TIEHANDLE by Sven Verdoolaege <skimo@dns.ufsia.ac.be> and Doug MacEachern <dougm@osf.org>
UNTIE by Nick Ing-Simmons <nick@ing-simmons.net>
SCALAR by Tassilo von Parseval <tassilo.von.parseval@rwth-aachen.de>
Tying Arrays by Casey West <casey@geeknest.com>
And that's the whole page, bestie β this was perl v5.42.3, dated 2026-08-03, and it's the PERLTIE(1) page. Go tie something iconic. πβ¨π
π¦ where this page comes from
- fedora 43: perl-doc 5.42.3-524.fc43 Β· (GPL-1.0-or-later OR Artistic-1.0-Perl) AND Unicode-3.0 AND LicenseRef-Fedora-UltraPermissive
- fedora 44: perl-doc 5.42.3-525.fc44 Β· (GPL-1.0-or-later OR Artistic-1.0-Perl) AND Unicode-3.0 AND LicenseRef-Fedora-UltraPermissive
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms