簡體   English   中英

在 Perl 中,$1 變量的“在替換迭代器中使用未初始化的值”錯誤

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM