Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.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
Loops 如何将所有值从循环写入文件,而不仅仅是最后一个值?_Loops_File_Perl_Io - Fatal编程技术网

Loops 如何将所有值从循环写入文件,而不仅仅是最后一个值?

Loops 如何将所有值从循环写入文件,而不仅仅是最后一个值?,loops,file,perl,io,Loops,File,Perl,Io,我想在文本文件中写入所有服务器值。但我的输出文本文件只能写入最后一个值。例如,$theServer值是 as1tp.com as2tp.com as3tp.com as4tp.com as5tp.com 我不能在输出文本文件中写入所有这些服务器值,而只能在文本文件中写入最后一个值as5tp.com。下面是我的代码。如何将所有值写入tier1.txt文件 use strict; use warnings; my $outputfile= "tier1.txt" my $the

我想在文本文件中写入所有服务器值。但我的输出文本文件只能写入最后一个值。例如,
$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
循环之外,这样文件就不会在每次循环迭代时被覆盖。请记住,您是在
'>'
模式下打开的(写入,而不是附加):


将打开和关闭开关移到外部loop@ikegami我试图将open和close语句移到循环之外,但只看到了最后一个REVERR名称:(有一个分号(
)第3行中缺少。另外,您能告诉我们
@theResult
数组的
转储程序值是多少吗?@ikegami,vkk05:感谢您的评论。我在您的评论中使用了这些想法,添加了一些解释,并将其添加到社区wiki答案中。谢谢,但您不需要将其设置为社区wiki:)
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;