32.6. Class::Struct
The Class::Struct module provides a way to
"declare" a class as having objects whose fields are of a specific
type. The function that does this is called
struct. Because structures or records are not base
types in Perl, each time you want to create a class to provide a
record-like data object, you have to define a constructor method along
with accessor methods for each data field, sometimes called "wrapper"
methods. The Class::Struct module's
struct function alleviates this tedium by creating
a class for you on the fly. You just tell it what data members should
exist and their types. The function creates a constructor method
named new in the package specified by the first
argument, plus an attribute accessor method for each member, as
specified by the second argument, which should be a hash reference.
Field types are specified as either a built-in type using the customary "$", "@", "%", and "&" symbols, or as another class using the class name. The type of each field will be enforced when you try to set the value. Many standard modules use Class::Struct to create their objects and accessors, including Net::hostent and User::pwent, whose source you can look at as a model. See also the CPAN modules Tie::SecureHash and Class::Multimethods for more elaborate approaches to autogeneration of classes and accessor methods. See the section "Managing Instance Data" in Chapter 12, "Objects". ![]() Copyright © 2001 O'Reilly & Associates. All rights reserved. |
|