/
ch-2.pl
executable file
·57 lines (44 loc) · 932 Bytes
/
ch-2.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/usr/bin/perl
use 5.020;
use warnings;
use English qw/ -no_match_vars /;
sub readText {
my ($filename) = @_;
my $text;
open my $fh, '<', $filename or die "$OS_ERROR\n";
local $RS = undef;
$text = <$fh>;
close $fh;
return $text;
}
sub removePunctuation {
my ($text) = @_;
$text =~ s/ \. | " | \( | \) | , | 's | --/ /gmsx;
return $text;
}
sub countWords {
my ($text) = @_;
my %count;
my @words = split /\s+/, $text;
for my $word (@words) {
$count{$word}++;
}
return \%count;
}
sub display {
my ($count) = @_;
my %frequency;
map {push @{$frequency{$count->{$_}}}, $_; } sort keys %{$count};
for my $key (sort keys %frequency) {
say "$key ", (join q{ }, @{$frequency{$key}}), "\n";
}
}
display(
countWords(
removePunctuation(
readText(
'./input'
)
)
)
);