Benjamin Trott > Filter-Handle-0.03 > Filter::Handle

Download:
Filter-Handle-0.03.tar.gz

Dependencies

Annotate this POD

CPAN RT

Open  1
View Bugs
Report a bug
Module Version: 0.03   Source  

NAME ^

Filter::Handle - Apply filters to output filehandles

SYNOPSIS ^

    use Filter::Handle;
    my $f = Filter::Handle->new(\*STDOUT);
    $f->print(...);

    use Filter::Handle qw/subs/;
    Filter \*STDOUT;
    ...
    UnFilter \*STDOUT;

    tie *STDOUT, 'Filter::Handle', \*HANDLE;
    ...
    untie *STDOUT;

DESCRIPTION ^

Filter::Handle allows you to apply arbitrary filters to output filehandles. You can perform any sorts of transformations on the outgoing text: you can prepend it with some data, you can replace all instances of one word with another, etc.

You can even filter all of your output to one filehandle and send it to another; for example, you can filter everything written to STDOUT and write it instead to another filehandle. To do this, you need to explicitly use the tie interface (see below).

Calling Interfaces

There are three interfaces to filtering a handle:

Customized Filters

The default filter is relatively boring: it simply prepends any text you print with the filename and line of the invoking caller. You'll probably want to do something more interesting.

To do so, pass an anonymous subroutine as a second argument to either the new method, if you're using the OO interface, or to the Filter function, if you're using the functional interface. Your subroutine will be passed the list originally passed to print, and it should return another list, suitable for passing to your (unfiltered) output filehandle.

For example, say that we want to replace all instances of "blue" with "red". We could say:

    use Filter::Handle qw/subs/;

    Filter \*STDOUT,
        sub { local $_ = "@_"; s/blue/red/g; $_ };

    print "My house is blue.\n";
    print "So is my cat, whose nose is blue.\n";

    UnFilter \*STDOUT;

    print "And the plane is also blue.\n";

This prints:

    My house is red.
    So is my cat, whose nose is red.
    And the plane is also blue.

As expected.

Tips, Tricks, Samples

CAVEATS ^

Note that this won't work correctly with output from XSUBs or system calls. This is due to a limitation of Perl's tie mechanism when tying filehandles.

AUTHOR ^

Benjamin Trott, ben@rhumba.pair.com

CREDITS ^

Thanks to tilly, chromatic, and merlyn at PerlMonks.org for suggestions, critiques, and code samples.