How can I properly align UTF-8 strings with Perl's printf?

后端 未结 3 1164
囚心锁ツ
囚心锁ツ 2021-01-18 15:38

what is the right way to get here a beautiful output ( all lines the same indent )?

#!/usr/bin/env perl
use warnings;
use strict;
use DBI;

my $phone_book =          


        
3条回答
  •  余生分开走
    2021-01-18 15:55

    You can't use Unicode with printf if you have code points that take 0 or 2 print columns instead of 1, which it appears you do.

    You need to use Unicode::GCString instead.

    Wrong way:

    printf "%-10.10s", our $string;
    

    Right way:

    use Unicode::GCString;
    
    my $gcstring = Unicode::GCString->new(our $string);
    my $colwidth = $gcstring->columns();
    if ($colwidth > 10) {
        print $gcstring->substr(0,10);
    } else {
        print " " x (10 - $colwidth);
        print $gcstring;
    }
    

提交回复
热议问题