This is a little tricky - if you weren't storing the data with DB_File I'd point you to Tie::IxHash which allows in-order storage/retrieval for Hashes. But of course that is already tieing the hash.
The best way I can see to do this is to embed some information in your key that can be used to still sort the data and store it in a BTREE. Otherwise just keep two lists - one for your data (the DB_HASH you already have) and an array which stores the order you have inserted things. Of course it has to be kept up to date when you remove things and that can get obnoxious.
Here is some code that would let you store things in-order. This hides the key revisions using filter_store_key and filter_fetch_key. The key thing here is that you can't use the hash functions but need to use OO interface instead {seq,put,get,del}. Hopefully you can get by with that. BerkeleyDB may have a nicer interface for what you need I'm not sure.
#!/usr/bin/perl -w
use strict;
use DB_File;
my %myhash;
my $keycount = 0; # if you're going to go away and come back
# from this program - make keycount persistent data somehow
# simple interface
my $filename = undef; # leave it undef for in-memory BDB
my $b = new DB_File::BTREEINFO;
$b->{'compare'} = \&_compare;
my $db = tie(%myhash, 'DB_File', $filename, O_CREAT|O_RDWR, 0666, $b);
$db->filter_store_key(sub { $_ .= "-".$keycount++;} );
$db->filter_fetch_key(sub { $_ =~ s/\-(\d+)$//; $_; } );
my ($key);
$key = 'first';
$db->put($key,10);
$key = 'second';
$db->put($key,12);
$key = 'third';
$db->put($key,8.0);
$key = 'fourth';
$db->put($key,'#five');
$key = undef;
my ($val,$status);
for( $status = $db->seq($key, $val, R_FIRST);
$status == 0 ;
$status = $db->seq($key,$val,R_NEXT) ) {
print "$key -> $val\n";
}
sub _compare {
my ($key,$key2) = @_;
my $rc;
# a little bit of protection here in case
# something wacky happens you don't get hit
# with undef errors out the wazzo.
if( (my ($orderpart1) = ($key =~ /\-(\d+)/)) &&
(my ($orderpart2) = ($key2 =~ /\-(\d+)/) )) {
$rc = $orderpart1 <=> $orderpart2;
} else {
$rc = $key cmp $key2;
}
$rc;
}
|