You must keep the guard object (the value of $t1
) alive. If all references to it are gone, it will get destroyed, and that cancels the event.
Referencing $t1
in the closure causes the closure to capture it, keeping it alive past it's normal death at then end of func
.
If you want to capture a variable you don't otherwise need, you can use
$t2 if 0; # Keep timer alive until process exit.
Here's a simple example of a closure:
sub make_closure {
my ($x) = @_;
return sub {
print("$x\n");
};
}
my $f1 = make_closure("Hello, World!");
my $f2 = make_closure("Allo, Jeune Renard!");
$f1->();
$f2->();
Notice how the closure (the anon sub) captures the $x
that existed at the time?