Last active
May 15, 2018 14:39
-
-
Save grimm26/655a37578147fd0b9cf6a4c766479824 to your computer and use it in GitHub Desktop.
count vowels
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
# | |
use strict; | |
my %vowels = ( | |
a => 0, | |
e => 0, | |
i => 0, | |
o => 0, | |
u => 0 | |
); | |
while(<>) { | |
my @chars = split '' ; | |
&count_vowels(\%vowels, \@chars); | |
} | |
&print_vowel_counts(\%vowels); | |
&print_most_common_vowel(\%vowels); | |
### subs | |
sub print_vowel_counts { | |
my $rh_counts = shift; | |
my $total = 0; | |
foreach my $vowel (sort keys %$rh_counts) { | |
print "$vowel => $rh_counts->{$vowel}\n"; | |
$total += $rh_counts->{$vowel}; | |
} | |
print "\nTotal vowels = $total\n"; | |
} | |
sub count_vowels { | |
my $rh_counts = shift; | |
my $rl_chars = shift; | |
foreach my $char (@$rl_chars) { | |
if (defined $rh_counts->{$char}) { | |
$rh_counts->{$char}++; | |
} | |
} | |
} | |
sub print_most_common_vowel { | |
my $rh_vowels = shift; | |
my $rh_flipped = &flip_hash($rh_vowels); | |
foreach my $count (sort numerically keys %$rh_flipped) { | |
print 'Most common vowel'. ($#{$rh_flipped->{$count}} > 0 ? 's' : '') .': '. join(',',@{$rh_flipped->{$count}}) ." ($count)\n"; | |
last; | |
} | |
} | |
sub flip_hash { | |
my $rh_hash = shift; | |
my %new; | |
while(my ($k, $v) = each %$rh_hash) { | |
push(@{$new{$v}}, $k); | |
} | |
return \%new; | |
} | |
sub numerically { $b <=> $a } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment