SPUG: Reference to a hash
Matt Tucker
tuck at whistlingfish.net
Fri Mar 22 02:24:46 CST 2002
-- Jim Flanagan <jimfl at tensegrity.net> spake thusly:
> What you really want is an anonymous hashref, rather than a
> reference to a specific named hash. One way to get that is the loop
> that you have below. Another way is to just say
>
> $HoH{$key}{$heading} = {%hash};
>
> This creates a new, anonymous hash with the same keys/values as
> %hash.
Note that this essentially does a copy of the hash when you do that.
Sometimes a slightly more efficient solution is to use a locally scoped
hash that gets created anew each time. For instance, instead of:
while (my $line = <STDIN>) {
%hash = my_func($line);
...
$things{$key} = {%hash};
}
It would be slightly more efficient (for large hashes at least) to do:
while (my $line = <STDIN>) {
my %hash = my_func($line);
...
$things{$key} = \%hash;
}
Since %hash gets recreated each time through the loop, you don't have
the problem of it getting overwritten. This will only make a difference
for very large hashes, but I figured it was worth pointing out.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 232 bytes
Desc: not available
Url : http://mail.pm.org/archives/spug-list/attachments/20020322/d7be643c/attachment.bin
More information about the spug-list
mailing list