Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl Program to Print Unicode From Hex Value

I am starting up with Perl and confused on how to render unicode characters given a hex string variable.

#!/usr/bin/perl
use warnings;

foreach my $i (0..10000) {
    my $hex = sprintf("%X", $i);
    print("unicode of $i is \x{$hex}\n");
}
print("\x{2620}\n");
print("\x{BEEF}\n");

Gives me the warning: Illegal hexadecimal digit '$' ignored at perl.pl line 9.

and no value prints for \x{$hex}

like image 605
Questioner Avatar asked Aug 20 '18 23:08

Questioner


3 Answers

Both chr($num) and pack('W', $num) produce a string consisting of the single character with the specified value, just like "\x{XXXX}" does.

As such, you can use

print("unicode of $i is ".chr(hex($hex))."\n");

or just

print("unicode of $i is ".chr($i)."\n");

Note that your program makes no sense without

use open ':std', ':encoding(UTF-8)';
like image 55
ikegami Avatar answered Nov 19 '22 14:11

ikegami


Yup. You can't do that. No variable interpolation allowed in the middle of a \x like that. You can use chr() to get that character though.

like image 40
Randal Schwartz Avatar answered Nov 19 '22 13:11

Randal Schwartz


Randal's answer is correct. For more info, you might want to read perluniintro.

From there, you can find, for example:

At run-time you can use:

 use charnames ();
 my $hebrew_alef_from_name
                      = charnames::string_vianame("HEBREW LETTER ALEF");
 my $hebrew_alef_from_code_point = charnames::string_vianame("U+05D0");
like image 45
jwd Avatar answered Nov 19 '22 12:11

jwd