blob: c560ba5cacbceb51156881fa61e1117299bdc9cd (
plain)
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
|
#!/usr/bin/env perl
use v5.20;
use utf8;
use strict;
use warnings;
use autodie;
use feature qw(say signatures);
no warnings 'experimental::signatures';
use List::Util qw(reduce);
run_challenge();
sub run_challenge() {
my ($input_file) = @ARGV;
my $frequencies_to_words =
frequency_sort( words( sanitize_input( read_file($input_file) ) ) );
print_word_frequencies($frequencies_to_words);
}
sub print_word_frequencies($frequencies) {
say join( ' ', $_, @{ $frequencies->{$_} } )
for sort { $a <=> $b } keys %{$frequencies};
}
sub frequency_sort(@words) {
my %word_count;
$word_count{$_}++ for @words;
my %frequencies;
push @{ $frequencies{ $word_count{$_} } }, $_ for sort keys %word_count;
return \%frequencies;
}
# split the given string into words
sub words($str) {
return split( /\s+/, $str );
}
# replace illegal chars with whitespace
sub sanitize_input($input) {
return $input =~ s/[\."\(\),]|--|'s/ /rg;
}
# read the whole file
sub read_file($filename) {
local $/ = undef;
open( my $fh, '<', $filename );
my $out = <$fh>;
close($fh);
return $out;
}
|