Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

loading array from txt file 1

Status
Not open for further replies.

u8ug2tfj

Programmer
Joined
Feb 20, 2007
Messages
4
Location
US
I have managed to load form data t a text file that has each element separated by double quotes and commas ("item1","item2","item3"...) and I want to get open this file and use the data to repopulate an array so that I can use an item (@array[0]) to fill in a form value.

I have tried this:
open FROMFILE"<array.txt";
@array=<FROMFILE>;

But all of the data is loaded into the first element (@array[0]). Is there a way I can repopulate the array?

thanks.
 
looks like when you wrote the file you didn't insert a new line between each item. No biggie. just split on ","
Code:
open FROMFILE, "<array.txt" or die $!; 
$line=<FROMFILE>;
@elements=split (/","/, $line);
You'll still need to strip the leading and trailing quotes from the first and last elements
Code:
$elements[0]=~s/"//g;
$elements[$#elements]=~s/"//g;


Paul
------------------------------------
Spend an hour a week on CPAN, helps cure all known programming ailments ;-)
 
Thanks. Still a problem. Script runs but no output.

***text file looks like this***
"item1","item2","item3"

***code looks like this now***
open (FROMFILE,"<array.txt");
$line=<FROMFILE>;
@elements=split (/","/, $line);
close(FROMFILE);

$elements[0]=~s/"//g;
$elements[$#elements]=~s/"//g;

print "Content-type: text/html","\n\n";
print $element[1]; # Print out element one from array

exit(0);
***

but it prints blank.

-Gary
 
Ok. Let me make it a general question. I want to save an array on a server so I can use it again, changing and calling each element in the array. It's not a big array so no need for a SQL database or anything... just maybe 50 elements maximum.

The elements will be strings, possibly containing commas as part of the content.

I need to "print/write" the array to a file, then be able to open the file and re-assembly the array. Then I can make an element, say $array[2] for example, a variable and use it in an HTML page.

How can I do this? Or can it be done?
 
OK... got it to run! Thanks much!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top