【问题标题】:Issues of saving an array into a plain text file将数组保存到纯文本文件中的问题
【发布时间】:2016-08-22 15:41:59
【问题描述】:

我已经建立了一个数组,例如 A = [a1,a2,...aN]。如何将此数组保存到数据文件中,每个元素放置在一行。换句话说,对于数组 A,文件应该是这样的

a1
a2
a3
...

【问题讨论】:

    标签: perl


    【解决方案1】:

    非常简单(当然,这是假设您的数组被明确指定为数组数据结构,您的问题并不太清楚):

    #!/usr/bin/perl -w
    use strict;
    
    my @a = (1, 2, 3); # The array we want to save
    
    # Open a file named "output.txt"; die if there's an error
    open my $fh, '>', "output.txt" or die "Cannot open output.txt: $!";
    
    # Loop over the array
    foreach (@a)
    {
        print $fh "$_\n"; # Print each entry in our array to the file
    }
    close $fh; # Not necessary, but nice to do
    

    上述脚本会将以下内容写入“output.txt”:

    1
    2
    3
    

    【讨论】:

    • 现在您应该使用 'open' 的 3 参数形式。另外,您最好将文件句柄放入词法中,例如"打开我的 $file, '>', 'output.txt' ..."
    • @hochgurgler +1 原因可以在这里找到:stackoverflow.com/questions/1479741/…
    • @hochgurgler 感谢您的信息。我不知道存在 3 参数形式,更不用说这是最佳实践!
    【解决方案2】:

    如果你不想要foreach 循环,你可以这样做:

    print $fh join ("\n", @a);
    

    【讨论】:

    • 您的map 是多余的。
    • @Sobrique:确实,因为 'join' 内置函数已经是 'loopy'。我已将其删除,并在 join 的参数周围去掉了括号(待审核)。
    猜你喜欢
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多