my @storedContent = ();
my $string = "some content are stored....";
$string=~s/<whateverfind>/<whateverreplace>/gs && push @storedContent, $&;
print join "\n", @storedContent; #printing just <whateverfind>
我需要将找到的和相应的替换字符串存储在数组中。
我的预期输出是:
<whateverfind> <whateverreplace>
....
....
我该怎么做?
答案 0 :(得分:2)
s///
返回替换次数,因此您可以执行此操作:
push @storedContent,
('<whateverfind> <whateverreplace>') x $string =~ s/<whateverfind>/<whateverreplace>/g;
如果你想动态地做到这一点:
$string =~ s/<whateverfind>/
my $r = "<whateverreplace>";
push @storedContent, "$& $r";
$r
/eg;
请注意,使用$&
会对旧程序中程序中的所有正则表达式造成性能下降,因此您可能希望使用显式捕获:
$string =~ s/(<whateverfind>)/
my $r = "<whateverreplace>";
push @storedContent, "$1 $r";
$r
/eg;