#!/usr/bin/perl -w # vim:ts=4:sw=4 # Summary: CGI to count prevalence of birth months and draw pretty graphs. # Author: Chris Ball. # Function: To do silly things with graphs. use CGI qw/-no_xhtml :standard/; use CGI::Carp qw(fatalsToBrowser); use GD::Graph::pie; use strict; my ($name, $month); my @data; my (%name_month, %halfyear_freq, %season_freq); my $filename = "birthmonths.dat"; # Going to print the HTML page before input. print header, # Print the HTTP headers. start_html('Birth months.'), h1('Birth months.'), start_form, "Your name: ", textfield('name'), br, "Your birth month (1-12): ", textfield('month'), p, submit, end_form, hr; # If we have input, write it to the flat file. if ( param() ) { $name = param('name'); # Set local variables to the input $month = param('month'); # from the form. open(FILE, ">>$filename"); # open $filename for append/create if ($month > 0 and $month < 13) { print FILE "$name||$month\n"; } close(FILE); # reached EOF - close the file. } # Read the hashes from the file. open(FILE, "<$filename"); # open $filename for read while () { ($name, $month) = split(/\|\|/); $name_month{$name} = $month; } # Prep a table. print '
'; # Print name => month, create a hash of test => frequency. while (($name, $month) = each %name_month) { print ""; if (($month > 0) and ($month < 13)) { $season_freq{($month<10 and $month>3) ?"summer":"winter"}++; $halfyear_freq{($month>0 and $month<7) ?"onetosix":"seventotwelve"}++; } } # Tidy up the table. print '
NameBirthmonth
$name$month

'; # Print the totals. print "Total number of entries: " . scalar(keys(%name_month)) . "

"; print "January-June: $halfyear_freq{onetosix}
"; print "July-December: $halfyear_freq{seventotwelve}

"; print "April-September (Summer): $season_freq{summer}
"; print "October-August (Winter): $season_freq{winter}
"; # Prepare space for the image. print '
'; print '

'; # Graph one: 1-6/6-12 # Prepare GD's two-dimensional array. $data[0]=(["Months 1-6","Months 7-12"]); $data[1]=([$halfyear_freq{onetosix},$halfyear_freq{seventotwelve}]); # Plot. my $graph = GD::Graph::pie->new(400, 300); $graph->set( title => 'Geek birthdays - Half-year by Frequency.' ); my $gd = $graph->plot(\@data); open(IMG, '>halfyear.png') or die $!; binmode IMG; print IMG $gd->png; # Graph two: summer/winter # Prepare GD's two-dimensional array. $data[0]=(["Summer","Winter"]); $data[1]=([$season_freq{summer},$season_freq{winter}]); # Plot. my $graph = GD::Graph::pie->new(400, 300); $graph->set( title => 'Geek birthdays - Season by Frequency.' ); $graph->set( dclrs => [ qw(cyan lorange) ] ); my $gd = $graph->plot(\@data); open(IMG, '>season.png') or die $!; binmode IMG; print IMG $gd->png; print end_html; # wrap up the html..