I have built an array, such as A = [a1,a2,...aN]. How to save this array into a data file, with each element to be placed at one row. In other words, for the array A, the file should look like
a1
a2
a3
...
I have built an array, such as A = [a1,a2,...aN]. How to save this array into a data file, with each element to be placed at one row. In other words, for the array A, the file should look like
a1
a2
a3
...
Very simple (this is assuming, of course, that your array is explicitly specified as an array data structure, which your question doesn't quite make clear):
#!/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
The above script will write the following to "output.txt":
1
2
3
If you don't want the foreach
loop, you can do this:
print $fh join ("\n", @a);