URL encode and decode functions for Perl.
1 2 3 4 5 6 7 8 9 10 11 12 13 | sub urlencode {
my $s = shift;
$s =~ s/ /+/g;
$s =~ s/([^A-Za-z0-9\+-])/sprintf("%%%02X", ord($1))/seg;
return $s;
}
sub urldecode {
my $s = shift;
$s =~ s/\%([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
$s =~ s/\+/ /g;
return $s;
}
|
We have CPAN:
CPAN!? Seriously? You want me to load an entire CPAN module for just 5 lines of code!? No wonder there is so much code bloat out there!
Thank you Trent! Quick. Clean. Efficient.
Yes, Quick, Clean, Wrong.
That's almost the same as used in URI::Escape.pm except '/chr(hex($1))/eg' instead of '/pack .../seg'.
Speaking up for Egor's point here:
Generalizing, it's a pretty good ideal to package up all but the most trivial solutions. For me, that's anything that doesn't make a good alias for SH. Posting to CPAN may or may not make sense, but it's worth thinking about whether having others review, test and potentially even improve your code will help your projects in the long term.
I can confirm this code is broken in regard to the + character however there is a 3 line solution in the webmin libraries that works just fine (even with unicode).
Passing the string '1 + 1 = 2' to urlencode returns '1+++1+%3D+2', where urlize returned '1%20%2B%201%20%3D%202'.