-4

我想用数组中的字符串替换 {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));

更新

我尝试使用下面的代码作为米勒的修改版本(第一个答案)

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.
4

1 回答 1

3

Perhaps a more generalized search and replace will serve you better:

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;

Outputs:

My String: zero one two
于 2014-07-09T23:12:31.583 回答