2

假设我有一个带有 Perl 代码的文件:有人知道,是否有一个模块可以在该文件中找到某个子例程的结束“}”。例如:

#!/usr/bin/env perl
use warnings;
use 5.012;

routine_one( '{°^°}' );

routine_two();

sub routine_one {
    my $arg = shift;
    if ( $arg =~ /}\z/ ) {
    say "Hello my }";
    }
}

sub routine_two {
    say '...' for 0 .. 10
}

该模块应该能够删除整个routine_one,或者它应该可以告诉我该例程中关闭“}”的行号。

4

3 回答 3

12

如果要解析 Perl 代码,则需要使用PPI 。

于 2010-11-12T07:44:40.870 回答
3
#!/usr/bin/env perl
use warnings;
use 5.012;
use PPI;

my $file = 'Example.pm';

my $doc = PPI::Document->new( $file );
$doc->prune( 'PPI::Token::Pod' );
$doc->prune( 'PPI::Token::Comment' );
my $subs = $doc->find( sub { $_[1]->isa('PPI::Statement::Sub') and $_[1]->name eq 'layout' } );
die if @$subs != 1;

my $new = PPI::Document->new( \qq(sub layout {\n    say "my new layout_code";\n}) );
my $subs_new = $new->find( sub { $_[1]->isa('PPI::Statement::Sub') and $_[1]->name eq 'layout' } );


$subs->[0]->block->insert_before( $subs_new->[0]->block ) or die $!;
$subs->[0]->block->remove or die $!;


# $subs->[0]->replace( $subs_new->[0] );
# The ->replace method has not yet been implemented at /usr/local/lib/perl5/site_perl/5.12.2/PPI/Element.pm line 743.

$doc->save( $file ) or die $!;
于 2010-11-12T11:24:49.300 回答
0

如果您的子例程不包含任何空行,例如您的示例中的空行,则以下内容将起作用:

#!/usr/bin/perl -w

use strict;

$^I = ".bkp";  # to create a backup file

{
   local $/ = ""; # one paragraph constitutes one record
   while (<>) {
      unless (/^sub routine_one \{.+\}\s+$/s) {  # 's' => '.' will also match "\n"
         print;
      }
   }
}
于 2010-11-12T09:44:18.463 回答