Irrelevant has asked for the wisdom of the Perl Monks concerning the following question:
Say I've created an object with some class' new() method, and have references to it in various places. If I then want to replace the object - in all of these places - with another one, the intuitive thing doesn't work:
as it only changes that one reference.$a_ref_to_the_object = Class->new;
The following hack does work, but only if the object is stored internally as a hash:
However, this assumption is A Bad Thing, as the code will fall over if the internal representation changes. It also will not work if the object is tied.%$a_ref_to_the_object = %{Class->new};
This would work in a more general way:
but it would still fail if the object was tied, and it pains me to rely on eval()'s exception trapping.sub retarget_ref { my ($old, $new) = @_; ref $old and ref $new or return; local $SIG{__DIE__}; # disable any user error handlers eval { $$old = $$new }; $@ or return; eval { @$old = @$new }; $@ or return; eval { %$old = %$new }; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Changing the target of refs of unknown type
by Corion (Patriarch) on Feb 06, 2005 at 21:39 UTC | |
|
Re: Changing the target of refs of unknown type
by gaal (Parson) on Feb 06, 2005 at 21:01 UTC | |
|
Re: Changing the target of refs of unknown type
by stvn (Monsignor) on Feb 06, 2005 at 21:01 UTC | |
|
Re: Changing the target of refs of unknown type
by Fletch (Bishop) on Feb 06, 2005 at 23:24 UTC | |
|
Re: Changing the target of refs of unknown type
by Irrelevant (Sexton) on Feb 06, 2005 at 21:43 UTC |