Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

How to group identical words?

by Anonymous Monk
on Aug 18, 2008 at 20:35 UTC ( #705050=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello fellows! I am new to Perl world and I am trying to write a script to "group" identical words in a list of words I have.Imagine the following:
Jim Jim Jim Peter Anreas Nick Nick Nick Wolfgang Matthew John John John Nikolai
I want to print each name and next to it, how many times I have found it in my list.

Replies are listed 'Best First'.
Re: How to group identical words?
by FunkyMonk (Chancellor) on Aug 18, 2008 at 20:45 UTC
    Use a hash. Go read about them in perldata. Ask again if you get stuck.
Re: How to group identical words?
by Popcorn Dave (Abbot) on Aug 18, 2008 at 20:51 UTC
    Hint: look at hashes.

    Also, this looks a lot like homework. If it is, you're going to get a lot more help if you state that it is and you show what code you tried and where you got stuck.


    Revolution. Today, 3 O'Clock. Meet behind the monkey bars.

    I would love to change the world, but they won't give me the source code

Re: How to group identical words?
by JavaFan (Canon) on Aug 18, 2008 at 20:57 UTC
    Why bother writing a program if there's already one doing this?
    $ uniq -c Jim Jim Jim Peter Anreas Nick Nick Nick Wolfgang Matthew John John John NikolaiJim Peter Anreas Nick Wolfgang Matthew John Nikolai ^D 3 Jim 1 Peter 1 Anreas 3 Nick 1 Wolfgang 1 Matthew 3 John 1 NikolaiJim 1 Peter 1 Anreas 1 Nick 1 Wolfgang 1 Matthew 1 John 1 Nikolai $
      Because it's his first step towards building a more complex script involving hashes?
Re: How to group identical words?
by ikegami (Pope) on Aug 21, 2008 at 19:49 UTC
    while (<>) { chomp; next if defined($last) && $_ eq $last; $last = $_; print; }

    On the other hand, if you're trying to remove duplicates, the answer is in perlfaq4.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://705050]
Approved by toolic
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2021-11-28 09:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?