Book HomeJava and XSLTSearch this book

8.113. 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 to handle different parts of your source code. FILTER_ONLY takes several subroutines as options: code, executable, string, regex, quotelike, and all. code or executable filters all Perl code, except Pod or _ _DATA_ _ types. quotelike filters other Perl quotelike stuff, including here documents. string filters all string-related parts. regex filters all pattern-literal parts of quotelike.

For example, the following module will skip all incidences of Pod in the PodSucks module:

package PodSucks;
 
use Filter::Simple;
 
FILTER_ONLY
	executable => sub { s/x/X/g },
	executable => sub { print }
 
# True. True.
1;

The above code might not make that much sense, but take a look at the test program now, and it should become clear:

#!/usr/local/bin/perl -w

use PodSucks;

print "Flocks of Red Sox cause shocks to the Bronx.\n";
 
=pod
You will fear the wrath of Pod! Fear my wrath!
=cut

This prints:

Flocks of Red SoX cause shocks to the BronX.


Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.