First, the scenario. I decided to create an "Enforcer" class that lets me attach semi-permanent assertions to scalar variables. If any assignment violates the assertion, the program croaks. Here's a simple example:
So, having written a simple class to implement this, my first question is whether I'm reinventing the wheel. I didn't see anything that does precisely this on CPAN (though I suppose Tie::Watch could be co-opted for this purpose), but I can hardly claim comprehensive knowledge of everything that's on CPAN! (I'll probably go on and implement Enforced arrays and hashes anyway just for the learning experience, but I'd really like to know if somebody else has already been down this path.)my $positive_number; tie $positive_number, "Enforcer", sub {$_[0] > 0}; $positive_number = 2; # ok $positive_number = 6.4; # ok $positive_number = -1; # croak!
My second question is whether the TIESCALAR constructor can actually have access to the value of the variable that's being tied. In other words:
my $x = 2; tie $x, "Enforcer", sub {...} # can Enforcer::TIESCALAR know that $x is currently 2??
I didn't find any mention of this in perl manpages, The Camel, or Damian's OOP book -- nor did this thread, which also raised the question, seem to lead to a definitive yes-or-no answer.
I know I could get access to the value by stipulating that the tie be called like this:
tie $x, "Enforcer", $x, sub {...}
but that seems inelegant, to say the least.
Anyway, I'd appreciate any thoughts/comments/pointers on this topic... thanks!
In reply to two-part question about tied variables by seattlejohn
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |