home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book Home Programming PerlSearch this book

32.6. Class::Struct

use Class::Struct;

struct Manager => {         # Creates a Manager->new() constructor.
    name    => '$',         # Now name() method accesses a scalar value.
    salary  => '$',         # And so does salary().
    started => '$',         # And so does started().
};

struct Shoppe => {          # Creates a Shoppe->new() constructor.
    owner   => '$',         # Now owner() method accesses a scalar.
    addrs   => '@',         # And addrs() method accesses an array.
    stock   => '%',         # And stock() method accesses a hash.
    boss    => 'Manager',   # Initializes with Manager->new().
};

$store = Shoppe->new();
$store->owner('Abdul Alhazred');
$store->addrs(0, 'Miskatonic University');
$store->addrs(1, 'Innsmouth, Mass.');
$store->stock("books", 208);
$store->stock("charms", 3);
$store->stock("potions", "none");
$store->boss->name('Prof L. P. Haitch');
$store->boss->salary('madness');
$store->boss->started(scalar localtime);
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".



Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.