On 4/8/06, Nick Ing-Simmons <[EMAIL PROTECTED]> wrote:
>
> Ok, just checking that you didn't need access to VARIABLE for your
> "state" case to work.
no. State variable as tied is vastly inferior to externally scoped and
initialized native variable, but the package for it would look something like
package TiedState;
my %value;
sub TIESCALAR{
my ($pack, $initializer) = @_;
my @callerdata = caller;
exists [EMAIL PROTECTED]
or [EMAIL PROTECTED] = $initializer;
bless \(join $;, @callerdata);
};
sub FETCH{
return $value{${$_[0]}}
};
sub STORE{
$value{${$_[0]}} = $_[1];
};
sub clear{
delete $value{${$_[0]}};
};
__END__
=pod
tie a state variable like
sub some_routine_with_state{
tie my $statevar => TiedState => 'red';
...
};
and the first time it is seen it gets assigned the initializer value,
after that it works like a normal scalar variable. important:
each TiedState definition needs to be on its own line of code
due to the details of the implementation.
To clear a state variable so it will be reinitialized the next time
it gets tied, call the C<clear> method on the underlying reference:
tied($statevar)->clear;
This package is a demonstration of how to implement a state variable
using perltie. For production use, it is reccommended to prefer
an "externally initialized lexical" like so:
{ my $statevar = 'red';
sub some_routine_with_state{
...
};
}; # closes lexical scope for $statevar
I don't indent for scopes that are provided for variable visibility
restrictions only,
so I always put the declarations on the same line with their opening brace and
comment their closing brace.
=cut
------- end of file ------
Would anyone want this on CPAN? And if so what should it be named?
--
David L Nicol
Should the bike shed have bunks? Or maybe cots?