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 ...

Get Programming Perl, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.