简体   繁体   English

perl:传递子例程rexexp替换为搜索结果

[英]perl: passing subroutines rexexp replace with search results

i have the following perl subroutine: 我有以下perl子例程:

sub rep {

 defined ($filein = shift) || die ("no filein");
 defined ($fileout = shift) || die ("no fileout");
 $look = shift;
 $replace = shift;
 open (infile, "$filein")|| die;
 open (outfile, "> $fileout")|| die;
 while (<infile>) {
   s/$look/$replace/g;
   print outfile;
 }
(close the files)
}

and the following text: 以及以下文字:

kuku(fred) foo(3)
kuku(barney) foo(198)

i want to call it with the following structures: 我想用以下结构来调用它:

$look = kuku\((\w+)\) foo \((\d+)\),
$replace = gaga\(($1)\) bar\(($2)\).

but when i called the sub with the following (and it's variations), i couldn't make it accept the $1, $2 format: 但是当我使用以下(以及它的变体)调用sub时,我无法接受$ 1,$ 2格式:

&rep ($ARGV[0], $ARGV[1], 
    "kuku\\(\(\\w+\)\\) foo \\(\(\\d+\)\\)" , 
    "gaga\\(\(\$1\)\\) bar\\(\(\$2\)\\)");

all i get is: 我得到的是:

gaga($1) bar($2)
gaga($1) bar($2)

what am i doing wrong? 我究竟做错了什么? how can i make the subroutine identify the $1\\ $2 (...) as the search results of the search and replace? 如何让子程序识别$ 1 \\ $ 2(...)作为搜索和替换的搜索结果?

I'm not sure if substitution part in regex can be set in a way you want it without using eval /e , so this is how I would write this. 我不确定正则表达式中的替换部分是否可以在不使用eval /e情况下以你想要的方式设置,所以这就是我写这个的方法。

qr// parameter is real regex, followed by callback in which $_[0] is $1 qr//参数是真正的正则表达式,后跟回调,其中$_[0]$1

rep( $ARGV[0], $ARGV[1], qr/kuku\((\w+)\) foo \((\d+)\)/, sub { "gaga($_[0]) bar($_[1])" } );

sub rep {

  my ($filein, $fileout, $look, $replace) = @_;
  defined $filein or die "no filein";
  defined $fileout or die "no fileout";

  open (my $infile, "<", $filein) or die $!;
  open (my $outfile, ">", $fileout) or die $!;

  while (<$infile>) {
    s/$look/$replace->($1,$2)/ge;
    print $outfile;
  }
  # (close the files)
}

This could be even more simplified by just passing callback which would change $_ . 通过传递可以改变$_回调,可以更加简化这一点。

rep( $ARGV[0], $ARGV[1], sub { s|kuku\((\w+)\) foo \((\d+)\)|gaga($1) bar($2)| } );

sub rep {

  my ($filein, $fileout, $replace) = @_;
  defined $filein or die "no filein";
  defined $fileout or die "no fileout";

  open (my $infile, "<", $filein) or die $!;
  open (my $outfile, ">", $fileout) or die $!;

  while (<$infile>) {
    $replace->();
    print $outfile;
  }
  # (close the files)
}

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

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