Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

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

by Anonymous Monk
on Jan 20, 2012 at 03:38 UTC ( #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 (Scribe) 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?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://948877]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2018-02-24 10:55 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (310 votes). Check out past polls.