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

时间:2012-01-23 03:16:49

标签: perl

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

a1
a2
a3
...

2 个答案:

答案 0 :(得分: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

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

1
2
3

答案 1 :(得分:9)

如果您不想要foreach循环,可以执行以下操作:

print $fh join ("\n", @a);
相关问题