In Perl, 'Use of uninitialized value in substitution iterator' error for $1 variable

前端 未结 2 1174
误落风尘
误落风尘 2021-01-15 17:03

Working from an example found else where on stackoverflow.com I am attempting to replace on the Nth instance of a regex match on a string in Perl. My code is as follows:

相关标签:
2条回答
  • 2021-01-15 17:23

    I would write it like this

    The while loop iterates over occurrences of the \d+ pattern in the string. When the Nth occurrence is found the last match is replaced using a call to substr using the values in built-in arrays @- (the start of the last match) and @+ (the end of the last match)

    #!/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";
    

    output

    $ 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);
    
    0 讨论(0)
  • 2021-01-15 17:38

    $1 is only set after you capture a pattern, for example:

    $foo =~ /([0-9]+)/;
    # $1 equals whatever was matched between the parens above
    

    Try wrapping your matching in parens to capture it to $1

    0 讨论(0)
提交回复
热议问题