简体   繁体   中英

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//)? Apparently, the following code does not work. Is there a way to do what I want?

~$  ./subsuffix.pl 
xxx_$1_outsuffix.txt

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:

$filename =~ s/$insuffix$/qq("$outsuffix")/ee;

您可以使用/e修饰符将替换模式视为要评估的代码:

$filename =~ s/$insuffix$/ "_" . $1 . "_outsuffix.txt" /e;

What you have in $outsuffix is a template. Templates don't magically process themselves. You'll need to invoke a processor. String::Interpolate understands templates such as yours.

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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM