Re: To Reference or not to reference
- From: "Alexei A. Frounze" <alexfru@xxxxxxx>
- Date: Thu, 29 Mar 2007 09:14:09 -0700
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
.
- References:
- To Reference or not to reference
- From: Don Dukelow
- To Reference or not to reference
- Prev by Date: Re: XML parsing REST responses
- Next by Date: RE: Exiting loops
- Previous by thread: Re: To Reference or not to reference
- Next by thread: How does one get the difference between 2 dates/times and output in seconds?
- Index(es):
Relevant Pages
|
|