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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
RE: Module Proposal: Tie::SortHash
by KM (Priest) on Aug 18, 2000 at 23:36 UTC | |
by cwest (Friar) on Aug 18, 2000 at 23:46 UTC | |
by KM (Priest) on Aug 18, 2000 at 23:58 UTC | |
by jettero (Monsignor) on Aug 19, 2000 at 16:47 UTC | |
by KM (Priest) on Aug 21, 2000 at 17:11 UTC | |
by jettero (Monsignor) on Aug 21, 2000 at 20:01 UTC | |
|
RE (tilly) 1: Module Proposal: Tie::SortHash
by tilly (Archbishop) on Aug 19, 2000 at 00:06 UTC | |
by cwest (Friar) on Aug 19, 2000 at 00:13 UTC | |
by tilly (Archbishop) on Aug 19, 2000 at 00:18 UTC | |
|
RE: Module Proposal: Tie::SortHash
by chip (Curate) on Aug 20, 2000 at 14:02 UTC | |
|
(zdog) RE: Module Proposal (Is this the place for it?)
by zdog (Priest) on Aug 19, 2000 at 05:10 UTC |