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?

In reply to Sorted tied hash wierdness by genecutl

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.