regexperlirssi

replace {x} with param in string


I want to replace {x} where x is a number from 1-10 with a string from an array. The array is populated by splitting a string with whitespace.

I have put together some code but the regex is probably wrong.

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

Update

I've tried using the below code as a modified version of Miller's (the first answer)

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

Output

Not found 1 at myscript.pl line 160.

Solution

  • 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