Gossamer Forum
Home : General : Perl Programming :

ASCII to Hex?

Quote Reply
ASCII to Hex?
There's the nifty way to go from hex code to characters:
s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg

Is there something as nice to convert special characters into the hex code? I need to pass variables to a cgi script which may or may not include single quotes, @, #, $, commas, etc.

Is there something nifty to do it all at once, or do I need to check for each one individually?

Thanks much!


------------------
JPD
Quote Reply
Re: ASCII to Hex? In reply to
I use:

sub urlencode {
# --------------------------------------------------------
# Escapes a string to make it suitable for printing as a URL.
#
my($toencode) = shift;
$toencode =~ s/([^a-zA-Z0-9_\-.])/uc sprintf("%%%02x",ord($1))/eg;
return $toencode;
}

in Links which was shamelessly stolen from CGI.pm.

Hope that helps!

Alex
Quote Reply
Re: ASCII to Hex? In reply to
Wonderful! Thanks Alex!

I'm not above second-hand petty thievery!! Smile



------------------
JPD
Quote Reply
Re: ASCII to Hex? In reply to
If you are doing alot of escaping and unescaping, you can also use the URI::Escape module. If you only do one or two, continue using the methods describe above, it will save some resources.

To use URI::Escape, just do the following:

use URI::Escape;

$safe = uri_escape("10% is enough\n");
$verysafe = uri_escape("foo", "\0-\377");
$str = uri_unescape($safe);

$safe stores the escaped string, $verysafe allows you to add additional characters that require escaping, and $str holds an unescaped string.

One item of interest I have noted in using the LWP module to download web pages and references is that file names with "&" characters often add an additional problem by denoting them as html substrings (&amp Wink. This cannot be used in a valid URL and must be additionally parsed. This may also occur for other values.



------------------
Fred Hirsch
Web Consultant & Programmer