如何从循环中将所有值写入文件,而不仅仅是最后一个值?
How to write all values into a file from a loop, not just the last value?
我想将所有服务器值写入文本文件。但是我的输出文本文件只能写最后一个值。例如,$theServer
值为
as1tp.com
as2tp.com
as3tp.com
as4tp.com
as5tp.com
我不能在输出文本文件中写入所有这些服务器值,我只能在我的文本文件中写入最后一个值 as5tp.com
。下面是我的代码。如何将所有值写入 tier1.txt
文件?
use strict;
use warnings;
my $outputfile= "tier1.txt"
my $theServer;
foreach my $theServernameInfo (@theResult){
$theServer = $theServernameInfo->[0];
print "$theServer\n";
open(my $fh, '>', $outputfile) or die "Could not open file '$outputfile' $!";
print $fh "$theServer";
close $fh;
}
下面的代码应该可以工作。正如评论者所建议的那样,我插入了缺少的分号。我将 open
和 close
移到了 foreach
循环之外,这样文件就不会在每次循环迭代时被覆盖。请记住,您以 '>'
模式打开它(写入,而不是追加):
use strict;
use warnings;
my $outputfile = "tier1.txt";
open( my $fh, '>', $outputfile ) or die "Could not open file '$outputfile' $!";
foreach my $theServernameInfo ( @theResult ) {
my $theServer = $theServernameInfo->[0];
print "$theServer\n";
print { $fh } "$theServer\n";
}
close $fh;
我想将所有服务器值写入文本文件。但是我的输出文本文件只能写最后一个值。例如,$theServer
值为
as1tp.com
as2tp.com
as3tp.com
as4tp.com
as5tp.com
我不能在输出文本文件中写入所有这些服务器值,我只能在我的文本文件中写入最后一个值 as5tp.com
。下面是我的代码。如何将所有值写入 tier1.txt
文件?
use strict;
use warnings;
my $outputfile= "tier1.txt"
my $theServer;
foreach my $theServernameInfo (@theResult){
$theServer = $theServernameInfo->[0];
print "$theServer\n";
open(my $fh, '>', $outputfile) or die "Could not open file '$outputfile' $!";
print $fh "$theServer";
close $fh;
}
下面的代码应该可以工作。正如评论者所建议的那样,我插入了缺少的分号。我将 open
和 close
移到了 foreach
循环之外,这样文件就不会在每次循环迭代时被覆盖。请记住,您以 '>'
模式打开它(写入,而不是追加):
use strict;
use warnings;
my $outputfile = "tier1.txt";
open( my $fh, '>', $outputfile ) or die "Could not open file '$outputfile' $!";
foreach my $theServernameInfo ( @theResult ) {
my $theServer = $theServernameInfo->[0];
print "$theServer\n";
print { $fh } "$theServer\n";
}
close $fh;