#!/usr/bin/perl -s
# urlencode - URL or HTML encode or decode the given strings
# Steve Kinzler, kinzler@cs.indiana.edu, Jan 03/Aug 09
# http://www.cs.indiana.edu/~kinzler/home.html#web
$usage = "$0 [ -d ] [ -H [ -q ] ] [ arg ... ]
-d decode instead of encode
-H HTML coding instead of URL coding
-q also HTML encode double-quotes
If no arguments are given, standard input is used.\n";
die $usage if $h;
$in = (@ARGV) ? join(' ', @ARGV) : join('', <>);
print $H ? ($d ? &htmldecode($in) : &htmlencode($in))
: ($d ? &urldecode( $in) : &urlencode( $in), "\n");
###############################################################################
sub urlencode {
local($_, $mlm) = (join('', @_), $*);
$* = 1;
s/[^ \w!\$'()*,\-.]/sprintf('%%%02x', ord $&)/ge;
s/ /+/g;
$* = $mlm;
return $_;
}
sub urldecode {
local($_, $mlm) = (join('', @_), $*);
$* = 1;
s/\+/ /g;
s/%([\da-f]{2})/pack('C', hex $1)/gie;
$* = $mlm;
return $_;
}
sub htmlencode {
local($_, $mlm) = (join('', @_), $*);
$* = 1;
s/&/&/g;
s/</g;
s/>/>/g;
s/"/"/g if $q;
$* = $mlm;
return $_;
}
sub htmldecode {
local($_, $mlm) = (join('', @_), $*);
$* = 1;
s/&/&/g;
s/<//g;
s/"/"/g;
$* = $mlm;
return $_;
}