⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 perlfilter.1

📁 视频监控网络部分的协议ddns,的模块的实现代码,请大家大胆指正.
💻 1
📖 第 1 页 / 共 2 页
字号:
executable is the C preprocessor bundled with your C compiler..PPThe source filter distribution includes two modules that simplify thistask: \f(CW\*(C`Filter::exec\*(C'\fR and \f(CW\*(C`Filter::sh\*(C'\fR. Both allow you to run anyexternal executable. Both use a coprocess to control the flow of datainto and out of the external executable. (For details on coprocesses,see Stephens, W.R. \*(L"Advanced Programming in the \s-1UNIX\s0 Environment.\*(R"Addison-Wesley, \s-1ISBN\s0 0\-210\-56317\-7, pages 441\-445.) The differencebetween them is that \f(CW\*(C`Filter::exec\*(C'\fR spawns the external commanddirectly, while \f(CW\*(C`Filter::sh\*(C'\fR spawns a shell to execute the externalcommand. (Unix uses the Bourne shell; \s-1NT\s0 uses the cmd shell.) Spawninga shell allows you to make use of the shell metacharacters andredirection facilities..PPHere is an example script that uses \f(CW\*(C`Filter::sh\*(C'\fR:.PP.Vb 3\&    use Filter::sh \*(Aqtr XYZ PQR\*(Aq;\&    $a = 1;\&    print "XYZ a = $a\en";.Ve.PPThe output you'll get when the script is executed:.PP.Vb 1\&    PQR a = 1.Ve.PPWriting a source filter as a separate executable works fine, but asmall performance penalty is incurred. For example, if you execute thesmall example above, a separate subprocess will be created to run theUnix \f(CW\*(C`tr\*(C'\fR command. Each use of the filter requires its own subprocess.If creating subprocesses is expensive on your system, you might want toconsider one of the other options for creating source filters..SH "WRITING A SOURCE FILTER IN PERL".IX Header "WRITING A SOURCE FILTER IN PERL"The easiest and most portable option available for creating your ownsource filter is to write it completely in Perl. To distinguish thisfrom the previous two techniques, I'll call it a Perl source filter..PPTo help understand how to write a Perl source filter we need an exampleto study. Here is a complete source filter that performs rot13decoding. (Rot13 is a very simple encryption scheme used in Usenetpostings to hide the contents of offensive posts. It moves every letterforward thirteen places, so that A becomes N, B becomes O, and Zbecomes M.).PP.Vb 1\&   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;.Ve.PPAll Perl source filters are implemented as Perl classes and have thesame basic structure as the example above..PPFirst, we include the \f(CW\*(C`Filter::Util::Call\*(C'\fR module, which exports anumber of functions into your filter's namespace. The filter shownabove uses two of these functions, \f(CW\*(C`filter_add()\*(C'\fR and\&\f(CW\*(C`filter_read()\*(C'\fR..PPNext, we create the filter object and associate it with the sourcestream by defining the \f(CW\*(C`import\*(C'\fR function. If you know Perl wellenough, you know that \f(CW\*(C`import\*(C'\fR is called automatically every time amodule is included with a use statement. This makes \f(CW\*(C`import\*(C'\fR the idealplace to both create and install a filter object..PPIn the example filter, the object (\f(CW$ref\fR) is blessed just like anyother Perl object. Our example uses an anonymous array, but this isn'ta requirement. Because this example doesn't need to store any contextinformation, we could have used a scalar or hash reference just aswell. The next section demonstrates context data..PPThe association between the filter object and the source stream is madewith the \f(CW\*(C`filter_add()\*(C'\fR function. This takes a filter object as aparameter (\f(CW$ref\fR in this case) and installs it in the source stream..PPFinally, there is the code that actually does the filtering. For thistype of Perl source filter, all the filtering is done in a methodcalled \f(CW\*(C`filter()\*(C'\fR. (It is also possible to write a Perl source filterusing a closure. See the \f(CW\*(C`Filter::Util::Call\*(C'\fR manual page for moredetails.) It's called every time the Perl parser needs another line ofsource to process. The \f(CW\*(C`filter()\*(C'\fR method, in turn, reads lines fromthe source stream using the \f(CW\*(C`filter_read()\*(C'\fR function..PPIf a line was available from the source stream, \f(CW\*(C`filter_read()\*(C'\fRreturns a status value greater than zero and appends the line to \f(CW$_\fR.A status value of zero indicates end-of-file, less than zero means anerror. The filter function itself is expected to return its status inthe same way, and put the filtered line it wants written to the sourcestream in \f(CW$_\fR. The use of \f(CW$_\fR accounts for the brevity of most Perlsource filters..PPIn order to make use of the rot13 filter we need some way of encodingthe source file in rot13 format. The script below, \f(CW\*(C`mkrot13\*(C'\fR, doesjust that..PP.Vb 5\&    die "usage mkrot13 filename\en" unless @ARGV;\&    my $in = $ARGV[0];\&    my $out = "$in.tmp";\&    open(IN, "<$in") or die "Cannot open file $in: $!\en";\&    open(OUT, ">$out") or die "Cannot open file $out: $!\en";\&\&    print OUT "use Rot13;\en";\&    while (<IN>) {\&       tr/a\-zA\-Z/n\-za\-mN\-ZA\-M/;\&       print OUT;\&    }\&\&    close IN;\&    close OUT;\&    unlink $in;\&    rename $out, $in;.Ve.PPIf we encrypt this with \f(CW\*(C`mkrot13\*(C'\fR:.PP.Vb 1\&    print " hello fred \en";.Ve.PPthe result will be this:.PP.Vb 2\&    use Rot13;\&    cevag "uryyb serq\ea";.Ve.PPRunning it produces this output:.PP.Vb 1\&    hello fred.Ve.SH "USING CONTEXT: THE DEBUG FILTER".IX Header "USING CONTEXT: THE DEBUG FILTER"The rot13 example was a trivial example. Here's another demonstrationthat shows off a few more features..PPSay you wanted to include a lot of debugging code in your Perl scriptduring development, but you didn't want it available in the releasedproduct. Source filters offer a solution. In order to keep the examplesimple, let's say you wanted the debugging output to be controlled byan environment variable, \f(CW\*(C`DEBUG\*(C'\fR. Debugging code is enabled if thevariable exists, otherwise it is disabled..PPTwo special marker lines will bracket debugging code, like this:.PP.Vb 5\&    ## DEBUG_BEGIN\&    if ($year > 1999) {\&       warn "Debug: millennium bug in year $year\en";\&    }\&    ## DEBUG_END.Ve.PPWhen the \f(CW\*(C`DEBUG\*(C'\fR environment variable exists, the filter ensures thatPerl parses only the code between the \f(CW\*(C`DEBUG_BEGIN\*(C'\fR and \f(CW\*(C`DEBUG_END\*(C'\fRmarkers. That means that when \f(CW\*(C`DEBUG\*(C'\fR does exist, the code aboveshould be passed through the filter unchanged. The marker lines canalso be passed through as-is, because the Perl parser will see them ascomment lines. When \f(CW\*(C`DEBUG\*(C'\fR isn't set, we need a way to disable thedebug code. A simple way to achieve that is to convert the linesbetween the two markers into comments:.PP.Vb 5\&    ## DEBUG_BEGIN\&    #if ($year > 1999) {\&    #     warn "Debug: millennium bug in year $year\en";\&    #}\&    ## DEBUG_END.Ve.PPHere is the complete Debug filter:.PP.Vb 1\&    package Debug;\&\&    use strict;\&    use warnings;\&    use Filter::Util::Call;\&\&    use constant TRUE => 1;\&    use constant FALSE => 0;\&\&    sub import {\&       my ($type) = @_;\&       my (%context) = (\&         Enabled => defined $ENV{DEBUG},\&         InTraceBlock => FALSE,\&         Filename => (caller)[1],\&         LineNo => 0,\&         LastBegin => 0,\&       );\&       filter_add(bless \e%context);\&    }\&\&    sub Die {\&       my ($self) = shift;\&       my ($message) = shift;\&       my ($line_no) = shift || $self\->{LastBegin};\&       die "$message at $self\->{Filename} line $line_no.\en"\&    }\&\&    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 (/^\es*##\es*DEBUG_BEGIN/ ) {\&              $self\->Die("Nested DEBUG_BEGIN", $self\->{LineNo})\&          } elsif (/^\es*##\es*DEBUG_END/) {\&              $self\->{InTraceBlock} = FALSE;\&          }\&\&          # comment out the debug lines when the filter is disabled\&          s/^/#/ if ! $self\->{Enabled};\&       } elsif ( /^\es*##\es*DEBUG_BEGIN/ ) {\&          $self\->{InTraceBlock} = TRUE;\&          $self\->{LastBegin} = $self\->{LineNo};\&       } elsif ( /^\es*##\es*DEBUG_END/ ) {\&          $self\->Die("DEBUG_END has no DEBUG_BEGIN", $self\->{LineNo});\&       }\&       return $status;\&    }\&\&    1;.Ve.PPThe big difference between this filter and the previous example is theuse of context data in the filter object. The filter object is based ona hash reference, and is used to keep various pieces of contextinformation between calls to the filter function. All but two of thehash fields are used for error reporting. The first of those two,Enabled, is used by the filter to determine whether the debugging codeshould be given to the Perl parser. The second, InTraceBlock, is truewhen the filter has encountered a \f(CW\*(C`DEBUG_BEGIN\*(C'\fR line, but has not yetencountered the following \f(CW\*(C`DEBUG_END\*(C'\fR line..PPIf you ignore all the error checking that most of the code does, theessence of the filter is as follows:.PP.Vb 4\&    sub filter {\&       my ($self) = @_;\&       my ($status);\&       $status = filter_read();\&\&       # deal with EOF/error first\&       return $status if $status <= 0;\&       if ($self\->{InTraceBlock}) {\&          if (/^\es*##\es*DEBUG_END/) {\&             $self\->{InTraceBlock} = FALSE\&          }\&\&          # comment out debug lines when the filter is disabled\&          s/^/#/ if ! $self\->{Enabled};\&       } elsif ( /^\es*##\es*DEBUG_BEGIN/ ) {\&          $self\->{InTraceBlock} = TRUE;\&       }\&       return $status;\&    }.Ve.PPBe warned: just as the C\-preprocessor doesn't know C, the Debug filterdoesn't know Perl. It can be fooled quite easily:.PP.Vb 3\&    print <<EOM;\&    ##DEBUG_BEGIN\&    EOM.Ve.PPSuch things aside, you can see that a lot can be achieved with a modestamount of code..SH "CONCLUSION".IX Header "CONCLUSION"You now have better understanding of what a source filter is, and youmight even have a possible use for them. If you feel like playing withsource filters but need a bit of inspiration, here are some extrafeatures you could add to the Debug filter..PPFirst, an easy one. Rather than having debugging code that isall-or-nothing, it would be much more useful to be able to controlwhich specific blocks of debugging code get included. Try extending thesyntax for debug blocks to allow each to be identified. The contents ofthe \f(CW\*(C`DEBUG\*(C'\fR environment variable can then be used to control whichblocks get included..PPOnce you can identify individual blocks, try allowing them to benested. That isn't difficult either..PPHere is an interesting idea that doesn't involve the Debug filter.Currently Perl subroutines have fairly limited support for formalparameter lists. You can specify the number of parameters and theirtype, but you still have to manually take them out of the \f(CW@_\fR arrayyourself. Write a source filter that allows you to have a namedparameter list. Such a filter would turn this:.PP.Vb 1\&    sub MySub ($first, $second, @rest) { ... }.Ve.PPinto this:.PP.Vb 6\&    sub MySub($$@) {\&       my ($first) = shift;\&       my ($second) = shift;\&       my (@rest) = @_;\&       ...\&    }.Ve.PPFinally, if you feel like a real challenge, have a go at writing afull-blown Perl macro preprocessor as a source filter. Borrow theuseful features from the C preprocessor and any other macro processorsyou know. The tricky bit will be choosing how much knowledge of Perl'ssyntax you want your filter to have..SH "THINGS TO LOOK OUT FOR".IX Header "THINGS TO LOOK OUT FOR".ie n .IP "Some Filters Clobber the ""DATA"" Handle" 5.el .IP "Some Filters Clobber the \f(CWDATA\fR Handle" 5.IX Item "Some Filters Clobber the DATA Handle"Some source filters use the \f(CW\*(C`DATA\*(C'\fR handle to read the calling program.When using these source filters you cannot rely on this handle, nor expectany particular kind of behavior when operating on it.  Filters based onFilter::Util::Call (and therefore Filter::Simple) do not alter the \f(CW\*(C`DATA\*(C'\fRfilehandle..SH "REQUIREMENTS".IX Header "REQUIREMENTS"The Source Filters distribution is available on \s-1CPAN\s0, in.PP.Vb 1\&    CPAN/modules/by\-module/Filter.Ve.PPStarting from Perl 5.8 Filter::Util::Call (the core part of theSource Filters distribution) is part of the standard Perl distribution.Also included is a friendlier interface called Filter::Simple, byDamian Conway..SH "AUTHOR".IX Header "AUTHOR"Paul Marquess <Paul.Marquess@btinternet.com>.SH "Copyrights".IX Header "Copyrights"This article originally appeared in The Perl Journal #11, and iscopyright 1998 The Perl Journal. It appears courtesy of Jon Orwant andThe Perl Journal.  This document may be distributed under the same termsas Perl itself.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -