Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: How to convert between Unicode codepoint and UTF8 character code on Perl?

by ikegami (Patriarch)
on Oct 25, 2021 at 15:40 UTC ( [id://11138021]=note: print w/replies, xml ) Need Help??


in reply to How to convert between Unicode codepoint and UTF8 character code on Perl?

if the string "U+03C0" (or "0x03C0") is entered, then I want the string "0xCF80" to be printed (without quotes).

use Encode qw( encode_utf8 ); s{ ^ U\+ ( [0-9a-fA-F]+ ) \z }{ "0x" . uc(unpack("H*", encode_utf8(chr(hex($1))))) }xe;
  1. chr(hex($1)) gets a character with the specified value.
  2. encode_utf8(...) encodes the code point.
  3. uc(unpack("H*", ...)) converts the byte sequence to hex.

If the string "0xCF80" is entered, then I want the string "U+03C0" (or "0x03C0") to be printed (without quotes).

use Encode qw( decode_utf8 ); s{ ^ 0x ( (?: [0-9a-fA-F]{2} ){1,4} ) \z }{ sprintf("U+%X", ord(decode_utf8(pack("H*", $1)))) }xe;
  1. pack("H*", $1) gets a string of bytes with the specified values.
  2. decode_utf8(...) decodes to a code point.
  3. sprintf("%X", ord(...)) converts the character to hex.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (5)
As of 2024-04-24 11:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found