How to print Hexagram in Perl?

Viewed 89

I am trying to print the first hexagram from here in Perl.

The code below doesn't generate any errors, but doesn't print any hexagrams either.

use warnings;
use open ':encoding(utf8)';
binmode(STDOUT, ":utf8");

print "\x{4DC0}\n";

I was hoping to see this "䷀" not "Σ╖Ç".

1 Answers

You tell Perl your terminal is expecting UTF-8, but your terminal appears to expect one of the following:[1]

Seeing as these are all Windows code pages, I presume the terminal in question is a Windows console. If so, you can find out which encoding is expected using either of these commands:

chcp

perl -le"use Win32; print Win32::GetACP()"

Prepend cp to the number to get a name you can use with the Encode module (which is used by the :encoding layer).

Knowing the expected encoding won't help you, however. None of the character sets of these encodings contains "䷀", so your terminal can't display "䷀" without change.

You can switch the encoding expected by a Windows console to UTF-8 by issuing the following command:

chcp 65001

You may have to adjust the font in the console's properties.


  1. I obtained the list of possible encodings using the following program:

    use strict;
    use warnings;
    use feature qw( say );
    use utf8;
    use Encode qw( decode encode_utf8 );
    
    my $output = encode_utf8("\x{4DC0}");
    my $displayed = "䷀";
    
    for my $encoding (Encode->encodings(":all")) {
       defined( my $got = eval { decode($encoding, $output, Encode::FB_CROAK|Encode::LEAVE_SRC) } )
          or next;
    
       say $encoding if $output eq $displayed;
    }
    

    (Make sure the file is encoded using UTF-8.)

Related