So you have something like the following:

my $addr = 0x1234; my $ident = "abc"; my %by_addr = ( $addr => $ident ); my %by_ident = ( $ident => $addr );

A copy of the address and of the identifier are stored in the elements of each hash. (The key of an element is stored in the element to distinguish elements in collisions.) You can cut the number of scalars (or is it string buffers?) in half as follows:

use Data::Alias qw( alias ); sub find_undef_element { my ($hash) = @_; while (my ($key, $val) = each(%$hash)) { if (!defined($val)) { keys(%$hash); # Reset iterator. return $key; } } return undef; } my $addr = 0x1234; my $ident = "abc"; my %by_addr; my %by_ident; $by_addr{$addr} = undef; $by_ident{$ident} = undef; alias my $shared_addr = find_undef_element(\%by_addr); alias my $shared_ident = find_undef_element(\%by_ident); alias $by_addr{$shared_addr} = $shared_ident; alias $by_ident{$shared_ident} = $shared_addr;

Of course, constructing is going to be much slower. I think you can avoid iterating through the hash (and avoid using Data::Alias) by dropping to C, but if you can do that, you could use a C-based data structure and use strings instead of scalars.

Update: It seems that only the string buffers are getting shared, not the entire scalar.


In reply to Re: Bidirectional lookup algorithm? (Updated: further info.) by ikegami
in thread Bidirectional lookup algorithm? (Updated: further info.) by BrowserUk

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.