This is a good idea, although I think I may have made the problem statement over-specific—I'd really like to be able to handle any circular reference, not just a reference to an array of several copies of a single variable. Thus, maybe the appropriate thing to do would be
sub switch_var {
tie $_[2], to => $_[1];
}
package to;
sub TIESCALAR {
bless \$_[1] => $_[0];
}
sub STORE { ${$_[0]} = $_[1] }
sub FETCH { ${$_[0]} }
(There's some package out there already on CPAN that uses the
to package for similar effect, but I can't find it. UPDATE: It's
Tie::Util. Also, the functionality that I've described is quite similar—indeed, maybe identical—to that provided by
Tie::Coupler.)
I wonder if there's a non-tie-based solution? I might have to do switch_var several times, and going through many ties could get quite slow.