URL encoding using Perl

URL encoding, is a mechanism for encoding information in a Uniform Resource Identifier (URI) under certain circumstances. Although it is known as URL encoding it is, in fact, used more generally within the main Uniform Resource Identifier (URI) set, which includes both Uniform Resource Locator (URL) and Uniform Resource Name (URN).

The subroutine below will encode a string for use in a URL:

sub urlencode {

   my $string = $_[0];

   $string =~ s/([^a-zA-Z0-9_-.])/uc sprintf("%%%02x",ord($1))/eg;

   return($string);

}

To call the subroutine:

$toencode = urlencode($toencode);

posted March 10, 2010 in Perl