#!/usr/bin/perl -w use strict; my $path = "C:/Scripts/votes.txt"; # read votes my @votes; open my $fh, '<', $path; while (<$fh>) { chomp; my @items = split /,/, $_; push @votes, \@items; } close $fh; my ($winner, $percentage) = process_votes ( votes => \@votes ); printf "The winner is %s with %.2f of the vote.\n", $winner, $percentage; sub process_votes { # recursive function my %options = @_; my @votes; if ($options{exclude}) { foreach (@{$options{votes}}) { my @valid = grep { $_ ne $options{exclude} } @{$_}; push @votes, \@valid; } } else { @votes = @{$options{votes}}; } my (%candidate, $total); foreach (@votes) { $candidate{$_->[0]}->{votes}++; $total++; } my $winner; foreach (keys %candidate) { $candidate{$_}->{percent} = (100 * $candidate{$_}->{votes}) / $total; } my @sorted = sort { $candidate{$b}->{percent} <=> $candidate{$a}->{percent} } keys %candidate; if ($candidate{$sorted[0]}->{percent} > 50) { return ($sorted[0], $candidate{$sorted[0]}->{percent}); } else { process_votes( votes => \@votes, exclude => $sorted[$#sorted], ); } }