jmClifford has asked for the wisdom of the Perl Monks concerning the following question:

Hi. I have the following code (and output);

print sprintf ("%-6s", "°C"). "|\n"; print sprintf ("%-6s", "Deg C")."|\n"; --------------------------------------- Output; °C | Deg C |

It appears the 2 bytes involved with the ° character is comprehended as 2 spaces and so my vertical bars do not align. Is there a way around this issue (without just avoiding such characters) ??

Regards JC......

Replies are listed 'Best First'.
Re: Issue of formatting columns of data
by choroba (Cardinal) on Sep 25, 2024 at 15:49 UTC
    You need to
    1. Save the source file as UTF-8.
    2. Tell Perl that it is UTF-8.
    3. Tell Perl to encode the output as UTF-8.
    #! /usr/bin/perl use warnings; use strict; use utf8; use open IO => ':encoding(UTF-8)', ':std'; print sprintf ("%-6s", "°C"). "|\n"; print sprintf ("%-6s", "Deg C")."|\n";
    Output (in a UTF-8 terminal):
    °C    |
    Deg C |
    

    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
      Any of these would work:

      • binmode STDOUT, "encoding(UTF-8)"
      • binmode STDOUT, ":utf8"
      • use open qw(:std :utf8);
      • perl -C your_script
        • *please* do NOT promote binmode ..., ":utf8";, as that is unsafe
        • The :encoding(utf-8)" is missing a :
        • perl -C is for output only (I'd use -COE for clarity), not for the source code. UTF-8 in source code requires perl -COE -Mutf8 -wE'say "°C"'

        Enjoy, Have FUN! H.Merijn