in reply to Is it possible to create a sub exclusive to a sub?
Update: ihb pointed this out before I did.
All of the other solutions so far create the anonymous sub inside the calling sub, so they recreate it on every call. A better way that avoids that wasted effort would be
BEGIN { my $bar = sub { # ... }; sub foo { # ... $bar->( $baz ); # ... $bar->( $quux ); # ... } }
The BEGIN avoids a trap for the unwary: you might otherwise call foo() before the assignment to $bar has run, blowing up the script. If this code is in a module, there is an implicit BEGIN around all of the code, so this might not be necessary (your call), but it's a good defensive habit nonetheless.
Makeshifts last the longest.
|
|---|