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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|