Coro-LocalScalar

 view release on metacpan or  search on metacpan

LocalScalar.pm  view on Meta::CPAN

use Carp;
use Scalar::Util qw/weaken/;
our $VERSION = '0.21';

=head1 NAME

Coro::LocalScalar - local() for Coro

=head1 ABOUT

Perl local() function unuseful for Coro threads. This module uses tie magick to make scalar local for each Coro thread. Unlike L<Coro::Specific> this module destroys all data attached to coroutine when coroutine gets destroyed. It's useful when you n...

=head1 SYNOPSIS

	use Coro;
	use Coro::LocalScalar;
	use Coro::EV;
	
	my $scalar;
	
	Coro::LocalScalar->new->localize($scalar);

LocalScalar.pm  view on Meta::CPAN

	
	my $local_lvalue_closure = $obj->closure; # lvalue coderef
	
	$local_lvalue_closure->() = "local data"; # no tie magick used
	

	
	my $testobj = Someclass->new;
	
	# attach setter/getter and tied hash element to your object
	$obj->attach($testobj, 'element_local_in_coros');
	
	$testobj->element_local_in_coros("data");
	$testobj->element_local_in_coros = "data";
	
	$testobj->{element_local_in_coros}; # tie magick used


=cut





sub new { bless {} } 
sub TIESCALAR {$_[1]};

LocalScalar.pm  view on Meta::CPAN

	$_[0];
}




sub _proto : lvalue {
	my $self = shift;
	
	unless(exists($self->{$Coro::current})){
		my $coro = $Coro::current;
		
		$self->{$coro} = undef;
		
		# init coro data destructor
			$coro->on_destroy(sub {
				
				${ $self->{scalar} } = undef; # Delete scalar value to prevent unexpected behavior
				#perl stores values in scalar even if it tied. When Coro::LocalScalar destroys internal value, value stored in scalar still persists although you expected that it would be deleted( and DESTROY called if it`s object)
				
				delete $self->{$coro};
				undef $coro; 
			});
		
	};
	if(@_){ $self->{$Coro::current} = shift }
	
	$self->{$Coro::current};
}

*STORE = *_proto;



( run in 0.321 second using v1.01-cache-2.11-cpan-3cd7ad12f66 )