AnomalousMonk,
You are correct. I was mistakenly being overprotective since I was treating an anonymous sub invocation like I was doing an eval. There is no need to worry about scoping of anything except global variables when calling the anon sub. Thank you for making me rethink this.
Nevertheless, if this was anything more than an example, I would also redesign the method so that it doesn't require an explicit assignment to $_ within the anonymous sub but instead does that assignment for you.
$self->{ $key } = $subref->();
I chose to add parameter variables as a way of making the method self-documenting, but I didn't want the anonymous subroutine to have access to the deeper mechanisms of the object. Ideally, the only variable within the anonymous sub will be $_. However, to prevent a user from taking advantage of the lexicals $self and $key, I explicitly hid them.
If this was anything more than an example, I probably would've localized @_. But then again, I would also redesign the method so that it doesn't require an explicit assignment to $_ within the anonymous sub, but instead does that assignment for you.
$self->{ $key } = $subref->();
|