I'm new to perl and need to read a txt file into a hash and then perfrom the following.

Read in the file

Create a Hash

For each word in the file, count how many times the word occurs. Store the word a hash which is indexed with the words the represent the number of occurances ie:

One

Two

Three

And then, for each word, place it once in the corresponding hash row so that we know all the words that occur n times.
Then print out the hash like this:
The words a, not, blue occurred 3 times in the file. Etc… etc….

open(FILE,"<file.txt");
undef($/); #sucks the entire file in at once
while(<FILE>){
	(@words)=split(/\s+/);	
}
close FILE;

for (@words){
	s/[\,|\.|\!|\?|\:|\;]//g; #removed punctuation
	$word{$_}++;
}

for (sort keys %word){
	print "$_ occurred $word{$_} times\n";
}

How's that?

open(FILE,"<file.txt");
undef($/); #sucks the entire file in at once
while(<FILE>){
	(@words)=split(/\s+/);	
}
close FILE;

for (@words){
	s/[\,|\.|\!|\?|\:|\;]//g; #removed punctuation
	$word{$_}++;
}

for (sort keys %word){
	print "$_ occurred $word{$_} times\n";
}

How's that?

Thank you, works like a champ!

perlnewbe

Thank you, works like a champ!

...then mark the thread as solved please.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.