2

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
...
user288609
  • 11,491
  • 24
  • 77
  • 114

2 Answers2

12

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
Jonah Bishop
  • 11,967
  • 5
  • 44
  • 72
  • 4
    Nowadays you should be using the 3-argument form of 'open'. Also you would be better putting your filehandle into a lexical, e.g. "open my $file, '>', 'output.txt' ..." – zgpmax Jan 23 '12 at 12:08
  • @hochgurgler +1 The reason can be found here: http://stackoverflow.com/questions/1479741/why-is-three-argument-open-calls-with-lexical-filehandles-a-perl-best-practice – dgw Jan 23 '12 at 12:17
  • @hochgurgler Thanks for the info. I had no idea that a 3-argument form existed, let along that it was a best practice! – Jonah Bishop Jan 23 '12 at 14:26
10

If you don't want the foreach loop, you can do this:

print $fh join ("\n", @a);
Sobrique
  • 52,335
  • 6
  • 56
  • 99
j poplar
  • 101
  • 1
  • 3