in reply to Re: Versatile subs
in thread Versatile subs
To the OP, yes, it seems like you're starting down a reasonable road. Along that road is revdiablo's suggestion, which is a significant improvement, both in speed and maintainability (compile time errors can be caught easier).
To continue along this road (IMO), which is something I've done many times, I've started to take some serious advantage of $_. Rather than passing in a variable, just assign it to $_. Then your get_data call would look like:
As you can see, this can really trivialise the code. The cost (and there is always a cost, otherwise it wouldn't be called a 'trade-off' ;-}) is that you have to be extra careful to localise $_ appropriately. So you have to localise $_ in the get_data function, saving the original value, perhaps, if you'll still need it after the callback, and, should you need $_ again in the callback, localise it again there. However, 99.999% of the time, you won't need to do so in the callback, continuing to make this a pretty good tradeoff.get_data( pre => undef, while => sub { # 'handle' may be a better key, IMO tr/ / /s; }, post => sub { write_log("Found $count instances"); }, );
As a secondary change, I'd call this function "_get_data" instead as a signifier that this is an internal-to-your-module function and probably should not be called directly by anyone outside your function. However, I wouldn't go overboard and force it on anyone by, for example, making it a lexically scoped anonymous sub, such as:
But that's just me.my $_get_data = sub { ... };
|
|---|