找到子程序的最后一个“}”

时间:2010-11-12 07:28:03

标签: regex perl parsing module subroutine

假设我有一个带有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,或者它应该告诉我该例程中结束“}”的行号。

3 个答案:

答案 0 :(得分:12)

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

答案 1 :(得分: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 $!;

答案 2 :(得分: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;
      }
   }
}