【问题标题】:How to write all values into a file from a loop, not just the last value?如何将所有值从循环写入文件,而不仅仅是最后一个值?
【发布时间】:2021-01-08 04:17:07
【问题描述】:

我想将所有服务器值写入文本文件。但是我的输出文本文件只能写最后一个值。例如,$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;
    
}

【问题讨论】:

  • 将打开和关闭移出循环
  • @ikegami 我试图将 open 和 close 语句移到循环之外,也只看到最后一个 rerver 名称:(
  • 第三行缺少分号(;)。
  • 您能否告诉我们Dumper 数组的Dumper 值是什么?

标签: loops file perl io


【解决方案1】:

以下代码应该可以工作。正如评论者所建议的,我插入了缺少的分号。我将openclose 移到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;

【讨论】:

  • @ikegami, vkk05 : 感谢 cmets。我在您的 cmets 中使用了这些想法,添加了一些解释并将其作为社区 wiki 答案。
  • 谢谢,但您不需要将其设为社区 wiki :)
猜你喜欢
  • 2021-03-22
  • 1970-01-01
  • 1970-01-01
  • 2021-09-15
  • 2021-01-19
  • 1970-01-01
  • 2020-10-27
  • 1970-01-01
  • 2015-03-10
相关资源
最近更新 更多