Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Help with accepting inputs, wordcount, and print to a file

by aaron_baugher (Deacon)
on Sep 10, 2012 at 18:01 UTC ( #992815=note: print w/ replies, xml ) Need Help??


in reply to Help with accepting inputs, wordcount, and print to a file

This may seem like a simple task, but it's fairly complex for a beginner. It involves reading lines from a file, splitting them into words, using a hash to count appearances of certain words, and printing the contents of a hash. That gives you some things to look for in whatever learning materials you're using.

If I were writing this, the first question I would ask is, "Where do the 'certain words' come from?" If they are in a file, then the first thing you need to do is open that file, read the words from it, and put them into a hash as its keys. That might mean chomping the words, or splitting lines, depending on how the words are saved in that file. Alternatively, if the certain words are being passed on the command line, you can get them from @ARGV and put them in a hash from there.

Then you can open the file you want to search in, and start reading lines. Now you have a choice: you can split each line into words, and check your hash for each word, incrementing it if it is found. Or you can loop through your hash keys, using a regex to count the number of times each hash key appears in the line, and incrementing the key's value accordingly. Which method is faster will depend on the ratio of 'certain words' to 'all words', but I would try the regex method first.

After you've read through the whole file, you need to print out the results. Loop through your hash's keys, printing the key and its value (the number of times found). You may also wish to sort on the keys or the values as part of this loop, so check out the documentation for sort as well if that's the case.

Aaron B.
Available for small or large Perl jobs; see my home node.


Comment on Re: Help with accepting inputs, wordcount, and print to a file

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://992815]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (15)
As of 2014-10-02 13:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    What is your favourite meta-syntactic variable name?














    Results (58 votes), past polls