我已经构建了一个数组,例如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)
小智 9
如果你不想要foreach循环,你可以这样做:
Run Code Online (Sandbox Code Playgroud)print $fh join ("\n", @a);