Scalar-Tying Methods
Now that you’ve seen a sample of what’s to come, let’s develop a more
elaborate scalar-tying class. Instead of using any canned package
for the base class (especially since scalars are so simple), we’ll
look at each of the four methods in turn, building an example class
named ScalarFile. Scalars tied to
this class contain regular strings, and each such variable is
implicitly associated with a file where that string is stored. (You
might name your variables to remind you to which file you’re
referring.) Variables are tied to the class this way:
use ScalarFile; # load ScalarFile.pm tie $camel, "ScalarFile", "/tmp/camel.lot";
Once the variable has been tied, its previous contents are
clobbered, and the internal connection between the variable and its
object overrides the variable’s normal semantics. When you ask for
the value of $camel, it now reads
the contents of /tmp/camel.lot,
and when you assign a value to $camel, it writes the new contents out to
/tmp/camel.lot, obliterating
any previous occupants.
The tie is on the variable, not the value, so the tied nature of a variable does not propagate across assignment. For example, let’s say you copy a variable that’s been tied:
$dromedary = $camel;
Instead of reading the value in the ordinary fashion from the
$camel scalar variable, Perl
invokes the FETCH method on the
associated underlying object. It’s as though you’d written
this:
$dromedary = (tied $camel)–>FETCH():
Or if you remember the object returned by tie, you ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access