seattlejohn has asked for the wisdom of the Perl Monks concerning the following question:
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!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: two-part question about tied variables
by japhy (Canon) on Jan 13, 2002 at 07:30 UTC | |
by seattlejohn (Deacon) on Jan 13, 2002 at 21:07 UTC | |
by dragonchild (Archbishop) on Jan 14, 2002 at 19:31 UTC | |
by japhy (Canon) on Jan 14, 2002 at 19:33 UTC | |
|
Re: two-part question about tied variables
by IlyaM (Parson) on Jan 13, 2002 at 07:14 UTC | |
|
Re: two-part question about tied variables
by robin (Chaplain) on Jan 13, 2002 at 22:42 UTC | |
|
Re: two-part question about tied variables
by Stegalex (Chaplain) on Jan 13, 2002 at 17:56 UTC |