PerlIO::via#
Write a PerlIO layer in Perl: open with :via(MyClass) and I/O dispatches to your class.
PerlIO::via provides the :via(CLASS) layer. A handle opened or binmoded with it routes every I/O operation to a method call on CLASS, so the whole behaviour of a layer - buffering, filtering, transcoding - is defined by an ordinary Perl class:
package PerlIO::via::UpperCase;
sub PUSHED { my ($class, $mode, $fh) = @_; bless {}, $class }
sub WRITE { my ($self, $buf, $fh) = @_; print $fh uc $buf; length $buf }
sub FILL { my ($self, $fh) = @_; scalar <$fh> }
package main;
open my $out, '>:via(UpperCase)', $file or die $!;
print $out "hello\n"; # the file gets HELLO
CLASS is looked up as PerlIO::via::CLASS first and as CLASS itself second, so both spellings of the layer name work. If neither package exists the layer warns Cannot find package 'CLASS' and fails to be pushed; :via() with no name at all warns No package specified.
PUSHED is the only method a class must supply. It is called with the class name and the open mode. If it returns an object, that object becomes the invocant for every later call; a true non-object return is taken as a failure code and aborts the push. Every other method is optional - when one is missing, the layer falls back to the default behaviour for that operation. The full set is PUSHED, POPPED, OPEN, FDOPEN, SYSOPEN, GETARG, FILENO, READ, WRITE, FILL, CLOSE, SEEK, TELL, UNREAD, FLUSH, SETLINEBUF, CLEARERR, ERROR, EOF, BINMODE and UTF8.
Each method receives the object, then its own arguments, then - when there is a layer below - a filehandle onto that layer. That handle is how a class reads and writes the data passing through it.
Reading goes through FILL when the class defines one: the layer buffers what FILL returns and hands it upwards a piece at a time. With no FILL, READ is called instead and must return how many bytes it put in the buffer; a count outside the requested range warns Invalid return from CLASS::READ = N, expected undef or 0 to M and fails with EINVAL.
UTF8 is called with a true value when the layer below already delivers characters; returning true marks this layer’s data as characters too. BINMODE returning undef, or not being defined at all, pops the layer.
This is a native implementation of PerlIO::via 0.21; its PerlIO/via.pm is used unchanged.
Differences from upstream#
None.
Modules#
PerlIO::via::QuotedPrint- PerlIO layer for quoted-printable strings