URI::EscapeSection: User Contributed Perl Documentation (3)Updated: 2004-01-14 |
URI::EscapeSection: User Contributed Perl Documentation (3)Updated: 2004-01-14 |
use URI::Escape;
$safe = uri_escape("10% is enough\n");
$verysafe = uri_escape("foo", "\0-\377");
$str = uri_unescape($safe);
"A" .. "Z", "a" .. "z", "0" .. "9",
";", "/", "?", ":", "@", "&", "=", "+", "$", ",", "[", "]", # reserved
"-", "_", ".", "!", "~", "*", "'", "(", ")"
In addition, any byte (octet) can be represented in a URI by an escape sequence: a triplet consisting of the character ``%'' followed by two hexadecimal digits. A byte can also be represented directly by a character, using the US-ASCII character for that octet (iff the character is part of "uric").
Some of the "uric" characters are reserved for use as delimiters or as part of certain URI components. These must be escaped if they are to be treated as ordinary data. Read RFC 2396 for further details.
The functions provided (and exported by default) from this module are:
The uri_escape() function takes an optional second argument that overrides the set of characters that are to be escaped. The set is specified as a string that can be used in a regular expression character class (between [ ]). E.g.:
"\x00-\x1f\x7f-\xff" # all control and hi-bit characters "a-z" # all lower case characters "^A-Za-z" # everything not a letter
The default set of characters to be escaped is all those which are not part of the "uric" character class shown above as well as the reserved characters. I.e. the default is:
"^A-Za-z0-9\-_.!~*'()"
This does the same as:
$string =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
but does not modify the string in-place as this RE would. Using the uri_unescape() function instead of the RE might make the code look cleaner and is a few characters less to type.
In a simple benchmark test I did, calling the function (instead of the inline RE above) if a few chars were unescaped was something like 40% slower, and something like 700% slower if none were. If you are going to unescape a lot of times it might be a good idea to inline the RE.
If the uri_unescape() function is passed multiple strings, then each one is returned unescaped.
The module can also export the %escapes hash, which contains the mapping from all 256 bytes to the corresponding escape codes. Lookup in this hash is faster than evaluating "sprintf("%%%02X", ord($byte))" each time.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.