Try this on for size:

#!/usr/bin/perl -w use Carp; my %people = ( Bob => { age => 60, town => 'Harrisburg' }, Joe => { age => 55, town => 'Calgary' }, Sue => { age => 40, town => 'Houston' }, Jim => { age => 42, town => 'Dresden' }, Ann => { age => 47, town => 'Los Angeles' }, ); my %data_types = ( age => 'numeric', town => 'text', # etc... ); sub sort_people_by { my ($people,$sortby,$dir) = @_; my $dtype = $data_types{$sortby}; if(!$dtype) { croak "No data type defined for $sortby"; } elsif($dtype eq 'numeric') { if($dir eq 'ASC') { return sort { $people->{$a}->{$sortby} <=> $people->{$b}->{$sortby} } keys %$people; } else { return sort { $people->{$b}->{$sortby} <=> $people->{$a}->{$sortby} } keys %$people; } } elsif($dtype eq 'text') { if($dir eq 'ASC') { return sort { $people->{$a}->{$sortby} cmp $people->{$b}->{$sortby} } keys %$people; } else { return sort { $people->{$b}->{$sortby} cmp $people->{$a}->{$sortby} } keys %$people; } } else { croak "Data type $dtype unknown"; } } sub print_people_sorted_by { my ($people,$sortby,$dir) = @_; foreach my $person (sort_people_by($people,$sortby,$dir)) { print "$person - $people{$person}{$sortby}\n"; } } print_people_sorted_by(\%people,'age','ASC'); print_people_sorted_by(\%people,'town','DESC');

Updated style to be closer to PBP, since I need the practice anyways - old habits die hard :)


In reply to Re: sort direction by ph713
in thread sort direction by rsiedl

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.