#! /Users/jj/bin/perl5.10.0 use strict; use warnings; my @votes; open VOTES,'<','votes.txt' or die "Cannot open votes.txt: $!"; while () { chomp; # Removes newline # The split command splits a string into a list and returns that list # Enclosing a list with square brackets [..] creates a reference push @votes,[split /,/]; } close VOTES; my (@rank,%total); do { # Clear out the previous totals undef %total; # Count the votes $total{$_->[0]}++ foreach (@votes); # Rank the candidates in order @rank = sort {$total{$b} <=> $total{$a}} keys %total; # Remove the loser from the list of votes foreach my $vote (@votes) { # $vote is an array reference, so @$votes gives us the complete array # # $vote is also an alias, so modifying it will change the 'real' # vote in the @votes array # # The 'grep' command filters an array based on an expression, locally # setting $_ to each element of the array $vote = [ grep {$_ ne $rank[-1]} @$vote ]; } # Repeat until we have a winner (someone gets more than 50% of the votes) } until ($total{$rank[0]} / @votes > 0.5); printf ("The winner is %s with %f%%\n",$rank[0],$total{$rank[0]}/@votes*100);