簡體   English   中英

如何在perl(s //)中使用變量作為替換文本?

[英]How to use a variable as the substitution text in perl (s//)?

我想在Perl(s //)中使用變量作為替換文本嗎? 顯然,以下代碼不起作用。 有什么方法可以做我想要的嗎?

~$  ./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";

通常不評估該替換。 您必須在替換的末尾添加幾個/e ,並添加一些引號,以使其在第一次評估后保持有效的表達式:

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

您可以使用/e修飾符將替換模式視為要評估的代碼:

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

$outsuffix是一個模板。 模板不會神奇地處理自己。 您需要調用處理器。 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM