Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Just a general question as to whether there is a better way to accomplish this.

given an array, what is the best way to write that array to a file. One index per line. Lets define best 3 ways.

1) Most efficient (CPU/Disk/Memory).
2) Most efficient (Time).
3) Least amount of Code (Just for fun).

Normally I do the following:
open(FILE,">$filename") or die "Couldn't open file: $!"; foreach (@my_array) { print FILE $_; } close(FILE);

Replies are listed 'Best First'.
Re: Printing arrays to a file.
by Zaxo (Archbishop) on Nov 25, 2002 at 18:49 UTC
    { local $, = $/; open my $file,'>', $filename or die 'Couldn't open file: ", $!; print $file @my_array or die $!; close $file or die $!; }

    That does it all in a single print statement without concatenation. On item at a time is printed and terminated with the portable newline, default $/. The error checking is a bonus, and the lexical filehandle will close itself it the block is exited abnormally. Run benchmarks if you like, it ought to be ok, but on a filesystem, performance first means getting it right. You want to know if the print fails.

    After Compline,
    Zaxo

Re: Printing arrays to a file.
by thelenm (Vicar) on Nov 25, 2002 at 18:58 UTC
    It looks like the elements in your array must already end in newlines (and have no newlines otherwise). That may be a valid assumption for your situation, but if you have more complicated data you want to recover, you may want to use something like Data::Dumper instead.

    If all you're doing is printing an array to a file, you can do it without a for loop, which seems to be quite a bit faster on my laptop using this benchmark code:

    use Benchmark 'cmpthese'; my @a = map {"$_\n"} 1..1000000; cmpthese(100, { forloop => sub { open FILE, ">file.out" or die "Can't open file: $!\n"; print FILE $_ for @a; close FILE; }, array => sub { open FILE, ">file.out" or die "Can't open file: $!\n"; print FILE @a; close FILE; } });
    Results:
    Benchmark: timing 100 iterations of array, forloop... array: 28 wallclock secs (22.62 usr + 2.74 sys = 25.36 CPU) @ 3 +.94/s (n=100) forloop: 69 wallclock secs (61.52 usr + 2.75 sys = 64.27 CPU) @ 1 +.56/s (n=100) Rate forloop array forloop 1.56/s -- -61% array 3.94/s 153% --

    -- Mike

    --
    just,my${.02}

Re: Printing arrays to a file.
by dpuu (Chaplain) on Nov 25, 2002 at 18:56 UTC
    Many ways:
    print FILE "$_\n" for @array; print FILE join "\n", @array, ""; print FILE map "$_\n", @array; do { local $,="\n"; print FILE @array };
    I wouldn't like to say which is fastest (I'd guess the third). --Dave