in reply to Re^2: De-Overload reference?
in thread De-Overload reference?
#!/usr/bin/perl use warnings; use strict; use feature qw{ say }; use threads; use threads::shared; my $done :shared; my $t = 'threads'->create(sub { my %count; my $l2 = 'LanX'->new(42); # <- You can move this into the below l +oop, too. until ($done) { ++$count{ $l2->{value} }; } for my $key (keys %count) { say "$key: $count{$key}"; } }); { package LanX; use overload '%{}' => \&_nothing, '""' => sub { $_[0]->_underload(\&_value) }; sub new { bless {value => $_[1]}, $_[0] } sub inc { $_[0]->_underload(sub { ++$_[0]->{value} }) } sub value { $_[0]->_underload(\&_value) } sub _nothing { { value => 'nothing' } } sub _value { $_[0]->{value} } sub _underload { my ($self, $sub) = @_; overload->unimport('%{}'); my $v = $self->$sub; sleep 1 if 0 == threads->tid; overload->import('%{}' => \&_nothing); return $v } } my $l = 'LanX'->new(12); say "deref\t" => $l->{value}; # nothing say "l\t" => $l; # 12 say "deref\t" => $l->{value}; # nothing say "inc\t" => $l->inc; # 13 say "l\t" => $l; # 13 say "inc\t" => $l->inc; # 14 say "l\t" => $l; # 14 say "deref\t" => $l->{value}; # nothing $done = 1; $t->join;
> the idea to just temporarily bless this $self to another neutral class
Brilliant idea. Seems less ugly, but it's not 100% clear why it's there, so probably needs a comment or a good name for the class.
sub _underload { my ($self, $sub) = @_; my $class = ref $self; bless $self, 'Cancel::LanX::So::We::Can::Dereference'; my $v = $self->$sub; sleep 1 if 0 == threads->tid; bless $self, $class; return $v }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: De-Overload reference?
by LanX (Saint) on Apr 17, 2024 at 16:51 UTC | |
by choroba (Cardinal) on Apr 17, 2024 at 20:23 UTC | |
by LanX (Saint) on Apr 18, 2024 at 13:22 UTC | |
by choroba (Cardinal) on Apr 18, 2024 at 13:23 UTC | |
|
Re^4: De-Overload reference?
by LanX (Saint) on Apr 17, 2024 at 18:40 UTC |