.\" Automatically generated by Pod::Man v1.34, Pod::Parser v1.13
.\"
.\" Standard preamble:
.\" ========================================================================
.de Sh \" Subsection heading
.br
.if t .Sp
.ne 5
.PP
\fB\\$1\fR
.PP
..
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Vb \" Begin verbatim text
.ft CW
.nf
.ne \\$1
..
.de Ve \" End verbatim text
.ft R
.fi
..
.\" Set up some character translations and predefined strings. \*(-- will
.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
.\" double quote, and \*(R" will give a right double quote. | will give a
.\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to
.\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C'
.\" expand to `' in nroff, nothing in troff, for use with C<>.
.tr \(*W-|\(bv\*(Tr
.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
.ie n \{\
. ds -- \(*W-
. ds PI pi
. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
. ds L" ""
. ds R" ""
. ds C` ""
. ds C' ""
'br\}
.el\{\
. ds -- \|\(em\|
. ds PI \(*p
. ds L" ``
. ds R" ''
'br\}
.\"
.\" If the F register is turned on, we'll generate index entries on stderr for
.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
.\" entries marked with X<> in POD. Of course, you'll have to process the
.\" output yourself in some meaningful fashion.
.if \nF \{\
. de IX
. tm Index:\\$1\t\\n%\t"\\$2"
..
. nr % 0
. rr F
.\}
.\"
.\" For nroff, turn off justification. Always turn off hyphenation; it makes
.\" way too many mistakes in technical documents.
.hy 0
.if n .na
.\"
.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
.\" Fear. Run. Save yourself. No user-serviceable parts.
. \" fudge factors for nroff and troff
.if n \{\
. ds #H 0
. ds #V .8m
. ds #F .3m
. ds #[ \f1
. ds #] \fP
.\}
.if t \{\
. ds #H ((1u-(\\\\n(.fu%2u))*.13m)
. ds #V .6m
. ds #F 0
. ds #[ \&
. ds #] \&
.\}
. \" simple accents for nroff and troff
.if n \{\
. ds ' \&
. ds ` \&
. ds ^ \&
. ds , \&
. ds ~ ~
. ds /
.\}
.if t \{\
. ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
. ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
. ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
. ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
. ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
. ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
.\}
. \" troff and (daisy-wheel) nroff accents
.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
.ds ae a\h'-(\w'a'u*4/10)'e
.ds Ae A\h'-(\w'A'u*4/10)'E
. \" corrections for vroff
.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
. \" for low resolution devices (crt and lpr)
.if \n(.H>23 .if \n(.V>19 \
\{\
. ds : e
. ds 8 ss
. ds o a
. ds d- d\h'-1'\(ga
. ds D- D\h'-1'\(hy
. ds th \o'bp'
. ds Th \o'LP'
. ds ae ae
. ds Ae AE
.\}
.rm #[ #] #H #V #F C
.\" ========================================================================
.\"
.IX Title "PERLFILTER 1"
.TH PERLFILTER 1 "2002-11-24" "perl v5.8.0" "Perl Programmers Reference Guide"
.SH "NAME"
perlfilter \- Source Filters
.SH "DESCRIPTION"
.IX Header "DESCRIPTION"
This article is about a little-known feature of Perl called
\&\fIsource filters\fR. Source filters alter the program text of a module
before Perl sees it, much as a C preprocessor alters the source text of
a C program before the compiler sees it. This article tells you more
about what source filters are, how they work, and how to write your
own.
.PP
The original purpose of source filters was to let you encrypt your
program source to prevent casual piracy. This isn't all they can do, as
you'll soon learn. But first, the basics.
.SH "CONCEPTS"
.IX Header "CONCEPTS"
Before the Perl interpreter can execute a Perl script, it must first
read it from a file into memory for parsing and compilation. If that
script itself includes other scripts with a \f(CW\*(C`use\*(C'\fR or \f(CW\*(C`require\*(C'\fR
statement, then each of those scripts will have to be read from their
respective files as well.
.PP
Now think of each logical connection between the Perl parser and an
individual file as a \fIsource stream\fR. A source stream is created when
the Perl parser opens a file, it continues to exist as the source code
is read into memory, and it is destroyed when Perl is finished parsing
the file. If the parser encounters a \f(CW\*(C`require\*(C'\fR or \f(CW\*(C`use\*(C'\fR statement in
a source stream, a new and distinct stream is created just for that
file.
.PP
The diagram below represents a single source stream, with the flow of
source from a Perl script file on the left into the Perl parser on the
right. This is how Perl normally operates.
.PP
.Vb 1
\& file -------> parser
.Ve
.PP
There are two important points to remember:
.IP "1." 5
Although there can be any number of source streams in existence at any
given time, only one will be active.
.IP "2." 5
Every source stream is associated with only one file.
.PP
A source filter is a special kind of Perl module that intercepts and
modifies a source stream before it reaches the parser. A source filter
changes our diagram like this:
.PP
.Vb 1
\& file ----> filter ----> parser
.Ve
.PP
If that doesn't make much sense, consider the analogy of a command
pipeline. Say you have a shell script stored in the compressed file
\&\fItrial.gz\fR. The simple pipeline command below runs the script without
needing to create a temporary file to hold the uncompressed file.
.PP
.Vb 1
\& gunzip -c trial.gz | sh
.Ve
.PP
In this case, the data flow from the pipeline can be represented as follows:
.PP
.Vb 1
\& trial.gz ----> gunzip ----> sh
.Ve
.PP
With source filters, you can store the text of your script compressed and use a source filter to uncompress it for Perl's parser:
.PP
.Vb 2
\& compressed gunzip
\& Perl program ---> source filter ---> parser
.Ve
.SH "USING FILTERS"
.IX Header "USING FILTERS"
So how do you use a source filter in a Perl script? Above, I said that
a source filter is just a special kind of module. Like all Perl
modules, a source filter is invoked with a use statement.
.PP
Say you want to pass your Perl source through the C preprocessor before
execution. You could use the existing \f(CW\*(C`\-P\*(C'\fR command line option to do
this, but as it happens, the source filters distribution comes with a C
preprocessor filter module called Filter::cpp. Let's use that instead.
.PP
Below is an example program, \f(CW\*(C`cpp_test\*(C'\fR, which makes use of this filter.
Line numbers have been added to allow specific lines to be referenced
easily.
.PP
.Vb 4
\& 1: use Filter::cpp ;
\& 2: #define TRUE 1
\& 3: $a = TRUE ;
\& 4: print "a = $a\en" ;
.Ve
.PP
When you execute this script, Perl creates a source stream for the
file. Before the parser processes any of the lines from the file, the
source stream looks like this:
.PP
.Vb 1
\& cpp_test ---------> parser
.Ve
.PP
Line 1, \f(CW\*(C`use Filter::cpp\*(C'\fR, includes and installs the \f(CW\*(C`cpp\*(C'\fR filter
module. All source filters work this way. The use statement is compiled
and executed at compile time, before any more of the file is read, and
it attaches the cpp filter to the source stream behind the scenes. Now
the data flow looks like this:
.PP
.Vb 1
\& cpp_test ----> cpp filter ----> parser
.Ve
.PP
As the parser reads the second and subsequent lines from the source
stream, it feeds those lines through the \f(CW\*(C`cpp\*(C'\fR source filter before
processing them. The \f(CW\*(C`cpp\*(C'\fR filter simply passes each line through the
real C preprocessor. The output from the C preprocessor is then
inserted back into the source stream by the filter.
.PP
.Vb 5
\& .-> cpp --.
\& | |
\& | |
\& | <-'
\& cpp_test ----> cpp filter ----> parser
.Ve
.PP
The parser then sees the following code:
.PP
.Vb 3
\& use Filter::cpp ;
\& $a = 1 ;
\& print "a = $a\en" ;
.Ve
.PP
Let's consider what happens when the filtered code includes another
module with use:
.PP
.Vb 5
\& 1: use Filter::cpp ;
\& 2: #define TRUE 1
\& 3: use Fred ;
\& 4: $a = TRUE ;
\& 5: print "a = $a\en" ;
.Ve
.PP
The \f(CW\*(C`cpp\*(C'\fR filter does not apply to the text of the Fred module, only
to the text of the file that used it (\f(CW\*(C`cpp_test\*(C'\fR). Although the use
statement on line 3 will pass through the cpp filter, the module that
gets included (\f(CW\*(C`Fred\*(C'\fR) will not. The source streams look like this
after line 3 has been parsed and before line 4 is parsed:
.PP
.Vb 1
\& cpp_test ---> cpp filter ---> parser (INACTIVE)
.Ve
.PP
.Vb 1
\& Fred.pm ----> parser
.Ve
.PP
As you can see, a new stream has been created for reading the source
from \f(CW\*(C`Fred.pm\*(C'\fR. This stream will remain active until all of \f(CW\*(C`Fred.pm\*(C'\fR
has been parsed. The source stream for \f(CW\*(C`cpp_test\*(C'\fR will still exist,
but is inactive. Once the parser has finished reading Fred.pm, the
source stream associated with it will be destroyed. The source stream
for \f(CW\*(C`cpp_test\*(C'\fR then becomes active again and the parser reads line 4
and subsequent lines from \f(CW\*(C`cpp_test\*(C'\fR.
.PP
You can use more than one source filter on a single file. Similarly,
you can reuse the same filter in as many files as you like.
.PP
For example, if you have a uuencoded and compressed source file, it is
possible to stack a uudecode filter and an uncompression filter like
this:
.PP
.Vb 4
\& use Filter::uudecode ; use Filter::uncompress ;
\& M'XL(".H<US4''V9I;F%L')Q;>7/;1I;_>_I3=&E=%:F*I"T?22Q/
\& M6]9*<IQCO*XFT"0[PL%%'Y+IG?WN^ZYN-$'J.[.JE$,20/?K=_[>
\& ...
.Ve
.PP
Once the first line has been processed, the flow will look like this:
.PP
.Vb 2
\& file ---> uudecode ---> uncompress ---> parser
\& filter filter
.Ve
.PP
Data flows through filters in the same order they appear in the source
file. The uudecode filter appeared before the uncompress filter, so the
source file will be uudecoded before it's uncompressed.
.SH "WRITING A SOURCE FILTER"
.IX Header "WRITING A SOURCE FILTER"
There are three ways to write your own source filter. You can write it
in C, use an external program as a filter, or write the filter in Perl.
I won't cover the first two in any great detail, so I'll get them out
of the way first. Writing the filter in Perl is most convenient, so
I'll devote the most space to it.
.SH "WRITING A SOURCE FILTER IN C"
.IX Header "WRITING A SOURCE FILTER IN C"
The first of the three available techniques is to write the filter
completely in C. The external module you create interfaces directly
with the source filter hooks provided by Perl.
.PP
The advantage of this technique is that you have complete control over
the implementation of your filter. The big disadvantage is the
increased complexity required to write the filter \- not only do you
need to understand the source filter hooks, but you also need a
reasonable knowledge of Perl guts. One of the few times it is worth
going to this trouble is when writing a source scrambler. The
\&\f(CW\*(C`decrypt\*(C'\fR filter (which unscrambles the source before Perl parses it)
included with the source filter distribution is an example of a C
source filter (see Decryption Filters, below).
.IP "\fBDecryption Filters\fR" 5
.IX Item "Decryption Filters"
All decryption filters work on the principle of \*(L"security through
obscurity.\*(R" Regardless of how well you write a decryption filter and
how strong your encryption algorithm, anyone determined enough can
retrieve the original source code. The reason is quite simple \- once
the decryption filter has decrypted the source back to its original
form, fragments of it will be stored in the computer's memory as Perl
parses it. The source might only be in memory for a short period of
time, but anyone possessing a debugger, skill, and lots of patience can
eventually reconstruct your program.
.Sp
That said, there are a number of steps that can be taken to make life
difficult for the potential cracker. The most important: Write your
decryption filter in C and statically link the decryption module into
the Perl binary. For further tips to make life difficult for the
potential cracker, see the file \fIdecrypt.pm\fR in the source filters
module.
.SH "CREATING A SOURCE FILTER AS A SEPARATE EXECUTABLE"
.IX Header "CREATING A SOURCE FILTER AS A SEPARATE EXECUTABLE"
An alternative to writing the filter in C is to create a separate
executable in the language of your choice. The separate executable
reads from standard input, does whatever processing is necessary, and
writes the filtered data to standard output. \f(CW\*(C`Filter:cpp\*(C'\fR is an
example of a source filter implemented as a separate executable \- the
executable is the C preprocessor bundled with your C compiler.
.PP
The source filter distribution includes two modules that simplify this
task: \f(CW\*(C`Filter::exec\*(C'\fR and \f(CW\*(C`Filter::sh\*(C'\fR. Both allow you to run any
external executable. Both use a coprocess to control the flow of data
into and out of the external executable. (For details on coprocesses,
see Stephens, W.R. \*(L"Advanced Programming in the \s-1UNIX\s0 Environment.\*(R"
Addison\-Wesley, \s-1ISBN\s0 0\-210\-56317\-7, pages 441\-445.) The difference
between them is that \f(CW\*(C`Filter::exec\*(C'\fR spawns the external command
directly, while \f(CW\*(C`Filter::sh\*(C'\fR spawns a shell to execute the external
command. (Unix uses the Bourne shell; \s-1NT\s0 uses the cmd shell.) Spawning
a shell allows you to make use of the shell metacharacters and
redirection facilities.
.PP
Here is an example script that uses \f(CW\*(C`Filter::sh\*(C'\fR:
.PP
.Vb 3
\& use Filter::sh 'tr XYZ PQR' ;
\& $a = 1 ;
\& print "XYZ a = $a\en" ;
.Ve
.PP
The output you'll get when the script is executed:
.PP
.Vb 1
\& PQR a = 1
.Ve
.PP
Writing a source filter as a separate executable works fine, but a
small performance penalty is incurred. For example, if you execute the
small example above, a separate subprocess will be created to run the
Unix \f(CW\*(C`tr\*(C'\fR command. Each use of the filter requires its own subprocess.
If creating subprocesses is expensive on your system, you might want to
consider one of the other options for creating source filters.
.SH "WRITING A SOURCE FILTER IN PERL"
.IX Header "WRITING A SOURCE FILTER IN PERL"
The easiest and most portable option available for creating your own
source filter is to write it completely in Perl. To distinguish this
from the previous two techniques, I'll call it a Perl source filter.
.PP
To help understand how to write a Perl source filter we need an example
to study. Here is a complete source filter that performs rot13
decoding. (Rot13 is a very simple encryption scheme used in Usenet
postings to hide the contents of offensive posts. It moves every letter
forward thirteen places, so that A becomes N, B becomes O, and Z
becomes M.)
.PP
.Vb 1
\& package Rot13 ;
.Ve
.PP
.Vb 1
\& use Filter::Util::Call ;
.Ve
.PP
.Vb 5
\& sub import {
\& my ($type) = @_ ;
\& my ($ref) = [] ;
\& filter_add(bless $ref) ;
\& }
.Ve
.PP
.Vb 3
\& sub filter {
\& my ($self) = @_ ;
\& my ($status) ;
.Ve
.PP
.Vb 4
\& tr/n-za-mN-ZA-M/a-zA-Z/
\& if ($status = filter_read()) > 0 ;
\& $status ;
\& }
.Ve
.PP
.Vb 1
\& 1;
.Ve
.PP
All Perl source filters are implemented as Perl classes and have the
same basic structure as the example above.
.PP
First, we include the \f(CW\*(C`Filter::Util::Call\*(C'\fR module, which exports a
number of functions into your filter's namespace. The filter shown
above uses two of these functions, \f(CW\*(C`filter_add()\*(C'\fR and
\&\f(CW\*(C`filter_read()\*(C'\fR.
.PP
Next, we create the filter object and associate it with the source
stream by defining the \f(CW\*(C`import\*(C'\fR function. If you know Perl well
enough, you know that \f(CW\*(C`import\*(C'\fR is called automatically every time a
module is included with a use statement. This makes \f(CW\*(C`import\*(C'\fR the ideal
place to both create and install a filter object.
.PP
In the example filter, the object (\f(CW$ref\fR) is blessed just like any
other Perl object. Our example uses an anonymous array, but this isn't
a requirement. Because this example doesn't need to store any context
information, we could have used a scalar or hash reference just as
well. The next section demonstrates context data.
.PP
The association between the filter object and the source stream is made
with the \f(CW\*(C`filter_add()\*(C'\fR function. This takes a filter object as a
parameter (\f(CW$ref\fR in this case) and installs it in the source stream.
.PP
Finally, there is the code that actually does the filtering. For this
type of Perl source filter, all the filtering is done in a method
called \f(CW\*(C`filter()\*(C'\fR. (It is also possible to write a Perl source filter
using a closure. See the \f(CW\*(C`Filter::Util::Call\*(C'\fR manual page for more
details.) It's called every time the Perl parser needs another line of
source to process. The \f(CW\*(C`filter()\*(C'\fR method, in turn, reads lines from
the source stream using the \f(CW\*(C`filter_read()\*(C'\fR function.
.PP
If a line was available from the source stream, \f(CW\*(C`filter_read()\*(C'\fR
returns a status value greater than zero and appends the line to \f(CW$_\fR.
A status value of zero indicates end\-of\-file, less than zero means an
error. The filter function itself is expected to return its status in
the same way, and put the filtered line it wants written to the source
stream in \f(CW$_\fR. The use of \f(CW$_\fR accounts for the brevity of most Perl
source filters.
.PP
In order to make use of the rot13 filter we need some way of encoding
the source file in rot13 format. The script below, \f(CW\*(C`mkrot13\*(C'\fR, does
just that.
.PP
.Vb 5
\& die "usage mkrot13 filename\en" unless @ARGV ;
\& my $in = $ARGV[0] ;
\& my $out = "$in.tmp" ;
\& open(IN, "<$in") or die "Cannot open file $in: $!\en";
\& open(OUT, ">$out") or die "Cannot open file $out: $!\en";
.Ve
.PP
.Vb 5
\& print OUT "use Rot13;\en" ;
\& while (<IN>) {
\& tr/a-zA-Z/n-za-mN-ZA-M/ ;
\& print OUT ;
\& }
.Ve
.PP
.Vb 4
\& close IN;
\& close OUT;
\& unlink $in;
\& rename $out, $in;
.Ve
.PP
If we encrypt this with \f(CW\*(C`mkrot13\*(C'\fR:
.PP
.Vb 1
\& print " hello fred \en" ;
.Ve
.PP
the result will be this:
.PP
.Vb 2
\& use Rot13;
\& cevag "uryyb serq\ea" ;
.Ve
.PP
Running it produces this output:
.PP
.Vb 1
\& hello fred
.Ve
.SH "USING CONTEXT: THE DEBUG FILTER"
.IX Header "USING CONTEXT: THE DEBUG FILTER"
The rot13 example was a trivial example. Here's another demonstration
that shows off a few more features.
.PP
Say you wanted to include a lot of debugging code in your Perl script
during development, but you didn't want it available in the released
product. Source filters offer a solution. In order to keep the example
simple, let's say you wanted the debugging output to be controlled by
an environment variable, \f(CW\*(C`DEBUG\*(C'\fR. Debugging code is enabled if the
variable exists, otherwise it is disabled.
.PP
Two special marker lines will bracket debugging code, like this:
.PP
.Vb 5
\& ## DEBUG_BEGIN
\& if ($year > 1999) {
\& warn "Debug: millennium bug in year $year\en" ;
\& }
\& ## DEBUG_END
.Ve
.PP
When the \f(CW\*(C`DEBUG\*(C'\fR environment variable exists, the filter ensures that
Perl parses only the code between the \f(CW\*(C`DEBUG_BEGIN\*(C'\fR and \f(CW\*(C`DEBUG_END\*(C'\fR
markers. That means that when \f(CW\*(C`DEBUG\*(C'\fR does exist, the code above
should be passed through the filter unchanged. The marker lines can
also be passed through as\-is, because the Perl parser will see them as
comment lines. When \f(CW\*(C`DEBUG\*(C'\fR isn't set, we need a way to disable the
debug code. A simple way to achieve that is to convert the lines
between the two markers into comments:
.PP
.Vb 5
\& ## DEBUG_BEGIN
\& #if ($year > 1999) {
\& # warn "Debug: millennium bug in year $year\en" ;
\& #}
\& ## DEBUG_END
.Ve
.PP
Here is the complete Debug filter:
.PP
.Vb 1
\& package Debug;
.Ve
.PP
.Vb 3
\& use strict;
\& use warnings;
\& use Filter::Util::Call ;
.Ve
.PP
.Vb 2
\& use constant TRUE => 1 ;
\& use constant FALSE => 0 ;
.Ve
.PP
.Vb 11
\& sub import {
\& my ($type) = @_ ;
\& my (%context) = (
\& Enabled => defined $ENV{DEBUG},
\& InTraceBlock => FALSE,
\& Filename => (caller)[1],
\& LineNo => 0,
\& LastBegin => 0,
\& ) ;
\& filter_add(bless \e%context) ;
\& }
.Ve
.PP
.Vb 6
\& sub Die {
\& my ($self) = shift ;
\& my ($message) = shift ;
\& my ($line_no) = shift || $self->{LastBegin} ;
\& die "$message at $self->{Filename} line $line_no.\en"
\& }
.Ve
.PP
.Vb 5
\& sub filter {
\& my ($self) = @_ ;
\& my ($status) ;
\& $status = filter_read() ;
\& ++ $self->{LineNo} ;
.Ve
.PP
.Vb 6
\& # deal with EOF/error first
\& if ($status <= 0) {
\& $self->Die("DEBUG_BEGIN has no DEBUG_END")
\& if $self->{InTraceBlock} ;
\& return $status ;
\& }
.Ve
.PP
.Vb 6
\& if ($self->{InTraceBlock}) {
\& if (/^\es*##\es*DEBUG_BEGIN/ ) {
\& $self->Die("Nested DEBUG_BEGIN", $self->{LineNo})
\& } elsif (/^\es*##\es*DEBUG_END/) {
\& $self->{InTraceBlock} = FALSE ;
\& }
.Ve
.PP
.Vb 10
\& # comment out the debug lines when the filter is disabled
\& s/^/#/ if ! $self->{Enabled} ;
\& } elsif ( /^\es*##\es*DEBUG_BEGIN/ ) {
\& $self->{InTraceBlock} = TRUE ;
\& $self->{LastBegin} = $self->{LineNo} ;
\& } elsif ( /^\es*##\es*DEBUG_END/ ) {
\& $self->Die("DEBUG_END has no DEBUG_BEGIN", $self->{LineNo});
\& }
\& return $status ;
\& }
.Ve
.PP
.Vb 1
\& 1 ;
.Ve
.PP
The big difference between this filter and the previous example is the
use of context data in the filter object. The filter object is based on
a hash reference, and is used to keep various pieces of context
information between calls to the filter function. All but two of the
hash fields are used for error reporting. The first of those two,
Enabled, is used by the filter to determine whether the debugging code
should be given to the Perl parser. The second, InTraceBlock, is true
when the filter has encountered a \f(CW\*(C`DEBUG_BEGIN\*(C'\fR line, but has not yet
encountered the following \f(CW\*(C`DEBUG_END\*(C'\fR line.
.PP
If you ignore all the error checking that most of the code does, the
essence of the filter is as follows:
.PP
.Vb 4
\& sub filter {
\& my ($self) = @_ ;
\& my ($status) ;
\& $status = filter_read() ;
.Ve
.PP
.Vb 6
\& # deal with EOF/error first
\& return $status if $status <= 0 ;
\& if ($self->{InTraceBlock}) {
\& if (/^\es*##\es*DEBUG_END/) {
\& $self->{InTraceBlock} = FALSE
\& }
.Ve
.PP
.Vb 7
\& # comment out debug lines when the filter is disabled
\& s/^/#/ if ! $self->{Enabled} ;
\& } elsif ( /^\es*##\es*DEBUG_BEGIN/ ) {
\& $self->{InTraceBlock} = TRUE ;
\& }
\& return $status ;
\& }
.Ve
.PP
Be warned: just as the C\-preprocessor doesn't know C, the Debug filter
doesn't know Perl. It can be fooled quite easily:
.PP
.Vb 3
\& print <<EOM;
\& ##DEBUG_BEGIN
\& EOM
.Ve
.PP
Such things aside, you can see that a lot can be achieved with a modest
amount of code.
.SH "CONCLUSION"
.IX Header "CONCLUSION"
You now have better understanding of what a source filter is, and you
might even have a possible use for them. If you feel like playing with
source filters but need a bit of inspiration, here are some extra
features you could add to the Debug filter.
.PP
First, an easy one. Rather than having debugging code that is
all\-or\-nothing, it would be much more useful to be able to control
which specific blocks of debugging code get included. Try extending the
syntax for debug blocks to allow each to be identified. The contents of
the \f(CW\*(C`DEBUG\*(C'\fR environment variable can then be used to control which
blocks get included.
.PP
Once you can identify individual blocks, try allowing them to be
nested. That isn't difficult either.
.PP
Here is an interesting idea that doesn't involve the Debug filter.
Currently Perl subroutines have fairly limited support for formal
parameter lists. You can specify the number of parameters and their
type, but you still have to manually take them out of the \f(CW@_\fR array
yourself. Write a source filter that allows you to have a named
parameter list. Such a filter would turn this:
.PP
.Vb 1
\& sub MySub ($first, $second, @rest) { ... }
.Ve
.PP
into this:
.PP
.Vb 6
\& sub MySub($$@) {
\& my ($first) = shift ;
\& my ($second) = shift ;
\& my (@rest) = @_ ;
\& ...
\& }
.Ve
.PP
Finally, if you feel like a real challenge, have a go at writing a
full-blown Perl macro preprocessor as a source filter. Borrow the
useful features from the C preprocessor and any other macro processors
you know. The tricky bit will be choosing how much knowledge of Perl's
syntax you want your filter to have.
.SH "REQUIREMENTS"
.IX Header "REQUIREMENTS"
The Source Filters distribution is available on \s-1CPAN\s0, in
.PP
.Vb 1
\& CPAN/modules/by-module/Filter
.Ve
.PP
Starting from Perl 5.8 Filter::Util::Call (the core part of the
Source Filters distribution) is part of the standard Perl distribution.
Also included is a friendlier interface called Filter::Simple, by
Damian Conway.
.SH "AUTHOR"
.IX Header "AUTHOR"
Paul Marquess <Paul.Marquess@btinternet.com>
.SH "Copyrights"
.IX Header "Copyrights"
This article originally appeared in The Perl Journal #11, and is
copyright 1998 The Perl Journal. It appears courtesy of Jon Orwant and
The Perl Journal. This document may be distributed under the same terms
as Perl itself.
|