CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

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

 



cathy
newbie

Aug 9, 2000, 4:06 PM

Post #1 of 3 (594 views)
Write an array to a file Can't Post

How do you write an array to a flat file?


randor
User

Aug 10, 2000, 3:58 AM

Post #2 of 3 (594 views)
Re: Write an array to a file [In reply to] Can't Post

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

Post #3 of 3 (594 views)
Re: Write an array to a file [In reply to] Can't Post

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


 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives