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:
#!/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";
For
./replace_integer.pl 3 "INTEGER_PLACEHOLDER" "method(0, 1 ,6);"
I'd expect an output of
RESULT: method(0, 1 ,INTEGER_PLACEHOLDER);
Unfortunately I get an output of
RESULT: method(, ,INTEGER_PLACEHOLDER);
With these warnings/errors
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.
Line 26 is the following line:
$string =~ s/[0-9]+/replacen($index,$1,$replacement)/eg;
I have determined this is due to $1 being uninitialised. To my understanding $1 should have the value of the last match. Given my very simple regex ([0-9]+
) I see no reason why it should be uninitialised.
I am aware there are easier ways to find and replace the Nth instance in sed but I will require Perl's back and forward references once this hurdle is overcome (not supported by sed)
Does anyone know the cause of this error and how to fix it?
I am using Perl v5.18.2 , built for x86_64-linux-gnu-thread-multi
Thank you for your time.
s/([0-9]+)/replacen($index,$1,$replacement)/eg;
. See stackoverflow.com/questions/19387952/…$&
instead of$1