rapture has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I am trying to manipulate URL with the following format:
http://myurl.com/page.pl?key1=va1&key2=val2&key3=val3
Now, I have this array:
@value = ("AAA", "BBB", "CCC", "DDD");
For the URL, I want to replace the values with the ones in the array one by one, in other words, I want to reconstruct the URL so that I get the following:
http://myurl.com/page.pl?key1=AAA&key2=val2&key3=val3 http://myurl.com/page.pl?key1=val1&key2=AAA&key3=val3 http://myurl.com/page.pl?key1=val1key2=val2&key3=AAA http://myurl.com/page.pl?key1=BBB&key2=val2&key3=val3 http://myurl.com/page.pl?key1=val1&key2=BBB&key3=val3 http://myurl.com/page.pl?key1=val1key2=val2&key3=BBB
and so on... What's the best way to do it? My Perl data structure is very rusty....

Replies are listed 'Best First'.
Re: Manipulating URLs
by davorg (Chancellor) on May 15, 2002 at 09:03 UTC

    Assuming you don't have any multi-valued CGI parameters, I'd probably do something like this:

    #!/usr/bin/perl -w use strict; use CGI qw(param url); my $me = url; my %params; my @params = param; $params{$_} = param($_) foreach @params; my @value = qw(AAA BBB CCC DDD); foreach my $v (@value) { foreach my $p (0 .. $#params) { print "$me?". join '&', map { "$params[$_]=" . ($p == $_ ? $v : $params{$params[$_]}) } 0 .. $#params; print "\n"; } print "\n"; }
    --
    <http://www.dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

•Re: Manipulating URLs
by merlyn (Sage) on May 15, 2002 at 14:13 UTC
    #!/usr/bin/perl use URI; my $ORIG = "http://myurl.com/page.pl?key1=va1&key2=val2&key3=val3"; my @value = qw(AAA BBB CCC DDD); my $u = URI->new($ORIG); my %params = $u->query_form; for my $newvalue (@value) { for my $key (sort keys %params) { my %p = (%params, $key, $newvalue); $u->query_form(%p); print "$u\n"; } }

    -- Randal L. Schwartz, Perl hacker

Re: Manipulating URLs
by hopes (Friar) on May 15, 2002 at 08:47 UTC
    Try this..., in this case you needn't any data structure, I think
    $url='http://myurl.com/page.pl?key1=val1&key2=val2&key3=val3'; @value = ("AAA", "BBB", "CCC", "DDD"); for $val (@value) { for (1..3) { $t=$url; $t=~s/\bkey$_=val$_\b/key$_=$val/i; print $t,$/; } }


    Hopes
    $_=$,=q,\,@4O,,s,^$,$\,,s,s,^,b9,s, $_^=q,$\^-]!,,print