Fixing your code so that it works and also demonstrates that things don't stop being tied shows that my code works fine with such things …
I agree that my code isn't a very
good implementation of a
tied variable, but it is what I meant (UPDATE 3: except for the silly out-of-place
$class), and fixing it breaks the example. :-) (Your code doesn't quite fix it, because you try to assign to a read-only variable. Something like
sub Tie::TIESCALAR { return bless \( my $o = $_[1] ) => $_[0] } would be better, I think.)
As a less offensive example, if I replace your STORE by
sub Tie::STORE {
${$_[0]} = $_[1] unless defined ${$_[0]}
}
then it's clear that the
localisation isn't really protecting anything in the inner scope from changing:
tie my $x, 'Tie';
my $f = sub { $x };
{
my $scope = tempSet(\$x, 2);
print $f->(), "\n"; # => 2 is still tied
}
$x = 1;
print $f->(), "\n"; # => 2 is still tied
Your comment
Yes, in contrast, local is implemented in a way that it temporarily hides the tied nature of the localized scalar.
hits the nail on your head—I want precisely something that has the
same effect for lexicals, of setting aside their previous value, whatever that value is, and restoring it undisturbed afterwards. (In particular,
$x should not be
tied in the inner scope, even if it is outside.)
UPDATE 1: Actually, testing with tie our $x, 'Tie' and an interior local $x seems to show that localisation of globals doesn't behave the way I want, either! (See Re^6: Local for lexicals (untie) for a simpler example.)
UPDATE 2: Changed if defined test to unless defined.