in reply to Re: (MeowChow) Re: Aliasing Variables
in thread Aliasing Variables

Look carefully at the sequence and line numbers of the carp output from this:
  
use strict; use vars qw($obj); use Carp qw(carp croak cluck confess); use Cwd; sub TIESCALAR { my $var; carp "tie:\t",\$var," = $_[0]\n"; bless \$var + => shift; } sub FETCH { carp "fetch:\t$_[0] == ${$_[0]}\n"; ${$_[0]} } sub STORE { carp "store:\t$_[0] = $_[1]\n"; ${$_[0]} = $_[1]} tie $obj => 'main'; $obj = 'foo'; { my $x = 1; my $y = $obj; local $obj = 'bar'; } ### OUTPUT ### tie: SCALAR(0x8106d78) = main main::TIESCALAR('main') called at - line 10 store: main=SCALAR(0x8106d78) = foo main::STORE('main=SCALAR(0x8106d78)', 'foo') called at - line +11 fetch: main=SCALAR(0x8106d78) == foo main::FETCH('main=SCALAR(0x8106d78)') called at - line 14 fetch: main=SCALAR(0x8106d78) == foo main::FETCH('main=SCALAR(0x8106d78)') called at - line 15 store: main=SCALAR(0x8106d78) = main::STORE('main=SCALAR(0x8106d78)', undef) called at - line +15 store: main=SCALAR(0x8106d78) = bar main::STORE('main=SCALAR(0x8106d78)', 'bar') called at - line +15 store: main=SCALAR(0x8106d78) = foo main::STORE('main=SCALAR(0x8106d78)', 'foo') called at - line +13
I'm not sure exactly what you're asking, but I think this may answer your question :-)
   MeowChow                                   
               s aamecha.s a..a\u$&owag.print

Replies are listed 'Best First'.
Re: (MeowChow - tied local wierdness) Re3: Aliasing Variables
by John M. Dlugosz (Monsignor) on Jul 23, 2001 at 02:50 UTC
    Yes, that matches what this node relies on, that local works by saving the old value and restoring it, exactly like assignments would. In your example, $obj is always pointing to the same SV.

    However, using Alias, e.g. from the module:

    @DYNAMIC = qw(m n o); { local @DYNAMIC; alias DYNAMIC => $tmp, PERM => $tmp; $DYNAMIC[2] = 'zzz'; # prints "abzzzd|abzzzd|abzzzd" print @$tmp, "|", @DYNAMIC, "|", @PERM, "\n"; } # prints "mno|pqr" print @DYNAMIC, "|", @PERM, "\n";
    The Alias re-binds the symbol @DYNAMIC, essentially the same as *DYNAMIC=$tmp;. @DYNAMIC now aliases @$tmp.

    But look at the local. It will restore the list @DYNAMIC, which means it will un-do this binding operation. If going out of scope does a STORE as you show, essentially @DYNAMIC=@saved;, it will overwrite the contents of @$tmp, as opposed to restoring the action of the *DYNAMIC=$tmp;. Follow me? He did not say local *DYNAMIC.

    If local worked by pointing the symbol to a new SV, then there would be no need to FETCH/STORE, and the tie would not be preserved.

    So there is still more to it than meets the eye.

    —John