Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Tied Variables - why?

by boo_radley (Parson)
on Sep 07, 2002 at 15:54 UTC ( [id://195879]=note: print w/replies, xml ) Need Help??


in reply to Tied Variables - why?

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://195879]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (5)
As of 2024-04-23 17:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found