Get the Unicode value of a character in Perl

To get the Unicode value of a character in Perl, use ord. For example,

#!/usr/bin/perl
binmode STDOUT, ":utf8";
use utf8;
my @chars = qw/a A 笑 ☺/;
for (@chars) {
    printf "%s: 0x%X\n", $_, ord ($_);
}

(download)

The output looks like this:

a: 0x61
A: 0x41
笑: 0x7B11
☺: 0x263A

For details of the binmode and use utf8 statements, please refer to this Unicode tutorial.

To convert Unicode numbers into characters, use chr. For example,

#!/usr/bin/perl
binmode STDOUT, ":utf8";
my @p = (0x61, 0x41, 0x7B11, 0x263A);
for (@p) {
    printf "0x%X: %s\n", $_, chr ($_);
}

(download)

The output looks like this:

0x61: a
0x41: A
0x7B11: 笑
0x263A: ☺


Copyright © Ben Bullock 2009-2023. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer