3 ## See POD after __END__
8 use vars qw(@ISA @EXPORT);
16 ## Tested on 5.002 and 5.003 without class membership tests:
17 my $CHECK_CLASS_MEMBERSHIP = ($] >= 5.003_95);
21 if (@_) { $print = shift }
26 package Class::Struct::Tie_ISA;
30 return bless [], $class;
34 my ($self, $index, $value) = @_;
35 Class::Struct::_subclass_error();
39 my ($self, $index) = @_;
48 # Determine parameter list structure, one of:
49 # struct( class => [ element-list ])
50 # struct( class => { element-list })
51 # struct( element-list )
52 # Latter form assumes current package name as struct name.
55 my $base_type = ref $_[1];
56 if ( $base_type eq 'HASH' ) {
61 elsif ( $base_type eq 'ARRAY' ) {
68 $class = (caller())[0];
71 _usage_error() if @decls % 2 == 1;
73 # Ensure we are not, and will not be, a subclass.
79 _subclass_error() if @$isa;
80 tie @$isa, 'Class::Struct::Tie_ISA';
84 croak "function 'new' already defined in package $class"
85 if do { no strict 'refs'; defined &{$class . "::new"} };
95 $out = "{\n package $class;\n use Carp;\n sub new {\n";
99 my( $cmt, $name, $type, $elem );
101 if( $base_type eq 'HASH' ){
102 $out .= " my(\$r) = {};\n";
105 elsif( $base_type eq 'ARRAY' ){
106 $out .= " my(\$r) = [];\n";
108 while( $idx < @decls ){
109 $name = $decls[$idx];
110 $type = $decls[$idx+1];
111 push( @methods, $name );
112 if( $base_type eq 'HASH' ){
115 elsif( $base_type eq 'ARRAY' ){
120 if( $type =~ /^\*(.)/ ){
125 $out .= " \$r->$elem = [];$cmt\n";
128 elsif( $type eq '%' ){
129 $out .= " \$r->$elem = {};$cmt\n";
132 elsif ( $type eq '$') {
133 $out .= " \$r->$elem = undef;$cmt\n";
135 elsif( $type =~ /^\w+(?:::\w+)*$/ ){
136 $out .= " \$r->$elem = '${type}'->new();$cmt\n";
137 $classes{$name} = $type;
141 croak "'$type' is not a valid struct element type";
145 $out .= " bless \$r;\n }\n";
147 # Create accessor methods.
149 if ( $got_class && $CHECK_CLASS_MEMBERSHIP ) {
150 $out .= " use UNIVERSAL;\n";
152 my( $pre, $pst, $sel );
154 foreach $name (@methods){
155 if ( do { no strict 'refs'; defined &{$class . "::$name"} } ) {
156 carp "function '$name' already defined, overrides struct accessor method"
160 $pre = $pst = $cmt = $sel = '';
161 if( defined $refs{$name} ){
164 $cmt = " # returns ref";
166 $out .= " sub $name {$cmt\n my \$r = shift;\n";
167 if( $base_type eq 'ARRAY' ){
171 elsif( $base_type eq 'HASH' ){
174 if( defined $arrays{$name} ){
175 $out .= " my \$i;\n";
176 $out .= " \@_ ? (\$i = shift) : return $pre\$r->$elem$pst;\n";
179 elsif( defined $hashes{$name} ){
180 $out .= " my \$i;\n";
181 $out .= " \@_ ? (\$i = shift) : return $pre\$r->$elem$pst;\n";
184 elsif( defined $classes{$name} ){
185 if ( $CHECK_CLASS_MEMBERSHIP ) {
186 $out .= " croak '$name argument is wrong class' if \@_ && ! UNIVERSAL::isa(\$_[0], '$type');\n";
189 $out .= " croak 'Too many args to $name' if \@_ > 1;\n";
190 $out .= " \@_ ? ($pre\$r->$elem$sel = shift$pst) : $pre\$r->$elem$sel$pst;\n";
196 print $out if $print;
197 my $result = eval $out;
202 confess "struct usage error";
205 sub _subclass_error {
206 croak 'struct class cannot be a subclass (@ISA not allowed)';
216 Class::Struct - declare struct-like datatypes as Perl classes
221 # declare struct, based on array:
222 struct( CLASS_NAME => [ ELEMENT_NAME => ELEMENT_TYPE, ... ]);
223 # declare struct, based on hash:
224 struct( CLASS_NAME => { ELEMENT_NAME => ELEMENT_TYPE, ... });
228 # declare struct, based on array, implicit class name:
229 struct( ELEMENT_NAME => ELEMENT_TYPE, ... );
234 # declare struct with four types of elements:
235 struct( s => '$', a => '@', h => '%', c => 'My_Other_Class' );
237 $obj = new Myobj; # constructor
239 # scalar type accessor:
240 $element_value = $obj->s; # element value
241 $obj->s('new value'); # assign to element
243 # array type accessor:
244 $ary_ref = $obj->a; # reference to whole array
245 $ary_element_value = $obj->a(2); # array element value
246 $obj->a(2, 'new value'); # assign to array element
248 # hash type accessor:
249 $hash_ref = $obj->h; # reference to whole hash
250 $hash_element_value = $obj->h('x'); # hash element value
251 $obj->h('x', 'new value'); # assign to hash element
253 # class type accessor:
254 $element_value = $obj->c; # object reference
255 $obj->c->method(...); # call method of object
256 $obj->c(new My_Other_Class); # assign a new object
261 C<Class::Struct> exports a single function, C<struct>.
262 Given a list of element names and types, and optionally
263 a class name, C<struct> creates a Perl 5 class that implements
264 a "struct-like" data structure.
266 The new class is given a constructor method, C<new>, for creating
269 Each element in the struct data has an accessor method, which is
270 used to assign to the element and to fetch its value. The
271 default accessor can be overridden by declaring a C<sub> of the
272 same name in the package. (See Example 2.)
274 Each element's type can be scalar, array, hash, or class.
277 =head2 The C<struct()> function
279 The C<struct> function has three forms of parameter-list.
281 struct( CLASS_NAME => [ ELEMENT_LIST ]);
282 struct( CLASS_NAME => { ELEMENT_LIST });
283 struct( ELEMENT_LIST );
285 The first and second forms explicitly identify the name of the
286 class being created. The third form assumes the current package
287 name as the class name.
289 An object of a class created by the first and third forms is
290 based on an array, whereas an object of a class created by the
291 second form is based on a hash. The array-based forms will be
292 somewhat faster and smaller; the hash-based forms are more
295 The class created by C<struct> must not be a subclass of another
296 class other than C<UNIVERSAL>.
298 A function named C<new> must not be explicitly defined in a class
299 created by C<struct>.
301 The I<ELEMENT_LIST> has the form
305 Each name-type pair declares one element of the struct. Each
306 element name will be defined as an accessor method unless a
307 method by that name is explicitly defined; in the latter case, a
308 warning is issued if the warning flag (B<-w>) is set.
311 =head2 Element Types and Accessor Methods
313 The four element types -- scalar, array, hash, and class -- are
314 represented by strings -- C<'$'>, C<'@'>, C<'%'>, and a class name --
315 optionally preceded by a C<'*'>.
317 The accessor method provided by C<struct> for an element depends
318 on the declared type of the element.
322 =item Scalar (C<'$'> or C<'*$'>)
324 The element is a scalar, and is initialized to C<undef>.
326 The accessor's argument, if any, is assigned to the element.
328 If the element type is C<'$'>, the value of the element (after
329 assignment) is returned. If the element type is C<'*$'>, a reference
330 to the element is returned.
332 =item Array (C<'@'> or C<'*@'>)
334 The element is an array, initialized to C<()>.
336 With no argument, the accessor returns a reference to the
337 element's whole array.
339 With one or two arguments, the first argument is an index
340 specifying one element of the array; the second argument, if
341 present, is assigned to the array element. If the element type
342 is C<'@'>, the accessor returns the array element value. If the
343 element type is C<'*@'>, a reference to the array element is
346 =item Hash (C<'%'> or C<'*%'>)
348 The element is a hash, initialized to C<()>.
350 With no argument, the accessor returns a reference to the
351 element's whole hash.
353 With one or two arguments, the first argument is a key specifying
354 one element of the hash; the second argument, if present, is
355 assigned to the hash element. If the element type is C<'%'>, the
356 accessor returns the hash element value. If the element type is
357 C<'*%'>, a reference to the hash element is returned.
359 =item Class (C<'Class_Name'> or C<'*Class_Name'>)
361 The element's value must be a reference blessed to the named
362 class or to one of its subclasses. The element is initialized to
363 the result of calling the C<new> constructor of the named class.
365 The accessor's argument, if any, is assigned to the element. The
366 accessor will C<croak> if this is not an appropriate object
369 If the element type does not start with a C<'*'>, the accessor
370 returns the element value (after assignment). If the element type
371 starts with a C<'*'>, a reference to the element itself is returned.
381 Giving a struct element a class type that is also a struct is how
382 structs are nested. Here, C<timeval> represents a time (seconds and
383 microseconds), and C<rusage> has two elements, each of which is of
389 ru_utime => timeval, # seconds
390 ru_stime => timeval, # microseconds
400 # $t->ru_utime and $t->ru_stime are objects of type timeval.
402 # set $t->ru_utime to 100.0 sec and $t->ru_stime to 5.0 sec.
403 $t->ru_utime->tv_secs(100);
404 $t->ru_utime->tv_usecs(0);
405 $t->ru_stime->tv_secs(5);
406 $t->ru_stime->tv_usecs(0);
411 An accessor function can be redefined in order to provide
412 additional checking of values, etc. Here, we want the C<count>
413 element always to be nonnegative, so we redefine the C<count>
414 accessor accordingly.
420 struct ( 'MyObj', { count => '$', stuff => '%' } );
422 # override the default accessor method for 'count'
426 die 'count must be nonnegative' if $_[0] < 0;
427 $self->{'count'} = shift;
428 warn "Too many args to count" if @_;
430 return $self->{'count'};
435 print "\$x->count(5) = ", $x->count(5), "\n";
436 # prints '$x->count(5) = 5'
438 print "\$x->count = ", $x->count, "\n";
439 # prints '$x->count = 5'
441 print "\$x->count(-5) = ", $x->count(-5), "\n";
442 # dies due to negative argument!
445 =head1 Author and Modification History
448 Renamed to C<Class::Struct> and modified by Jim Miner, 1997-04-02.
450 members() function removed.
451 Documentation corrected and extended.
452 Use of struct() in a subclass prohibited.
453 User definition of accessor allowed.
454 Treatment of '*' in element types corrected.
455 Treatment of classes as element types corrected.
456 Class name to struct() made optional.
457 Diagnostic checks added.
460 Originally C<Class::Template> by Dean Roehrich.
462 # Template.pm --- struct/member template builder
466 # changes/bugs fixed since 28nov94 version:
468 # changes/bugs fixed since 21nov94 version:
470 # changes/bugs fixed since 02sep94 version:
471 # - Moved to Class::Template.
472 # changes/bugs fixed since 20feb94 version:
473 # - Updated to be a more proper module.
474 # - Added "use strict".
475 # - Bug in build_methods, was using @var when @$var needed.
476 # - Now using my() rather than local().
478 # Uses perl5 classes to create nested data types.
479 # This is offered as one implementation of Tom Christiansen's "structs.pl"