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
  • 12,465
  • 26
  • 85
  • 127

2 Answers2

13

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
  • 12,279
  • 6
  • 49
  • 74
  • 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
11

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

print $fh join ("\n", @a);
Sobrique
  • 52,974
  • 7
  • 60
  • 101
j poplar
  • 111
  • 1
  • 3