n'th regex match の抽出に関する以前の質問からフォローアップすると、見つかった場合は、一致を置き換える必要があります。
/e
抽出サブルーチンを定義して修飾子で代入して呼べないかと考えました。私は明らかに間違っていました (確かに、私はXY 問題を抱えていました)。
use strict;
use warnings;
sub extract_quoted { # à la codaddict
my ($string, $index) = @_;
while($string =~ /'(.*?)'/g) {
$index--;
return $1 if(! $index);
}
return;
}
my $string = "'How can I','use' 'PERL','to process this' 'line'";
extract_quoted ( $string, 3 );
$string =~ s/&extract_quoted($string,2)/'Perl'/e;
print $string; # Prints 'How can I','use' 'PERL','to process this' 'line'
もちろん、この手法には他にも多くの問題があります。
- 異なる位置に同一の一致がある場合はどうなりますか?
- 一致するものが見つからない場合はどうなりますか?
このような状況を踏まえて、これをどのように実装できるかを考えています。