Debian Codegraph @

upstream/opensuse-tumbleweed/man1/perlfilter.1

raw
1 .\" -*- mode: troff; coding: utf-8 -*-
2 .\" Automatically generated by Pod::Man v6.0.2 (Pod::Simple 3.45)
3 .\"
4 .\" Standard preamble:
5 .\" ========================================================================
6 .de Sp \" Vertical space (when we can't use .PP)
7 .if t .sp .5v
8 .if n .sp
9 ..
10 .de Vb \" Begin verbatim text
11 .ft CW
12 .nf
13 .ne \\$1
14 ..
15 .de Ve \" End verbatim text
16 .ft R
17 .fi
18 ..
19 .\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>.
20 .ie n \{\
21 . ds C` ""
22 . ds C' ""
23 'br\}
24 .el\{\
25 . ds C`
26 . ds C'
27 'br\}
28 .\"
29 .\" Escape single quotes in literal strings from groff's Unicode transform.
30 .ie \n(.g .ds Aq \(aq
31 .el .ds Aq '
32 .\"
33 .\" If the F register is >0, we'll generate index entries on stderr for
34 .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
35 .\" entries marked with X<> in POD. Of course, you'll have to process the
36 .\" output yourself in some meaningful fashion.
37 .\"
38 .\" Avoid warning from groff about undefined register 'F'.
39 .de IX
40 ..
41 .nr rF 0
42 .if \n(.g .if rF .nr rF 1
43 .if (\n(rF:(\n(.g==0)) \{\
44 . if \nF \{\
45 . de IX
46 . tm Index:\\$1\t\\n%\t"\\$2"
47 ..
48 . if !\nF==2 \{\
49 . nr % 0
50 . nr F 2
51 . \}
52 . \}
53 .\}
54 .rr rF
55 .\"
56 .\" Required to disable full justification in groff 1.23.0.
57 .if n .ds AD l
58 .\" ========================================================================
59 .\"
60 .IX Title "PERLFILTER 1"
61 .TH PERLFILTER 1 2026-03-09 "perl v5.42.1" "Perl Programmers Reference Guide"
62 .\" For nroff, turn off justification. Always turn off hyphenation; it makes
63 .\" way too many mistakes in technical documents.
64 .if n .ad l
65 .nh
66 .SH NAME
67 perlfilter \- Source Filters
68 .SH DESCRIPTION
69 .IX Header "DESCRIPTION"
70 This article is about a little\-known feature of Perl called
71 \&\fIsource filters\fR. Source filters alter the program text of a module
72 before Perl sees it, much as a C preprocessor alters the source text of
73 a C program before the compiler sees it. This article tells you more
74 about what source filters are, how they work, and how to write your
75 own.
76 .PP
77 The original purpose of source filters was to let you encrypt your
78 program source to prevent casual reading. This isn\*(Aqt all they can do, as
79 you\*(Aqll soon learn. But first, the basics.
80 .SH CONCEPTS
81 .IX Header "CONCEPTS"
82 Before the Perl interpreter can execute a Perl script, it must first
83 read it from a file into memory for parsing and compilation. If that
84 script itself includes other scripts with a \f(CW\*(C`use\*(C'\fR or \f(CW\*(C`require\*(C'\fR
85 statement, then each of those scripts will have to be read from their
86 respective files as well.
87 .PP
88 Now think of each logical connection between the Perl parser and an
89 individual file as a \fIsource stream\fR. A source stream is created when
90 the Perl parser opens a file, it continues to exist as the source code
91 is read into memory, and it is destroyed when Perl is finished parsing
92 the file. If the parser encounters a \f(CW\*(C`require\*(C'\fR or \f(CW\*(C`use\*(C'\fR statement in
93 a source stream, a new and distinct stream is created just for that
94 file.
95 .PP
96 The diagram below represents a single source stream, with the flow of
97 source from a Perl script file on the left into the Perl parser on the
98 right. This is how Perl normally operates.
99 .PP
100 .Vb 1
101 \& file \-\-\-\-\-\-\-> parser
102 .Ve
103 .PP
104 There are two important points to remember:
105 .IP 1. 5
106 Although there can be any number of source streams in existence at any
107 given time, only one will be active.
108 .IP 2. 5
109 Every source stream is associated with only one file.
110 .PP
111 A source filter is a special kind of Perl module that intercepts and
112 modifies a source stream before it reaches the parser. A source filter
113 changes our diagram like this:
114 .PP
115 .Vb 1
116 \& file \-\-\-\-> filter \-\-\-\-> parser
117 .Ve
118 .PP
119 If that doesn\*(Aqt make much sense, consider the analogy of a command
120 pipeline. Say you have a shell script stored in the compressed file
121 \&\fItrial.gz\fR. The simple pipeline command below runs the script without
122 needing to create a temporary file to hold the uncompressed file.
123 .PP
124 .Vb 1
125 \& gunzip \-c trial.gz | sh
126 .Ve
127 .PP
128 In this case, the data flow from the pipeline can be represented as follows:
129 .PP
130 .Vb 1
131 \& trial.gz \-\-\-\-> gunzip \-\-\-\-> sh
132 .Ve
133 .PP
134 With source filters, you can store the text of your script compressed and use a source filter to uncompress it for Perl\*(Aqs parser:
135 .PP
136 .Vb 2
137 \& compressed gunzip
138 \& Perl program \-\-\-> source filter \-\-\-> parser
139 .Ve
140 .SH "USING FILTERS"
141 .IX Header "USING FILTERS"
142 So how do you use a source filter in a Perl script? Above, I said that
143 a source filter is just a special kind of module. Like all Perl
144 modules, a source filter is invoked with a use statement.
145 .PP
146 Say you want to pass your Perl source through the C preprocessor before
147 execution. As it happens, the source filters distribution comes with a C
148 preprocessor filter module called Filter::cpp.
149 .PP
150 Below is an example program, \f(CW\*(C`cpp_test\*(C'\fR, which makes use of this filter.
151 Line numbers have been added to allow specific lines to be referenced
152 easily.
153 .PP
154 .Vb 4
155 \& 1: use Filter::cpp;
156 \& 2: #define TRUE 1
157 \& 3: $a = TRUE;
158 \& 4: print "a = $a\en";
159 .Ve
160 .PP
161 When you execute this script, Perl creates a source stream for the
162 file. Before the parser processes any of the lines from the file, the
163 source stream looks like this:
164 .PP
165 .Vb 1
166 \& cpp_test \-\-\-\-\-\-\-\-\-> parser
167 .Ve
168 .PP
169 Line 1, \f(CW\*(C`use Filter::cpp\*(C'\fR, includes and installs the \f(CW\*(C`cpp\*(C'\fR filter
170 module. All source filters work this way. The use statement is compiled
171 and executed at compile time, before any more of the file is read, and
172 it attaches the cpp filter to the source stream behind the scenes. Now
173 the data flow looks like this:
174 .PP
175 .Vb 1
176 \& cpp_test \-\-\-\-> cpp filter \-\-\-\-> parser
177 .Ve
178 .PP
179 As the parser reads the second and subsequent lines from the source
180 stream, it feeds those lines through the \f(CW\*(C`cpp\*(C'\fR source filter before
181 processing them. The \f(CW\*(C`cpp\*(C'\fR filter simply passes each line through the
182 real C preprocessor. The output from the C preprocessor is then
183 inserted back into the source stream by the filter.
184 .PP
185 .Vb 5
186 \& .\-> cpp \-\-.
187 \& | |
188 \& | |
189 \& | <\-\*(Aq
190 \& cpp_test \-\-\-\-> cpp filter \-\-\-\-> parser
191 .Ve
192 .PP
193 The parser then sees the following code:
194 .PP
195 .Vb 3
196 \& use Filter::cpp;
197 \& $a = 1;
198 \& print "a = $a\en";
199 .Ve
200 .PP
201 Let\*(Aqs consider what happens when the filtered code includes another
202 module with use:
203 .PP
204 .Vb 5
205 \& 1: use Filter::cpp;
206 \& 2: #define TRUE 1
207 \& 3: use Fred;
208 \& 4: $a = TRUE;
209 \& 5: print "a = $a\en";
210 .Ve
211 .PP
212 The \f(CW\*(C`cpp\*(C'\fR filter does not apply to the text of the Fred module, only
213 to the text of the file that used it (\f(CW\*(C`cpp_test\*(C'\fR). Although the use
214 statement on line 3 will pass through the cpp filter, the module that
215 gets included (\f(CW\*(C`Fred\*(C'\fR) will not. The source streams look like this
216 after line 3 has been parsed and before line 4 is parsed:
217 .PP
218 .Vb 1
219 \& cpp_test \-\-\-> cpp filter \-\-\-> parser (INACTIVE)
220 \&
221 \& Fred.pm \-\-\-\-> parser
222 .Ve
223 .PP
224 As you can see, a new stream has been created for reading the source
225 from \f(CW\*(C`Fred.pm\*(C'\fR. This stream will remain active until all of \f(CW\*(C`Fred.pm\*(C'\fR
226 has been parsed. The source stream for \f(CW\*(C`cpp_test\*(C'\fR will still exist,
227 but is inactive. Once the parser has finished reading Fred.pm, the
228 source stream associated with it will be destroyed. The source stream
229 for \f(CW\*(C`cpp_test\*(C'\fR then becomes active again and the parser reads line 4
230 and subsequent lines from \f(CW\*(C`cpp_test\*(C'\fR.
231 .PP
232 You can use more than one source filter on a single file. Similarly,
233 you can reuse the same filter in as many files as you like.
234 .PP
235 For example, if you have a uuencoded and compressed source file, it is
236 possible to stack a uudecode filter and an uncompression filter like
237 this:
238 .PP
239 .Vb 4
240 \& use Filter::uudecode; use Filter::uncompress;
241 \& M\*(AqXL(".H<US4\*(Aq\*(AqV9I;F%L\*(Aq)Q;>7/;1I;_>_I3=&E=%:F*I"T?22Q/
242 \& M6]9*<IQCO*XFT"0[PL%%\*(AqY+IG?WN^ZYN\-$\*(AqJ.[.JE$,20/?K=_[>
243 \& ...
244 .Ve
245 .PP
246 Once the first line has been processed, the flow will look like this:
247 .PP
248 .Vb 2
249 \& file \-\-\-> uudecode \-\-\-> uncompress \-\-\-> parser
250 \& filter filter
251 .Ve
252 .PP
253 Data flows through filters in the same order they appear in the source
254 file. The uudecode filter appeared before the uncompress filter, so the
255 source file will be uudecoded before it\*(Aqs uncompressed.
256 .SH "WRITING A SOURCE FILTER"
257 .IX Header "WRITING A SOURCE FILTER"
258 There are three ways to write your own source filter. You can write it
259 in C, use an external program as a filter, or write the filter in Perl.
260 I won\*(Aqt cover the first two in any great detail, so I\*(Aqll get them out
261 of the way first. Writing the filter in Perl is most convenient, so
262 I\*(Aqll devote the most space to it.
263 .SH "WRITING A SOURCE FILTER IN C"
264 .IX Header "WRITING A SOURCE FILTER IN C"
265 The first of the three available techniques is to write the filter
266 completely in C. The external module you create interfaces directly
267 with the source filter hooks provided by Perl.
268 .PP
269 The advantage of this technique is that you have complete control over
270 the implementation of your filter. The big disadvantage is the
271 increased complexity required to write the filter \- not only do you
272 need to understand the source filter hooks, but you also need a
273 reasonable knowledge of Perl guts. One of the few times it is worth
274 going to this trouble is when writing a source scrambler. The
275 \&\f(CW\*(C`decrypt\*(C'\fR filter (which unscrambles the source before Perl parses it)
276 included with the source filter distribution is an example of a C
277 source filter (see Decryption Filters, below).
278 .IP "\fBDecryption Filters\fR" 5
279 .IX Item "Decryption Filters"
280 All decryption filters work on the principle of "security through
281 obscurity." Regardless of how well you write a decryption filter and
282 how strong your encryption algorithm is, anyone determined enough can
283 retrieve the original source code. The reason is quite simple:
284 in order to execute your program Perl must parse its source code.
285 This means that Perl must have all the information needed to decrypt
286 your program, and that means that that information is also available to
287 anyone able to run the program.
288 .Sp
289 That said, there are a number of steps that can be taken to make life
290 difficult for the potential reader. The most important: Write your
291 decryption filter in C and statically link the decryption module into
292 the Perl binary. For further tips to make life difficult for the
293 potential reader, see the file \fIdecrypt.pm\fR in the source filters
294 distribution.
295 .SH "CREATING A SOURCE FILTER AS A SEPARATE EXECUTABLE"
296 .IX Header "CREATING A SOURCE FILTER AS A SEPARATE EXECUTABLE"
297 An alternative to writing the filter in C is to create a separate
298 executable in the language of your choice. The separate executable
299 reads from standard input, does whatever processing is necessary, and
300 writes the filtered data to standard output. \f(CW\*(C`Filter::cpp\*(C'\fR is an
301 example of a source filter implemented as a separate executable \- the
302 executable is the C preprocessor bundled with your C compiler.
303 .PP
304 The source filter distribution includes two modules that simplify this
305 task: \f(CW\*(C`Filter::exec\*(C'\fR and \f(CW\*(C`Filter::sh\*(C'\fR. Both allow you to run any
306 external executable. Both use a coprocess to control the flow of data
307 into and out of the external executable. (For details on coprocesses,
308 see Stephens, W.R., "Advanced Programming in the UNIX Environment."
309 Addison\-Wesley, ISBN 0\-210\-56317\-7, pages 441\-445.) The difference
310 between them is that \f(CW\*(C`Filter::exec\*(C'\fR spawns the external command
311 directly, while \f(CW\*(C`Filter::sh\*(C'\fR spawns a shell to execute the external
312 command. (Unix uses the Bourne shell; NT uses the cmd shell.) Spawning
313 a shell allows you to make use of the shell metacharacters and
314 redirection facilities.
315 .PP
316 Here is an example script that uses \f(CW\*(C`Filter::sh\*(C'\fR:
317 .PP
318 .Vb 3
319 \& use Filter::sh \*(Aqtr XYZ PQR\*(Aq;
320 \& $a = 1;
321 \& print "XYZ a = $a\en";
322 .Ve
323 .PP
324 The output you\*(Aqll get when the script is executed:
325 .PP
326 .Vb 1
327 \& PQR a = 1
328 .Ve
329 .PP
330 Writing a source filter as a separate executable works fine, but a
331 small performance penalty is incurred. For example, if you execute the
332 small example above, a separate subprocess will be created to run the
333 Unix \f(CW\*(C`tr\*(C'\fR command. Each use of the filter requires its own subprocess.
334 If creating subprocesses is expensive on your system, you might want to
335 consider one of the other options for creating source filters.
336 .SH "WRITING A SOURCE FILTER IN PERL"
337 .IX Header "WRITING A SOURCE FILTER IN PERL"
338 The easiest and most portable option available for creating your own
339 source filter is to write it completely in Perl. To distinguish this
340 from the previous two techniques, I\*(Aqll call it a Perl source filter.
341 .PP
342 To help understand how to write a Perl source filter we need an example
343 to study. Here is a complete source filter that performs rot13
344 decoding. (Rot13 is a very simple encryption scheme used in Usenet
345 postings to hide the contents of offensive posts. It moves every letter
346 forward thirteen places, so that A becomes N, B becomes O, and Z
347 becomes M.)
348 .PP
349 .Vb 1
350 \& package Rot13;
351 \&
352 \& use Filter::Util::Call;
353 \&
354 \& sub import {
355 \& my ($type) = @_;
356 \& my ($ref) = [];
357 \& filter_add(bless $ref);
358 \& }
359 \&
360 \& sub filter {
361 \& my ($self) = @_;
362 \& my ($status);
363 \&
364 \& tr/n\-za\-mN\-ZA\-M/a\-zA\-Z/
365 \& if ($status = filter_read()) > 0;
366 \& $status;
367 \& }
368 \&
369 \& 1;
370 .Ve
371 .PP
372 All Perl source filters are implemented as Perl classes and have the
373 same basic structure as the example above.
374 .PP
375 First, we include the \f(CW\*(C`Filter::Util::Call\*(C'\fR module, which exports a
376 number of functions into your filter\*(Aqs namespace. The filter shown
377 above uses two of these functions, \f(CWfilter_add()\fR and
378 \&\f(CWfilter_read()\fR.
379 .PP
380 Next, we create the filter object and associate it with the source
381 stream by defining the \f(CW\*(C`import\*(C'\fR function. If you know Perl well
382 enough, you know that \f(CW\*(C`import\*(C'\fR is called automatically every time a
383 module is included with a use statement. This makes \f(CW\*(C`import\*(C'\fR the ideal
384 place to both create and install a filter object.
385 .PP
386 In the example filter, the object (\f(CW$ref\fR) is blessed just like any
387 other Perl object. Our example uses an anonymous array, but this isn\*(Aqt
388 a requirement. Because this example doesn\*(Aqt need to store any context
389 information, we could have used a scalar or hash reference just as
390 well. The next section demonstrates context data.
391 .PP
392 The association between the filter object and the source stream is made
393 with the \f(CWfilter_add()\fR function. This takes a filter object as a
394 parameter (\f(CW$ref\fR in this case) and installs it in the source stream.
395 .PP
396 Finally, there is the code that actually does the filtering. For this
397 type of Perl source filter, all the filtering is done in a method
398 called \f(CWfilter()\fR. (It is also possible to write a Perl source filter
399 using a closure. See the \f(CW\*(C`Filter::Util::Call\*(C'\fR manual page for more
400 details.) It\*(Aqs called every time the Perl parser needs another line of
401 source to process. The \f(CWfilter()\fR method, in turn, reads lines from
402 the source stream using the \f(CWfilter_read()\fR function.
403 .PP
404 If a line was available from the source stream, \f(CWfilter_read()\fR
405 returns a status value greater than zero and appends the line to \f(CW$_\fR.
406 A status value of zero indicates end\-of\-file, less than zero means an
407 error. The filter function itself is expected to return its status in
408 the same way, and put the filtered line it wants written to the source
409 stream in \f(CW$_\fR. The use of \f(CW$_\fR accounts for the brevity of most Perl
410 source filters.
411 .PP
412 In order to make use of the rot13 filter we need some way of encoding
413 the source file in rot13 format. The script below, \f(CW\*(C`mkrot13\*(C'\fR, does
414 just that.
415 .PP
416 .Vb 5
417 \& die "usage mkrot13 filename\en" unless @ARGV;
418 \& my $in = $ARGV[0];
419 \& my $out = "$in.tmp";
420 \& open(IN, "<$in") or die "Cannot open file $in: $!\en";
421 \& open(OUT, ">$out") or die "Cannot open file $out: $!\en";
422 \&
423 \& print OUT "use Rot13;\en";
424 \& while (<IN>) {
425 \& tr/a\-zA\-Z/n\-za\-mN\-ZA\-M/;
426 \& print OUT;
427 \& }
428 \&
429 \& close IN;
430 \& close OUT;
431 \& unlink $in;
432 \& rename $out, $in;
433 .Ve
434 .PP
435 If we encrypt this with \f(CW\*(C`mkrot13\*(C'\fR:
436 .PP
437 .Vb 1
438 \& print " hello fred \en";
439 .Ve
440 .PP
441 the result will be this:
442 .PP
443 .Vb 2
444 \& use Rot13;
445 \& cevag "uryyb serq\ea";
446 .Ve
447 .PP
448 Running it produces this output:
449 .PP
450 .Vb 1
451 \& hello fred
452 .Ve
453 .SH "USING CONTEXT: THE DEBUG FILTER"
454 .IX Header "USING CONTEXT: THE DEBUG FILTER"
455 The rot13 example was a trivial example. Here\*(Aqs another demonstration
456 that shows off a few more features.
457 .PP
458 Say you wanted to include a lot of debugging code in your Perl script
459 during development, but you didn\*(Aqt want it available in the released
460 product. Source filters offer a solution. In order to keep the example
461 simple, let\*(Aqs say you wanted the debugging output to be controlled by
462 an environment variable, \f(CW\*(C`DEBUG\*(C'\fR. Debugging code is enabled if the
463 variable exists, otherwise it is disabled.
464 .PP
465 Two special marker lines will bracket debugging code, like this:
466 .PP
467 .Vb 5
468 \& ## DEBUG_BEGIN
469 \& if ($year > 1999) {
470 \& warn "Debug: millennium bug in year $year\en";
471 \& }
472 \& ## DEBUG_END
473 .Ve
474 .PP
475 The filter ensures that Perl parses the code between the <DEBUG_BEGIN>
476 and \f(CW\*(C`DEBUG_END\*(C'\fR markers only when the \f(CW\*(C`DEBUG\*(C'\fR environment variable
477 exists. That means that when \f(CW\*(C`DEBUG\*(C'\fR does exist, the code above
478 should be passed through the filter unchanged. The marker lines can
479 also be passed through as\-is, because the Perl parser will see them as
480 comment lines. When \f(CW\*(C`DEBUG\*(C'\fR isn\*(Aqt set, we need a way to disable the
481 debug code. A simple way to achieve that is to convert the lines
482 between the two markers into comments:
483 .PP
484 .Vb 5
485 \& ## DEBUG_BEGIN
486 \& #if ($year > 1999) {
487 \& # warn "Debug: millennium bug in year $year\en";
488 \& #}
489 \& ## DEBUG_END
490 .Ve
491 .PP
492 Here is the complete Debug filter:
493 .PP
494 .Vb 1
495 \& package Debug;
496 \&
497 \& use v5.36;
498 \& use Filter::Util::Call;
499 \&
500 \& use constant TRUE => 1;
501 \& use constant FALSE => 0;
502 \&
503 \& sub import {
504 \& my ($type) = @_;
505 \& my (%context) = (
506 \& Enabled => defined $ENV{DEBUG},
507 \& InTraceBlock => FALSE,
508 \& Filename => (caller)[1],
509 \& LineNo => 0,
510 \& LastBegin => 0,
511 \& );
512 \& filter_add(bless \e%context);
513 \& }
514 \&
515 \& sub Die {
516 \& my ($self) = shift;
517 \& my ($message) = shift;
518 \& my ($line_no) = shift || $self\->{LastBegin};
519 \& die "$message at $self\->{Filename} line $line_no.\en"
520 \& }
521 \&
522 \& sub filter {
523 \& my ($self) = @_;
524 \& my ($status);
525 \& $status = filter_read();
526 \& ++ $self\->{LineNo};
527 \&
528 \& # deal with EOF/error first
529 \& if ($status <= 0) {
530 \& $self\->Die("DEBUG_BEGIN has no DEBUG_END")
531 \& if $self\->{InTraceBlock};
532 \& return $status;
533 \& }
534 \&
535 \& if ($self\->{InTraceBlock}) {
536 \& if (/^\es*##\es*DEBUG_BEGIN/ ) {
537 \& $self\->Die("Nested DEBUG_BEGIN", $self\->{LineNo})
538 \& } elsif (/^\es*##\es*DEBUG_END/) {
539 \& $self\->{InTraceBlock} = FALSE;
540 \& }
541 \&
542 \& # comment out the debug lines when the filter is disabled
543 \& s/^/#/ if ! $self\->{Enabled};
544 \& } elsif ( /^\es*##\es*DEBUG_BEGIN/ ) {
545 \& $self\->{InTraceBlock} = TRUE;
546 \& $self\->{LastBegin} = $self\->{LineNo};
547 \& } elsif ( /^\es*##\es*DEBUG_END/ ) {
548 \& $self\->Die("DEBUG_END has no DEBUG_BEGIN", $self\->{LineNo});
549 \& }
550 \& return $status;
551 \& }
552 \&
553 \& 1;
554 .Ve
555 .PP
556 The big difference between this filter and the previous example is the
557 use of context data in the filter object. The filter object is based on
558 a hash reference, and is used to keep various pieces of context
559 information between calls to the filter function. All but two of the
560 hash fields are used for error reporting. The first of those two,
561 Enabled, is used by the filter to determine whether the debugging code
562 should be given to the Perl parser. The second, InTraceBlock, is true
563 when the filter has encountered a \f(CW\*(C`DEBUG_BEGIN\*(C'\fR line, but has not yet
564 encountered the following \f(CW\*(C`DEBUG_END\*(C'\fR line.
565 .PP
566 If you ignore all the error checking that most of the code does, the
567 essence of the filter is as follows:
568 .PP
569 .Vb 4
570 \& sub filter {
571 \& my ($self) = @_;
572 \& my ($status);
573 \& $status = filter_read();
574 \&
575 \& # deal with EOF/error first
576 \& return $status if $status <= 0;
577 \& if ($self\->{InTraceBlock}) {
578 \& if (/^\es*##\es*DEBUG_END/) {
579 \& $self\->{InTraceBlock} = FALSE
580 \& }
581 \&
582 \& # comment out debug lines when the filter is disabled
583 \& s/^/#/ if ! $self\->{Enabled};
584 \& } elsif ( /^\es*##\es*DEBUG_BEGIN/ ) {
585 \& $self\->{InTraceBlock} = TRUE;
586 \& }
587 \& return $status;
588 \& }
589 .Ve
590 .PP
591 Be warned: just as the C\-preprocessor doesn\*(Aqt know C, the Debug filter
592 doesn\*(Aqt know Perl. It can be fooled quite easily:
593 .PP
594 .Vb 3
595 \& print <<EOM;
596 \& ##DEBUG_BEGIN
597 \& EOM
598 .Ve
599 .PP
600 Such things aside, you can see that a lot can be achieved with a modest
601 amount of code.
602 .SH CONCLUSION
603 .IX Header "CONCLUSION"
604 You now have better understanding of what a source filter is, and you
605 might even have a possible use for them. If you feel like playing with
606 source filters but need a bit of inspiration, here are some extra
607 features you could add to the Debug filter.
608 .PP
609 First, an easy one. Rather than having debugging code that is
610 all\-or\-nothing, it would be much more useful to be able to control
611 which specific blocks of debugging code get included. Try extending the
612 syntax for debug blocks to allow each to be identified. The contents of
613 the \f(CW\*(C`DEBUG\*(C'\fR environment variable can then be used to control which
614 blocks get included.
615 .PP
616 Once you can identify individual blocks, try allowing them to be
617 nested. That isn\*(Aqt difficult either.
618 .PP
619 Here is an interesting idea that doesn\*(Aqt involve the Debug filter.
620 Currently Perl subroutines have fairly limited support for formal
621 parameter lists. You can specify the number of parameters and their
622 type, but you still have to manually take them out of the \f(CW@_\fR array
623 yourself. Write a source filter that allows you to have a named
624 parameter list. Such a filter would turn this:
625 .PP
626 .Vb 1
627 \& sub MySub ($first, $second, @rest) { ... }
628 .Ve
629 .PP
630 into this:
631 .PP
632 .Vb 6
633 \& sub MySub($$@) {
634 \& my ($first) = shift;
635 \& my ($second) = shift;
636 \& my (@rest) = @_;
637 \& ...
638 \& }
639 .Ve
640 .PP
641 Finally, if you feel like a real challenge, have a go at writing a
642 full\-blown Perl macro preprocessor as a source filter. Borrow the
643 useful features from the C preprocessor and any other macro processors
644 you know. The tricky bit will be choosing how much knowledge of Perl\*(Aqs
645 syntax you want your filter to have.
646 .SH LIMITATIONS
647 .IX Header "LIMITATIONS"
648 Source filters only work on the string level, thus are highly limited
649 in its ability to change source code on the fly. It cannot detect
650 comments, quoted strings, heredocs, it is no replacement for a real
651 parser.
652 The only stable usage for source filters are encryption, compression,
653 or the byteloader, to translate binary code back to source code.
654 .PP
655 See for example the limitations in Switch, which uses source filters,
656 and thus is does not work inside a string eval, the presence of
657 regexes with embedded newlines that are specified with raw \f(CW\*(C`/.../\*(C'\fR
658 delimiters and don\*(Aqt have a modifier \f(CW\*(C`//x\*(C'\fR are indistinguishable from
659 code chunks beginning with the division operator \f(CW\*(C`/\*(C'\fR. As a workaround
660 you must use \f(CW\*(C`m/.../\*(C'\fR or \f(CW\*(C`m?...?\*(C'\fR for such patterns. Also, the presence of
661 regexes specified with raw \f(CW\*(C`?...?\*(C'\fR delimiters may cause mysterious
662 errors. The workaround is to use \f(CW\*(C`m?...?\*(C'\fR instead. See
663 <https://metacpan.org/pod/Switch#LIMITATIONS>.
664 .PP
665 Currently the content of the \f(CW\*(C`_\|_DATA_\|_\*(C'\fR block is not filtered.
666 .PP
667 Currently internal buffer lengths are limited to 32\-bit only.
668 .SH "THINGS TO LOOK OUT FOR"
669 .IX Header "THINGS TO LOOK OUT FOR"
670 .ie n .IP "Some Filters Clobber the ""DATA"" Handle" 5
671 .el .IP "Some Filters Clobber the \f(CWDATA\fR Handle" 5
672 .IX Item "Some Filters Clobber the DATA Handle"
673 Some source filters use the \f(CW\*(C`DATA\*(C'\fR handle to read the calling program.
674 When using these source filters you cannot rely on this handle, nor expect
675 any particular kind of behavior when operating on it. Filters based on
676 Filter::Util::Call (and therefore Filter::Simple) do not alter the \f(CW\*(C`DATA\*(C'\fR
677 filehandle, but on the other hand totally ignore the text after \f(CW\*(C`_\|_DATA_\|_\*(C'\fR.
678 .SH REQUIREMENTS
679 .IX Header "REQUIREMENTS"
680 The Source Filters distribution is available on CPAN, in
681 .PP
682 .Vb 1
683 \& CPAN/modules/by\-module/Filter
684 .Ve
685 .PP
686 Starting from Perl 5.8 Filter::Util::Call (the core part of the
687 Source Filters distribution) is part of the standard Perl distribution.
688 Also included is a friendlier interface called Filter::Simple, by
689 Damian Conway.
690 .SH AUTHOR
691 .IX Header "AUTHOR"
692 Paul Marquess <[email protected]>
693 .PP
694 Reini Urban <[email protected]>
695 .SH Copyrights
696 .IX Header "Copyrights"
697 The first version of this article originally appeared in The Perl
698 Journal #11, and is copyright 1998 The Perl Journal. It appears
699 courtesy of Jon Orwant and The Perl Journal. This document may be
700 distributed under the same terms as Perl itself.