[英]Perl - printing output after a for loop
I have this code where I have problem getting the output I want: 我在无法获取所需输出的地方有以下代码:
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";
I am trying to print out the output after it run finish the for loop 6 times (3 to 8). 我试图在输出运行完for循环6次(3到8)后打印输出。 The data should arrange something like this:
数据应安排如下:
Desired output (eg): 所需的输出(例如):
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
Instead, it print out only the last column: 相反,它仅打印出最后一列:
A B C 4
C D F 1
G H I 0
so I change to this line by adding the "." 因此我通过添加“。”更改为这一行。 to join the 6 columns together
将6列连接在一起
$variable1 .= "$ratio1"; # problem with this line
and I get weird output like this: 我得到这样奇怪的输出:
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 ...
Is there anything wrong with my code somewhere? 我的代码在哪里有问题吗?
Yes, you need to declare and initialize your $variable1
before your for loop 是的,您需要在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
Alternatively, you could avoid a temporary buffer, and just print within the for loop 或者,您可以避免使用临时缓冲区,而只需在for循环中打印
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.