my @ordered_keys; if ($sort eq 't') { # Calculate the order in which we want to process %tests. # (Sort keys by ascending numerical Total.) @ordered_keys = sort { $tests{$a}{Total} <=> $tests{$b}{Total} } keys %tests; } elsif ($sort eq 'v') { # Calculate the order in which we want to process %tests. # (Sort keys by ascending numerical Value.) @ordered_keys = sort { $tests{$a}{Value} <=> $tests{$b}{Value} } keys %tests; } foreach my $key (@ordered_keys) { my $val = $tests{$key}; print "$key\n"; print " Total: $val->{Total}\n"; print " Value: $val->{Value}\n\n"; } #### my $sorter; if ($sort eq 't') { # Sort keys by ascending numerical Total. $sorter = sub { my ($tests) = @_; return sort { $tests->{$a}{Total} <=> $tests->{$b}{Total} } keys %$tests; }; } elsif ($sort eq 'v') { # Sort keys by ascending numerical Value. $sorter = sub { my ($tests) = @_; return sort { $tests->{$a}{Value} <=> $tests->{$b}{Value} } keys %$tests; }; } foreach my $key ($sorter->(\%tests)) { my $val = $tests{$key}; print "$key\n"; print " Total: $val->{Total}\n"; print " Value: $val->{Value}\n\n"; }