[英]How to use a variable as the substitution text in perl (s//)?
I want to use a variable as the substitution text in perl (s//)? 我想在Perl(s //)中使用变量作为替换文本吗? Apparently, the following code does not work.
显然,以下代码不起作用。 Is there a way to do what I want?
有什么方法可以做我想要的吗?
~$ ./subsuffix.pl
xxx_$1_outsuffix.txt
subsuffix.pl : subsuffix.pl:
#!/usr/bin/env perl
use strict;
use warnings;
my $filename="xxx_5p_insuffix.txt";
my $insuffix="_((5|3)p)_insuffix.txt";
my $outsuffix = '_$1_outsuffix.txt';
#result of the following is what I expect
#$filename =~ s/$insuffix$/_$1_outsuffix.txt/;
#But I want used a variable as the substitution text.
#Unfortunately, the following do not work.
$filename =~ s/$insuffix$/$outsuffix/;
print "$filename\n";
The replacement is normally not evaluated. 通常不评估该替换。 You have to add a couple of
/e
's at the end of the substitution and add some quotes to keep it a valid expression after the 1st evaluation: 您必须在替换的末尾添加几个
/e
,并添加一些引号,以使其在第一次评估后保持有效的表达式:
$filename =~ s/$insuffix$/qq("$outsuffix")/ee;
您可以使用/e
修饰符将替换模式视为要评估的代码:
$filename =~ s/$insuffix$/ "_" . $1 . "_outsuffix.txt" /e;
What you have in $outsuffix
is a template. $outsuffix
是一个模板。 Templates don't magically process themselves. 模板不会神奇地处理自己。 You'll need to invoke a processor.
您需要调用处理器。 String::Interpolate understands templates such as yours.
String :: Interpolate可以理解您的模板。
use String::Interpolate qw( interpolate );
my $filename="xxx_5p_insuffix.txt";
my $insuffix="_((5|3)p)_insuffix.txt";
my $outsuffix = '_$1_outsuffix.txt';
$filename =~ s/$insuffix$/interpolate($outsuffix)/e;
print "$filename\n";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.