Skip to content

Instantly share code, notes, and snippets.

@scovetta
Created September 16, 2014 06:03
Show Gist options
  • Save scovetta/7671406ad3c864569b2f to your computer and use it in GitHub Desktop.
Save scovetta/7671406ad3c864569b2f to your computer and use it in GitHub Desktop.
Caching URL encoder for Perl
#!/usr/bin/perl -w
use strict;
use warnings;
use feature (qw/state/);
sub encode {
state %hashMap;
if (not %hashMap) {
%hashMap = ();
my $encodeStr = "!\"#$%&'()*+,-./0123456789:;<=>?@[\\]^_`" .
"abcdefghijklmnopqrstuvwxyz{|}~ ABCDEFGHIJK" .
"LMNOPQRSTUVXYZ";
for (my $i=0; $i<length($encodeStr); $i++) {
my $ch = substr($encodeStr, $i, 1);
$hashMap{$ch} = sprintf('%%%x', ord($ch));
}
}
my $target = shift;
if (exists($hashMap{$target})) {
return $hashMap{$target};
} else {
return $target;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment