/
Escape.pm
69 lines (52 loc) · 1.49 KB
/
Escape.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#
# $Id: Escape.pm,v 3.2 1995/08/10 13:44:59 aas Exp $
#
package URI::Escape;
=head1 NAME
uri_escape - Escape unsafe characters
uri_unescape - Unescape escaped characters
=head1 SYNOPSIS
use URI::Escape;
$safe = uri_escape("10% is enough\n");
$str = uri_unescape($safe);
=head1 DESCRIPTION
This module provide functions to escape and unescape URIs strings.
Some characters are regarded as "unsafe" and must be escaped in
accordance with RFC 1738. Escaped characters are represented by a
triplet consisting of the character "%" followed by two hexadecimal
digits.
The uri_escape() function takes an optional second argument that
overrides the set of characters that are to be escaped.
=head1 SEE ALSO
L<URI::URL>
=cut
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(uri_escape uri_unescape);
@EXPORT_OK = qw(%escapes);
# Build a char->hex map
for (0..255) {
$escapes{chr($_)} = sprintf("%%%02X", $_);
}
sub uri_escape
{
my($text, $patn) = @_;
if ($patn){
$text =~ s/([$patn])/$escapes{$1}/g;
return $text;
}
# Default unsafe characters. (RFC1738 section 2.2)
$text =~ s/([\x00-\x20"#%;<>?{}|\\\\^~`\[\]\x7F-\xFF])/$escapes{$1}/g; #"
$text;
}
sub uri_unescape
{
my($text) = @_;
return undef unless defined $text;
# Note from RFC1630: "Sequences which start with a percent sign
# but are not followed by two hexadecimal characters are reserved
# for future extension"
$text =~ s/%([\dA-Fa-f][\dA-Fa-f])/chr(hex($1))/eg;
$text;
}
1;