Home: Perl Programming Help: Intermediate:
Write an array to a file



cathy
newbie

Aug 9, 2000, 4:06 PM


Views: 1057
Write an array to a file

How do you write an array to a flat file?


randor
User

Aug 10, 2000, 3:58 AM


Views: 1057
Re: Write an array to a file

open FILE, ">file.txt";
##NOTE: > overwrites, >> appends file (adds to the end of it)
print FILE "@array\n";
close FILE;

hope this helps,
Randor


japhy
Enthusiast

Aug 10, 2000, 5:25 AM


Views: 1057
Re: Write an array to a file

It helps to know what CONTENT you have in the array. Is it an array of lines to print to a file?

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


open OUTPUT, ">file"; # change to >> for appending
print OUTPUT @lines;
close OUTPUT;
</pre><HR></BLOCKQUOTE>

If the elements of the array don't have newlines, but you want them printed, then you can do one of these two things:

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


open OUTPUT, ">file";
{
local ($\, $,) = ("\n","\n");
print OUTPUT @lines;
}
close OUTPUT;
</pre><HR></BLOCKQUOTE>

or:

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


open OUTPUT, ">file";
print OUTPUT map "$_\n", @lines;
close OUTPUT;
</pre><HR></BLOCKQUOTE>

If the array holds a set of data that you want printed as ONE line of the file, then you can do something like:

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


open OUTPUT, ">file";
print OUTPUT "@lines\n";
close OUTPUT;
</pre><HR></BLOCKQUOTE>

or

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


open OUTPUT, ">file";
print OUTPUT join("\t", @lines), "\n";
close OUTPUT;
</pre><HR></BLOCKQUOTE>

That last example makes the elements separated by tabs.

------------------
Jeff "japhy" Pinyan -- accomplished author, consultant, hacker, and teacher