Unsorted List:beta, apple, gamma globulin, alpha, zeta, gesorenplatz!!, gamma, delta, foolish mortal, Sorted List:, beta, zeta, alpha, apple, delta, gamma, foolish mortal, gamma globulin, gesorenplatz!! #### #!/usr/bin/perl -w # # Orcish_Ex.pl # # Exercises from the "Orcish Sorting" section of perlmonks tutorial node # "Resorting to Sorting" (id=node 128722). # # Exercise 1: # Q: Why should you make the caching hash viewable only by the # sorting function? How is this accomplished? # # A: To avoid namespace pollution. By declaring locally in a block. # (My answers. I haven't checked 'em yet.) # NOTE: while coding it up, I started to suspect that %cache should # be nulled out, or successive sort calls could botch it up. Is it # a problem? See Orcish_Ex_test.pl # # Exercise 2: # Use Orcish Manuever to sort a list of strings in the same way as # described in Naive section, Exercise 1. # # Note: Yes, there is an intentional blank line at the end so we can see # where the empty string will sort to! # use strict; use warnings; # Orcish section { my %cache; sub len_or_str { my $va = ($cache{$a} ||= [ length($a), substr($a,0,5) ]); my $vb = ($cache{$b} ||= [ length($b), substr($b,0,5) ]); return ($va->[0] <=> $vb->[0]) or ($va->[1] cmp $vb->[1]); } sub print_cache { print "Cache after sort:\n"; for my $k (keys %cache) { print "\t", $k, " => [", $cache{$k}->[0], ", ", $cache{$k}->[1], "]\n"; } } } sub print_msg_list { my $msg = shift @_; print $msg, join(", ", @_), "\n"; } my @unsorted = ; chomp @unsorted; &print_msg_list("Unsorted List:", @unsorted); my @sorted = sort len_or_str @unsorted; &print_msg_list("Sorted List:", @sorted); &print_cache; __DATA__ beta apple gamma globulin alpha zeta gesorenplatz!! gamma delta foolish mortal