Seth Woolley's Man Viewer

perlfilter(1) - perlfilter - Source Filters - man 1 perlfilter

([section] manual, -k keyword, -K [section] search, -f whatis)
man plain no title

PERLFILTER(1)          Perl Programmers Reference Guide          PERLFILTER(1)

       perlfilter - Source Filters

       This article is about a little-known feature of Perl called source fil-
       ters. 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(1,2) your own.

       The original purpose of source filters was to let you encrypt your pro-
       gram source to prevent casual piracy. This isn't all they can do, as
       you'll soon learn. But first, the basics.

       Before the Perl interpreter can execute a Perl script, it must first
       read(2,n,1 builtins) it from a file(1,n) into memory for parsing and compilation. If that
       script itself includes other scripts with a "use" or "require" state-
       ment, then each of those scripts will have to be read(2,n,1 builtins) from their
       respective files as well.

       Now think of each logical connection between the Perl parser and an
       individual file(1,n) as a source stream. A source stream is created when the
       Perl parser opens a file(1,n), it continues to exist as the source code is
       read(2,n,1 builtins) into memory, and it is destroyed when Perl is finished parsing the
       file. If the parser encounters a "require" or "use" statement in(1,8) a
       source stream, a new and distinct stream is created just for that file.

       The diagram below represents a single source stream, with the flow of
       source from a Perl script file(1,n) on the left into the Perl parser on the
       right. This is how Perl normally operates.

           file(1,n) -------> parser

       There are two important points to remember:

       1.   Although there can be any number of source streams in(1,8) existence at
            any given time(1,2,n), only one will be active.

       2.   Every source stream is associated with only one file.

       A source filter(1,3x,3x curs_util) is a special kind of Perl module that intercepts and
       modifies a source stream before it reaches the parser. A source filter(1,3x,3x curs_util)
       changes our diagram like this:

           file(1,n) ----> filter(1,3x,3x curs_util) ----> parser

       If that doesn't make much sense, consider the analogy of a command
       pipeline. Say you have a shell script stored in(1,8) the compressed file(1,n)
       trial.gz. The simple pipeline command below runs the script without
       needing to create a temporary file(1,n) to hold the uncompressed file.

           gunzip -c trial.gz | sh

       In this case, the data flow from the pipeline can be represented as

           trial.gz ----> gunzip ----> sh

       With source filters, you can store the text of your script compressed
       and use a source filter(1,3x,3x curs_util) to uncompress it for Perl's parser:

            compressed           gunzip
           Perl program ---> source filter(1,3x,3x curs_util) ---> parser

       So how do you use a source filter(1,3x,3x curs_util) in(1,8) a Perl script? Above, I said that
       a source filter(1,3x,3x curs_util) is just a special kind of module. Like all Perl mod-
       ules, a source filter(1,3x,3x curs_util) is invoked with a use statement.

       Say you want to pass your Perl source through the C preprocessor before
       execution. You could use the existing "-P" command line option to do
       this, but as it happens, the source filters distribution comes with a C
       preprocessor filter(1,3x,3x curs_util) module called Filter::cpp. Let's use that instead.

       Below is an example program, "cpp_test", which makes use of this fil-
       ter.  Line numbers have been added to allow specific lines to be refer-
       enced easily.

           1: use Filter::cpp ;
           2: #define TRUE 1
           3: $a = TRUE ;
           4: print "a = $a\n" ;

       When you execute this script, Perl creates a source stream for the
       file. Before the parser processes any of the lines from the file(1,n), the
       source stream looks like this:

           cpp_test ---------> parser

       Line 1, "use Filter::cpp", includes and installs the "cpp" filter(1,3x,3x curs_util) mod-
       ule. All source filters work this way. The use statement is compiled
       and executed at compile time(1,2,n), before any more of the file(1,n) is read(2,n,1 builtins), and
       it attaches the cpp filter(1,3x,3x curs_util) to the source stream behind the scenes. Now
       the data flow looks like this:

           cpp_test ----> cpp filter(1,3x,3x curs_util) ----> parser

       As the parser reads the second and subsequent lines from the source
       stream, it feeds those lines through the "cpp" source filter(1,3x,3x curs_util) before
       processing them. The "cpp" filter(1,3x,3x curs_util) 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.

                         .-> cpp --.
                         |         |
                         |         |
                         |       <-'
          cpp_test ----> cpp filter(1,3x,3x curs_util) ----> parser

       The parser then sees the following code:

           use Filter::cpp ;
           $a = 1 ;
           print "a = $a\n" ;

       Let's consider what happens when the filtered code includes another
       module with use:

           1: use Filter::cpp ;
           2: #define TRUE 1
           3: use Fred ;
           4: $a = TRUE ;
           5: print "a = $a\n" ;

       The "cpp" filter(1,3x,3x curs_util) does not apply to the text of the Fred module, only to
       the text of the file(1,n) that used it ("cpp_test"). Although the use state-
       ment on line 3 will pass through the cpp filter(1,3x,3x curs_util), the module that gets(3,n)
       included ("Fred") will not. The source streams look(1,8,3 Search::Dict) like this after
       line 3 has been parsed and before line 4 is parsed:

           cpp_test ---> cpp filter(1,3x,3x curs_util) ---> parser (INACTIVE)

  ----> parser

       As you can see, a new stream has been created for reading the source
       from "". This stream will remain active until all of ""
       has been parsed. The source stream for "cpp_test" will still exist, but
       is inactive. Once the parser has finished reading, the source
       stream associated with it will be destroyed. The source stream for
       "cpp_test" then becomes active again and the parser reads line 4 and
       subsequent lines from "cpp_test".

       You can use more than one source filter(1,3x,3x curs_util) on a single file. Similarly,
       you can reuse the same filter(1,3x,3x curs_util) in(1,8) as many files as you like.

       For example, if(3,n) you have a uuencoded and compressed source file(1,n), it is
       possible to stack a uudecode filter(1,3x,3x curs_util) and an uncompression filter(1,3x,3x curs_util) like

           use Filter::uudecode ; use Filter::uncompress ;

       Once the first line has been processed, the flow will look(1,8,3 Search::Dict) like this:

           file(1,n) ---> uudecode ---> uncompress ---> parser
                      filter(1,3x,3x curs_util)         filter(1,3x,3x curs_util)

       Data flows through filters in(1,8) the same order they appear in(1,8) the source
       file. The uudecode filter(1,3x,3x curs_util) appeared before the uncompress filter(1,3x,3x curs_util), so the
       source file(1,n) will be uudecoded before it's uncompressed.

       There are three ways to write(1,2) your own source filter. You can write(1,2) it
       in(1,8) C, use an external program as a filter(1,3x,3x curs_util), or write(1,2) the filter(1,3x,3x curs_util) in(1,8) Perl.
       I won't cover the first two in(1,8) any great detail, so I'll get them out
       of the way first. Writing the filter(1,3x,3x curs_util) in(1,8) Perl is most convenient, so
       I'll devote the most space to it.

       The first of the three available techniques is to write(1,2) the filter(1,3x,3x curs_util) com-
       pletely in(1,8) C. The external module you create interfaces directly with
       the source filter(1,3x,3x curs_util) hooks provided by Perl.

       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(1,2) the filter(1,3x,3x curs_util) - not only do you
       need to understand the source filter(1,3x,3x curs_util) hooks, but you also need a reason-
       able knowledge of Perl guts. One of the few times it is worth going to
       this trouble is when writing a source scrambler. The "decrypt" filter(1,3x,3x curs_util)
       (which unscrambles the source before Perl parses it) included with the
       source filter(1,3x,3x curs_util) distribution is an example of a C source filter(1,3x,3x curs_util) (see
       Decryption Filters, below).

       Decryption Filters
            All decryption filters work on the principle of "security through
            obscurity." Regardless of how well you write(1,2) a decryption filter(1,3x,3x curs_util)
            and how strong your encryption algorithm, anyone determined enough
            can retrieve the original source code. The reason is quite simple
            - once the decryption filter(1,3x,3x curs_util) has decrypted the source back to its
            original form, fragments of it will be stored in(1,8) the computer's
            memory as Perl parses it. The source might only be in(1,8) memory for a
            short period of time(1,2,n), but anyone possessing a debugger, skill, and
            lots of patience can eventually reconstruct your program.

            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(1,3x,3x curs_util) in(1,8) C and statically link(1,2) the decryp-
            tion module into the Perl binary. For further tips to make life
            difficult for the potential cracker, see the file(1,n) in(1,8)
            the source filters module.

       An alternative to writing the filter(1,3x,3x curs_util) in(1,8) C is to create a separate exe-
       cutable in(1,8) 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. "Filter:cpp" is an example of a
       source filter(1,3x,3x curs_util) implemented as a separate executable - the executable is
       the C preprocessor bundled with your C compiler.

       The source filter(1,3x,3x curs_util) distribution includes two modules that simplify this
       task: "Filter::exec" and "Filter::sh". Both allow you to run any exter-
       nal 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. "Advanced Programming in(1,8) the UNIX Environment."  Addi-
       son-Wesley, ISBN 0-210-56317-7, pages 441-445.) The difference between
       them is that "Filter::exec" spawns the external command directly, while
       "Filter::sh" spawns a shell to execute the external command. (Unix uses
       the Bourne shell; NT uses the cmd shell.) Spawning a shell allows you
       to make use of the shell metacharacters and redirection facilities.

       Here is an example script that uses "Filter::sh":

           use Filter::sh 'tr XYZ PQR' ;
           $a = 1 ;
           print "XYZ a = $a\n" ;

       The output you'll get when the script is executed:

           PQR a = 1

       Writing a source filter(1,3x,3x curs_util) as a separate executable works fine, but a
       small performance penalty is incurred. For example, if(3,n) you execute the
       small example above, a separate subprocess will be created to run the
       Unix "tr" command. Each use of the filter(1,3x,3x curs_util) 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.

       The easiest and most portable option available for creating your own
       source filter(1,3x,3x curs_util) is to write(1,2) it completely in(1,8) Perl. To distinguish this
       from the previous two techniques, I'll call it a Perl source filter.

       To help understand how to write(1,2) a Perl source filter(1,3x,3x curs_util) we need an example
       to study. Here is a complete source filter(1,3x,3x curs_util) that performs rot13 decod-
       ing. (Rot13 is a very simple encryption scheme used in(1,8) 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.)

          package Rot13 ;

          use Filter::Util::Call ;

          sub import {
             my ($type) = @_ ;
             my ($ref) = [] ;
             filter_add(bless $ref) ;

          sub filter(1,3x,3x curs_util) {
             my ($self) = @_ ;
             my ($status) ;

                if(3,n) ($status = filter_read()) > 0 ;
             $status ;


       All Perl source filters are implemented as Perl classes and have the
       same basic structure as the example above.

       First, we include the "Filter::Util::Call" module, which exports a num-
       ber of functions into your filter(1,3x,3x curs_util)'s namespace. The filter(1,3x,3x curs_util) shown above
       uses two of these functions, "filter_add()" and "filter_read()".

       Next, we create the filter(1,3x,3x curs_util) object and associate it with the source
       stream by defining the "import" function. If you know Perl well enough,
       you know that "import" is called automatically every time(1,2,n) a module is
       included with a use statement. This makes "import" the ideal place to
       both create and install a filter(1,3x,3x curs_util) object.

       In the example filter(1,3x,3x curs_util), the object ($ref) 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.

       The association between the filter(1,3x,3x curs_util) object and the source stream is made
       with the "filter_add()" function. This takes a filter(1,3x,3x curs_util) object as a
       parameter ($ref in(1,8) this case) and installs it in(1,8) the source stream.

       Finally, there is the code that actually does the filtering. For this
       type of Perl source filter(1,3x,3x curs_util), all the filtering is done in(1,8) a method
       called "filter(1,3x,3x curs_util)()". (It is also possible to write(1,2) a Perl source filter(1,3x,3x curs_util)
       using a closure. See the "Filter::Util::Call" manual page for more
       details.) It's called every time(1,2,n) the Perl parser needs another line of
       source to process. The "filter(1,3x,3x curs_util)()" method, in(1,8) turn, reads lines from the
       source stream using the "filter_read()" function.

       If a line was available from the source stream, "filter_read()" returns
       a status value greater than zero and appends the line to $_.  A status
       value of zero indicates end-of-file, less(1,3) than zero means an error. The
       filter(1,3x,3x curs_util) function itself is expected to return its status in(1,8) the same
       way, and put the filtered line it wants written to the source stream in(1,8)
       $_. The use of $_ accounts for the brevity of most Perl source filters.

       In order to make use of the rot13 filter(1,3x,3x curs_util) we need some way of encoding(3,n)
       the source file(1,n) in(1,8) rot13 format. The script below, "mkrot13", does just

           die "usage mkrot13 filename\n" unless @ARGV ;
           my $in(1,8) = $ARGV[0] ;
           my $out = "$in.tmp" ;
           open(2,3,n)(IN, "<$in(1,8)") or die "Cannot open(2,3,n) file(1,n) $in: $!\n";
           open(2,3,n)(OUT, ">$out") or die "Cannot open(2,3,n) file(1,n) $out: $!\n";

           print OUT "use Rot13;\n" ;
           while (<IN>) {
              tr/a-zA-Z/n-za-mN-ZA-M/ ;
              print OUT ;

           close(2,7,n) IN;
           close(2,7,n) OUT;
           unlink(1,2) $in(1,8);
           rename(1,2,n) $out, $in(1,8);

       If we encrypt this with "mkrot13":

           print " hello fred \n" ;

       the result will be this:

           use Rot13;
           cevag "uryyb serq\a" ;

       Running it produces this output:

           hello fred

       The rot13 example was a trivial example. Here's another demonstration
       that shows off a few more features.

       Say you wanted to include a lot of debugging code in(1,8) your Perl script
       during development, but you didn't want it available in(1,8) 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, "DEBUG". Debugging code is enabled if(3,n) the
       variable exists, otherwise it is disabled.

       Two special marker lines will bracket debugging code, like this:

           ## DEBUG_BEGIN
           if(3,n) ($year > 1999) {
              warn "Debug: millennium bug in(1,8) year $year\n" ;
           ## DEBUG_END

       When the "DEBUG" environment variable exists, the filter(1,3x,3x curs_util) ensures that
       Perl parses only the code between the "DEBUG_BEGIN" and "DEBUG_END"
       markers. That means that when "DEBUG" does exist, the code above should
       be passed through the filter(1,3x,3x curs_util) unchanged. The marker lines can also be
       passed through as-is, because the Perl parser will see them as comment
       lines. When "DEBUG" isn't set(7,n,1 builtins), 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:

           ## DEBUG_BEGIN
           #if(3,n) ($year > 1999) {
           #     warn "Debug: millennium bug in(1,8) year $year\n" ;
           ## DEBUG_END

       Here is the complete Debug filter:

           package Debug;

           use strict;
           use warnings;
           use Filter::Util::Call ;

           use constant TRUE => 1 ;
           use constant FALSE => 0 ;

           sub import {
              my ($type) = @_ ;
              my (%context) = (
                Enabled => defined $ENV{DEBUG},
                InTraceBlock => FALSE,
                Filename => (caller)[1],
                LineNo => 0,
                LastBegin => 0,
              ) ;
              filter_add(bless \%context) ;

           sub Die {
              my ($self) = shift ;
              my ($message) = shift ;
              my ($line_no) = shift || $self->{LastBegin} ;
              die "$message at $self->{Filename} line $line_no.\n"

           sub filter(1,3x,3x curs_util) {
              my ($self) = @_ ;
              my ($status) ;
              $status = filter_read() ;
              ++ $self->{LineNo} ;

              # deal with EOF/error(8,n) first
              if(3,n) ($status <= 0) {
                  $self->Die("DEBUG_BEGIN has no DEBUG_END")
                      if(3,n) $self->{InTraceBlock} ;
                  return $status ;

              if(3,n) ($self->{InTraceBlock}) {
                 if(3,n) (/^\s*##\s*DEBUG_BEGIN/ ) {
                     $self->Die("Nested DEBUG_BEGIN", $self->{LineNo})
                 } elsif (/^\s*##\s*DEBUG_END/) {
                     $self->{InTraceBlock} = FALSE ;

                 # comment out the debug lines when the filter(1,3x,3x curs_util) is disabled
                 s/^/#/ if(3,n) ! $self->{Enabled} ;
              } elsif ( /^\s*##\s*DEBUG_BEGIN/ ) {
                 $self->{InTraceBlock} = TRUE ;
                 $self->{LastBegin} = $self->{LineNo} ;
              } elsif ( /^\s*##\s*DEBUG_END/ ) {
                 $self->Die("DEBUG_END has no DEBUG_BEGIN", $self->{LineNo});
              return $status ;

           1 ;

       The big difference between this filter(1,3x,3x curs_util) and the previous example is the
       use of context data in(1,8) the filter(1,3x,3x curs_util) object. The filter(1,3x,3x curs_util) object is based on
       a hash reference, and is used to keep various pieces of context infor-
       mation between calls to the filter(1,3x,3x curs_util) function. All but two of the hash
       fields are used for error(8,n) reporting. The first of those two, Enabled,
       is used by the filter(1,3x,3x curs_util) to determine whether the debugging code should be
       given to the Perl parser. The second, InTraceBlock, is true when the
       filter(1,3x,3x curs_util) has encountered a "DEBUG_BEGIN" line, but has not yet encoun-
       tered the following "DEBUG_END" line.

       If you ignore all the error(8,n) checking that most of the code does, the
       essence of the filter(1,3x,3x curs_util) is as follows:

           sub filter(1,3x,3x curs_util) {
              my ($self) = @_ ;
              my ($status) ;
              $status = filter_read() ;

              # deal with EOF/error(8,n) first
              return $status if(3,n) $status <= 0 ;
              if(3,n) ($self->{InTraceBlock}) {
                 if(3,n) (/^\s*##\s*DEBUG_END/) {
                    $self->{InTraceBlock} = FALSE

                 # comment out debug lines when the filter(1,3x,3x curs_util) is disabled
                 s/^/#/ if(3,n) ! $self->{Enabled} ;
              } elsif ( /^\s*##\s*DEBUG_BEGIN/ ) {
                 $self->{InTraceBlock} = TRUE ;
              return $status ;

       Be warned: just as the C-preprocessor doesn't know C, the Debug filter(1,3x,3x curs_util)
       doesn't know Perl. It can be fooled quite easily:

           print <<EOM;

       Such things aside, you can see that a lot can be achieved with a modest
       amount of code.

       You now have better understanding of what a source filter(1,3x,3x curs_util) 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 fea-
       tures you could add to the Debug filter.

       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 "DEBUG" environment variable can then be used to control which
       blocks get included.

       Once you can identify individual blocks, try allowing them to be
       nested. That isn't difficult either.

       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 @_ array
       yourself. Write a source filter(1,3x,3x curs_util) that allows you to have a named(5,8) parame-
       ter list. Such a filter(1,3x,3x curs_util) would turn this:

           sub MySub ($first, $second, @rest) { ... }

       into this:

           sub MySub($$@) {
              my ($first) = shift ;
              my ($second) = shift ;
              my (@rest) = @_ ;

       Finally, if(3,n) you feel like a real challenge, have a go at writing a
       full-blown Perl macro preprocessor as a source filter. Borrow the use-
       ful features from the C preprocessor and any other macro processors you
       know. The tricky bit will be choosing how much knowledge of Perl's syn-
       tax you want your filter(1,3x,3x curs_util) to have.

       Some Filters Clobber the "DATA" Handle
            Some source filters use the "DATA" handle to read(2,n,1 builtins) the calling pro-
            gram.  When using these source filters you cannot rely on this
            handle, nor expect any particular kind of behavior when operating
            on it.  Filters based on Filter::Util::Call (and therefore Fil-
            ter::Simple) do not alter the "DATA" filehandle.

       The Source Filters distribution is available on CPAN, in(1,8)


       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

       Paul Marquess <>

       This article originally appeared in(1,8) The Perl Journal #11, and is copy-
       right 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.

perl v5.8.5                       2004-04-23                     PERLFILTER(1)

References for this manual (incoming links)