Search code examples
perlsource-filter

Why are Perl source filters bad and when is it OK to use them?


It is "common knowledge" that source filters are bad and should not be used in production code.

When answering a a similar, but more specific question I couldn't find any good references that explain clearly why filters are bad and when they can be safely used. I think now is time to create one.

  1. Why are source filters bad?
  2. When is it OK to use a source filter?

Solution

  • Only perl can parse Perl (see this example):

    @result = (dothis $foo, $bar);
    
    # Which of the following is it equivalent to?
    @result = (dothis($foo), $bar);
    @result = dothis($foo, $bar);
    

    This kind of ambiguity makes it very hard to write source filters that always succeed and do the right thing. When things go wrong, debugging is awkward.

    After crashing and burning a few times, I have developed the superstitious approach of never trying to write another source filter.

    I do occasionally use Smart::Comments for debugging, though. When I do, I load the module on the command line:

    $ perl -MSmart::Comments test.pl
    

    so as to avoid any chance that it might remain enabled in production code.

    See also: Perl Cannot Be Parsed: A Formal Proof