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