Welcome to Linux Knowledge Base and Tutorial
"The place where you learn linux"
Linux Magazine: The source for advanced Linux know-how

 Create an AccountHome | Submit News | Your Account  

Tutorial Menu
Linux Tutorial Home
Table of Contents

· Introduction to Operating Systems
· Linux Basics
· Working with the System
· Shells and Utilities
· Editing Files
· Basic Administration
· The Operating System
· The X Windowing System
· The Computer Itself
· Networking
· System Monitoring
· Solving Problems
· Security
· Installing and Upgrading
· Linux and Windows

Man Pages
Linux Topics
Test Your Knowledge

Site Menu
Site Map
Copyright Info
Terms of Use
Privacy Info
Masthead / Impressum
Your Account

Private Messages

News Archive
Submit News
User Articles
Web Links


The Web

Who's Online
There are currently, 55 guest(s) and 0 member(s) that are online.

You are an Anonymous user. You can register for free by clicking here




       This article is about a little-known feature of Perl
       called source filters. Source filters alter the program
       text of a module before Perl sees it, much as a C prepro­
       cessor 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

       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.


       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 "use" or "require" statement, then each of those
       scripts will have to be read from their respective files
       as well.

       Now think of each logical connection between the Perl
       parser and an individual file as a source stream. 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 "require" or "use" state­
       ment in a source stream, a new and distinct stream is cre­
       ated just for that file.

       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 nor­
       mally operates.

           file -------> parser

       There are two important points to remember:

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

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

       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:

           file ----> filter ----> parser

       If that doesn't make much sense, consider the analogy of a
       Perl's parser:

            compressed           gunzip
           Perl program ---> source filter ---> parser


       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 mod­
       ule. Like all Perl modules, a source filter is invoked
       with a use statement.

       Say you want to pass your Perl source through the C pre­
       processor 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 preproces­
       sor filter module called Filter::cpp. Let's use that

       Below is an example program, "cpp_test", which makes use
       of this filter.  Line numbers have been added to allow
       specific lines to be referenced 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, the source stream looks like this:

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

       Line 1, "use Filter::cpp", includes and installs the "cpp"
       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 fil­
       ter to the source stream behind the scenes. Now the data
       flow looks like this:

           cpp_test ----> cpp filter ----> parser

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

                         .-> cpp --.
                         |         |
                         |         |

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

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

           cpp_test ---> cpp filter ---> parser (INACTIVE)

           Fred.pm ----> parser

       As you can see, a new stream has been created for reading
       the source from "Fred.pm". This stream will remain active
       until all of "Fred.pm" has been parsed. The source stream
       for "cpp_test" 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 "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 on a single file.
       Similarly, you can reuse the same filter in as many files
       as you like.

       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:

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

       Once the first line has been processed, the flow will look
       like this:

           file ---> uudecode ---> uncompress ---> parser
                      filter         filter

       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 uude­
       coded before it's uncompressed.


       There are three ways to write your own source filter. You
       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 "decrypt"
       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,

       Decryption Filters
            All decryption filters work on the principle of
            "security through obscurity." 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, frag­
            ments 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.

            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
            decrypt.pm in the source filters module.


       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 what­
       ever processing is necessary, and writes the filtered data
       to standard output. "Filter:cpp" is an example of a source
       filter implemented as a separate executable - the exe­
       cutable is the C preprocessor bundled with your C com­

       The source filter distribution includes two modules that
       simplify this task: "Filter::exec" and "Filter::sh". 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. "Advanced Programming in the UNIX Environ­
       ment."  Addison-Wesley, ISBN 0-210-56317-7, pages
       441-445.) The difference between them is that "Fil­
       ter::exec" spawns the external command directly, while
       "Filter::sh" spawns a shell to execute the external com­

       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 sepa­
       rate subprocess will be created to run the Unix "tr" com­
       mand. 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 creat­
       ing source filters.


       The easiest and most portable option available for creat­
       ing your own source filter is to write it completely in
       Perl. To distinguish this from the previous two tech­
       niques, I'll call it a Perl source filter.

       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 con­
       tents 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 {
             my ($self) = @_ ;
             my ($status) ;

                if ($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 number of functions into your filter's names­
       pace. The filter shown above uses two of these functions,
       "filter_add()" and "filter_read()".

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

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

       If a line was available from the source stream, "fil­
       ter_read()" returns a status value greater than zero and
       appends the line to $_.  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 $_. The use of $_ accounts for the
       brevity of most Perl source filters.

       In order to make use of the rot13 filter we need some way
       of encoding the source file in rot13 format. The script
       below, "mkrot13", does just that.

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

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

           close IN;
           close OUT;
           unlink $in;
           rename $out, $in;

       If we encrypt this with "mkrot13":

           print " hello fred \n" ;

       the result will be this:

       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 the variable exists, otherwise it is disabled.

       Two special marker lines will bracket debugging code, like

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

       When the "DEBUG" environment variable exists, the filter
       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 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, 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

           ## DEBUG_BEGIN
           #if ($year > 1999) {
           #     warn "Debug: millennium bug in 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 filter {
              my ($self) = @_ ;
              my ($status) ;
              $status = filter_read() ;
              ++ $self->{LineNo} ;

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

              if ($self->{InTraceBlock}) {
                 if (/^\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 is disabled
                 s/^/#/ if ! $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 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 encoun­
       tered a "DEBUG_BEGIN" line, but has not yet encountered
       the following "DEBUG_END" line.

       If you ignore all the error checking that most of the code
       does, the essence of the filter is as follows:

           sub filter {
              my ($self) = @_ ;
              my ($status) ;
              $status = filter_read() ;


       Be warned: just as the C-preprocessor doesn't know C, the
       Debug filter doesn't know Perl. It can be fooled quite

           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
       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.

       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 that allows you to have a named parameter
       list. Such a filter would turn this:

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

       into this:

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

       Finally, if you feel like a real challenge, have a go at
       writing a full-blown Perl macro preprocessor as a source


       The Source Filters distribution is available on CPAN, in


       Starting from Perl 5.8 Filter::Util::Call (the core part
       of the Source Filters distribution) is part of the stan­
       dard Perl distribution.  Also included is a friendlier
       interface called Filter::Simple, by Damian Conway.


       Paul Marquess <Paul.Marquess@btinternet.com>


       This article originally appeared in The Perl Journal #11,
       and is copyright 1998 The Perl Journal. It appears cour­
       tesy of Jon Orwant and The Perl Journal.  This document
       may be distributed under the same terms as Perl itself.

perl v5.8.1                 2003-09-02              PERLFILTER(1)

An undefined database error occurred. SELECT distinct pages.pagepath,pages.pageid FROM pages, page2command WHERE pages.pageid = page2command.pageid AND commandid =

Show your Support for the Linux Tutorial

Purchase one of the products from our new online shop. For each product you purchase, the Linux Tutorial gets a portion of the proceeds to help keep us going.



Security Code
Security Code
Type Security Code

Don't have an account yet? You can create one. As a registered user you have some advantages like theme manager, comments configuration and post comments with your name.

Help if you can!

Amazon Wish List

Did You Know?
You can choose larger fonts by selecting a different themes.


Tell a Friend About Us

Bookmark and Share

Web site powered by PHP-Nuke

Is this information useful? At the very least you can help by spreading the word to your favorite newsgroups, mailing lists and forums.
All logos and trademarks in this site are property of their respective owner. The comments are property of their posters. Articles are the property of their respective owners. Unless otherwise stated in the body of the article, article content (C) 1994-2013 by James Mohr. All rights reserved. The stylized page/paper, as well as the terms "The Linux Tutorial", "The Linux Server Tutorial", "The Linux Knowledge Base and Tutorial" and "The place where you learn Linux" are service marks of James Mohr. All rights reserved.
The Linux Knowledge Base and Tutorial may contain links to sites on the Internet, which are owned and operated by third parties. The Linux Tutorial is not responsible for the content of any such third-party site. By viewing/utilizing this web site, you have agreed to our disclaimer, terms of use and privacy policy. Use of automated download software ("harvesters") such as wget, httrack, etc. causes the site to quickly exceed its bandwidth limitation and are therefore expressly prohibited. For more details on this, take a look here

PHP-Nuke Copyright © 2004 by Francisco Burzi. This is free software, and you may redistribute it under the GPL. PHP-Nuke comes with absolutely no warranty, for details, see the license.
Page Generation: 0.09 Seconds