perltie.pod
来自「ARM上的如果你对底层感兴趣」· POD 代码 · 共 877 行 · 第 1/2 页
POD
877 行
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 it
would probably be more portable to open the file manually (and somewhat
more efficient). Of course, because dot files are a Unixy concept, we're
not that concerned.
=item STORE this, key, value
This method will be 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.
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(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;
}
=item 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.
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(). If you want to emulate the normal behavior of delete(),
you should return whatever FETCH would have returned for this key.
In this example, we have chosen instead to return a value which tells
the caller whether the file was successfully deleted.
=item CLEAR this
This method is triggered when the whole hash is to be cleared, usually by
assigning the empty list to it.
In our example, that would remove all the user's dot files! It's such a
dangerous thing that they'll have to set CLOBBER to something higher than
1 to make it happen.
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);
}
}
=item EXISTS this, key
This method is triggered when the user uses the exists() function
on a particular hash. In our example, we'll look at the C<{LIST}>
hash element for this:
sub EXISTS {
carp &whowasi if $DEBUG;
my $self = shift;
my $dot = shift;
return exists $self->{LIST}->{$dot};
}
=item FIRSTKEY this
This method will be triggered when the user is going
to iterate through the hash, such as via a keys() or each()
call.
sub FIRSTKEY {
carp &whowasi if $DEBUG;
my $self = shift;
my $a = keys %{$self->{LIST}}; # reset each() iterator
each %{$self->{LIST}}
}
=item NEXTKEY this, lastkey
This method gets triggered during a keys() or each() iteration. It has a
second argument which is the last key that had been accessed. This is
useful if you're carrying about ordering or calling the iterator from more
than one sequence, or not really storing things in a hash anywhere.
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} }
}
=item 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. Here's a very simple function:
sub DESTROY {
carp &whowasi if $DEBUG;
}
=back
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);
=head2 Tying FileHandles
This is partially implemented now.
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 and DESTROY.
It 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.
In our example we're going to create a shouting handle.
package Shout;
=over
=item 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 }
=item WRITE this, LIST
This method will be called when the handle is written to via the
C<syswrite> function.
sub WRITE {
$r = shift;
my($buf,$len,$offset) = @_;
print "WRITE called, \$buf=$buf, \$len=$len, \$offset=$offset";
}
=item PRINT this, LIST
This method will be triggered every time the tied handle is printed to
with the C<print()> function.
Beyond its self reference it also expects the list that was passed to
the print function.
sub PRINT { $r = shift; $$r++; print join($,,map(uc($_),@_)),$\ }
=item PRINTF this, LIST
This method will be triggered every time the tied handle is printed to
with the C<printf()> function.
Beyond its self reference it also expects the format and list that was
passed to the printf function.
sub PRINTF {
shift;
my $fmt = shift;
print sprintf($fmt, @_)."\n";
}
=item READ this, LIST
This method will be called when the handle is read from via the C<read>
or C<sysread> functions.
sub READ {
$r = shift;
my($buf,$len,$offset) = @_;
print "READ called, \$buf=$buf, \$len=$len, \$offset=$offset";
}
=item READLINE this
This method will be called when the handle is read from via <HANDLE>.
The method should return undef when there is no more data.
sub READLINE { $r = shift; "PRINT called $$r times\n"; }
=item GETC this
This method will be called when the C<getc> function is called.
sub GETC { print "Don't GETC, Get Perl"; return "a"; }
=item CLOSE this
This method will be called when the handle is closed via the C<close>
function.
sub CLOSE { print "CLOSE called.\n" }
=item DESTROY this
As with the other types of ties, this method will be called when the
tied handle is about to be destroyed. This is useful for debugging and
possibly cleaning up.
sub DESTROY { print "</shout>\n" }
=back
Here's how to use our little example:
tie(*FOO,'Shout');
print FOO "hello\n";
$a = 4; $b = 6;
print FOO $a, " plus ", $b, " equals ", $a + $b, "\n";
print <FOO>;
=head2 The C<untie> Gotcha
If you intend making use of the object returned from either tie() or
tied(), and if the tie's target class defines a destructor, there is a
subtle gotcha you I<must> guard against.
As setup, consider this (admittedly rather 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 strict;
use IO::File;
sub TIESCALAR {
my $class = shift;
my $filename = shift;
my $handle = new IO::File "> $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;
Here is 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 is executed:
The Start
1
4
5
The End
So far so good. Those of you who have been paying attention will have
spotted that the tied object hasn't been used so far. So lets add an
extra method to the Remember class to allow comments to be included in
the file -- say, something like this:
sub comment {
my $self = shift;
my $text = shift;
my $handle = $self->{FH};
print $handle $text, "\n";
}
And here is the previous example modified to use the C<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 is executed there is no output. Here's why:
When a variable is tied, it is associated with the object which is the
return value of the TIESCALAR, TIEARRAY, or TIEHASH function. This
object normally has only one reference, namely, the implicit reference
from the tied variable. When untie() is called, that reference is
destroyed. Then, as in the first example above, the object's
destructor (DESTROY) is called, which is normal for objects that have
no more valid references; and thus the file is closed.
In the second example, however, we have stored another reference to
the tied object in C<$x>. That means that when untie() gets called
there will still be a valid reference to the object in existence, so
the destructor is not called at that time, and thus the file is not
closed. The reason there is no output is because the file buffers
have not been flushed to disk.
Now that you know what the problem is, what can you do to avoid it?
Well, the good old C<-w> flag will spot any instances where you call
untie() and there are still valid references to the tied object. If
the second script above is run with the C<-w> flag, Perl prints this
warning message:
untie attempted while 1 inner references still exist
To get the script to work properly and silence the warning make sure
there are no valid references to the tied object I<before> untie() is
called:
undef $x;
untie $fred;
=head1 SEE ALSO
See L<DB_File> or L<Config> for some interesting tie() implementations.
=head1 BUGS
Tied arrays are I<incomplete>. They are also distinctly lacking something
for the C<$#ARRAY> access (which is hard, as it's an lvalue), as well as
the other obvious array functions, like push(), pop(), shift(), unshift(),
and splice().
You cannot easily tie a multilevel data structure (such as a hash of
hashes) to a dbm file. The first problem is that 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 experimental
module that does attempt to address this need partially is the MLDBM
module. Check your nearest CPAN site as described in L<perlmodlib> for
source code to MLDBM.
=head1 AUTHOR
Tom Christiansen
TIEHANDLE by Sven Verdoolaege <F<skimo@dns.ufsia.ac.be>> and Doug MacEachern <F<dougm@osf.org>>
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?