Overclock.net banner
1 - 3 of 3 Posts

· Registered
Joined
·
1,238 Posts
Discussion Starter · #1 ·
ok so i have an assignment and its all done except for one little thing i cant figure out...im sure its somthing simple i just cant see it
here is the program i have to do
Quote:
2. Write a program that reads a series of words (one word per line) until end-of-input, then prints a summary of how many times each word was seen. Sort the output in lexicographic order.
If the input were
Fred
Barney
Fred
Dino
Wilma
Fred
The output would be:
Barney: 1, Dino: 1, Fred: 3, Wilma: 1
and here is my code

Code:

Code:
my(@words, %count, $word);
chomp(@words = <STDIN>);

foreach $word (@words)
{
        $count{$word} += 1;
}

foreach $word (sort keys %count)
{
print ("$word: $count{$word} " );
}
my output is like this

Code:

Code:
Barney: 1 Dino: 1 Fred: 3 Wilma: 1
so it works perfectly except i wanted to make it comma separated without having a comma before the first element or after the last i cant seem to figure it out
 

· Premium Member
Joined
·
7,864 Posts
This is quite simple. Instead of printing each iteration out, append it to the end of a string with a comma afterwards. eg

Code:

Code:
$string .= "$word: $count{$word}, "
Then outside of the foreach loop, print the entire string, cropping out the trailing comma. Use substr for that.

Also, if you're using strict, then make sure you declare your variable before the foreach.
 
1 - 3 of 3 Posts
This is an older thread, you may not receive a response, and could be reviving an old thread. Please consider creating a new thread.
Top