From: PerlFAQ Server on
This is an excerpt from the latest version perlfaq9.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .

--------------------------------------------------------------------

9.10: How do I decode or create those %-encodings on the web?

(contributed by brian d foy)

Those "%" encodings handle reserved characters in URIs, as described in
RFC 2396, Section 2. This encoding replaces the reserved character with
the hexadecimal representation of the character's number from the
US-ASCII table. For instance, a colon, ":", becomes %3A.

In CGI scripts, you don't have to worry about decoding URIs if you are
using "CGI.pm". You shouldn't have to process the URI yourself, either
on the way in or the way out.

If you have to encode a string yourself, remember that you should never
try to encode an already-composed URI. You need to escape the components
separately then put them together. To encode a string, you can use the
the "URI::Escape" module. The "uri_escape" function returns the escaped
string:

my $original = "Colon : Hash # Percent %";

my $escaped = uri_escape( $original )

print "$string\n"; # 'Colon%20%3A%20Hash%20%23%20Percent%20%25%20'

To decode the string, use the "uri_unescape" function:

my $unescaped = uri_unescape( $escaped );

print $unescaped; # back to original

If you wanted to do it yourself, you simply need to replace the reserved
characters with their encodings. A global substitution is one way to do
it:

# encode
$string =~ s/([^^A-Za-z0-9\-_.!~*'()])/ sprintf "%%%0x", ord $1 /eg;

#decode
$string =~ s/%([A-Fa-f\d]{2})/chr hex $1/eg;



--------------------------------------------------------------------

The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in
perlfaq.pod.