Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re^3: What's the weaken here for?

by Anonymous Monk
on Jan 20, 2012 at 03:38 UTC ( [id://948877]=note: print w/replies, xml ) Need Help??


in reply to Re^2: What's the weaken here for?
in thread What's the weaken here for?

The actual code is the sub once of Mojo::EventEmitter

The author must have done this for some reason...

Yeah, well Mr. Sherlock, that code is different than what you posted. The reason is always the same, circular references prevent release of memory

{ my $foo = {}; # ref count 1 $foo->{foo} = $foo; # ref count 2 } ### $foo goes out of scope here, memory should be released to perl # here, $foo is not addressable (you can't refer to it by $foo), # but its memory is not released until exit # because there is still a reference to $foo # it refers to it self, its self-referential, a circular reference # for memory held by $foo to be released after $foo goes out of scope # $foo->{foo} has to be weakened, the reference count decreased

The actual code, which you should have copy/pasted to get a reasonable answer, since editing code you don't understand changes its meaning

sub once { my ($self, $name, $cb) = @_; weaken $self; my $wrapper; $wrapper = sub { # a special kind of circular reference # CLOSURE, $wrapper keeps $self alive after return $wrapper (REFCNT+1) # $wrapper refers to itself, CIRCULAR REFERENCE $self->unsubscribe($name => $wrapper); $cb->(@_); }; $self->on($name => $wrapper); # potential CIRCULAR REFERENCE (on pro +bably also stores $wrapper, but it probably also uses weaken ) weaken $wrapper; return $wrapper; }

How do I post a question effectively? says, when reducing code size, reduce to the essence, don't change the essence :)

Replies are listed 'Best First'.
Re^4: What's the weaken here for?
by PerlOnTheWay (Monk) on Jan 20, 2012 at 05:44 UTC

    What about weaken $self?

    It's not done in other subs..

      What about weaken $self? It's not done in other subs..

      As I explained in the comments, its a closure. You can read more at in-depth tutorials on closures

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://948877]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (5)
As of 2024-04-25 14:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found