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:

get_data( pre => undef, while => sub { # 'handle' may be a better key, IMO tr/ / /s; }, post => sub { write_log("Found $count instances"); }, );
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.

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:

my $_get_data = sub { ... };
But that's just me.


In reply to Re^2: Versatile subs by Tanktalus
in thread Versatile subs by eff_i_g

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.