I've already sort of asked this in a previous thread (Using tie to return value of anonymous sub), but now I've figured out one of the real problems and simplified it a bit.

Basically I want to auto-evaluate anonymous subroutines on access and have it work whether or not arguments are passed to the routine. In other words, I need some way of figuring out how the return value of some FETCH sub is going to be evaluated -- not in void/scalar/array context, but if it's going to be dereferenced as a subroutine.

Example of what I'd like to do:

my $sub = sub { print "I see arguments\n" if @_; print "Hello\n"; }; # $sub might be in a hash somewhere print $sub; # I expect "Hello" print $sub->("foo", "bar"); # I should see "I see arguments" too.

What I'm using this for is attributes for objects. $enemy->{strength} could be 5 or a subroutine that factors in stuff dynamically. But when I access it (print "Watch out!\n" if $enemy->{strength} > $player->{strength}), I don't want to care about the implementation of strength. But sometimes I will want to pass in parameters. If I make a tie interface to return the return value of the code ref, then I lose the ability to pass in parameters.

I've sort of figured out the solution: Only tie certain 'layers' of my object's data structure. Things like the dynamic strength coderef wouldn't really need to take arguments anyway. So there really isn't a problem. But now it bugs me: There should be a way to make easy things easy and tough things possible.


In reply to Auto-evaluating anonymous subroutines by dabreegster

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.