Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Issue of formatting columns of data

by jmClifford (Acolyte)
on Sep 25, 2024 at 15:31 UTC ( [id://11161936]=perlquestion: print w/replies, xml ) Need Help??

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11161936]
Approved by choroba
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (2)
As of 2024-10-08 05:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    The PerlMonks site front end has:





    Results (44 votes). Check out past polls.

    Notices?
    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.