[英]In Perl, 'Use of uninitialized value in substitution iterator' error for $1 variable
从在stackoverflow.com上找到的其他示例中工作,我试图替换 Perl 中字符串上正则表达式匹配的第 N 个实例。 我的代码如下:
#!/usr/bin/env perl
use strict;
use warnings;
my $num_args = $#ARGV +1;
if($num_args != 3) {
print "\nUsage: replace_integer.pl occurance replacement to_replace";
print "\nE.g. `./replace_integer.pl 1 \"INTEGER_PLACEHOLDER\" \"method(0 , 1, 6);\"`";
print "\nWould output: \"method(INTEGER_PLACEMENT , 1, 6);\"\n";
exit;
}
my $string =$ARGV[2];
my $cont =0;
sub replacen {
my ($index,$original,$replacement) = @_;
$cont++;
return $cont == $index ? $replacement: $original;
}
sub replace_quoted {
my ($string, $index,$replacement) = @_;
$cont = 0; # initialize match counter
$string =~ s/[0-9]+/replacen($index,$1,$replacement)/eg;
return $string;
}
my $result = replace_quoted ( $string, $ARGV[0] ,$ARGV[1]);
print "RESULT: $result\n";
为了
./replace_integer.pl 3 "INTEGER_PLACEHOLDER" "method(0, 1 ,6);"
我希望输出
RESULT: method(0, 1 ,INTEGER_PLACEHOLDER);
不幸的是我得到的输出
RESULT: method(, ,INTEGER_PLACEHOLDER);
出现这些警告/错误
Use of uninitialized value in substitution iterator at ./replace_integer.pl line 26.
Use of uninitialized value in substitution iterator at ./replace_integer.pl line 26.
第 26 行是以下行:
$string =~ s/[0-9]+/replacen($index,$1,$replacement)/eg;
我已经确定这是由于 $1 未初始化。 据我了解,$1 应该具有最后一场比赛的价值。 鉴于我非常简单的正则表达式 ( [0-9]+
),我认为没有理由不初始化它。
我知道有更简单的方法可以在 sed 中查找和替换第 N 个实例,但是一旦克服了这个障碍(sed 不支持),我将需要 Perl 的后向和前向引用
有谁知道这个错误的原因以及如何解决它?
我正在使用 Perl v5.18.2 ,专为 x86_64-linux-gnu-thread-multi 构建
感谢您的时间。
$1 仅在您捕获模式后设置,例如:
$foo =~ /([0-9]+)/;
# $1 equals whatever was matched between the parens above
尝试将您的匹配包装在括号中以将其捕获为 1 美元
我会这样写
while
循环遍历字符串中出现的\\d+
模式。 当找到第 N 个匹配项时,使用内置数组@-
(最后一个匹配的开始)和@+
(最后一个匹配的结束)中的值调用substr
替换最后一个匹配
#!/usr/bin/env perl
use strict;
use warnings;
@ARGV = ( 3, 'INTEGER_PLACEHOLDER', 'method(0, 1, 6);' );
if ( @ARGV != 3 ) {
print qq{\nUsage: replace_integer.pl occurrence replacement to_replace};
print qq{\nE.g. `./replace_integer.pl 1 "INTEGER_PLACEHOLDER" "method(0 , 1, 6);"`};
print qq{\nWould output: "method(INTEGER_PLACEMENT , 1, 6);"\n};
exit;
}
my ( $occurrence, $replacement, $string ) = @ARGV;
my $n;
while ( $string =~ /\d+/g ) {
next unless ++$n == $occurrence;
substr $string, $-[0], $+[0]-$-[0], $replacement;
last;
}
print "RESULT: $string\n";
$ replace_integer.pl 3 INTEGER_PLACEHOLDER 'method(0, 1, 6);'
RESULT: method(0, 1, INTEGER_PLACEHOLDER);
$ replace_integer.pl 2 INTEGER_PLACEHOLDER 'method(0, 1, 6);'
RESULT: method(0, INTEGER_PLACEHOLDER, 6);
$ replace_integer.pl 1 INTEGER_PLACEHOLDER 'method(0, 1, 6);'
RESULT: method(INTEGER_PLACEHOLDER, 1, 6);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.