Blame


1 ffd9a51f 2023-08-04 jrmu #!/usr/bin/perl
2 ffd9a51f 2023-08-04 jrmu
3 ffd9a51f 2023-08-04 jrmu #Write a program that reads a series of words (with one word per line) until
4 ffd9a51f 2023-08-04 jrmu #end-of-input, then prints a summary of how many times each word was seen.
5 ffd9a51f 2023-08-04 jrmu #(Hint: remember that when an undefined value is used as if it were a number,
6 ffd9a51f 2023-08-04 jrmu #Perl automatically converts it to 0. It may help to look back at the earlier
7 ffd9a51f 2023-08-04 jrmu #exercise that kept a running total.) So, if the input words were fred,
8 ffd9a51f 2023-08-04 jrmu #barney, fred, dino, wilma, fred (all on separate lines), the output should
9 ffd9a51f 2023-08-04 jrmu #tell us that fred was seen 3 times. For extra credit, sort the summary words
10 ffd9a51f 2023-08-04 jrmu #in code point order in the output.
11 ffd9a51f 2023-08-04 jrmu
12 ffd9a51f 2023-08-04 jrmu use warnings;
13 ffd9a51f 2023-08-04 jrmu use strict;
14 ffd9a51f 2023-08-04 jrmu use utf8;
15 ffd9a51f 2023-08-04 jrmu use Data::Dumper;
16 ffd9a51f 2023-08-04 jrmu
17 ffd9a51f 2023-08-04 jrmu my %count;
18 ffd9a51f 2023-08-04 jrmu print "Type some words, with one word per line:\n";
19 ffd9a51f 2023-08-04 jrmu chomp(my @words = <>);
20 ffd9a51f 2023-08-04 jrmu foreach my $word (@words) {
21 ffd9a51f 2023-08-04 jrmu $count{$word}++;
22 ffd9a51f 2023-08-04 jrmu }
23 ffd9a51f 2023-08-04 jrmu foreach my $word (sort(keys %count)) {
24 ffd9a51f 2023-08-04 jrmu print "$word: $count{$word}\n";
25 ffd9a51f 2023-08-04 jrmu }