I decided to do some experimenting with tied variables, and I've found myself with two questions that I hope the collective wisdom of the monks may be able to help with.

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:

my $positive_number; tie $positive_number, "Enforcer", sub {$_[0] > 0}; $positive_number = 2; # ok $positive_number = 6.4; # ok $positive_number = -1; # croak!
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 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

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.