Tying Filehandles

A class implementing a tied filehandle should define the following methods: TIEHANDLE and at least one of PRINT, PRINTF, WRITE, READLINE, GETC, and READ. The class can also provide a DESTROY method, as well as BINMODE, OPEN, CLOSE, EOF, FILENO, SEEK, TELL, READ, and WRITE methods to enable the corresponding Perl built-ins for the tied filehandle. (Well, that isn’t quite true: WRITE corresponds to syswrite and has nothing to do with Perl’s built-in write function for printing with format declarations.)

Tied filehandles are especially useful when Perl is embedded in another program (such as Apache or vi) and output to STDOUT or STDERR needs to be redirected in some special way.

But filehandles don’t actually have to be tied to a file at all. You can use output statements to build up an in-memory data structure and input statements to read them back in. Here’s an easy way to reverse a sequence of print and printf statements without reversing the individual lines:

package ReversePrint 0.01 { use strict; sub TIEHANDLE { my $class = shift; bless [], $class; } sub PRINT { my $self = shift; push @$self, join("" => @_); } sub PRINTF { my $self = shift; my $fmt = shift; push @$self, sprintf($fmt, @_); } sub READLINE { my $self = shift; pop @$self; } } my $m = "––MORE––\n"; tie *REV, "ReversePrint"; # Do some prints and printfs. print REV "The fox is now dead.$m"; printf REV <<"END", int rand 10000000; The quick brown fox jumps over the lazy dog %d times! END print REV <<"END"; ...

Get Programming Perl, 4th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.