I want to hear what you think. I've got a module written called Tie::SortHash. I think it's something everyone can use. Observe:
# tie HASH, 'Tie::SortHash', ANON_HASH, SORT_EXPR tie my %hash, 'Tie::SortHash', { 'John Doe' => 25, 'Jane Doe' => 39, 'Jim Baker' => 30 }, q( my( $c, $d ) = ( $a, $b ); $c =~ s/\w+\s//; $d =~ s/\w+\s//; $c cmp $d || $hash{$b} <=> $hash{$ +a} );
Now, when you iterate over the hash, it will always come out in sorted order you've specified.
print "$_\t$hash{$_}\n" foreach keys %hash; <code> will <b>always</b> produce: <code> Jim Baker 30 Jane Doe 39 John Doe 20
This stops the annoying need to say:
foreach ( sort keys %hash ) { ... }
All the time.

I have also added the ability to update your sort block at any time:

(tied %hash)->newsortblock( q($b cmp $a) );
And the sort block must be passed as a non-interpolated string becuase it was the only way to allow complex sorts. ( ie. sort on value ). And inside the sort string, the variable %hash is generic, it would be the same for this example:
my %people = ( 'John Doe' => 25, 'Jane Doe' => 39, 'Jim Baker' => 30 ); my $sortblock = q( my( $c, $d ) = ( $a, $b ); $c =~ s/\w+\s//; $d =~ s/\w+\s//; $c cmp $d || $hash{$b} <=> $hash{$a} ); tie %people, 'Tie::SortHash', { %people }, $sortblock;
Feedback welcome, prefferably in the form of "Yeah, I like that" or "What tha...?"
--
Casey

In reply to Module Proposal: Tie::SortHash by cwest

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.