1Class::Struct(3pm) Perl Programmers Reference Guide Class::Struct(3pm)
2
3
4
6 Class::Struct - declare struct-like datatypes as Perl classes
7
9 use Class::Struct;
10 # declare struct, based on array:
11 struct( CLASS_NAME => [ ELEMENT_NAME => ELEMENT_TYPE, ... ]);
12 # declare struct, based on hash:
13 struct( CLASS_NAME => { ELEMENT_NAME => ELEMENT_TYPE, ... });
14
15 package CLASS_NAME;
16 use Class::Struct;
17 # declare struct, based on array, implicit class name:
18 struct( ELEMENT_NAME => ELEMENT_TYPE, ... );
19
20 # Declare struct at compile time
21 use Class::Struct CLASS_NAME => [ ELEMENT_NAME => ELEMENT_TYPE, ... ];
22 use Class::Struct CLASS_NAME => { ELEMENT_NAME => ELEMENT_TYPE, ... };
23
24 # declare struct at compile time, based on array, implicit class name:
25 package CLASS_NAME;
26 use Class::Struct ELEMENT_NAME => ELEMENT_TYPE, ... ;
27
28 package Myobj;
29 use Class::Struct;
30 # declare struct with four types of elements:
31 struct( s => '$', a => '@', h => '%', c => 'My_Other_Class' );
32
33 $obj = new Myobj; # constructor
34
35 # scalar type accessor:
36 $element_value = $obj->s; # element value
37 $obj->s('new value'); # assign to element
38
39 # array type accessor:
40 $ary_ref = $obj->a; # reference to whole array
41 $ary_element_value = $obj->a(2); # array element value
42 $obj->a(2, 'new value'); # assign to array element
43
44 # hash type accessor:
45 $hash_ref = $obj->h; # reference to whole hash
46 $hash_element_value = $obj->h('x'); # hash element value
47 $obj->h('x', 'new value'); # assign to hash element
48
49 # class type accessor:
50 $element_value = $obj->c; # object reference
51 $obj->c->method(...); # call method of object
52 $obj->c(new My_Other_Class); # assign a new object
53
55 "Class::Struct" exports a single function, "struct". Given a list of
56 element names and types, and optionally a class name, "struct" creates
57 a Perl 5 class that implements a "struct-like" data structure.
58
59 The new class is given a constructor method, "new", for creating struct
60 objects.
61
62 Each element in the struct data has an accessor method, which is used
63 to assign to the element and to fetch its value. The default accessor
64 can be overridden by declaring a "sub" of the same name in the package.
65 (See Example 2.)
66
67 Each element's type can be scalar, array, hash, or class.
68
69 The "struct()" function
70 The "struct" function has three forms of parameter-list.
71
72 struct( CLASS_NAME => [ ELEMENT_LIST ]);
73 struct( CLASS_NAME => { ELEMENT_LIST });
74 struct( ELEMENT_LIST );
75
76 The first and second forms explicitly identify the name of the class
77 being created. The third form assumes the current package name as the
78 class name.
79
80 An object of a class created by the first and third forms is based on
81 an array, whereas an object of a class created by the second form is
82 based on a hash. The array-based forms will be somewhat faster and
83 smaller; the hash-based forms are more flexible.
84
85 The class created by "struct" must not be a subclass of another class
86 other than "UNIVERSAL".
87
88 It can, however, be used as a superclass for other classes. To
89 facilitate this, the generated constructor method uses a two-argument
90 blessing. Furthermore, if the class is hash-based, the key of each
91 element is prefixed with the class name (see Perl Cookbook, Recipe
92 13.12).
93
94 A function named "new" must not be explicitly defined in a class
95 created by "struct".
96
97 The ELEMENT_LIST has the form
98
99 NAME => TYPE, ...
100
101 Each name-type pair declares one element of the struct. Each element
102 name will be defined as an accessor method unless a method by that name
103 is explicitly defined; in the latter case, a warning is issued if the
104 warning flag (-w) is set.
105
106 Class Creation at Compile Time
107 "Class::Struct" can create your class at compile time. The main reason
108 for doing this is obvious, so your class acts like every other class in
109 Perl. Creating your class at compile time will make the order of
110 events similar to using any other class ( or Perl module ).
111
112 There is no significant speed gain between compile time and run time
113 class creation, there is just a new, more standard order of events.
114
115 Element Types and Accessor Methods
116 The four element types -- scalar, array, hash, and class -- are
117 represented by strings -- '$', '@', '%', and a class name -- optionally
118 preceded by a '*'.
119
120 The accessor method provided by "struct" for an element depends on the
121 declared type of the element.
122
123 Scalar ('$' or '*$')
124 The element is a scalar, and by default is initialized to "undef"
125 (but see "Initializing with new").
126
127 The accessor's argument, if any, is assigned to the element.
128
129 If the element type is '$', the value of the element (after
130 assignment) is returned. If the element type is '*$', a reference
131 to the element is returned.
132
133 Array ('@' or '*@')
134 The element is an array, initialized by default to "()".
135
136 With no argument, the accessor returns a reference to the element's
137 whole array (whether or not the element was specified as '@' or
138 '*@').
139
140 With one or two arguments, the first argument is an index
141 specifying one element of the array; the second argument, if
142 present, is assigned to the array element. If the element type is
143 '@', the accessor returns the array element value. If the element
144 type is '*@', a reference to the array element is returned.
145
146 As a special case, when the accessor is called with an array
147 reference as the sole argument, this causes an assignment of the
148 whole array element. The object reference is returned.
149
150 Hash ('%' or '*%')
151 The element is a hash, initialized by default to "()".
152
153 With no argument, the accessor returns a reference to the element's
154 whole hash (whether or not the element was specified as '%' or
155 '*%').
156
157 With one or two arguments, the first argument is a key specifying
158 one element of the hash; the second argument, if present, is
159 assigned to the hash element. If the element type is '%', the
160 accessor returns the hash element value. If the element type is
161 '*%', a reference to the hash element is returned.
162
163 As a special case, when the accessor is called with a hash
164 reference as the sole argument, this causes an assignment of the
165 whole hash element. The object reference is returned.
166
167 Class ('Class_Name' or '*Class_Name')
168 The element's value must be a reference blessed to the named class
169 or to one of its subclasses. The element is not initialized by
170 default.
171
172 The accessor's argument, if any, is assigned to the element. The
173 accessor will "croak" if this is not an appropriate object
174 reference.
175
176 If the element type does not start with a '*', the accessor returns
177 the element value (after assignment). If the element type starts
178 with a '*', a reference to the element itself is returned.
179
180 Initializing with "new"
181 "struct" always creates a constructor called "new". That constructor
182 may take a list of initializers for the various elements of the new
183 struct.
184
185 Each initializer is a pair of values: element name" => "value. The
186 initializer value for a scalar element is just a scalar value. The
187 initializer for an array element is an array reference. The initializer
188 for a hash is a hash reference.
189
190 The initializer for a class element is an object of the corresponding
191 class, or of one of it's subclasses, or a reference to a hash
192 containing named arguments to be passed to the element's constructor.
193
194 See Example 3 below for an example of initialization.
195
197 Example 1
198 Giving a struct element a class type that is also a struct is how
199 structs are nested. Here, "Timeval" represents a time (seconds and
200 microseconds), and "Rusage" has two elements, each of which is of
201 type "Timeval".
202
203 use Class::Struct;
204
205 struct( Rusage => {
206 ru_utime => 'Timeval', # user time used
207 ru_stime => 'Timeval', # system time used
208 });
209
210 struct( Timeval => [
211 tv_secs => '$', # seconds
212 tv_usecs => '$', # microseconds
213 ]);
214
215 # create an object:
216 my $t = Rusage->new(ru_utime=>Timeval->new(), ru_stime=>Timeval->new());
217
218 # $t->ru_utime and $t->ru_stime are objects of type Timeval.
219 # set $t->ru_utime to 100.0 sec and $t->ru_stime to 5.0 sec.
220 $t->ru_utime->tv_secs(100);
221 $t->ru_utime->tv_usecs(0);
222 $t->ru_stime->tv_secs(5);
223 $t->ru_stime->tv_usecs(0);
224
225 Example 2
226 An accessor function can be redefined in order to provide
227 additional checking of values, etc. Here, we want the "count"
228 element always to be nonnegative, so we redefine the "count"
229 accessor accordingly.
230
231 package MyObj;
232 use Class::Struct;
233
234 # declare the struct
235 struct ( 'MyObj', { count => '$', stuff => '%' } );
236
237 # override the default accessor method for 'count'
238 sub count {
239 my $self = shift;
240 if ( @_ ) {
241 die 'count must be nonnegative' if $_[0] < 0;
242 $self->{'MyObj::count'} = shift;
243 warn "Too many args to count" if @_;
244 }
245 return $self->{'MyObj::count'};
246 }
247
248 package main;
249 $x = new MyObj;
250 print "\$x->count(5) = ", $x->count(5), "\n";
251 # prints '$x->count(5) = 5'
252
253 print "\$x->count = ", $x->count, "\n";
254 # prints '$x->count = 5'
255
256 print "\$x->count(-5) = ", $x->count(-5), "\n";
257 # dies due to negative argument!
258
259 Example 3
260 The constructor of a generated class can be passed a list of
261 element=>value pairs, with which to initialize the struct. If no
262 initializer is specified for a particular element, its default
263 initialization is performed instead. Initializers for non-existent
264 elements are silently ignored.
265
266 Note that the initializer for a nested class may be specified as an
267 object of that class, or as a reference to a hash of initializers
268 that are passed on to the nested struct's constructor.
269
270 use Class::Struct;
271
272 struct Breed =>
273 {
274 name => '$',
275 cross => '$',
276 };
277
278 struct Cat =>
279 [
280 name => '$',
281 kittens => '@',
282 markings => '%',
283 breed => 'Breed',
284 ];
285
286
287 my $cat = Cat->new( name => 'Socks',
288 kittens => ['Monica', 'Kenneth'],
289 markings => { socks=>1, blaze=>"white" },
290 breed => Breed->new(name=>'short-hair', cross=>1),
291 or: breed => {name=>'short-hair', cross=>1},
292 );
293
294 print "Once a cat called ", $cat->name, "\n";
295 print "(which was a ", $cat->breed->name, ")\n";
296 print "had two kittens: ", join(' and ', @{$cat->kittens}), "\n";
297
299 Modified by Damian Conway, 2001-09-10, v0.62.
300
301 Modified implicit construction of nested objects.
302 Now will also take an object ref instead of requiring a hash ref.
303 Also default initializes nested object attributes to undef, rather
304 than calling object constructor without args
305 Original over-helpfulness was fraught with problems:
306 * the class's constructor might not be called 'new'
307 * the class might not have a hash-like-arguments constructor
308 * the class might not have a no-argument constructor
309 * "recursive" data structures didn't work well:
310 package Person;
311 struct { mother => 'Person', father => 'Person'};
312
313 Modified by Casey West, 2000-11-08, v0.59.
314
315 Added the ability for compile time class creation.
316
317 Modified by Damian Conway, 1999-03-05, v0.58.
318
319 Added handling of hash-like arg list to class ctor.
320
321 Changed to two-argument blessing in ctor to support
322 derivation from created classes.
323
324 Added classname prefixes to keys in hash-based classes
325 (refer to "Perl Cookbook", Recipe 13.12 for rationale).
326
327 Corrected behaviour of accessors for '*@' and '*%' struct
328 elements. Package now implements documented behaviour when
329 returning a reference to an entire hash or array element.
330 Previously these were returned as a reference to a reference
331 to the element.
332
333 Renamed to "Class::Struct" and modified by Jim Miner, 1997-04-02.
334
335 members() function removed.
336 Documentation corrected and extended.
337 Use of struct() in a subclass prohibited.
338 User definition of accessor allowed.
339 Treatment of '*' in element types corrected.
340 Treatment of classes as element types corrected.
341 Class name to struct() made optional.
342 Diagnostic checks added.
343
344 Originally "Class::Template" by Dean Roehrich.
345
346 # Template.pm --- struct/member template builder
347 # 12mar95
348 # Dean Roehrich
349 #
350 # changes/bugs fixed since 28nov94 version:
351 # - podified
352 # changes/bugs fixed since 21nov94 version:
353 # - Fixed examples.
354 # changes/bugs fixed since 02sep94 version:
355 # - Moved to Class::Template.
356 # changes/bugs fixed since 20feb94 version:
357 # - Updated to be a more proper module.
358 # - Added "use strict".
359 # - Bug in build_methods, was using @var when @$var needed.
360 # - Now using my() rather than local().
361 #
362 # Uses perl5 classes to create nested data types.
363 # This is offered as one implementation of Tom Christiansen's "structs.pl"
364 # idea.
365
366
367
368perl v5.12.4 2011-06-01 Class::Struct(3pm)