Encoding URIs with URI::Escape

Sometimes we want to output anchor tags <A HREF="..."> referring to another CGI script, and pass parameters along with it, thus:

<A HREF="lookup.cgi?title=Programming Perl&publisher=O'Reilly">
O'Reilly's Programming Perl
</A>

However, spaces and apostrophes aren't allowed in URIs, so we have to encode them into the "percent-encoded" format. This format replaces most non-alphanumeric characters with two hexadecimal digits. For instance, a space becomes %20 and a tilde becomes %7E.

The Perl module we use to encode URIs in this manner is URI::Escape. Its documentation is available by typing perldoc URI::Escape.

Use it as follows:

#!/usr/bin/perl -w

use strict;
use URI::Escape;

my $book_lookup =
"lookup.cgi?title=Programming Perl&publisher=O'Reilly";

my $encoded_url = uri_escape($address);
my $original_url = uri_unescape($encoded_url);

Exercise

  1. Try out the above script cgi-bin/escape.cgi you'll need to print out the values of $encoded_url and $original_url