将数组保存到纯文本文件的问题

use*_*609 1 perl

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

a1
a2
a3
...
Run Code Online (Sandbox Code Playgroud)

Jon*_*hop 10

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

#!/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
Run Code Online (Sandbox Code Playgroud)

上面的脚本会将以下内容写入"output.txt":

1
2
3
Run Code Online (Sandbox Code Playgroud)

  • 现在你应该使用'开放'的3参数形式.另外你最好将文件句柄放入词法中,例如"打开我的文件,'>','output.txt'......" (4认同)

小智 9

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

print $fh join ("\n", @a);
Run Code Online (Sandbox Code Playgroud)

  • 你的`map`是多余的. (3认同)