Perl Program to Print Unicode From Hex Value
Asked Answered
J

3

6

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}

Jodijodie answered 20/8, 2018 at 23:46 Comment(0)
M
8

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)';
Miun answered 21/8, 2018 at 0:31 Comment(0)
F
4

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.

Fearless answered 20/8, 2018 at 23:55 Comment(0)
U
1

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");
Ube answered 21/8, 2018 at 0:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.