问题描述
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 = [ [ qw( name number ) ],
[ 'Kroner', 123456789 ],
[ 'Holler', 123456789 ],
[ 'Mühßig', 123456789 ],
[ 'Singer', 123456789 ],
[ 'Maurer', 123456789 ],
];
my $dbh = DBI->connect( "DBI:CSV:", { RaiseError => 1 } );
$dbh->do( qq{ CREATE TEMP TABLE phone_book AS IMPORT( ? ) }, {}, $phone_book );
my $sth = $dbh->prepare( qq{ SELECT name, number FROM phone_book } );
$sth->execute;
my $array_ref = $sth->fetchall_arrayref();
for my $row ( @$array_ref ) {
printf "%9s %10s\n", @$row;
}
# OUTPUT:
# Kroner 123456789
# Holler 123456789
# Mühßig 123456789
# Singer 123456789
# Maurer 123456789
推荐答案
我还没有重现它,但是松散地说,似乎正在发生的是这是字符编码不匹配。很可能您的Perl源文件已被保存为UTF-8编码。但是您尚未在脚本中启用使用utf8;
。因此,它将每个非ASCII德语字符解释为两个字符,并相应地设置填充。但您正在运行的终端也是UTF-8模式,因此字符打印正确。尝试添加使用警告;
,我敢打赌你得到一个警告打印,我不会惊讶,如果添加使用utf8;
实际上解决了这个问题。
I haven't been able to reproduce it, but loosely speaking what seems to be happening is that it's a character encoding mismatch. Most likely your Perl source file has been saved in UTF-8 encoding. However you have not enabled use utf8;
in the script. So it's interpreting each of the non-ASCII German characters as being two characters and setting the padding accordingly. But the terminal you're running on is also in UTF-8 mode so the characters print correctly. Try adding use warnings;
and I'll bet you get a warning printed, and I would not be surprised if adding use utf8;
actually fixes the problem.
这篇关于如何将UTF-8字符串与Perl的printf正确对齐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!