perl – 如何在我加载的模块中使用Smart :: Comments而不更改其
如何为我的原始脚本以及它直接加载的任何模块指定Smart :: Comments.但是,由于它是一个源过滤器,如果应用于每个其他加载模块加载的每个模块,它可能会造成严重破坏.
例如,我的脚本包括 use Neu::Image; 我想为Neu :: Image加载 $perl -MSmart::Comments script.pl 不为Neu :: Image加载Smart :: Comments. 此行为在Smart::Comments documentation中描述:
我已经看过的一些其他事情: > Perl Command-Line Options 替代方法 解决方法
您几乎肯定希望通过适当设置$Smart_Comments将Smart :: Comments添加到包含此类的模块,然后添加
flip the switch in your environment.
藏匿,进口劫持猴子修补是疯狂的. 但也许你会遇到那种事情.假设你有Foo.pm: package Foo; use Exporter 'import'; our @EXPORT = qw/ foo /; #use Smart::Comments; sub foo { my @result; for (my $i = 0; $i < 5; $i++) { ### $i push @result => $i if $i % 2 == 0; } wantarray ? @result : @result; } 1; 普通用法: $perl -MFoo -e 'print foo,"n"' 024 当然,平凡无聊乏味.有了run-foo,我们采取大胆,潇洒的步骤! #! /usr/bin/perl use warnings; use strict; BEGIN { unshift @INC => &;inject_smart_comments; my %direct; open my $fh,"<",$0 or die "$0: open: $!"; while (<$fh>) { ++$direct{$1} if /^s*uses+([A-Z][:w]*)/; } close $fh; sub inject_smart_comments { my(undef,$path) = @_; s/[/]/::/g,s/.pm$// for my $mod = $path; if ($direct{$mod}) { open my $fh,$path or die "$0: open $path: $!"; return sub { return 0 unless defined($_ = <$fh>); s{^(s*packages+[A-Z][:w]*s*;s*)$} {$1 use Smart::Comments;n}; return 1; }; } } } use Foo; print foo,"n"; (请原谅紧凑性:我缩小它所以它将适合未展开的块.) 输出: $./run-foo ### $i: 0 ### $i: 1 ### $i: 2 ### $i: 3 ### $i: 4 024 ?万岁! 使用 通过尝试使用正则表达式解析Perl代码,例如,如果包声明本身不在一行上,则代码将中断.品尝季节. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |