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
...

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

3 Comments

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' ..."
@hochgurgler +1 The reason can be found here: stackoverflow.com/questions/1479741/…
@hochgurgler Thanks for the info. I had no idea that a 3-argument form existed, let along that it was a best practice!
10

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

print $fh join ("\n", @a);

2 Comments

Your map is redundant.
@Sobrique: indeed, since the 'join' builtin is already 'loopy'. I've removed it, and ditched the parentheses round join's arguments (pending review).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.