genecutl has asked for the wisdom of the Perl Monks concerning the following question:
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?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";
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Sorted tied hash wierdness
by Chmrr (Vicar) on Nov 18, 2003 at 23:49 UTC | |
by genecutl (Beadle) on Nov 19, 2003 at 00:01 UTC | |
Re: Sorted tied hash wierdness
by Roger (Parson) on Nov 19, 2003 at 00:03 UTC |