Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
printf格式在perl中不起作用_Perl - Fatal编程技术网

printf格式在perl中不起作用

printf格式在perl中不起作用,perl,Perl,我正在使用printf格式化输出。但我无法正确格式化它。有人能帮我指出下面这段代码的错误吗 my $sql1 = "select col1,col2,col3 from MYTABLE order by 1"; my $sth = $dbh->prepare($sql1); $sth->execute(); # or die $DBI::errstr; my $resultref = $sth->fetchall_arrayref(); foreach (@$resultr

我正在使用printf格式化输出。但我无法正确格式化它。有人能帮我指出下面这段代码的错误吗

my $sql1 = "select col1,col2,col3 from MYTABLE order by 1";
my $sth = $dbh->prepare($sql1);
$sth->execute(); # or die $DBI::errstr;

my $resultref = $sth->fetchall_arrayref();

foreach (@$resultref) {
    print "\n $_->[0] $_->[1] $_->[2] $_->[3]"; # prints 1 row, 3 fields. Fine!
    printf ("%8d %8d %8d ", $_->[0], $_->[1], $_->[2]); # prints 0 for all... why?

  # So i tried the following but still the issue
    my $t1 = $_->[0];
    my $t2 = $_->[1];
    my $t3 = $_->[2];
    my $t4 = $_->[3];

    print "$t1,$t2"; #works
    printf "%8d %8d", $t1, $t2; # doesnt work . why?
}

不知道您使用的是哪个DBH,我猜可能是列以字符串的形式返回,Perl甚至没有意识到它有一个数字。你有没有试过这样的方法: printf%8d%8d%8d,0+$\>[0],0+$\>[1],0+$\>[2]

至于原因,您可以查看Scalar::Utils,询问Perl它认为标量中包含什么。作为对Perl的扩展,Perl中显示的数据可能是粗糙的。我猜Perl会想:
Scalar::Util::isdual$->[0]将返回为false。但是添加0技巧应该迫使它重新评估这一点。

谢谢各位,我找到了答案。 首先,我使用了tripleee建议的strict和warnings,这导致了另一个错误,如下所示:

参数\x{44}\x{4c}。。。在sprintf的main3.pl第44行中不是数字

稍后,我首先使用sprintf转换了输出t字符串,并将%d更改为%s

最后看起来是这样的:

my $string = sprintf ("%22s %18s",$_->[0],$_->[1]); # store it first
print $string;   #Now prints fine

不,我试过了。。。没用。输出仍然相同。不管怎么说,它的字符串还是数字都不重要。我想我只是假设您使用了%8d,所以正在尝试打印数字。是%22s将在该位置打印一个数字或字符串。%d将尝试强制字符串为数字,如果失败,请使用strict;使用警告;应该是您的第一道防线。首先存储它应该与您的输出是否符合预期无关。printf%22s%18s,$\u0],$\u1];应该足够了。不是吗?