3 ## See POD after __END__
8 use warnings::register;
9 our(@ISA, @EXPORT, $VERSION);
19 ## Tested on 5.002 and 5.003 without class membership tests:
20 my $CHECK_CLASS_MEMBERSHIP = ($] >= 5.003_95);
24 if (@_) { $print = shift }
29 package Class::Struct::Tie_ISA;
33 return bless [], $class;
37 my ($self, $index, $value) = @_;
38 Class::Struct::_subclass_error();
42 my ($self, $index) = @_;
48 return scalar(@$self);
58 $self->export_to_level( 1, $self, @EXPORT );
60 # This is admittedly a little bit silly:
61 # do we ever export anything else than 'struct'...?
62 $self->export_to_level( 1, $self, @_ );
70 # Determine parameter list structure, one of:
71 # struct( class => [ element-list ])
72 # struct( class => { element-list })
73 # struct( element-list )
74 # Latter form assumes current package name as struct name.
77 my $base_type = ref $_[1];
78 if ( $base_type eq 'HASH' ) {
83 elsif ( $base_type eq 'ARRAY' ) {
90 $class = (caller())[0];
94 _usage_error() if @decls % 2 == 1;
96 # Ensure we are not, and will not be, a subclass.
100 \@{$class . '::ISA'};
102 _subclass_error() if @$isa;
103 tie @$isa, 'Class::Struct::Tie_ISA';
105 # Create constructor.
107 croak "function 'new' already defined in package $class"
108 if do { no strict 'refs'; defined &{$class . "::new"} };
118 $out = "{\n package $class;\n use Carp;\n sub new {\n";
119 $out .= " my (\$class, \%init) = \@_;\n";
120 $out .= " \$class = __PACKAGE__ unless \@_;\n";
124 my( $cmt, $name, $type, $elem );
126 if( $base_type eq 'HASH' ){
127 $out .= " my(\$r) = {};\n";
130 elsif( $base_type eq 'ARRAY' ){
131 $out .= " my(\$r) = [];\n";
133 while( $idx < @decls ){
134 $name = $decls[$idx];
135 $type = $decls[$idx+1];
136 push( @methods, $name );
137 if( $base_type eq 'HASH' ){
138 $elem = "{'${class}::$name'}";
140 elsif( $base_type eq 'ARRAY' ){
145 if( $type =~ /^\*(.)/ ){
149 my $init = "defined(\$init{'$name'}) ? \$init{'$name'} :";
151 $out .= " croak 'Initializer for $name must be array reference'\n";
152 $out .= " if defined(\$init{'$name'}) && ref(\$init{'$name'}) ne 'ARRAY';\n";
153 $out .= " \$r->$elem = $init [];$cmt\n";
156 elsif( $type eq '%' ){
157 $out .= " croak 'Initializer for $name must be hash reference'\n";
158 $out .= " if defined(\$init{'$name'}) && ref(\$init{'$name'}) ne 'HASH';\n";
159 $out .= " \$r->$elem = $init {};$cmt\n";
162 elsif ( $type eq '$') {
163 $out .= " \$r->$elem = $init undef;$cmt\n";
165 elsif( $type =~ /^\w+(?:::\w+)*$/ ){
166 $init = "defined(\$init{'$name'}) ? \%{\$init{'$name'}} : ()";
167 $out .= " croak 'Initializer for $name must be hash reference'\n";
168 $out .= " if defined(\$init{'$name'}) && ref(\$init{'$name'}) ne 'HASH';\n";
169 $out .= " \$r->$elem = '${type}'->new($init);$cmt\n";
170 $classes{$name} = $type;
174 croak "'$type' is not a valid struct element type";
178 $out .= " bless \$r, \$class;\n }\n";
180 # Create accessor methods.
182 my( $pre, $pst, $sel );
184 foreach $name (@methods){
185 if ( do { no strict 'refs'; defined &{$class . "::$name"} } ) {
186 warnings::warnif("function '$name' already defined, overrides struct accessor method");
189 $pre = $pst = $cmt = $sel = '';
190 if( defined $refs{$name} ){
193 $cmt = " # returns ref";
195 $out .= " sub $name {$cmt\n my \$r = shift;\n";
196 if( $base_type eq 'ARRAY' ){
200 elsif( $base_type eq 'HASH' ){
201 $elem = "{'${class}::$name'}";
203 if( defined $arrays{$name} ){
204 $out .= " my \$i;\n";
205 $out .= " \@_ ? (\$i = shift) : return \$r->$elem;\n";
206 $out .= " if (ref(\$i) eq 'ARRAY' && !\@_) { \$r->$elem = \$i; return \$r }\n";
209 elsif( defined $hashes{$name} ){
210 $out .= " my \$i;\n";
211 $out .= " \@_ ? (\$i = shift) : return \$r->$elem;\n";
212 $out .= " if (ref(\$i) eq 'HASH' && !\@_) { \$r->$elem = \$i; return \$r }\n";
215 elsif( defined $classes{$name} ){
216 if ( $CHECK_CLASS_MEMBERSHIP ) {
217 $out .= " croak '$name argument is wrong class' if \@_ && ! UNIVERSAL::isa(\$_[0], '$classes{$name}');\n";
220 $out .= " croak 'Too many args to $name' if \@_ > 1;\n";
221 $out .= " \@_ ? ($pre\$r->$elem$sel = shift$pst) : $pre\$r->$elem$sel$pst;\n";
227 print $out if $print;
228 my $result = eval $out;
233 confess "struct usage error";
236 sub _subclass_error {
237 croak 'struct class cannot be a subclass (@ISA not allowed)';
247 Class::Struct - declare struct-like datatypes as Perl classes
252 # declare struct, based on array:
253 struct( CLASS_NAME => [ ELEMENT_NAME => ELEMENT_TYPE, ... ]);
254 # declare struct, based on hash:
255 struct( CLASS_NAME => { ELEMENT_NAME => ELEMENT_TYPE, ... });
259 # declare struct, based on array, implicit class name:
260 struct( ELEMENT_NAME => ELEMENT_TYPE, ... );
262 # Declare struct at compile time
263 use Class::Struct CLASS_NAME => [ ELEMENT_NAME => ELEMENT_TYPE, ... ];
264 use Class::Struct CLASS_NAME => { ELEMENT_NAME => ELEMENT_TYPE, ... };
268 # declare struct with four types of elements:
269 struct( s => '$', a => '@', h => '%', c => 'My_Other_Class' );
271 $obj = new Myobj; # constructor
273 # scalar type accessor:
274 $element_value = $obj->s; # element value
275 $obj->s('new value'); # assign to element
277 # array type accessor:
278 $ary_ref = $obj->a; # reference to whole array
279 $ary_element_value = $obj->a(2); # array element value
280 $obj->a(2, 'new value'); # assign to array element
282 # hash type accessor:
283 $hash_ref = $obj->h; # reference to whole hash
284 $hash_element_value = $obj->h('x'); # hash element value
285 $obj->h('x', 'new value'); # assign to hash element
287 # class type accessor:
288 $element_value = $obj->c; # object reference
289 $obj->c->method(...); # call method of object
290 $obj->c(new My_Other_Class); # assign a new object
294 C<Class::Struct> exports a single function, C<struct>.
295 Given a list of element names and types, and optionally
296 a class name, C<struct> creates a Perl 5 class that implements
297 a "struct-like" data structure.
299 The new class is given a constructor method, C<new>, for creating
302 Each element in the struct data has an accessor method, which is
303 used to assign to the element and to fetch its value. The
304 default accessor can be overridden by declaring a C<sub> of the
305 same name in the package. (See Example 2.)
307 Each element's type can be scalar, array, hash, or class.
309 =head2 The C<struct()> function
311 The C<struct> function has three forms of parameter-list.
313 struct( CLASS_NAME => [ ELEMENT_LIST ]);
314 struct( CLASS_NAME => { ELEMENT_LIST });
315 struct( ELEMENT_LIST );
317 The first and second forms explicitly identify the name of the
318 class being created. The third form assumes the current package
319 name as the class name.
321 An object of a class created by the first and third forms is
322 based on an array, whereas an object of a class created by the
323 second form is based on a hash. The array-based forms will be
324 somewhat faster and smaller; the hash-based forms are more
327 The class created by C<struct> must not be a subclass of another
328 class other than C<UNIVERSAL>.
330 It can, however, be used as a superclass for other classes. To facilitate
331 this, the generated constructor method uses a two-argument blessing.
332 Furthermore, if the class is hash-based, the key of each element is
333 prefixed with the class name (see I<Perl Cookbook>, Recipe 13.12).
335 A function named C<new> must not be explicitly defined in a class
336 created by C<struct>.
338 The I<ELEMENT_LIST> has the form
342 Each name-type pair declares one element of the struct. Each
343 element name will be defined as an accessor method unless a
344 method by that name is explicitly defined; in the latter case, a
345 warning is issued if the warning flag (B<-w>) is set.
347 =head2 Class Creation at Compile Time
349 C<Class::Struct> can create your class at compile time. The main reason
350 for doing this is obvious, so your class acts like every other class in
351 Perl. Creating your class at compile time will make the order of events
352 similar to using any other class ( or Perl module ).
354 There is no significant speed gain between compile time and run time
355 class creation, there is just a new, more standard order of events.
357 =head2 Element Types and Accessor Methods
359 The four element types -- scalar, array, hash, and class -- are
360 represented by strings -- C<'$'>, C<'@'>, C<'%'>, and a class name --
361 optionally preceded by a C<'*'>.
363 The accessor method provided by C<struct> for an element depends
364 on the declared type of the element.
368 =item Scalar (C<'$'> or C<'*$'>)
370 The element is a scalar, and by default is initialized to C<undef>
371 (but see L<Initializing with new>).
373 The accessor's argument, if any, is assigned to the element.
375 If the element type is C<'$'>, the value of the element (after
376 assignment) is returned. If the element type is C<'*$'>, a reference
377 to the element is returned.
379 =item Array (C<'@'> or C<'*@'>)
381 The element is an array, initialized by default to C<()>.
383 With no argument, the accessor returns a reference to the
384 element's whole array (whether or not the element was
385 specified as C<'@'> or C<'*@'>).
387 With one or two arguments, the first argument is an index
388 specifying one element of the array; the second argument, if
389 present, is assigned to the array element. If the element type
390 is C<'@'>, the accessor returns the array element value. If the
391 element type is C<'*@'>, a reference to the array element is
394 As a special case, when the accessor is called with an array reference
395 as the sole argument, this causes an assignment of the whole array element.
396 The object reference is returned.
398 =item Hash (C<'%'> or C<'*%'>)
400 The element is a hash, initialized by default to C<()>.
402 With no argument, the accessor returns a reference to the
403 element's whole hash (whether or not the element was
404 specified as C<'%'> or C<'*%'>).
406 With one or two arguments, the first argument is a key specifying
407 one element of the hash; the second argument, if present, is
408 assigned to the hash element. If the element type is C<'%'>, the
409 accessor returns the hash element value. If the element type is
410 C<'*%'>, a reference to the hash element is returned.
412 As a special case, when the accessor is called with a hash reference
413 as the sole argument, this causes an assignment of the whole hash element.
414 The object reference is returned.
416 =item Class (C<'Class_Name'> or C<'*Class_Name'>)
418 The element's value must be a reference blessed to the named
419 class or to one of its subclasses. The element is initialized to
420 the result of calling the C<new> constructor of the named class.
422 The accessor's argument, if any, is assigned to the element. The
423 accessor will C<croak> if this is not an appropriate object
426 If the element type does not start with a C<'*'>, the accessor
427 returns the element value (after assignment). If the element type
428 starts with a C<'*'>, a reference to the element itself is returned.
432 =head2 Initializing with C<new>
434 C<struct> always creates a constructor called C<new>. That constructor
435 may take a list of initializers for the various elements of the new
438 Each initializer is a pair of values: I<element name>C< =E<gt> >I<value>.
439 The initializer value for a scalar element is just a scalar value. The
440 initializer for an array element is an array reference. The initializer
441 for a hash is a hash reference.
443 The initializer for a class element is also a hash reference, and the
444 contents of that hash are passed to the element's own constructor.
446 See Example 3 below for an example of initialization.
454 Giving a struct element a class type that is also a struct is how
455 structs are nested. Here, C<timeval> represents a time (seconds and
456 microseconds), and C<rusage> has two elements, each of which is of
462 ru_utime => timeval, # seconds
463 ru_stime => timeval, # microseconds
474 # $t->ru_utime and $t->ru_stime are objects of type timeval.
475 # set $t->ru_utime to 100.0 sec and $t->ru_stime to 5.0 sec.
476 $t->ru_utime->tv_secs(100);
477 $t->ru_utime->tv_usecs(0);
478 $t->ru_stime->tv_secs(5);
479 $t->ru_stime->tv_usecs(0);
483 An accessor function can be redefined in order to provide
484 additional checking of values, etc. Here, we want the C<count>
485 element always to be nonnegative, so we redefine the C<count>
486 accessor accordingly.
492 struct ( 'MyObj', { count => '$', stuff => '%' } );
494 # override the default accessor method for 'count'
498 die 'count must be nonnegative' if $_[0] < 0;
499 $self->{'count'} = shift;
500 warn "Too many args to count" if @_;
502 return $self->{'count'};
507 print "\$x->count(5) = ", $x->count(5), "\n";
508 # prints '$x->count(5) = 5'
510 print "\$x->count = ", $x->count, "\n";
511 # prints '$x->count = 5'
513 print "\$x->count(-5) = ", $x->count(-5), "\n";
514 # dies due to negative argument!
518 The constructor of a generated class can be passed a list
519 of I<element>=>I<value> pairs, with which to initialize the struct.
520 If no initializer is specified for a particular element, its default
521 initialization is performed instead. Initializers for non-existent
522 elements are silently ignored.
524 Note that the initializer for a nested struct is specified
525 as an anonymous hash of initializers, which is passed on to the nested
526 struct's constructor.
545 my $cat = Cat->new( name => 'Socks',
546 kittens => ['Monica', 'Kenneth'],
547 markings => { socks=>1, blaze=>"white" },
548 breed => { name=>'short-hair', cross=>1 },
551 print "Once a cat called ", $cat->name, "\n";
552 print "(which was a ", $cat->breed->name, ")\n";
553 print "had two kittens: ", join(' and ', @{$cat->kittens}), "\n";
557 =head1 Author and Modification History
559 Modified by Casey West, 2000-11-08, v0.59.
561 Added the ability for compile time class creation.
563 Modified by Damian Conway, 1999-03-05, v0.58.
565 Added handling of hash-like arg list to class ctor.
567 Changed to two-argument blessing in ctor to support
568 derivation from created classes.
570 Added classname prefixes to keys in hash-based classes
571 (refer to "Perl Cookbook", Recipe 13.12 for rationale).
573 Corrected behaviour of accessors for '*@' and '*%' struct
574 elements. Package now implements documented behaviour when
575 returning a reference to an entire hash or array element.
576 Previously these were returned as a reference to a reference
579 Renamed to C<Class::Struct> and modified by Jim Miner, 1997-04-02.
581 members() function removed.
582 Documentation corrected and extended.
583 Use of struct() in a subclass prohibited.
584 User definition of accessor allowed.
585 Treatment of '*' in element types corrected.
586 Treatment of classes as element types corrected.
587 Class name to struct() made optional.
588 Diagnostic checks added.
590 Originally C<Class::Template> by Dean Roehrich.
592 # Template.pm --- struct/member template builder
596 # changes/bugs fixed since 28nov94 version:
598 # changes/bugs fixed since 21nov94 version:
600 # changes/bugs fixed since 02sep94 version:
601 # - Moved to Class::Template.
602 # changes/bugs fixed since 20feb94 version:
603 # - Updated to be a more proper module.
604 # - Added "use strict".
605 # - Bug in build_methods, was using @var when @$var needed.
606 # - Now using my() rather than local().
608 # Uses perl5 classes to create nested data types.
609 # This is offered as one implementation of Tom Christiansen's "structs.pl"