使用变量的perl正则表达式

时间:2013-12-18 16:30:31

标签: regex perl

这是一段代码:

$regex_match = "(.*).txt";
$replacement = "\$1.pdf";
my $new_replacement = ""; #???
my $new_regex_match = quotemeta ($regex_match); #???
$from = "test.txt";
(my $to = $from) =~ s{$regex_match}{$replacement}g;
print "From " . $from . " To " . $to  . "\n";

输出: 从test.txt到$ 1.pdf

我相信1美元不会被插值。需要改变什么? new_replacement和/或new_regex_match是什么?

1 个答案:

答案 0 :(得分:2)

您需要s///ee来强制进行评估。

my $regex_match = '(.*)\.txt';
my $replacement = '$1.".pdf"';

while (<>) {
    s/$regex_match/$replacement/ee;
    print;
}