[英]How can i search and replace multiple strings in a line - Perl
我想搜索并替换一行(字符串)中的多个字符串。
考虑我有三个变量
my $fruitone = "apple";
my $fruittwo = "orange";
my $fruitthree = "banana";
my string1 = "I have one ${fruitone} two ${fruittwo} and three ${fruitthree}";
我想用apple
等代替$fruitone
。
我的最终结果应该像
I have one apple two orange and three banana.
我可以用string1 =~ /$\\{(\\w+)\\}/$$1/;
替换一个string1 =~ /$\\{(\\w+)\\}/$$1/;
但是我在访问$2
和$3
物品时需要帮助
您的正则表达式只有一个捕获组,因此没有$2
或$3
可以访问。
如果要匹配多个内容,则需要在末尾添加g选项,如下所示
$string1=~ s/\$\{(\w+)\}/$$1/g;
注意:尽管它允许将任何变量替换为字符串,但这实际上不是编码的好方法。 您应该考虑使用散列来存储值以限制可以替换的值。
my %fruit=("fruitone" => "apple", "fruittwo"=>"orange","fruitthree" => "banana");
my $string1= 'I have one ${fruitone} two ${fruittwo} and three ${fruitthree}';
$string1 =~ s/\$\{(\w+)\}/$fruit{$1}/g;
这似乎可行:
my($fruitone, $fruittwo, $fruitthree) = ("apple", "orange", "banana");
my $string= 'I have one ${fruitone} two ${fruittwo} and three ${fruitthree}';
$string =~ s/(\$\{\w+\})/eval$1/ge;
或这个:
our($fruitone, $fruittwo, $fruitthree) = ("apple", "orange", "banana");
my $string= 'I have one ${fruitone} two ${fruittwo} and three ${fruitthree}';
$string =~ s/\$\{(\w+)\}/$$1/ge;
但是,如果可以的话,我建议您为水果使用哈希。
我认为您需要String::Interpolate
模块,但是由于我正在使用Android平板电脑,因此我目前无法使用非核心模块进行测试
我认为这应该工作
use strict;
use warnings 'all';
use String::Interpolate 'interpolate';
my $fruitone = "apple";
my $fruittwo = "orange";
my $fruitthree = "banana";
my $string = 'I have one ${fruitone} two ${fruittwo} and three ${fruitthree}';
print interpolate($string);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.