#!/usr/bin/perl -wT use CGI qw(:standard); use CGI::Carp qw(warningsToBrowser fatalsToBrowser); use strict; use Fcntl qw(:flock :seek); my $outfile = "/home/www/book/ch6/poll.out"; print header; print start_html("Results"); # open the file for reading open(IN, "$outfile") or &dienice("Couldn't open $outfile: $!"); # set a shared lock flock(IN, LOCK_SH); # then seek the beginning of the file seek(IN, 0, SEEK_SET); my $total_votes = 0; my %results = (); # initialize all of the counts to zero: foreach my $i ("fotr", "ttt", "rotk", "none") { $results{$i} = 0; } while (my $rec = <IN>) { chomp($rec); $total_votes++; $results{$rec}++; } close(IN); # new stuff: calculate and format percentages my %percents = (); foreach my $key (keys %results) { my $percent = ($results{$key} / $total_votes ) * 100; $percents{$key} = sprintf("%2d %%", $percent); } my %titles = ("fotr", "Fellowship of the Ring", "ttt", "The Two Towers", "rotk", "Return of the King", "none", "didn't watch them"); # now display a summary. use qq and a foreach loop # to save some typing. print qq( <b>Which was your favorite <i>Lord of the Rings</i> film?</b><br> <table border=0 width=50%> ); foreach my $i ("fotr", "ttt", "rotk", "none") { print qq(<tr> <td>$titles{$i}</td> <td>$percents{$i}</td> <td>$results{$i} votes</td> </tr> ); } print qq( </table> <p>$total_votes votes total</p> ); print end_html; sub dienice { my($msg) = @_; print h2("Error"); print $msg; print end_html; exit; }