Creating a CGI Query String from a hash using Perl

Posted by robbiebow on 21 July, 2008 under perl | Be the First to Comment

Imagine the scenario: you have a hash of arguments you want to send as a CGI query string to somewhere on the web. Or you might, for instance, need to create an unsubscribe URL to include in your newsletter emails so that people can click a link to stop getting your newsletter.

Here’s a one line solution:

my %args = (
id     => 102546,
key    => 'kljdlasjd3289290mkdlmca',
list   => 12,
action => 'unsubcribe',
);
my $query_string = join '&', map { "$_=$args{$_}" } keys %args;
my $url = "http://example.com/newsletter?$query_string";

That should create your query string out of all the elements of your hash.

Add A Comment