/
ch-2.pl
58 lines (46 loc) · 1.08 KB
/
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
58
#!/usr/bin/perl
#
# Perl Weekly Challenge - 081
#
# Task #2: Frequency Count
#
# https://perlweeklychallenge.org/blog/perl-weekly-challenge-081
#
use strict;
use warnings;
frequency_count(fetch_words($ARGV[0]));
#
#
# SUBROUTINES
sub fetch_words {
my ($file) = @_;
open(my $fh, "<:encoding(UTF-8)", $file)
or die "ERROR: Unable to open $file: $!\n";
my %words = ();
while (my $line = <$fh>) {
chomp $line;
$line =~ s/\.//g;
$line =~ s/\"//g;
$line =~ s/\(//g;
$line =~ s/\)//g;
$line =~ s/\,//g;
$line =~ s/\'s//g;
$line =~ s/\-\-/ /g;
foreach my $word (split /\s/, $line) {
$words{$word} += 1;
}
}
close($fh);
return \%words;
}
sub frequency_count {
my ($words) = @_;
my %frequency = ();
foreach my $word (keys %$words) {
$frequency{$words->{$word}} .= " " . $word;
}
foreach my $count (sort { $a <=> $b } keys %frequency) {
my @words = split / /, $frequency{$count};
printf("%d%s\n", $count, join(" ", sort @words));
}
}