PERLFILTER(1perl)

๐Ÿ“ฆ
version 5.44.0 ยท 2 versions
, in arch rolling

๐ŸŒธ PERLFILTER ๐ŸŒธ

okay bestie, welcome to perlfilter(1perl) from the Perl Programmers Reference Guide ๐Ÿ’– this is the whole tea on source filters, and honestly? it's giving niche-but-iconic. this is part 1 of 3, so buckle up โ€” more is coming, don't go anywhere.


โœจ NAME โœจ

perlfilter โ€” Source Filters ๐Ÿฆ‹


๐ŸŒˆ DESCRIPTION ๐ŸŒˆ

okay so this whole article is about a lowkey underrated feature of Perl called source filters. a source filter messes with the program text of a module before Perl even sees it โ€” think of it like how a C preprocessor edits a C program's source text before the compiler ever lays eyes on it. same energy, different language ๐Ÿ’… this piece walks you through what source filters actually are, how they work their magic, and how you can write your own.

the original glow-up reason for source filters was so you could encrypt your program source and stop nosy people from casually reading it. that's not all they can do though โ€” you'll find out soon enough. but first: the basics โœจ


๐Ÿง  CONCEPTS ๐Ÿง 

before the Perl interpreter can run a Perl script, it has to read it from a file into memory so it can parse and compile it. and if that script itself pulls in other scripts with a use or require statement, well โ€” each of those scripts has to be read from their own files too. no skipping, bestie.

now, think of every logical connection between the Perl parser and an individual file as a source stream. a source stream gets created when the Perl parser opens a file, it keeps existing while the source code is being read into memory, and it gets destroyed when Perl is done parsing that file. and if the parser bumps into a require or use statement inside a source stream? a brand new, distinct stream gets created just for that file. main character energy, honestly ๐Ÿ‘‘

the diagram below is one single source stream โ€” source flowing from a Perl script file on the left into the Perl parser on the right. this is how Perl normally operates:

    file -------> parser

two things you must remember, no cap:

  1. even though there can be any number of source streams alive at any given time, only one of them is active.
  2. every source stream is tied to exactly one file.

a source filter is a special kind of Perl module that intercepts and modifies a source stream before it reaches the parser. so our diagram gets a glow-up like this:

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

if that's not clicking, consider the analogy of a command pipeline. say you've got a shell script stored in the compressed file trial.gz. this simple pipeline runs the script without needing to make a temporary file to hold the uncompressed version:

    gunzip -c trial.gz | sh

in that case, the data flow from the pipeline looks like this:

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

and with source filters, you can store your script's text all compressed and use a source filter to uncompress it for Perl's parser:

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

๐Ÿ’– USING FILTERS ๐Ÿ’–

so how do you actually use a source filter in a Perl script? like I said up top, a source filter is just a special kind of module. and like all Perl modules, a source filter gets invoked with a use statement. periodt.

say you want to send your Perl source through the C preprocessor before execution. slay, because the source filters distribution ships with a C preprocessor filter module called Filter::cpp ๐ŸŽ€

here's an example program, cpp_test, that uses this filter. line numbers were added so you can reference specific lines easily:

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

when you run this script, Perl creates a source stream for the file. before the parser processes any of the lines from that 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 gets 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:

    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 just passes each line through the real C preprocessor. the output from the C preprocessor then gets inserted back into the source stream by the filter, like:

                 .-> cpp --.
                 |         |
                 |         |
                 |       <-'
  cpp_test ----> cpp filter ----> parser

and then the parser sees this code:

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

now let's think about 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 does not apply to the text of the Fred module โ€” only to the text of the file that used it (cpp_test). even though the use statement on line 3 passes through the cpp filter, the module that gets included (Fred) does not. so after line 3 has been parsed and before line 4 is parsed, the source streams look like this:

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

    Fred.pm ----> parser

see? a new stream got created to read the source from Fred.pm. this stream stays active until all of Fred.pm has been parsed. the source stream for cpp_test still exists, but it's inactive. once the parser finishes reading Fred.pm, the source stream tied to it gets destroyed. then the source stream for cpp_test becomes active again and the parser reads line 4 and everything after it from cpp_test ๐ŸŒŸ

and yes, you can stack more than one source filter on a single file. and similarly, you can reuse the same filter in as many files as you want. obsessed.

for example, if you've got a uuencoded and compressed source file, you can stack a uudecode filter and an uncompression filter like this:

    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=_[>
    ...

once that first line has been processed, the flow looks 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 showed up before the uncompress filter, so the source file gets uudecoded before it gets uncompressed. order matters, bestie ๐Ÿ’…


๐Ÿ› ๏ธ WRITING A SOURCE FILTER ๐Ÿ› ๏ธ

there are three ways to write your own source filter:

  • write it in C
  • use an external program as a filter
  • write the filter in Perl ๐Ÿ’–

I'm not gonna go super deep on the first two, so let's knock those out first. writing the filter in Perl is the most convenient, so that's the one getting the most space. as it should. ๐Ÿ‘‘


๐Ÿงš WRITING A SOURCE FILTER IN C ๐Ÿงš

technique number one of three: write the whole filter in C. the external module you create interfaces directly with the source filter hooks that Perl provides.

the advantage here is that you get complete control over how your filter is implemented. the big disadvantage? the complexity goes way up โ€” you don't just need to understand the source filter hooks, you also need a reasonable knowledge of Perl guts. one of the few times it's genuinely worth the trouble is when you're 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, below.

๐Ÿ’€ Decryption Filters ๐Ÿ’€

all decryption filters run on the principle of "security through obscurity." no matter how beautifully you write a decryption filter and how strong your encryption algorithm is, anyone determined enough can retrieve the original source code. the reason is actually pretty simple:

to execute your program, Perl must parse its source code. which means Perl must have all the information needed to decrypt your program โ€” and that means that same information is also available to literally anyone able to run the program. ๐Ÿ˜ญ

that said, there are a number of steps you can take to make life difficult for a potential reader. the most important one: write your decryption filter in C and statically link the decryption module into the Perl binary. for further tips on making life difficult for a potential reader, see the file decrypt.pm in the source filters distribution.


๐Ÿ“ CREATING A SOURCE FILTER AS A SEPARATE EXECUTABLE ๐Ÿ“

an alternative to writing the filter in C is to create a separate executable in whatever language you like. 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 implemented as a separate executable โ€” its executable is the C preprocessor bundled with your C compiler.

the source filter distribution includes two modules that make this task way easier: Filter::exec and Filter::sh. both let you 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 Environment." Addison-Wesley, ISBN 0-210-56317-7, pages 441-445.) the difference between the two 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 lets you make use of shell metacharacters and redirection facilities โœจ

here's an example script that uses Filter::sh:

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

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

    PQR a = 1

writing a source filter as a separate executable works fine, but there's a small performance penalty. for example, if you run that little example above, a separate subprocess gets created to run the Unix tr command. each use of the filter needs its own subprocess. so if creating subprocesses is expensive on your system, you might wanna consider one of the other options for creating source filters ๐Ÿซถ


๐Ÿ’– WRITING A SOURCE FILTER IN PERL ๐Ÿ’–

Okay so bestie, 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. ๐Ÿ’…

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.) โœจ

package Rot13;

use Filter::Util::Call;

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

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

   tr/n-za-mN-ZA-M/a-zA-Z/
      if ($status = filter_read()) > 0;
   $status;
}

1;

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 namespace. The filter shown above uses two of these functions, filter_add() and filter_read(). ๐Ÿ”ฅ

Next, we create the filter 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 a module is included with a use statement. This makes "import" the ideal place to both create and install a filter object. ๐Ÿ‘‘

In the example filter, 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 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 filtering. For this type of Perl source filter, all the filtering 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, filter_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:

use Rot13;
cevag "uryyb serq\a";

Running it produces this output:

hello fred

๐Ÿฆ‹ USING CONTEXT: THE DEBUG FILTER ๐Ÿฆ‹

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 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, "DEBUG". Debugging code is enabled if the variable exists, otherwise it is disabled. ๐Ÿ’…

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

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

The filter ensures that Perl parses the code between the <DEBUG_BEGIN> and "DEBUG_END" markers only when the "DEBUG" environment variable exists. 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 comments:

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

Here is the complete Debug filter:

package Debug;

use v5.36;
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 {
   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 encountered 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();

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

      # comment out debug lines when the filter is disabled
      s/^/#/ if ! $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 doesn't know Perl. It can be fooled quite easily:

print <<EOM;
##DEBUG_BEGIN
EOM

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


๐ŸŒˆ 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. โœจ

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 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. ๐Ÿ’…

๐Ÿ’€ LIMITATIONS

okay bestie, sit down, because this is the part where we're real with each other. ๐Ÿซถ

Source filters only work on the string level, which means they're highly limited in their ability to change source code on the fly. They cannot detect comments, quoted strings, heredocs โ€” nope, none of it. A source filter is no replacement for a real parser, periodt.

The only stable usage for source filters are encryption, compression, or the byteloader, to translate binary code back to source code. That's the vibe. Everything else is giving chaos. โœจ


See for example the limitations in Switch, which uses source filters, and thus it does not work inside a string eval. Also the presence of regexes with embedded newlines that are specified with raw /.../ delimiters and don't have a modifier //x are indistinguishable from code chunks beginning with the division operator /. ๐Ÿ˜ญ As a workaround you must use m/.../ or m?...? for such patterns. Also, the presence of regexes specified with raw ?...? delimiters may cause mysterious errors. The workaround is to use m?...? instead. See <https://metacpan.org/pod/Switch#LIMITATIONS>.

ngl "mysterious errors" is the most ominous phrasing ever and it is so real. use the workarounds. ๐Ÿ™ˆ

Currently the content of the __DATA__ block is not filtered.

Currently internal buffer lengths are limited to 32-bit only.


๐Ÿ‘€ THINGS TO LOOK OUT FOR

๐Ÿšจ Some Filters Clobber the DATA Handle

Some source filters use the DATA handle to read the calling program. So when you're using these source filters, bestie, you cannot rely on this handle, nor expect any particular kind of behavior when operating on it. It's giving unpredictable. ๐Ÿ’…

Filters based on Filter::Util::Call (and therefore Filter::Simple) do not alter the DATA filehandle, but on the other hand they totally ignore the text after __DATA__.

so like... pick your struggle. clobbered handle or ignored text. neither is iconic but that's the deal. ๐Ÿ˜ฎโ€๐Ÿ’จ

๐Ÿ“ฆ REQUIREMENTS

The Source Filters distribution is available on CPAN, in

CPAN/modules/by-module/Filter

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. We love a friendly interface. ๐Ÿซถ


๐Ÿ‘‘ AUTHOR

Paul Marquess <Paul.Marquess@btinternet.com>

Reini Urban <rurban@cpan.org>

๐ŸŒธ Copyrights

The first version of 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.


okay that's genuinely the whole page, we did it, we ate and left no crumbs. ๐Ÿ“โœจ this was perl v5.44.0, dated 2026-10-17 โ€” PERLFILTER(1perl), love her, read her, use her responsibly. bye bestie ๐Ÿ’–๐Ÿฆ‹

๐Ÿ“ฆ where this page comes from
  • arch rolling: perl 5.44.0-1 ยท Artistic-1.0-Perl AND GPL-1.0-or-later
  • ๐Ÿ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms