I've found this Perl code:
$url = "http://example.com/?param1=#param1#¶m2=#param2#"
$param1="hello";
$param2="world";
$url =~ s/#param1#/$param1/g;
$url =~ s/#param2#/$param2/g;
where the =~
operator applies a regex and replaces the original variable ($url
).
Is there a way in Perl to apply the change to another variable, and apply the two regexes in one statement?
Something that looks like this:
$url_template = "http://example.com/?param1=#param1#¶m2=#param2#"
$param1="hello";
$param2="world";
$url = $url_template ~ s/#param1#/$param1/g ~ s/#param2#/$param2/g;
This code does not work. The question is: how to make it work?
Also, is there a better way to format strings? For example
String.format("http://example.com/?param1={param1}¶m2={param2}", {"param1": param1, "param2": param2}).
Finally, is there a better way to format URL parameters (so that they are encoded properly)? For example
URL.format("http://example.com/?param1={param1}¶m2={param2}", {"param1": param1, "param2": param2}).
Update: Full answer based on choroba and aleroot:
my $template_url = "http://example.com/?param1=#param1#¶m2=#param2#";
my %params = (param1 => 'hello1', param2 => 'world2');
(my $url = $template_url) =~ s/#(.*?)#/$params{$1}/g;
For encoding of URLs, use URL::Encode.