in reply to RE:(7) Hash of hashes question
in thread Hash of hashes question

My complete code is a CGI that spits out the results inside the tables, so it's a bit ugly. Here I've commented out the CGI line, so it will print out the HTML without the header. You might want to redirect the output to a file, and view it in a browser.

I did wrap each version into a sub, as a max() should usually be used that way.

Also note that this code REQUIRES perl 5.6.0. If you have an old version, you will need to replace "our" with "use vars"

#!/usr/bin/perl use strict; #use CGI qw( header ); print header(); use Benchmark; use Devel::OpProf qw(profile zero_stats stats ); profile(1); # turn on profiling our $now = 8; # we'll pretend it's between 8 and 9 PM our %url = ( monday => { @{[map(($_,1), (1..1000))]} } ); #start profiling $|++; print "<TABLE>\n"; print "<TR><TD>\n"; my_profile( "grep",\&test_grep ); print "</TD><TD>\n"; my_profile( "if/then/else",\&test_if_then ); print "</TD><TD>\n"; my_profile( "book max()",\&test_max ); print "</TD></TR>\n"; # now lets benchmark print "<TR><TD COLSPAN=3><PRE>"; timethese(10000, { bench_grep => q{ test_grep(); }, bench_if_then => q{ test_if_then(); }, bench_max => q{ test_max(); }} ); print "</PRE></TD></TR></TABLE>\n"; sub test_grep { $now = (sort grep {$_ <= $now} keys %{$url{'monday'}})[-1]; } sub test_if_then { $now = ($now < $_ && $_ < 8 ? $_ : $now) for keys %{$url{'monday'} +}; } sub test_max { foreach ( keys %{$url{'monday'}} ) { $now = $_ if $_ > $now } } sub my_profile { my $title = shift; my $test_sub = shift || return; zero_stats; &$test_sub; stats_td( $title ); # print_stats; } sub stats_td { my $title = shift; my %stats = %{stats()}; print "<TABLE><TR><TH COLSPAN=2>&nbsp;$title<BR><HR></TH></TR>\n"; while ( my ( $stat, $value ) = each %stats ) { $stat =~ s/</\&lt\;/; $stat =~ s/>/\&gt\;/; if ( $value ) { $value =~ s/>/\&gt\;/; $value =~ s/</\&lt\;/; print "<TR><TH>$stat</TH><TD>$value</TD></TR>\n"; } } print "</TABLE>\n"; }

I just whipped this up without much planning, so there are some problems with it. One is that the call to stat() should be in my_profile() not stats_td(). But, because of it's location in stats_td(), it is a O(1) error, and so it shouldn't skew the results much.

Paris Sinclair    |    4a75737420416e6f74686572
pariss@efn.org    |    205065726c204861636b6572
I wear my Geek Code on my finger.