PDA

View Full Version : file to array split by comma


pb&j
02-27-2005, 06:59 AM
what would be the best (easiest) way to read a file, plunk it into an array, and split it up properly?

example file...
Joe Brown,5464
Adam Smith,8894
Janet Gains,2148
and so on...

trying to find a good way to read the file, plunk it into an array (or hash) and display it nicely.

thanks.

mlseim
02-27-2005, 05:16 PM
#!/usr/bin/perl

$database="myfile.txt";

open (ORGDB,"<$database");
@ODB=<ORGDB>;
close (ORGDB);
@SODB=sort(@ODB); #sorts alphabetically by the first element if you wish.

print "Content-type: text/html\n\n";
print "<html><head><title>This is a test</title></head>\n";
print "<body>\n";

foreach $rec (@SODB){
chomp($rec);
($name,$id)=split(/\,/,$rec); #split by comma

print "Name: $name &nbsp;&nbsp;&nbsp; ID: $id<br>\n";
}

print "</body></html>\n";


========================================
If the comma split doesn't work, you can try this.
(I can never remember if the esc is needed):
($name,$id)=split(/,/,$rec); #split by comma

Or, use a pipe:

Your data would be:

example file...
Joe Brown|5464
Adam Smith|8894
Janet Gains|2148
and so on...

($name,$id)=split(/\|/,$rec); #split by pipe separater


.

pb&j
02-27-2005, 08:24 PM
thanks for the reply. :thumbsup: