dabreegster has asked for the wisdom of the Perl Monks concerning the following question:
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Auto-evaluating anonymous subroutines
by ikegami (Patriarch) on Feb 21, 2006 at 00:49 UTC | |
by diotalevi (Canon) on Feb 21, 2006 at 02:12 UTC | |
by ikegami (Patriarch) on Feb 21, 2006 at 03:25 UTC | |
by diotalevi (Canon) on Feb 21, 2006 at 03:36 UTC | |
by skx (Parson) on Feb 21, 2006 at 14:44 UTC | |
|
Re: Auto-evaluating anonymous subroutines
by QM (Parson) on Feb 20, 2006 at 23:19 UTC | |
|
Re: Auto-evaluating anonymous subroutines
by dragonchild (Archbishop) on Feb 21, 2006 at 01:18 UTC | |
|
Re: Auto-evaluating anonymous subroutines
by Roy Johnson (Monsignor) on Feb 21, 2006 at 15:28 UTC |