perlfilter > 5.14.1 との差分

perlfilter 5.14.1 と 5.36.0 の差分

11
2=encoding euc-jp
2=encoding utf8
33
44=head1 NAME
55
66=begin original
77
88perlfilter - Source Filters
99
1010=end original
1111
1212perlfilter - ソースフィルタ
1313
1414=head1 DESCRIPTION
1515
1616=begin original
1717
1818This article is about a little-known feature of Perl called
1919I<source filters>. Source filters alter the program text of a module
2020before Perl sees it, much as a C preprocessor alters the source text of
2121a C program before the compiler sees it. This article tells you more
2222about what source filters are, how they work, and how to write your
2323own.
2424
2525=end original
2626
2727この記事は、ほとんど知られていない Perl の機能である I<ソースフィルタ> に
2828関するものです。
2929C プリプロセッサが C プログラムのソーステキストをコンパイラが見る前に
3030変更するように、ソースフィルタはモジュールのプログラム文を Perl が
3131見る前に変更します。
3232この記事は、ソースフィルタとは何か、どのように動作するのか、自分自身で
3333書くにはどうすればいいかについての情報を提供します。
3434
3535=begin original
3636
3737The original purpose of source filters was to let you encrypt your
3838program source to prevent casual piracy. This isn't all they can do, as
3939you'll soon learn. But first, the basics.
4040
4141=end original
4242
4343ソースフィルタの本来の目的は、カジュアルな盗み見を防ぐためにプログラム
4444ソースを暗号化するためでした。
4545これから学ぶように、出来ることはこれだけではありません。
4646しかしまずは基本からです。
4747
4848=head1 CONCEPTS
4949
5050(コンセプト)
5151
5252=begin original
5353
5454Before the Perl interpreter can execute a Perl script, it must first
5555read it from a file into memory for parsing and compilation. If that
5656script itself includes other scripts with a C<use> or C<require>
5757statement, then each of those scripts will have to be read from their
5858respective files as well.
5959
6060=end original
6161
6262Perl インタプリタが Perl スクリプトを実行できるようにする前に、
6363パースとコンパイルのためにまずファイルをメモリに読み込まなければなりません。
6464このスクリプト自身が C<use> 文や C<require> 文で他のスクリプトを
6565インクルードしているなら、それらのスクリプトも同様にファイルから読み込む
6666必要があります。
6767
6868=begin original
6969
7070Now think of each logical connection between the Perl parser and an
7171individual file as a I<source stream>. A source stream is created when
7272the Perl parser opens a file, it continues to exist as the source code
7373is read into memory, and it is destroyed when Perl is finished parsing
7474the file. If the parser encounters a C<require> or C<use> statement in
7575a source stream, a new and distinct stream is created just for that
7676file.
7777
7878=end original
7979
8080ここで、Perl パーサと個々のファイルとの論理的な接続を I<ソースストリーム>
8181(source stream) として考えます。
8282ソースストリームは Perl パーサがファイルを開いたときに作成され、
8383ソースコードがメモリに読み込まれている間存在し、Perl がファイルを
8484パースし終えたときに破壊されます。
8585パーサがソースストリーム中に C<require> 文や C<use> 文に出会うと、
8686新しく異なったストリームがそのファイルのために作成されます。
8787
8888=begin original
8989
9090The diagram below represents a single source stream, with the flow of
9191source from a Perl script file on the left into the Perl parser on the
9292right. This is how Perl normally operates.
9393
9494=end original
9595
9696以下の図は単一のソースストリームを表現していて、左側の Perl スクリプト
9797ファイルから右側の Perl パーサへのソースの流れです。
9898これは Perl が普通処理する方法です。
9999
100100 file -------> parser
101101
102102=begin original
103103
104104There are two important points to remember:
105105
106106=end original
107107
108108覚えておくべき重要なポイントが二つあります:
109109
110110=over 5
111111
112112=item 1.
113113
114114=begin original
115115
116116Although there can be any number of source streams in existence at any
117117given time, only one will be active.
118118
119119=end original
120120
121121同時に任意の数のソースストリームが存在できますが、一つだけが
122122有効となります。
123123
124124=item 2.
125125
126126=begin original
127127
128128Every source stream is associated with only one file.
129129
130130=end original
131131
132132各ソースストリームはただ一つのファイルと関連づけられます。
133133
134134=back
135135
136136=begin original
137137
138138A source filter is a special kind of Perl module that intercepts and
139139modifies a source stream before it reaches the parser. A source filter
140140changes our diagram like this:
141141
142142=end original
143143
144144ソースフィルタは、ソースストリームがパーサに届く前に捕まえて修正する、
145145特別な種類の Perl モジュールです。
146146ソースフィルタは以下のようにダイアグラムを変更します:
147147
148148 file ----> filter ----> parser
149149
150150=begin original
151151
152152If that doesn't make much sense, consider the analogy of a command
153153pipeline. Say you have a shell script stored in the compressed file
154154I<trial.gz>. The simple pipeline command below runs the script without
155155needing to create a temporary file to hold the uncompressed file.
156156
157157=end original
158158
159159これにあまり納得が出来ないなら、コマンドパイプラインの例えを
160160考えてみてください。
161161圧縮されたファイル I<trial.gz> に補完されたシェルスクリプトを
162162考えてみてください。
163163後述の単純なパイプラインコマンドは展開されたファイルを保管するための
164164一時ファイルを作ることなくスクリプトを実行します。
165165
166166 gunzip -c trial.gz | sh
167167
168168=begin original
169169
170170In this case, the data flow from the pipeline can be represented as follows:
171171
172172=end original
173173
174174この場合、パイプラインからのデータフローは以下のように表現できます:
175175
176176 trial.gz ----> gunzip ----> sh
177177
178178=begin original
179179
180180With source filters, you can store the text of your script compressed and use a source filter to uncompress it for Perl's parser:
181181
182182=end original
183183
184184ソースフィルタがあると、スクリプトのテキストを圧縮して、Perl パーサのために
185185展開するソースフィルタを使います:
186186
187187 compressed gunzip
188188 Perl program ---> source filter ---> parser
189189
190190=head1 USING FILTERS
191191
192192(フィルタを使う)
193193
194194=begin original
195195
196196So how do you use a source filter in a Perl script? Above, I said that
197197a source filter is just a special kind of module. Like all Perl
198198modules, a source filter is invoked with a use statement.
199199
200200=end original
201201
202202それで、どうやって Perl スクリプトでソースフィルタを使うのでしょう?
203203先に、ソースフィルタは単に特別な種類のモジュールであると言いました。
204204その他全ての Perl モジュールと同様、ソースフィルタは use 文で
205205起動されます。
206206
207207=begin original
208208
209209Say you want to pass your Perl source through the C preprocessor before
210210execution. As it happens, the source filters distribution comes with a C
211211preprocessor filter module called Filter::cpp.
212212
213213=end original
214214
215215Perl のソースを実行前に C のプリプロセッサを通したいとします。
216216たまたまソースフィルタ配布には Filter::cpp と呼ばれる C プリプロセッサ
217217フィルタモジュールが含まれています。
218218
219219=begin original
220220
221221Below is an example program, C<cpp_test>, which makes use of this filter.
222222Line numbers have been added to allow specific lines to be referenced
223223easily.
224224
225225=end original
226226
227227以下は、このフィルタを使うためのサンプルプログラムである C<cpp_test> です。
228228行番号は、特定の行を参照しやすくするために追加されています。
229229
230230 1: use Filter::cpp;
231231 2: #define TRUE 1
232232 3: $a = TRUE;
233233 4: print "a = $a\n";
234234
235235=begin original
236236
237237When you execute this script, Perl creates a source stream for the
238238file. Before the parser processes any of the lines from the file, the
239239source stream looks like this:
240240
241241=end original
242242
243243このスクリプトを実行すると、Perl はこのファイルのためのソースストリームを
244244作成します。
245245パーサがファイルから行を処理する前、ソースストリームは以下のように
246246なります:
247247
248248 cpp_test ---------> parser
249249
250250=begin original
251251
252252Line 1, C<use Filter::cpp>, includes and installs the C<cpp> filter
253253module. All source filters work this way. The use statement is compiled
254254and executed at compile time, before any more of the file is read, and
255255it attaches the cpp filter to the source stream behind the scenes. Now
256256the data flow looks like this:
257257
258258=end original
259259
2602601 行目の C<use Filter::cpp> で、C<cpp> モジュールをインクルードして
261261インストールします。
262262全てのソースフィルタはこのようにして動作します。
263263use 文はコンパイルされてコンパイル時に、ファイルの残りの部分が読み込まれる
264264前に実行され、背後でソースフィルタに cpp フィルタをくっつけます。
265265ここでデータフローは以下のようになります:
266266
267267 cpp_test ----> cpp filter ----> parser
268268
269269=begin original
270270
271271As the parser reads the second and subsequent lines from the source
272272stream, it feeds those lines through the C<cpp> source filter before
273273processing them. The C<cpp> filter simply passes each line through the
274274real C preprocessor. The output from the C preprocessor is then
275275inserted back into the source stream by the filter.
276276
277277=end original
278278
279279パーサがソースストリームから 2 行目以降を読むにつれて、処理する前に
280280C<cpp> ソースフィルタを通して行が供給されます。
281281C<cpp> フィルタは単に各行を実際の C プリプロセッサに通します。
282282C プリプロセッサからの出力はそれからフィルタによってソースストリームに
283283再挿入されます。
284284
285285 .-> cpp --.
286286 | |
287287 | |
288288 | <-'
289289 cpp_test ----> cpp filter ----> parser
290290
291291=begin original
292292
293293The parser then sees the following code:
294294
295295=end original
296296
297297それからパーサは以下のコードを見ます:
298298
299299 use Filter::cpp;
300300 $a = 1;
301301 print "a = $a\n";
302302
303303=begin original
304304
305305Let's consider what happens when the filtered code includes another
306306module with use:
307307
308308=end original
309309
310310フィルタされたコードに use を使ったもう一つのモジュールを含んでいる
311311場合に何が起きるかを考えてみましょう:
312312
313313 1: use Filter::cpp;
314314 2: #define TRUE 1
315315 3: use Fred;
316316 4: $a = TRUE;
317317 5: print "a = $a\n";
318318
319319=begin original
320320
321321The C<cpp> filter does not apply to the text of the Fred module, only
322322to the text of the file that used it (C<cpp_test>). Although the use
323323statement on line 3 will pass through the cpp filter, the module that
324324gets included (C<Fred>) will not. The source streams look like this
325325after line 3 has been parsed and before line 4 is parsed:
326326
327327=end original
328328
329329C<cpp> フィルタは Fred モジュールのテキストには適用されず、
330330フィルタが使われているファイル (C<cpp_test>) のテキストにのみ
331331適用されます。
3323323 行目の use 文は cpp フィルタに渡されますが、インクルードされる
333333モジュール (C<Fred>) は渡されません。
3343343 行目がパースされ、4 行目がパースされる前のソースストリームは
335335以下のようになります:
336336
337337 cpp_test ---> cpp filter ---> parser (INACTIVE)
338338
339339 Fred.pm ----> parser
340340
341341=begin original
342342
343343As you can see, a new stream has been created for reading the source
344344from C<Fred.pm>. This stream will remain active until all of C<Fred.pm>
345345has been parsed. The source stream for C<cpp_test> will still exist,
346346but is inactive. Once the parser has finished reading Fred.pm, the
347347source stream associated with it will be destroyed. The source stream
348348for C<cpp_test> then becomes active again and the parser reads line 4
349349and subsequent lines from C<cpp_test>.
350350
351351=end original
352352
353353見て分かるように、C<Fred.pm> からソースを読み込むための新しいストリームが
354354作成されます。
355355このストリームは C<Fred.pm> を全て読み込むまで有効のままです。
356356C<cpp_test> のためのソースストリームは存在したままですが、無効に
357357なっています。
358358パーサが Fred.pm からの読み込みを終了すると、これに関連づけられた
359359ソースストリームは破壊されます。
360360それから C<cpp_test> のためのソースストリームが再び有効になり、
361361パーサは C<cpp_test> から 4 行目以降を読み込みます。
362362
363363=begin original
364364
365365You can use more than one source filter on a single file. Similarly,
366366you can reuse the same filter in as many files as you like.
367367
368368=end original
369369
370370一つのファイルに複数のソースフィルタを使うことができます。
371371同様に、好きなだけ多くのファイルに対して同じフィルタを
372372再使用することができます。
373373
374374=begin original
375375
376376For example, if you have a uuencoded and compressed source file, it is
377377possible to stack a uudecode filter and an uncompression filter like
378378this:
379379
380380=end original
381381
382382例えば、uuencode されて圧縮されているソースファイルがある場合、
383383次のようにして uudecode フィルタと uncompress フィルタを
384384スタックさせることができます:
385385
386386 use Filter::uudecode; use Filter::uncompress;
387387 M'XL(".H<US4''V9I;F%L')Q;>7/;1I;_>_I3=&E=%:F*I"T?22Q/
388388 M6]9*<IQCO*XFT"0[PL%%'Y+IG?WN^ZYN-$'J.[.JE$,20/?K=_[>
389389 ...
390390
391391=begin original
392392
393393Once the first line has been processed, the flow will look like this:
394394
395395=end original
396396
397397最初の行が処理されると、フローは以下のようになります:
398398
399399 file ---> uudecode ---> uncompress ---> parser
400400 filter filter
401401
402402=begin original
403403
404404Data flows through filters in the same order they appear in the source
405405file. The uudecode filter appeared before the uncompress filter, so the
406406source file will be uudecoded before it's uncompressed.
407407
408408=end original
409409
410410データはソースファイルに現れたのと同じ順でフィルタを流れます。
411411uudecode フィルタは uncompress フィルタの前に現れるので、ソースファイルは
412412展開される前に uudecode されます。
413413
414414=head1 WRITING A SOURCE FILTER
415415
416416(ソースフィルタを書く)
417417
418418=begin original
419419
420420There are three ways to write your own source filter. You can write it
421421in C, use an external program as a filter, or write the filter in Perl.
422422I won't cover the first two in any great detail, so I'll get them out
423423of the way first. Writing the filter in Perl is most convenient, so
424424I'll devote the most space to it.
425425
426426=end original
427427
428428独自のソースフィルタを書くには三つの方法があります。
429429C で書くか、フィルタとして外部プログラムを使うか、Perl でフィルタを
430430書くかです。
431431最初の二つについてはあまり詳しくは記述しないので、先にこれらについて
432432触れます。
433433Perl でフィルタを書くのが一番便利なので、これに最大のスペースを割きます。
434434
435435=head1 WRITING A SOURCE FILTER IN C
436436
437437(C でソースフィルタを書く)
438438
439439=begin original
440440
441441The first of the three available techniques is to write the filter
442442completely in C. The external module you create interfaces directly
443443with the source filter hooks provided by Perl.
444444
445445=end original
446446
447447利用可能な三つのテクニックのうちの一つ目は、フィルタを完全に C で
448448書くことです。
449449作成した外部モジュールは Perl によって提供されるソースフィルタフックと
450450直接接続されます。
451451
452452=begin original
453453
454454The advantage of this technique is that you have complete control over
455455the implementation of your filter. The big disadvantage is the
456456increased complexity required to write the filter - not only do you
457457need to understand the source filter hooks, but you also need a
458458reasonable knowledge of Perl guts. One of the few times it is worth
459459going to this trouble is when writing a source scrambler. The
460460C<decrypt> filter (which unscrambles the source before Perl parses it)
461461included with the source filter distribution is an example of a C
462462source filter (see Decryption Filters, below).
463463
464464=end original
465465
466466このテクニックの利点は、フィルタの実装を完全に制御できることです。
467467大きな弱点は、フィルタを書くために必要な複雑性が増すことです -
468468ソースフィルタフックについて理解するだけでなく、Perl の内部に関する
469469ある程度の知識も必要です。
470470この困難に向かう価値のある数回に一回はソースのスクランブル化を
471471書くときです。
472472(Perl がパースする前にソースのスクランブルを解除する) C<decrypt> フィルタは
473473C ソースフィルタの例です (以下の Decryption Filters を参照してください)。
474474
475475=over 5
476476
477477=item B<Decryption Filters>
478478
479479(B<復号フィルタ>)
480480
481481=begin original
482482
483483All decryption filters work on the principle of "security through
484484obscurity." Regardless of how well you write a decryption filter and
485485how strong your encryption algorithm is, anyone determined enough can
486486retrieve the original source code. The reason is quite simple - once
487487the decryption filter has decrypted the source back to its original
488488form, fragments of it will be stored in the computer's memory as Perl
489489parses it. The source might only be in memory for a short period of
490490time, but anyone possessing a debugger, skill, and lots of patience can
491491eventually reconstruct your program.
492492
493493=end original
494494
495495全ての復号フィルタは「不明瞭さによるセキュリティ」の原則に則っています。
496496どれだけうまく復号フィルタを書いて、どんなに強い暗号化アルゴリズムを
497497使っても、十分な決意があれば元のソースコードを取得できます。
498498その理由はとても単純です - 一旦復号フィルタがソースを元の形に戻すと、その
499499一部は Perl がパースするためにコンピュータのメモリに保管されます。
500500ソースは短い時間の間だけしかメモリにないかもしれませんが、デバッガ、スキル、
501501多大な忍耐がある人なら最終的にはプログラムを再構成できます。
502502
503503=begin original
504504
505505That said, there are a number of steps that can be taken to make life
506506difficult for the potential cracker. The most important: Write your
507507decryption filter in C and statically link the decryption module into
508508the Perl binary. For further tips to make life difficult for the
509509potential cracker, see the file I<decrypt.pm> in the source filters
510510distribution.
511511
512512=end original
513513
514514潜在的なクラッカーに対して物事を難しくするために取るいくつかのステップが
515515あります。
516516最も重要なのは: 復号フィルタを C で書いて、復号モジュールを Perl バイナリと
517517静的にリンクすることです。
518518潜在的なクラッカーに対して物事を難しくするために取るさらなるステップは、
519519ソースフィルタ配布の I<decrypt.pm> ファイルを参照してください。
520520
521521=back
522522
523523=head1 CREATING A SOURCE FILTER AS A SEPARATE EXECUTABLE
524524
525525(独立した実行ファイルとしてソースフィルタとして作成する)
526526
527527=begin original
528528
529529An alternative to writing the filter in C is to create a separate
530530executable in the language of your choice. The separate executable
531531reads from standard input, does whatever processing is necessary, and
532532writes the filtered data to standard output. C<Filter::cpp> is an
533533example of a source filter implemented as a separate executable - the
534534executable is the C preprocessor bundled with your C compiler.
535535
536536=end original
537537
538538C でフィルタを書くための代替案は、好みの言語で独立した実行ファイルを
539539作ることです。
540540独立した実行ファイルは標準出力から読み込み、何か必要な処理を行い、
541541フィルタされたデータを標準出力に書き込みます。
542542C<Filter::cpp> は、独立した実行ファイルとして実行されたソースフィルタの
543543例です - 実行ファイルは C コンパイラに付いている C プリプロセッサです。
544544
545545=begin original
546546
547547The source filter distribution includes two modules that simplify this
548548task: C<Filter::exec> and C<Filter::sh>. Both allow you to run any
549549external executable. Both use a coprocess to control the flow of data
550550into and out of the external executable. (For details on coprocesses,
551551see Stephens, W.R., "Advanced Programming in the UNIX Environment."
552552Addison-Wesley, ISBN 0-210-56317-7, pages 441-445.) The difference
553553between them is that C<Filter::exec> spawns the external command
554554directly, while C<Filter::sh> spawns a shell to execute the external
555555command. (Unix uses the Bourne shell; NT uses the cmd shell.) Spawning
556556a shell allows you to make use of the shell metacharacters and
557557redirection facilities.
558558
559559=end original
560560
561561ソースフィルタ配布にはこのタスクを簡単にするための二つのモジュールが
562562あります: C<Filter::exec> と C<Filter::sh> です。
563563どちらも外部実行ファイルを実行します。
564564どちらも外部実行ファイルとのデータのやりとりを制御するのにコプロセスを
565565使います。
566566(コプロセスの詳細については、Stephens, W.R. による
567567"Advanced Programming in the UNIX Environment."
568568Addison-Wesley, ISBN 0-210-56317-7, 441-445 ページ を参照してください。)
569569二つの違いは、C<Filter::exec> は外部コマンドを直接起動しますが、
570570C<Filter::sh> は外部コマンドを起動するためのシェルを起動します。
571571(Unix は Bourne シェルを使います; NT は cmd シェルを使います。)
572572シェルを起動することにより、シェルのメタ文字とリダイレクト機構を
573573使えるようになります。
574574
575575=begin original
576576
577577Here is an example script that uses C<Filter::sh>:
578578
579579=end original
580580
581581以下は C<Filter::sh> を使ったスクリプトの例です:
582582
583583 use Filter::sh 'tr XYZ PQR';
584584 $a = 1;
585585 print "XYZ a = $a\n";
586586
587587=begin original
588588
589589The output you'll get when the script is executed:
590590
591591=end original
592592
593593スクリプトが実行されたときに得られる出力は:
594594
595595 PQR a = 1
596596
597597=begin original
598598
599599Writing a source filter as a separate executable works fine, but a
600600small performance penalty is incurred. For example, if you execute the
601601small example above, a separate subprocess will be created to run the
602602Unix C<tr> command. Each use of the filter requires its own subprocess.
603603If creating subprocesses is expensive on your system, you might want to
604604consider one of the other options for creating source filters.
605605
606606=end original
607607
608608独立した実行ファイルとしてソースフィルタを書くとうまく動作しますが、
609609小さい性能上のペナルティがあります。
610610例えば、上述の小さい例を実行すると、Unix の C<tr> コマンドを実行するために
611611別々のサブプロセスが作られます。
612それぞれのフィルタの使用には独自のサブプロセスが必要です。
612613サブシステムの作成のコストが高いシステムでは、ソースフィルタを作るための
613614その他の選択肢を考えたいかもしれません。
614615
615616=head1 WRITING A SOURCE FILTER IN PERL
616617
617618(Perl でソースフィルタを書く)
618619
619620=begin original
620621
621622The easiest and most portable option available for creating your own
622623source filter is to write it completely in Perl. To distinguish this
623624from the previous two techniques, I'll call it a Perl source filter.
624625
625626=end original
626627
627628独自のソースフィルタを作成するためのもっとも簡単でもっとも移植性のある
628629選択肢は、完全に Perl で書くことです。
629630これを前述の二つのテクニックと区別するために、ここではこれを
630631Perl ソースフィルタと呼びます。
631632
632633=begin original
633634
634635To help understand how to write a Perl source filter we need an example
635636to study. Here is a complete source filter that performs rot13
636637decoding. (Rot13 is a very simple encryption scheme used in Usenet
637638postings to hide the contents of offensive posts. It moves every letter
638639forward thirteen places, so that A becomes N, B becomes O, and Z
639640becomes M.)
640641
641642=end original
642643
643644Perl ソースフィルタの書き方を理解するのを助けるために、学習するための
644645例が必要です。
645646以下は rot13 復号を行う完全なソースフィルタです。
646647(rot13 は、攻撃的な投稿を隠すために Usenet 投稿で使われたとても簡単な
647648暗号スキームです。
648649これはそれぞれの英文字を 13 ずらします; 従って A は N に、B は O に、
649650Z は M になります。)
650651
651652 package Rot13;
652653
653654 use Filter::Util::Call;
654655
655656 sub import {
656657 my ($type) = @_;
657658 my ($ref) = [];
658659 filter_add(bless $ref);
659660 }
660661
661662 sub filter {
662663 my ($self) = @_;
663664 my ($status);
664665
665666 tr/n-za-mN-ZA-M/a-zA-Z/
666667 if ($status = filter_read()) > 0;
667668 $status;
668669 }
669670
670671 1;
671672
673=for apidoc filter_add
674=for apidoc filter_read
675
672676=begin original
673677
674678All Perl source filters are implemented as Perl classes and have the
675679same basic structure as the example above.
676680
677681=end original
678682
679683全ての Perl ソースフィルタは Perl クラスとして実装され、上述の例と
680684同じ基本構造を持ちます。
681685
682686=begin original
683687
684688First, we include the C<Filter::Util::Call> module, which exports a
685689number of functions into your filter's namespace. The filter shown
686690above uses two of these functions, C<filter_add()> and
687691C<filter_read()>.
688692
689693=end original
690694
691695まず、C<Filter::Util::Call> をインクルードして、多くの関数をフィルタの
692696名前空間にエクスポートします。
693697上述のフィルタはこれらの関数の内 C<filter_add()> と C<filter_read()> の
694698二つの関数を使います。
695699
696700=begin original
697701
698702Next, we create the filter object and associate it with the source
699703stream by defining the C<import> function. If you know Perl well
700704enough, you know that C<import> is called automatically every time a
701705module is included with a use statement. This makes C<import> the ideal
702706place to both create and install a filter object.
703707
704708=end original
705709
706710次に、フィルタオブジェクトを作って、C<import> 関数を定義することによって
707711これをソースストリームと結びつけます。
708712Perl のことを十分知っているなら、
709713C<import> は use 文でモジュールがインクルードされる旅に自動的に
710714呼び出されることを知っているでしょう。
711715これにより、C<import> はフィルタオブジェクトの作成とインストールに
712716最適の場所と言えます。
713717
714718=begin original
715719
716720In the example filter, the object (C<$ref>) is blessed just like any
717721other Perl object. Our example uses an anonymous array, but this isn't
718722a requirement. Because this example doesn't need to store any context
719723information, we could have used a scalar or hash reference just as
720724well. The next section demonstrates context data.
721725
722726=end original
723727
724728例のフィルタでは、オブジェクト (C<$ref>) はその他の Perl オブジェクトと
725729同じように bless されます。
726730この例では無名配列を使っていますが、これは必須ではありません。
727731この例では内容の情報を補完する必要がないので、スカラリファレンスや
728732ハッシュリファレンスでを使うこともできます。
729733次の節ではコンテキストデータを図示します。
730734
731735=begin original
732736
733737The association between the filter object and the source stream is made
734738with the C<filter_add()> function. This takes a filter object as a
735739parameter (C<$ref> in this case) and installs it in the source stream.
736740
737741=end original
738742
739743フィルタオブジェクトとソースストリームの関連付けは C<filter_add()> 関数で
740744行われます。
741745これはフィルタオブジェクト (今回の場合では C<$ref>) を引数に取って、
742746これをソースストリームに取り付けます。
743747
744748=begin original
745749
746750Finally, there is the code that actually does the filtering. For this
747751type of Perl source filter, all the filtering is done in a method
748752called C<filter()>. (It is also possible to write a Perl source filter
749753using a closure. See the C<Filter::Util::Call> manual page for more
750754details.) It's called every time the Perl parser needs another line of
751755source to process. The C<filter()> method, in turn, reads lines from
752756the source stream using the C<filter_read()> function.
753757
754758=end original
755759
756760最後に、実際にフィルタリングを行うコードがあります。
757761この種の Perl ソースフィルタのために、フィルタリングの全ては
758762C<filter()> と呼ばれるメソッドで行われます。
759763(クロージャを使って Perl ソースフィルタを書くことも可能です。
760764さらなる詳細については C<Filter::Util::Call> マニュアルページを
761765参照してください。)
762766これは Perl パーサが処理するソースの行が必要になる度に毎回呼び出されます。
763767C<filter()> メソッドは、C<filter_read()> 関数を使ってソースストリームから
764768順番に行を読み込みます。
765769
766770=begin original
767771
768772If a line was available from the source stream, C<filter_read()>
769773returns a status value greater than zero and appends the line to C<$_>.
770774A status value of zero indicates end-of-file, less than zero means an
771775error. The filter function itself is expected to return its status in
772776the same way, and put the filtered line it wants written to the source
773777stream in C<$_>. The use of C<$_> accounts for the brevity of most Perl
774778source filters.
775779
776780=end original
777781
778782ソースストリームから 1 行が利用可能になったら、C<filter_read()> は
7797830 より大きいステータス値を返して、C<$_> に行を追加します。
780784ステータス値が 0 の場合はファイル末尾を示し、0 より小さい場合は
781785エラーを意味します。
782786filter 関数自身はステータスを同じ方法で返し、ソースストリームに
783787書き込みたいフィルタリングされた行を C<$_> に入れることを
784788想定されています。
785789C<$_> の使い方はほとんどの Perl ソースフィルタの簡潔さを考慮に
786790入れています。
787791
788792=begin original
789793
790794In order to make use of the rot13 filter we need some way of encoding
791795the source file in rot13 format. The script below, C<mkrot13>, does
792796just that.
793797
794798=end original
795799
796800rot13 フィルタを使うには、ソースファイルを rot13 形式で符号化する
797801方法が必要です。
798802以下のスクリプト C<mkrot13> はそれを行います。
799803
800804 die "usage mkrot13 filename\n" unless @ARGV;
801805 my $in = $ARGV[0];
802806 my $out = "$in.tmp";
803807 open(IN, "<$in") or die "Cannot open file $in: $!\n";
804808 open(OUT, ">$out") or die "Cannot open file $out: $!\n";
805809
806810 print OUT "use Rot13;\n";
807811 while (<IN>) {
808812 tr/a-zA-Z/n-za-mN-ZA-M/;
809813 print OUT;
810814 }
811815
812816 close IN;
813817 close OUT;
814818 unlink $in;
815819 rename $out, $in;
816820
817821=begin original
818822
819823If we encrypt this with C<mkrot13>:
820824
821825=end original
822826
823827これを C<mkrot13> で暗号化すると:
824828
825829 print " hello fred \n";
826830
827831=begin original
828832
829833the result will be this:
830834
831835=end original
832836
833837結果は以下のようになります:
834838
835839 use Rot13;
836840 cevag "uryyb serq\a";
837841
838842=begin original
839843
840844Running it produces this output:
841845
842846=end original
843847
844848これを実行すると以下の出力を生成します:
845849
846850 hello fred
847851
848852=head1 USING CONTEXT: THE DEBUG FILTER
849853
850854(コンテキストを使う: デバッグフィルタ)
851855
852856=begin original
853857
854858The rot13 example was a trivial example. Here's another demonstration
855859that shows off a few more features.
856860
857861=end original
858862
859863rot13 の例はつまらない例でした。
860864以下は、もういくつかの機能を見せるための例です。
861865
862866=begin original
863867
864868Say you wanted to include a lot of debugging code in your Perl script
865869during development, but you didn't want it available in the released
866870product. Source filters offer a solution. In order to keep the example
867871simple, let's say you wanted the debugging output to be controlled by
868872an environment variable, C<DEBUG>. Debugging code is enabled if the
869873variable exists, otherwise it is disabled.
870874
871875=end original
872876
873877開発中に Perl スクリプトに大量のデバッグコードを含めておきたいけれども、
874878リリース製品では利用可能にしたくないとします。
875879ソースフィルタが解決法を提供します。
876880例を単純なままにするために、環境変数 C<DEBUG> で制御されるデバッグ出力が
877881ほしいとします。
878882デバッグコードは、環境変数が存在すれば有効になり、さもなければ
879883無効になります。
880884
881885=begin original
882886
883887Two special marker lines will bracket debugging code, like this:
884888
885889=end original
886890
887891次のように、二つの特殊なマーカー行でデバッグするコードを囲みます:
888892
889893 ## DEBUG_BEGIN
890894 if ($year > 1999) {
891895 warn "Debug: millennium bug in year $year\n";
892896 }
893897 ## DEBUG_END
894898
895899=begin original
896900
897901The filter ensures that Perl parses the code between the <DEBUG_BEGIN>
898902and C<DEBUG_END> markers only when the C<DEBUG> environment variable
899903exists. That means that when C<DEBUG> does exist, the code above
900904should be passed through the filter unchanged. The marker lines can
901905also be passed through as-is, because the Perl parser will see them as
902906comment lines. When C<DEBUG> isn't set, we need a way to disable the
903907debug code. A simple way to achieve that is to convert the lines
904908between the two markers into comments:
905909
906910=end original
907911
908912C<DEBUG> 環境変数が存在するとき、フィルタは Perl が C<DEBUG_BEGIN> と
909913C<DEBUG_END> のマーカーの間のコードだけをパースするようにします。
910914これにより、C<DEBUG> が存在すると、上述のコードはフィルタを変更なしで
911915通過して渡されます。
912916マーカー行もそのまま渡されます; Perl パーサはこれらをコメント行として
913917扱うからです。
914918C<DEBUG> が設定されていないとき、デバッグコードを無効にする方法が
915919必要になります。
916920これを達成する簡単な方法は、二つのマーカーの間の行をコメントに
917921変換することです:
918922
919923 ## DEBUG_BEGIN
920924 #if ($year > 1999) {
921925 # warn "Debug: millennium bug in year $year\n";
922926 #}
923927 ## DEBUG_END
924928
925929=begin original
926930
927931Here is the complete Debug filter:
928932
929933=end original
930934
931935以下は完全な Debug フィルタです:
932936
933937 package Debug;
934938
935 use strict;
939 use v5.36;
936 use warnings;
937940 use Filter::Util::Call;
938941
939942 use constant TRUE => 1;
940943 use constant FALSE => 0;
941944
942945 sub import {
943946 my ($type) = @_;
944947 my (%context) = (
945948 Enabled => defined $ENV{DEBUG},
946949 InTraceBlock => FALSE,
947950 Filename => (caller)[1],
948951 LineNo => 0,
949952 LastBegin => 0,
950953 );
951954 filter_add(bless \%context);
952955 }
953956
954957 sub Die {
955958 my ($self) = shift;
956959 my ($message) = shift;
957960 my ($line_no) = shift || $self->{LastBegin};
958961 die "$message at $self->{Filename} line $line_no.\n"
959962 }
960963
961964 sub filter {
962965 my ($self) = @_;
963966 my ($status);
964967 $status = filter_read();
965968 ++ $self->{LineNo};
966969
967970 # deal with EOF/error first
968971 if ($status <= 0) {
969972 $self->Die("DEBUG_BEGIN has no DEBUG_END")
970973 if $self->{InTraceBlock};
971974 return $status;
972975 }
973976
974977 if ($self->{InTraceBlock}) {
975978 if (/^\s*##\s*DEBUG_BEGIN/ ) {
976979 $self->Die("Nested DEBUG_BEGIN", $self->{LineNo})
977980 } elsif (/^\s*##\s*DEBUG_END/) {
978981 $self->{InTraceBlock} = FALSE;
979982 }
980983
981984 # comment out the debug lines when the filter is disabled
982985 s/^/#/ if ! $self->{Enabled};
983986 } elsif ( /^\s*##\s*DEBUG_BEGIN/ ) {
984987 $self->{InTraceBlock} = TRUE;
985988 $self->{LastBegin} = $self->{LineNo};
986989 } elsif ( /^\s*##\s*DEBUG_END/ ) {
987990 $self->Die("DEBUG_END has no DEBUG_BEGIN", $self->{LineNo});
988991 }
989992 return $status;
990993 }
991994
992995 1;
993996
994997=begin original
995998
996999The big difference between this filter and the previous example is the
9971000use of context data in the filter object. The filter object is based on
9981001a hash reference, and is used to keep various pieces of context
9991002information between calls to the filter function. All but two of the
10001003hash fields are used for error reporting. The first of those two,
10011004Enabled, is used by the filter to determine whether the debugging code
10021005should be given to the Perl parser. The second, InTraceBlock, is true
10031006when the filter has encountered a C<DEBUG_BEGIN> line, but has not yet
10041007encountered the following C<DEBUG_END> line.
10051008
10061009=end original
10071010
10081011このフィルタと以前の例との大きな違いは、フィルタオブジェクトの
10091012コンテキストデータの使用です。
10101013フィルタオブジェクトはハッシュリファレンスを基礎としていて、フィルタ関数の
10111014呼び出し間のコンテキスト情報の様々な断片を保持するために使われます。
10121015二つを除いた全てのハッシュフィールドはエラー報告のために使われます。
10131016二つの内一番目である Enabled は、デバッグコードが Perl パーサに
10141017与えられるべきかどうかを決定するために使われます。
10151018二番目である InTraceBlock は、フィルタが C<DEBUG_BEGIN> に遭遇したけれども
10161019まだ引き続く C<DEBUG_END> 行に出会っていないときに真となります。
10171020
10181021=begin original
10191022
10201023If you ignore all the error checking that most of the code does, the
10211024essence of the filter is as follows:
10221025
10231026=end original
10241027
10251028コードのほとんどが行っているエラーチェックの全てを無視すると、フィルタの
10261029本質は以下のようになります:
10271030
10281031 sub filter {
10291032 my ($self) = @_;
10301033 my ($status);
10311034 $status = filter_read();
10321035
10331036 # deal with EOF/error first
10341037 return $status if $status <= 0;
10351038 if ($self->{InTraceBlock}) {
10361039 if (/^\s*##\s*DEBUG_END/) {
10371040 $self->{InTraceBlock} = FALSE
10381041 }
10391042
10401043 # comment out debug lines when the filter is disabled
10411044 s/^/#/ if ! $self->{Enabled};
10421045 } elsif ( /^\s*##\s*DEBUG_BEGIN/ ) {
10431046 $self->{InTraceBlock} = TRUE;
10441047 }
10451048 return $status;
10461049 }
10471050
10481051=begin original
10491052
10501053Be warned: just as the C-preprocessor doesn't know C, the Debug filter
10511054doesn't know Perl. It can be fooled quite easily:
10521055
10531056=end original
10541057
10551058警告: C プリプロセッサが C のことを知らないのと同様、Debug フィルタは
10561059Perl のことを知りません。
10571060簡単にだませます:
10581061
10591062 print <<EOM;
10601063 ##DEBUG_BEGIN
10611064 EOM
10621065
10631066=begin original
10641067
10651068Such things aside, you can see that a lot can be achieved with a modest
10661069amount of code.
10671070
10681071=end original
10691072
10701073そのようなことを置いておいても、それほどでもない量のコードで多くのことが
10711074達成できるのが分かります。
10721075
10731076=head1 CONCLUSION
10741077
10751078(結び)
10761079
10771080=begin original
10781081
10791082You now have better understanding of what a source filter is, and you
10801083might even have a possible use for them. If you feel like playing with
10811084source filters but need a bit of inspiration, here are some extra
10821085features you could add to the Debug filter.
10831086
10841087=end original
10851088
10861089これで、ソースフィルタとは何かについてよりよく理解できたと思います;
10871090さらにこれらの可能性のある使い方を持っているかもしれません。
10881091もしソースフィルタで遊んでみたいと思っているけれどもちょっとした
10891092インスピレーションが必要なら、以下はデバッグフィルタに加えることが出来る
10901093追加機能です。
10911094
10921095=begin original
10931096
10941097First, an easy one. Rather than having debugging code that is
10951098all-or-nothing, it would be much more useful to be able to control
10961099which specific blocks of debugging code get included. Try extending the
10971100syntax for debug blocks to allow each to be identified. The contents of
10981101the C<DEBUG> environment variable can then be used to control which
10991102blocks get included.
11001103
11011104=end original
11021105
11031106まずは簡単なものです。
11041107デバッグコードをオールオアナッシングにするのではなく、どのブロックを
11051108デバッグコードとして使うかを制御できるようにすればもっと便利です。
11061109それぞれのデバッグブロックを識別できるように文法に文法を
11071110拡張してみてください。
11081111C<DEBUG> 環境変数の内容はどのブロックを使うかを制御するのに使えます。
11091112
11101113=begin original
11111114
11121115Once you can identify individual blocks, try allowing them to be
11131116nested. That isn't difficult either.
11141117
11151118=end original
11161119
11171120個々のブロックを識別できるようになったら、ネストできるように
11181121してみてください。
11191122これも難しくはありません。
11201123
11211124=begin original
11221125
11231126Here is an interesting idea that doesn't involve the Debug filter.
11241127Currently Perl subroutines have fairly limited support for formal
11251128parameter lists. You can specify the number of parameters and their
11261129type, but you still have to manually take them out of the C<@_> array
11271130yourself. Write a source filter that allows you to have a named
11281131parameter list. Such a filter would turn this:
11291132
11301133=end original
11311134
11321135これはデバッグフィルタに関係ない面白いアイデアです。
11331136今のところ Perl サブルーチンは公式な引数リストに限定的に対応しています。
11341137パラメータの数とその型は指定できますが、自力で C<@_> 配列から取り出す
11351138必要があります。
11361139名前付き引数リストを使えるようなソースフィルタを書きましょう。
11371140そのようなフィルタは以下のようなものを:
11381141
11391142 sub MySub ($first, $second, @rest) { ... }
11401143
11411144=begin original
11421145
11431146into this:
11441147
11451148=end original
11461149
11471150次のように変更します:
11481151
11491152 sub MySub($$@) {
11501153 my ($first) = shift;
11511154 my ($second) = shift;
11521155 my (@rest) = @_;
11531156 ...
11541157 }
11551158
11561159=begin original
11571160
11581161Finally, if you feel like a real challenge, have a go at writing a
11591162full-blown Perl macro preprocessor as a source filter. Borrow the
11601163useful features from the C preprocessor and any other macro processors
11611164you know. The tricky bit will be choosing how much knowledge of Perl's
11621165syntax you want your filter to have.
11631166
11641167=end original
11651168
11661169最後に、本当の挑戦を好むなら、本格的な Perl マクロプリプロセッサを
11671170ソースフィルタとして書いてみてください。
11681171C プリプロセッサやその他のマクロプロセッサから便利な機能を
11691172借りてきてください。
11701173トリッキーなところは、Perl の文法のどれくらいの知識をフィルタに持たせるかを
11711174選ぶところです。
11721175
1176=head1 LIMITATIONS
1177
1178(制限)
1179
1180=begin original
1181
1182Source filters only work on the string level, thus are highly limited
1183in its ability to change source code on the fly. It cannot detect
1184comments, quoted strings, heredocs, it is no replacement for a real
1185parser.
1186The only stable usage for source filters are encryption, compression,
1187or the byteloader, to translate binary code back to source code.
1188
1189=end original
1190
1191ソースフィルタは文字列レベルでしか動作しないので、その場でソースコードを
1192変換する能力はとても制限されています。
1193コメント、クォートされた文字列、ヒヤドキュメントは検出できず、実際の
1194パーサの代わりにはなりません。
1195ソースフィルタの唯一の安定した使用法は、暗号化、圧縮、バイトローダとして
1196バイナリコードをソースコードに戻すことです。
1197
1198=begin original
1199
1200See for example the limitations in L<Switch>, which uses source filters,
1201and thus is does not work inside a string eval, the presence of
1202regexes with embedded newlines that are specified with raw C</.../>
1203delimiters and don't have a modifier C<//x> are indistinguishable from
1204code chunks beginning with the division operator C</>. As a workaround
1205you must use C<m/.../> or C<m?...?> for such patterns. Also, the presence of
1206regexes specified with raw C<?...?> delimiters may cause mysterious
1207errors. The workaround is to use C<m?...?> instead. See
1208L<https://metacpan.org/pod/Switch#LIMITATIONS>.
1209
1210=end original
1211
1212例えば、L<Switch> での制限を参照してください;
1213これは、ソースフィルタを使っているために、文字列 eval の中や、
1214生の C</.../> 区切り文字で指定されて C<//x> 修飾子がなく、組み込みの改行を含む
1215正規表現の存在を、除算演算子 C</> で始まるコードの塊と区別できません。
1216回避策として、そのようなパターンでは C<m/.../> や C<m?...?> を使う
1217必要があります。
1218また、生の C<?...?> 区切り文字で指定された正規表現の存在は
1219不思議なエラーを引き起こすかも知れません。
1220回避方法は、代わりに C<m?...?> を使うことです。
1221L<https://metacpan.org/pod/Switch#LIMITATIONS> を参照してください。
1222
1223=begin original
1224
1225Currently the content of the C<__DATA__> block is not filtered.
1226
1227=end original
1228
1229現在のところ C<__DATA__> ブロックの中の内容はフィルタリングされません。
1230
1231=begin original
1232
1233Currently internal buffer lengths are limited to 32-bit only.
1234
1235=end original
1236
1237現在のところ内部バッファの長さは 32 ビットのみに制限されています。
1238
11731239=head1 THINGS TO LOOK OUT FOR
11741240
11751241(注意するべきこと)
11761242
11771243=over 5
11781244
11791245=item Some Filters Clobber the C<DATA> Handle
11801246
11811247(一部のフィルタは C<DATA> ハンドルを上書きします)
11821248
11831249=begin original
11841250
11851251Some source filters use the C<DATA> handle to read the calling program.
11861252When using these source filters you cannot rely on this handle, nor expect
11871253any particular kind of behavior when operating on it. Filters based on
11881254Filter::Util::Call (and therefore Filter::Simple) do not alter the C<DATA>
1189filehandle.
1255filehandle, but on the other hand totally ignore the text after C<__DATA__>.
11901256
11911257=end original
11921258
11931259一部のソースフィルタは、呼び出したプログラムを読み込むために
11941260C<DATA> ハンドルを使います。
11951261これらのソースフィルタを使うときには、このハンドルに依存したり、これを
11961262操作したときに何らかの特定の振る舞いを想定できません。
11971263Filter::Util::Call (従って Filter::Simple) を基礎としたフィルタは
1198C<DATA> ファイルハンドルを変更しません
1264C<DATA> ファイルハンドルを変更しませんが、一方、
1265C<__DATA__> の後のテキストは完全に無視されます。
11991266
12001267=back
12011268
12021269=head1 REQUIREMENTS
12031270
12041271(必要なもの)
12051272
12061273=begin original
12071274
12081275The Source Filters distribution is available on CPAN, in
12091276
12101277=end original
12111278
12121279ソースフィルタディストリビューションは CPAN の以下から利用可能です
12131280
12141281 CPAN/modules/by-module/Filter
12151282
12161283=begin original
12171284
12181285Starting from Perl 5.8 Filter::Util::Call (the core part of the
12191286Source Filters distribution) is part of the standard Perl distribution.
12201287Also included is a friendlier interface called Filter::Simple, by
12211288Damian Conway.
12221289
12231290=end original
12241291
12251292Perl 5.8 から、Filter::Util::Call (ソースフィルタ配布のコアの部分) は
12261293標準 Perl 配布の一部です。
12271294また、Damian Conway によるより親しみやすいインターフェースである
12281295Filter::Simple も含まれています。
12291296
12301297=head1 AUTHOR
12311298
12321299Paul Marquess E<lt>Paul.Marquess@btinternet.comE<gt>
12331300
1301Reini Urban E<lt>rurban@cpan.orgE<gt>
1302
12341303=head1 Copyrights
12351304
1236This article originally appeared in The Perl Journal #11, and is
1305The first version of this article originally appeared in The Perl
1237copyright 1998 The Perl Journal. It appears courtesy of Jon Orwant and
1306Journal #11, and is copyright 1998 The Perl Journal. It appears
1238The Perl Journal. This document may be distributed under the same terms
1307courtesy of Jon Orwant and The Perl Journal. This document may be
1239as Perl itself.
1308distributed under the same terms as Perl itself.
12401309
12411310=begin meta
12421311
12431312Translate: SHIRAKATA Kentaro <argrath@ub32.org>
12441313Status: completed
12451314
12461315=end meta