Chapter 3
Using Class::Struct
Class::Struct
9
exports a single subroutine, struct(), that allows you to build a class
skeleton with a single subroutine call. You pass the struct() routine information
about your attributes, and it generates and compiles the code for your new class,
including a constructor called new() and an accessor mutator for each attribute.
For example, say you're building a class to manage the scientific probes aboard the
BOA spacecraft. The BOA::Probe class has a number of attributes that describe an
individual probe. Here's what the class file looks like using Class::Struct:
package BOA::Probe;
use Class::Struct;
# create accessors and constructor
struct(id => $ ,
model => $ ,
contents => $ ,
heading => $ ,
status => $ );
The struct() call takes a list of key value pairs that describe the names of attributes
and their types. The preceding class uses the $ type, which indicates it is scalar.
This provides the interface you're familiar with the accessor mutator created
takes zero or one argument and gets or sets its value. After calling struct(), six new
methods are created one for each of the attributes and a new() method. This
new() takes a list of key value pairs to initialize the contents of the object. Here's an
example of how to use the new class:
# create a new probe
my $probe = BOA::Probe >new(id => 10503, model => "BOA Mark 10");
# modify heading and status
$probe >heading([10, 20, 100, 50]); # heading at (10,20,100) with at 50 kph
$probe >status("moving");
Class::Struct supports more than just scalar attributes. You can specify that an
attribute will hold an array, a hash, or an object of a specific class. This may seem
unnecessary the scalar attributes can already hold a reference to any of these
types but declaring these type allows Class::Struct to generate more powerful
9. Written by Jim Miner, based on Class::Template by Dean Roehrich. The module is included
with Perl.
88
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