#! /Users/jj/bin/perl5.10.0 use 5.010; use strict; use warnings; use autobox; use autobox::Core; use IO::File; #--Set up some additional autobox functions-------------------------------- sub SCALAR::open { my $filename = shift; my $filehandle = IO::File->new(); $filehandle->open($filename,@_); return $filehandle; } sub IO::File::getlines { my $filehandle = shift; my @lines = (<$filehandle>); return wantarray ? @lines : \@lines; } sub ARRAY::strip { my $ref = shift; my @data = map { s/^\s+//; s/\s+$//; $_ } @$ref; return wantarray ? @data : \@data; } sub ARRAY::split { my $ref = shift; my $spl = shift; my @data = map { [split $spl,$_] } @$ref; return wantarray ? @data : \@data; } sub ARRAY::last { # The 'last' function is already defined in autobox::Core, but returns # the _index_ of the last element, not the element itself. # # This behaviour is contradictory to the corresponding 'first' function # (which returns the first element, not the first index) so I am # redefining it here to DWIM :-) my $array = CORE::shift; return $array->[-1]; } #--Now, back to the show--------------------------------------------------- my @votes = 'votes.txt'->open->getlines->strip->split(','); my ($rank,%total); my $compare_votes = sub {$total{$_[1]} <=> $total{$_[0]}}; do { undef %total; $total{$_->first}++ foreach @votes; $rank = %total->keys->sort($compare_votes); @votes = map {$_->grep( sub{$_ ne $rank->last} )} @votes; } until ($total{$rank->first} / @votes > 0.5); printf ("The winner is %s with %f%%\n",$rank->first,$total{$rank->first}/@votes*100);