I've played around with this a few times. Most recently, I wound up using shared variables with our() and string eval'ing the sub. I had this luxury because my callback is usually called a few thousand times at a go, so the string eval doesn't hurt much. This way, I could use as many variables as I want, tied behind the scenes to the functions that did the real work. The ugliness from the user's point of view is that you have set_callback( q{...}, $opts ) instead of set_callback( sub{...}, $opts) or so, but that's necessary unless we want to use fully qualified variables.

In the end, it made my code uglier and slower than I wanted it to be (30 lines of e.g. $var1 = $hr->{var1} gets old), so I wound up scaling it back and just using 2 shared variables, $t and $d. Typing $t->{foo} just isn't that much more work than typing $foo, and it keeps the inner code from being needlessly horrific.

I'm sure there are better solutions, but this is one. HTH.


In reply to Re: Accessing variable in callback running context by brianski
in thread Accessing variable in callback running context by thewebsi

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.