diff options
| author | Steven Wilson <steven1170@zoho.eu> | 2019-10-28 20:30:11 +0000 |
|---|---|---|
| committer | Steven Wilson <steven1170@zoho.eu> | 2019-10-28 20:30:11 +0000 |
| commit | 9387b63ffdb79b3858cfea0df34c9d935ae146fd (patch) | |
| tree | 4da71859120e257066683006ded27557fcea4685 | |
| parent | 0fd7ce4b2b3450ccfdfb5e8bb2e804577c4d7a31 (diff) | |
| download | perlweeklychallenge-club-9387b63ffdb79b3858cfea0df34c9d935ae146fd.tar.gz perlweeklychallenge-club-9387b63ffdb79b3858cfea0df34c9d935ae146fd.tar.bz2 perlweeklychallenge-club-9387b63ffdb79b3858cfea0df34c9d935ae146fd.zip | |
add solution to week 32 task 1
| -rw-r--r-- | challenge-032/steven-wilson/perl5/ch-1.pl | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/challenge-032/steven-wilson/perl5/ch-1.pl b/challenge-032/steven-wilson/perl5/ch-1.pl new file mode 100644 index 0000000000..99b1e44d31 --- /dev/null +++ b/challenge-032/steven-wilson/perl5/ch-1.pl @@ -0,0 +1,53 @@ +#!/usr/bin/env perl +# Author: Steven Wilson +# Date: 2019-10-28 +# Week: 032 + +# Task #1 + +# Count instances +# Create a script that either reads standard input or one or more files +# specified on the command-line. Count the number of times and then +# print a summary, sorted by the count of each entry. +# So with the following input in file example.txt +# apple +# banana +# apple +# cherry +# cherry +# apple +# the script would display something like: +# apple 3 +# cherry 2 +# banana 1 +# For extra credit, add a -csv option to your script, which would generate: +# apple,3 +# cherry,2 +# banana,1 + +use strict; +use warnings; +use feature qw/ say /; + +my %word_count; +my $delimiter = "\t"; +if ( $ARGV[0] eq "-csv" ) { + shift @ARGV; + $delimiter = ","; +} + +for my $file (@ARGV) { + open my $fh, '<', $file or die "Can't open < $file: $!"; + while ( !eof $fh ) { + my $word = readline $fh; + chomp $word; + $word_count{$word} += 1; + } +} + +my @word_count_desc + = reverse sort { $word_count{$a} <=> $word_count{$b} } keys %word_count; + +for my $word (@word_count_desc) { + say "$word$delimiter$word_count{$word}"; +} |
