Re: To Reference or not to reference



Don Dukelow wrote:
I've written a Perl program that declares a hash at the top of the
program "%myHask;". It has worked great until now when one sub
program seams to be making its own copy of the hash. I can find no
typo's or anything but there my still be one there. My question is
would it be better to pass the global hash by reference to each sub
program to cut down on possible typo errors or just leave it global
and fix the problem I have?

There's no problem in copying a hash (or array) until it contains references to any other objects (scalars, hashes, arrays, whatever).

If it has, like in this example:
%o1 =
(
a => {d => 0},
b => {e => 1},
c => 2,
);

%o2 = %o1;

then the copy gets the same references, that is, $o1{a} and $o2{a} (same for {b}) will point/reference to the same object, which means if you modify it through %o1, you see the modification in %o2 too or in other words, they share data, instead of having separate copies of it.
If this is your problem, you can do a deeper copy of a hash with something like this:

sub CopyHash
{
my ($rInHash) = @_;
my %OutHash = ();
foreach my $k (keys %$rInHash)
{
my $s = $$rInHash{$k};
if ($s =~ /^HASH\(0x[0-9A-F]*\)$/i)
{
my %tmph = %{$$rInHash{$k}};
$OutHash{$k} = \%tmph;
}
else
{
$OutHash{$k} = $s;
}
}
return %OutHash;
}
%o3 = CopyHash(\%o1);

But the above won't work if the hash has reference to a hash which in turn has a reference to an object. The above routine doesn't go deeper than one level of nesting.

Alex

.



Relevant Pages

  • AW: returning hashes, and arrays
    ... It is much better to use reference when passing or retrieving more than ... Retrieve the values from a sub as refereces. ... I'm having trouble returning a hash from a subroutine, ... Must the hash and array really be a reference ...
    (perl.beginners)
  • Re: Problems passing a reference to a hash between functions
    ... > I have a sub which calls the fetchall_hashref method from the DBI ... > always pass a variable by reference and populate that variable. ... Declare a reference to a hash, ... subroutine, so when the subroutine sets $_, your changes will be ...
    (comp.lang.perl.misc)
  • Re: looking for help with a counting algorithm
    ... >> subcategory is counted, the code goes back up the tree to the root, adding ... >> involve retrieving all the category memberships from the database, ... sub ReadCategories{ ... ReadCategories is called with two empty hash pointers by any of the ...
    (comp.lang.perl.misc)
  • Re: Perl Bug or stupidity on my part? - I looked in FAQs and dejanews prior to posting
    ... > I am passing a reference to a hash where the key is a scalar and each ... > value is a reference to an array to another sub. ...
    (comp.lang.perl.misc)
  • Re: question plz
    ... That is the Perl dereferencing operator. ... Which offers a reference to an anonymous hash initiated with the pairs ... sub print_key_words { ...
    (perl.beginners)