PDA

View Full Version : reading text from file into array


brooklyn1126
05-16-2004, 09:42 PM
Hi i am trying to read from a text file and put each word into its own spot in the array and then print the array out with each word on its own line and it also outputs the amount of words in the file. I have it working except it only reads the first line of the text file. Here is my code. Thanks for any help.

open(HANDLE, "words.txt");

@words = split(/ /,<HANDLE>);
close(HANDLE);
$count = scalar(@words);

for($i = 0;$i < $count;$i++){
print "$words[$i]\n";
}

print "There are $count words in this file";

MattJakel
05-16-2004, 10:35 PM
I'm still a bit of a beginner but I think this should work.
Try:


my @words;
open(HANDLE, "words.txt");

@lines = <HANDLE>;
foreach $line (@lines) {
push @words split(/ /,$line);
}
close(HANDLE);
$count = scalar(@words);

for($i = 0;$i < $count;$i++){
print "@words[$i]\n";
}


I think the reason it was only getting the first line is because <HANDLE> was acting like a single variable instead of an array so you have to make it be an array. Tell me if it works.

brooklyn1126
05-17-2004, 12:51 AM
Im getting an error with this line: push @words split(/ /,$line);
This is the error: syntax error at perl4.pl line 6, near "@words split"
Im not sure what is wrong but it does look like the syntax is wrong.

brooklyn1126
05-17-2004, 12:54 AM
this is what i changed and it works: push (@words, split(/ /,$line));

thanks for the help

MattJakel
05-17-2004, 03:49 AM
Yeah, sorry I screwed up on that line. Glad I could help.

Matt