繁体   English   中英

如何从 Perl 脚本中删除除 shebang 行之外的所有注释?

[英]How can I strip all comments from a Perl script except for the shebang line?

我有一个 Perl 脚本,它从其他 Perl 脚本中删除注释:

open (INFILE, $file);
@data = <INFILE>;

foreach $data (@data)
{
    $data =~ s/#.*/ /g;
    print "$data";
}

问题是,此代码还删除了 shebang 行:

#!/usr/bin/perl

除了shebang,我怎样才能删除评论?

编写代码来去除注释并非易事,因为#字符可以在其他上下文中使用,而不仅仅是注释。 改用perltidy

perltidy --delete-block-comments --delete-side-comments foo

将从文件foo删除#注释(但不是 POD)并将输出写入foo.tdy shebang没有被剥离。

有一个方法PPR::decomment()可以使用:

use strict;
use warnings;
use PPR;

my $document = <<'EOF';
print "\n###################################\n";
print '\n###################################\n';
print '\nFollowed by comment \n'; # The comment
return $function && $function !~ /^[\s{}#]/;
EOF

my $res = PPR::decomment( $document );
print $res;

输出

print "\n###################################\n";
print '\n###################################\n';
print '\nFollowed by comment \n'; 
return $function && $function !~ /^[\s{}#]/;

如果不是练习, perltidy就是这样做的方法。 还有用于解析 perl 的PPI 可以使用PPI::Token::Comment标记来做一些比剥离更复杂的事情。

但是,要回答您的直接问题,请不要尝试在单个正则表达式中解决所有问题。 相反,将您的问题分解为逻辑信息和逻辑片段。 在这种情况下,如果您想跳过第一行,请使用逐行处理来方便地在$设置当前行号。

use strict;
use warnings;
use autodie;

my $file = '... your file...';

open my $fh, '<', $file;

while (<$fh>) {
    if ($. != 1) {
        s/#.*//;
    }

    print;
}

免责声明

正如每个人已经说过的那样,使用正则表达式解决这个问题的方法肯定是有缺陷的。 但是,我要让您的讲师受益匪浅,并且她/他的目标是通过故意给您一个超出正则表达式能力范围的问题来进行教学。 很好地找到所有这些边缘情况并弄清楚如何处理它们。

无论您做什么,都不要尝试使用单个正则表达式来解决它们。 打破你的问题,并使用大量的if的和elsif

由于您要求使用正则表达式解决方案:

'' =~ /(?{
   system("perltidy", "--delete-block-comments", "--delete-side-comments", $file);
   die "Can't launch perltidy: $!\n"                   if $? == -1;
   die "perltidy killed by signal ".( $? & 0x7F )."\n" if $? & 0x7F;
   die "perltidy exited with error ".( $? >> 8 )."\n"  if $? >> 8;
});

您似乎倾向于使用以下内容:

#!/usr/bin/perl
while (<>) {
   if ($. != 1) {
      s/#.*//;
   }
   print;
}

但它本身不起作用:

$ chmod u+x stripper.pl

$ stripper.pl stripper.pl >stripped_stripper.pl

$ chmod u+x stripped_stripper.pl

$ stripped_stripper.pl stripper.pl
Substitution pattern not terminated at ./stripped_stripper.pl line 4.

$ cat stripped_stripper.pl
#!/usr/bin/perl
while (<>) {
   if ($. != 1) {
      s/
   }
   print;
}

它也无法删除第一行的注释:

$ cat >first.pl
# This is my first Perl program!
print "Hello, World!\n";

$ stripper.pl first.pl
# This is my first Perl program!
print "Hello, World!\n";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM