[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index][Thread Index][Top&Search][Original]

How should local work with tied scalars?



I posted this to moderated a few weeks ago with no response.  Perhaps I
bored everyone with the code so they never got to my questions.  :-(

Then I posted to misc but it never got through.  I'm taking that as a
sign that it really belongs here.

This time I've put the questions first but they still refer to the code
that follows them.

First, is this what I should expect for localizing tied scalars?  i.e. a
FETCH of the old value, a STORE of "" (why?) and then a STORE of the new
value.  I didn't see this documented anywhere.

Second, why does the first case call FETCH again for each STORE (but
only when localized) while the second cases never do?  Something to do
with the alias?

I'm finding this confusing and don't think I could predict the behaviour
of a similar piece of code.

My code:

Case 1:

#!/usr/local/bin/perl -lw

package A;
sub TIESCALAR { my ($pkg, $value) = @_; bless \$value => $pkg }
sub FETCH     { print "FETCH '${ $_[0] }'"; return ${ $_[0] } }
sub STORE {
    print "STORE '$_[1]'";
    ${ $_[0] } = $_[1];
    B::foo();
    return ${ $_[0] };
}

package B;
tie $x, 'A';

sub foo { my $foo = $x }

package main;
*x = \$B::x;
$x = 1;
print $x;
{;
    print "begin local";
    local $x = 4;
    print "end local";
    print $x;
}
print $x;

package main;
sub foo { my $foo = $x }

__END__

Which gives:

STORE '1'
FETCH '1'
1
begin local
FETCH '1'
STORE ''
FETCH ''
STORE '4'
FETCH '4'
end local
FETCH '4'
4
STORE '4'
FETCH '4'
4

Case 2:

If I comment out the lines

package main;
*x = \$B::x;

or change the call to B::foo to main::foo then I get

STORE '1'
FETCH '1'
1
begin local
FETCH '1'
STORE ''
STORE '4'
end local
FETCH '4'
4
STORE '1'
FETCH '1'
1

-- 
Rick Delaney
rick.delaney@home.com


Follow-Ups from:
Ilya Zakharevich <ilya@math.ohio-state.edu>

[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index][Thread Index][Top&Search][Original]