I just got done writing and debugging some code which made use of a sorted tied hash using DB_File BTREE. I was getting weird results which I was able to track down to my custom sorting algorithm. Shown below is the pared-down code containing both the working and non-working versions of the sorting algorithm:
use Fcntl;
use DB_File;
my $db_file = '/tmp/db_file';
unlink $db_file if -e $db_file;
my $btree_info = new DB_File::BTREEINFO;
$btree_info->{'flags'} = R_DUP;
my $comparison_type = shift @ARGV;
if (! $comparison_type) {
# this method works
$btree_info->{'compare'} = sub { my($a,$b) = @_; $a <=> $b };
} else {
# this method does not work
$btree_info->{'compare'} = sub { $_->[0] <=> $_->[1] };
}
$tied_hash_obj = tie( %tied_hash, 'DB_File', $db_file, O_RDWR|O_CREAT,
+ 0640, $btree_info )
or die "Can't tie tied_hash to $db_file: $!";
for ( 0 .. 20) {
$tied_hash{rand(100)} = ++$i;
}
my ($status, $k, $v);
for (
$status = $tied_hash_obj->seq($k, $v, R_FIRST);
$status == 0;
$status = $tied_hash_obj->seq($k,$v, R_NEXT)
) {
push @vals_sorted_by_keys, $v;
push @sorted_keys, $k;
}
print join("\n", @vals_sorted_by_keys),"\n********\n";
print join("\n", @sorted_keys),"\n";
Comparing $_->[0] and $_>[1] directly, leads to all the keys coming out equal to the very first key. Saving $_>[0] and $_>[1] to temporary variables eliminates this problem. Can someone explain this?