Chapter 2
To implement a tied scalar class, you need to provide three methods
TIESCALAR(), FETCH(), and STORE(). The first, TIESCALAR(), is the constructor for the
tied scalar class. It works just like the new() methods you've seen previously it
takes some parameters and returns a bless()'d reference. Here's a possible imple
mentation for BOA::Thermostat::TIESCALAR():
package BOA::Thermostat;
sub TIESCALAR {
my $pkg = shift;
my $self = { @_ }; # retrieve named options into $self hash ref
# check for required compartment option
croak("Missing compartment number!") unless exists $self >{compartment};
# the vent is initially closed
$self >{vent_state} = 0;
# bless $self and return
return bless($self, $pkg);
}
This should look very familiar by now it's just a simple variation on a normal con
structor. The only difference is the name and the way it will be called by tie()
instead of directly. Notice that even though this code is emulating a scalar, there's
no need to use a scalar underneath the object itself is a hash in this example.
The remaining two methods are FETCH() and STORE(), which get called when
the tied variable is read and written, respectively. Here's the FETCH() implemen
tation for the BOA::Thermostat class:
# method called when scalar is read
sub FETCH {
my $self = shift;
return get_temp($self >{compartment});
}
FETCH() receives only the object as an argument and returns the results of calling
the class method get_temp() with the compartment number as a parameter. This
method will check the temperature in the given compartment and return it. I'll
leave implementing this method as an exercise for budding rocket scientists in the
audience.
58
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Inexpensive Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Jsp Hosting
Cheap Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved