I think you've stumbled onto one of the reasons why people use tied variables in the first place in your second example :

# objects my $var = new Squareable(5); $var->square(); print $var; # oh... yields 25... neato!
the output you'll get here (unless the Squareable author's been exceptionally concerned about creating a default accessor) is something similar to "Squareable=HASH(address)", not 25. print $var would print 25, however, when set up as a tied scalar.

Tied variables are set up to provide the programmer with a simple way of using accessors and mutators without having to worry about semantics at all.
I'd use create a tieable class if I were concerned about making a class behave and operate "just like" one of perl's 3 variable types.

When used correctly, tied variables can reduce the amount of knowledge a programmer needs to have about a given class ("Is squarable's output method ->output(), or ->product(), or ->result() ?" vs. "print $foo"). There's an excellent example in Damian Conway's OOP book that uses math classes : It's not as clear to have

$int->add(4); $int->divide(12); print $i->value();
as it would be to have
$i=$i+4; $i=$i/12; print $i;
(I can't remember offhand if tied variables allow you to use += and friends right now, or if that's just overloading, so I'll play it basic...)

As with anything, if tied variables are not a common part of your toolbox, comment their uses through your code to remind you and your maintainers of what's going on.


In reply to Re: Tied Variables - why? by boo_radley
in thread Tied Variables - why? by samurai

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.