saberworks has asked for the wisdom of the Perl Monks concerning the following question:

This is a weird question but I'm trying to track down a problem with Dancer's new "hooks" functionality. Adding a hook in Dancer essentially stores a list of code refs (subroutine references) in a list and then executes them in a loop like this:
$_->(@args) foreach @{$self->get_hooks_for($hook_name)};
The problem I'm having is that in a persistent environment (under plackup, where my modules aren't reloaded on each web request) in this list of code references one of them somehow goes undef during execution so that upon the next request Dancer dies with a runtime error (because $_ is undef and it's trying to call $_->(@args)).

If I use Data::Dumper just before and just after the line above I get this:
$VAR1 = [ sub { "DUMMY" }, sub { "DUMMY" } ];
$VAR1 = [ sub { "DUMMY" }, undef ];
If I change the original line in the Dancer module to this the error goes away:
foreach my $hook (@{ $self->get_hooks_for($hook_name) }) { $hook->(@args); }
This is really odd to me because I can't think of a way executing a coderef will turn it into undef. It seems like some issue with $_ getting overwritten somehow but I don't know how that could happen. I tried to repro this on a blank project by setting $_ to all sorts of values but wasn't able to.

Dancer (or plackup?) has an annoying habit of hiding errors in these hooks (If I explicitly call die('foo') it silently continues and 'foo' is lost in the ether, not showing up in the response or any error logs) but I did try to die inside the code ref to see if I could repro it.

Update: If I pull out the hooks separately ahead of time like this, it also fixes the bug:
my @hooks = @{ $self->get_hooks_for($hook_name) }; $_->(@args) foreach @hooks;
The "get_hooks_for" method does this: $self->hooks->{$hook_name} || []; And the "hooks" method is magically created like this: __PACKAGE__->attributes(qw/ hooks registered_hooks/); Thanks for any help.