我想用数组中的字符串替换{x},其中x是1-10中的数字。 通过用空格分割字符串来填充数组。
我已经整理了一些代码,但正则表达式可能是错误的。
my @params = split(' ', "Paramtest: {0} {1} {2}");
my $count = @params;
for (my $i = 0; $i <= $count; $i++) {
my $param = @params->[$i];
$cmd_data =~ s/{"$i"}/"$param"/;
if(!$cmd_data) {
$server->command(sprintf("msg $target %s incorrect syntax for %s.", $nick, "!params p1 p2 p3"));
return;
}
}
$server->command(sprintf("msg $target %s.", $cmd_data));
我尝试使用以下代码作为Miller的修改版本(第一个答案)
my @params = split(' ', "!fruit oranges apples");
my $cmd_data = "Fruits: {0} {1}";
$cmd_data =~ s{\{(\d+)\}}{
$params[$1] // die "Not found $1" #line 160
}eg;
$server->command(sprintf("msg $target %s.", $cmd_data));
输出
Not found 1 at myscript.pl line 160.
答案 0 :(得分:3)
也许更广泛的搜索和替换会更好地为您服务:
use strict;
use warnings;
my @params = qw(zero one two three four five six seven eight);
my $string = 'My String: {0} {1} {2}';
$string =~ s{\{(\d+)\}}{
$params[$1] // die "Not found $1"
}eg;
print $string;
输出:
My String: zero one two