Filter::Simple

Source filtering is a nice feature of newer versions of Perl (5.6 and later) because it allows the programmer to write extensions to the Perl language without tampering with the Perl source code itself. That is, you can create a macro language out of Perl.

Filter::Simple is based on Filter:Util::Call, but simplifies the means by which you can begin doing your own source filtering with Perl. Filter::Simple ships with the Perl 5.8 source kit.

Using Filter::Simple is, well, easy. Basically, Filter::Simple implements FILTER { ... }, which you can use to handle many of your simple source-filtering needs. Let’s say that you want a good glass of ale, and you decide that you don’t want Perl to print, but pint instead. You can implement something like the following with Filter::Simple. First, create a module called Print_to_Pint:

package Print_to_Pint;
 
use Filter::Simple;
FILTER { s/pint/print/g; }
 
# true
1;

Now, use Print_to_Pint to do something with pint:

#!/usr/local/bin/perl -w
 
use Print_to_Pint;
 
my $bottles = 99;
my $last = 1;
 
foreach my $bottle (reverse($last .. $bottles)) {
    pint "$bottle -> burp\n";
}

By default, Filter::Simple ignores no behavior, i.e., it stops filtering after a no Module is encountered. You can alter this behavior by passing another argument to use Filter::Simple or to FILTER { ... }. For example:

package Print_to_Pint;
use Filter::Simple;
    FILTER {
        s/pint/print/g;
}
"";

Filter::Simple also supports FILTER_ONLY, which allows you to support multiple filters ...

Get Perl in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.