Perl - 在for循环后打印输出

时间:2014-03-12 09:41:16

标签: perl for-loop

我有这个代码,我有问题得到我想要的输出:

print OUT1 "$first[0]\t$first[1]\t$first[2]\t";
for my $index1 (3..8)
{
  my $ratio1 = sprintf( "%.4f%s", $numerator/$denominator,"\t");
  #print OUT1 "$ratio1";
  $variable1 = "$ratio1"; # problem with this line  
} 

print OUT1 "$variable1";  # print to textfile
print OUT1 "\n";

我试图在输出完成for循环6次(3到8)后打印出输出。数据应该安排如下:

期望的输出(例如):

       A  B  C  4  4  4  4  4   4
       C  D  F  2  6  5  8  3   1
       G  H  I  6  1  2  4  7   0  

相反,它只打印出最后一列:

        A  B  C  4
        C  D  F  1
        G  H  I  0

所以我通过添加“。”来改变这一行。一起加入6列

        $variable1 .= "$ratio1"; # problem with this line  

我得到奇怪的输出:

        A  B  C  4  4  4  4  4  4
        A  B  C  4  4  4  4  4  4  2  6  
        A  B  C  4  4  4  4  4  4  2  6  4 
        A  B  C  4  4  4  4  4  4  2  6  4  6 
        A  B  C  4  4  4  4  4  4  2  6  4  6  1 ...

我的代码在某处有什么问题吗?

1 个答案:

答案 0 :(得分:0)

是的,您需要在for循环之前声明并初始化$variable1

print OUT1 "$first\t$second\t$third\t";
my $variable1 = '';
for my $index1 (3..8)
{
    $variable1 .= sprintf( "%.4f%s", $numerator/$denominator,"\t");
}
print OUT1 "$variable1";  # print to textfile

或者,您可以避免使用临时缓冲区,只需在for循环中打印