in reply to Sorting Problem

You need to print out a Content-Type header for your if condition, not just your else. You can/should use the header method in CGI.pm:
print $query->header;
That'll print out the HTTP header for you.

Also, when I just pasted in your code, it didn't compile, because you didn't declare $key, and you used strict. You can use

foreach my $key
to fix that.