in reply to •Re: Adding param to a specified URL
in thread Adding param to a specified URL

I failed to mention that I cannot replace existing parameters with the new one I am appending. The above code does this. So I have written the below which appears to work:
use strict;
use URI::URL;

sub addEnvVar ($$$$)
{
    my $URL = shift;
    my $name = shift;
    my $value = shift;
    my $returnRef = shift;

    # Create the URL as an object and extract already existing parameters.

    my $url = new URI::URL ($URL);
    my $qstring = $url->equery ();

    # Split the parameters up.

    my @params = split (/\&/, $qstring);

    # Split the name=value pairs up and place them in a parameter list.

    my @paramList;
    foreach my $param (@params)
    {
	my ($pname, $pvalue) = split (/\=/, $param);
	push (@paramList, $pname);
	push (@paramList, $pvalue);
    }

    # Add the new parameters to the end of the list.

    push (@paramList, $name);
    push (@paramList, $value);

    # Place the parameter list in the URL.

    $url->query_form (@paramList);

    # Get the resulting URL after appending the new variable.

    my $newURL = $url->as_string ();
    $$returnRef = $newURL;

    return 1;
}

The only minor problem I had testing this occurred when I tried to have parameters such as:
   carr%20ots=cooked
These would appear in the resulting URL as:
   carr%2520ots=cooked
But I'm not sure if its even legal to have such things in
parameters.  I think I'll stick with this for now.
Thanks a lot for your help,

Leigh
  • Comment on Re: •Re: Adding param to a specified URL

Replies are listed 'Best First'.
•Re: Re: •Re: Adding param to a specified URL
by merlyn (Sage) on Mar 28, 2002 at 19:21 UTC
    No no no. Far too much work.
    use URI; sub add_param { my $url = shift; # string my $name = shift; # string my $value = shift; #string $url = URI->new($url); $url->query_form($url->query_form, $name, $value); return $url->as_string; }
    But the problem is if you're going to call this more than once, you really ought to hoist it up to the outer level, or give it more than one pair at a time, or it will be doggy slow. </code>

    -- Randal L. Schwartz, Perl hacker