I've only seen (and used) this in a potential test&debug setting, like so
my $function = sub { ... }; if($isDebug) { $function = sub { ... } }
Depending on the scope and visibility of $function, it might be possible to replace this "function pointer" from the outside. This could be used to either change the algorithm, make custom callbacks or, again, for debugging. For example, it might be useful to provide pre-selected "random" dice rolls when testing a game engine.
my $getDiceRoll = sub { return int(rand() * 6) + 1; }; my $dicefh; if($regressionTest) { $getDiceRoll = sub { # READ NEXT DICE ROLL FROM dicerolls.txt if(!defined($dicefh)) { open($dicefh, '<', 'dicerolls.txt') dir die($!); } my $roll = <$dicefh>; chomp $roll; return $roll; } }
The nice thing about this, compared to the usual way of adding a bunch of IFs into the sub is that, well, you don't. Depending on what the function does and how often it it called, this may have relevance to the performance of the function.
Just imagine a graphics library that provides a getpixel() function. If it has to check every time you read out a pixel if it's in indexed or RGB mode while working on a big image, this can get awfully slow (see Autoclicker! Cheating is winning, too! for a practical example where performance matters). One way to potentially speed up things would be to overwrite the getpixel() function with the version optimised for the image that is currently being worked on. It's a bit higher on startup cost, but could save time overall when reading large portions of the pixel data.
Edit: Bugfix second code snippet. Thanks, johngg for the extra set of eyes!
In reply to Re: Anonymous subroutines
by cavac
in thread Anonymous subroutines
by Bod
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |