2

I've found this Perl code:

$url = "http://example.com/?param1=#param1#&param2=#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#&param2=#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}&param2={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}&param2={param2}", {"param1": param1, "param2": param2}).

Update: Full answer based on choroba and aleroot:

my $template_url = "http://example.com/?param1=#param1#&param2=#param2#";
my %params = (param1 => 'hello1', param2 => 'world2');
(my $url = $template_url) =~ s/#(.*?)#/$params{$1}/g;

For encoding of URLs, use URL::Encode.

4

2 回答 2

6

The Perl binding operator is =~, not ~=. It is not possible to make two substitutions at once, however it is possible to make the substitution happen as many times as needed with /g:

#!/usr/bin/perl
use warnings;
use strict;

my $url = 'http://example.com/?param1=#param1#&param2=#param2#';
my %params = ( param1 => 'hello',
               param2 => 'world',
             );
$url =~ s/#(.*?)#/$params{$1}/g;
print $url, "\n";

For encoding of URLs, use URL::Encode.

于 2013-08-15T09:19:08.040 回答
1

To store the regex substitution to another variable ($newurl) :

($newurl = $url) =~ s/#param1#/$param1/g;
于 2013-08-15T09:19:16.150 回答