Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

Word Counter

by plaid (Chaplain)
on May 09, 2000 at 11:27 UTC ( #10720=perlcraft: print w/replies, xml ) Need Help??

   1: Not a particularly useful program, but I had an assignment
   2: a while back in a class to write a program in the language
   3: of our choice to count the words in a text file, and print
   4: out the 10 most commonly used words.  It's not very fast,
   5: not very efficient, etc., but was fun to write.  After
   6: beating the program around for a while, I managed to get
   7: it down to:
   9: (Updated: removed unnecessary assignment to %a.  Thanks merlyn)
  10: perl -na0777e 'map {++$a{$_}} @F; print join("\n", (sort { $a{$b} <=> $a{$a} } keys %a)[0..9]), "\n"' <filename>
  12: And after all that, I didn't even get a very good grade.

Replies are listed 'Best First'.
RE: Word Counter
by merlyn (Sage) on May 09, 2000 at 16:55 UTC
    You wrote:
    perl -na0777e '%a = map {$_, ++$a{$_}} @F; print join("\n", (sort { $a +{$b} <=> $a{$a} } keys %a)[0..9]), "\n"' <filename>
    I don't like the %a = there. You're creating the hash inside the map, but then overwriting it with the values again. Messy messy. I'd stick with something like:
    perl -ne '$a{$_}++ for split; END { @a = sort { $a{$b} <=> $a{$a} } ke +ys %a; print "$_\n" for @a[0..9]; }' <filename>

    -- Randal L. Schwartz, Perl hacker

      How about a round of golf, merlyn? perl -ne '$a{$_}++ for split; END { print join "\n", (sort { $a{$b} <=> $a{$a} } keys %a)[0 .. 9]; } <filename>
        perl -lne '$a{$_}++ for split } print for (sort { $a{$b} <=> $a{$a} } keys %a)[0..9]; {' <filename> or even better: perl -lpe '$a{$_}++ for split } for ((sort { $a{$b} <=> $a{$a} } keys %a)[0..9]) {' <filename>

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlcraft [id://10720]
Approved by root
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (2)
As of 2022-05-20 06:48 GMT
Find Nodes?
    Voting Booth?
    Do you prefer to work remotely?

    Results (72 votes). Check out past polls.