Now, when you iterate over the hash, it will always come out in sorted order you've specified.# 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} );
This stops the annoying need to say:print "$_\t$hash{$_}\n" foreach keys %hash; <code> will <b>always</b> produce: <code> Jim Baker 30 Jane Doe 39 John Doe 20
All the time.foreach ( sort keys %hash ) { ... }
I have also added the ability to update your sort block at any time:
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:(tied %hash)->newsortblock( q($b cmp $a) );
Feedback welcome, prefferably in the form of "Yeah, I like that" or "What tha...?"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;
-- Casey
In reply to Module Proposal: Tie::SortHash by cwest
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |