Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Character conversion

by Anonymous Monk
on Feb 22, 2006 at 16:57 UTC ( [id://532012]=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Wise Monks,
I have a question regarding special character conversions. At the moment I convert a url string in the following way:
$url_string =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
How would I convert the other way around? I need to convert characters such as '&',':',etc to their '%' hex equivalents?
Thanks in advance for any help

Replies are listed 'Best First'.
Re: Character conversion
by Roy Johnson (Monsignor) on Feb 22, 2006 at 17:08 UTC
    If you insist on rolling your own, something like this:
    $url_string =~ s/([^[:alnum:]])/sprintf '%%%02x', ord($1)/eg; # thanks + for the 02, ikegami
    but it's probably better to find a module like URI::Escape.

    Caution: Contents may have been coded under pressure.

      That should be %02x, not %x, or else it will fail for "\x0" to "\xF".

      One reason URI::Escape is better is because it fails safely when provided with unicode characters, while your code fails badly.

      Thanks,
      This was exactly what I needed..
Re: Character conversion
by Fletch (Bishop) on Feb 22, 2006 at 17:07 UTC
Re: Character conversion
by vladb (Vicar) on Feb 22, 2006 at 17:09 UTC
    You can convert the other way using this line of code
    $str =~ s/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg;
    The reverse of what you do in your first regexp, which also could be simplified just a tiny bit like so
    $str =~ s/\%([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
    _____________________
    "We've all heard that a million monkeys banging on a million typewriters will eventually reproduce
    the entire works of Shakespeare. Now, thanks to the Internet, we know this is not true." - Robert Wilensky, University of California
Re: Character conversion
by CountOrlok (Friar) on Feb 22, 2006 at 17:07 UTC
    I think you are looking for the escapeHTML method in the CGI module.

    -imran

      No. URIs and HTML have very different escaping mechanisms.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://532012]
Approved by ww
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (8)
As of 2024-03-29 15:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found