📄 struct.pm
字号:
Each element in the struct data has an accessor method, which isused to assign to the element and to fetch its value. Thedefault accessor can be overridden by declaring a C<sub> of thesame name in the package. (See Example 2.)Each element's type can be scalar, array, hash, or class.=head2 The C<struct()> functionThe C<struct> function has three forms of parameter-list. struct( CLASS_NAME => [ ELEMENT_LIST ]); struct( CLASS_NAME => { ELEMENT_LIST }); struct( ELEMENT_LIST );The first and second forms explicitly identify the name of theclass being created. The third form assumes the current packagename as the class name.An object of a class created by the first and third forms isbased on an array, whereas an object of a class created by thesecond form is based on a hash. The array-based forms will besomewhat faster and smaller; the hash-based forms are moreflexible.The class created by C<struct> must not be a subclass of anotherclass other than C<UNIVERSAL>.It can, however, be used as a superclass for other classes. To facilitatethis, the generated constructor method uses a two-argument blessing.Furthermore, if the class is hash-based, the key of each element isprefixed with the class name (see I<Perl Cookbook>, Recipe 13.12).A function named C<new> must not be explicitly defined in a classcreated by C<struct>.The I<ELEMENT_LIST> has the form NAME => TYPE, ...Each name-type pair declares one element of the struct. Eachelement name will be defined as an accessor method unless amethod by that name is explicitly defined; in the latter case, awarning is issued if the warning flag (B<-w>) is set.=head2 Element Types and Accessor MethodsThe four element types -- scalar, array, hash, and class -- arerepresented by strings -- C<'$'>, C<'@'>, C<'%'>, and a class name --optionally preceded by a C<'*'>.The accessor method provided by C<struct> for an element dependson the declared type of the element.=over=item Scalar (C<'$'> or C<'*$'>)The element is a scalar, and by default is initialized to C<undef>(but see L<Initializing with new>).The accessor's argument, if any, is assigned to the element.If the element type is C<'$'>, the value of the element (afterassignment) is returned. If the element type is C<'*$'>, a referenceto the element is returned.=item Array (C<'@'> or C<'*@'>)The element is an array, initialized by default to C<()>.With no argument, the accessor returns a reference to theelement's whole array (whether or not the element wasspecified as C<'@'> or C<'*@'>).With one or two arguments, the first argument is an indexspecifying one element of the array; the second argument, ifpresent, is assigned to the array element. If the element typeis C<'@'>, the accessor returns the array element value. If theelement type is C<'*@'>, a reference to the array element isreturned.=item Hash (C<'%'> or C<'*%'>)The element is a hash, initialized by default to C<()>.With no argument, the accessor returns a reference to theelement's whole hash (whether or not the element wasspecified as C<'%'> or C<'*%'>).With one or two arguments, the first argument is a key specifyingone element of the hash; the second argument, if present, isassigned to the hash element. If the element type is C<'%'>, theaccessor returns the hash element value. If the element type isC<'*%'>, a reference to the hash element is returned.=item Class (C<'Class_Name'> or C<'*Class_Name'>)The element's value must be a reference blessed to the namedclass or to one of its subclasses. The element is initialized tothe result of calling the C<new> constructor of the named class.The accessor's argument, if any, is assigned to the element. Theaccessor will C<croak> if this is not an appropriate objectreference.If the element type does not start with a C<'*'>, the accessorreturns the element value (after assignment). If the element typestarts with a C<'*'>, a reference to the element itself is returned.=back=head2 Initializing with C<new>C<struct> always creates a constructor called C<new>. That constructormay take a list of initializers for the various elements of the newstruct.Each initializer is a pair of values: I<element name>C< =E<gt> >I<value>.The initializer value for a scalar element is just a scalar value. Theinitializer for an array element is an array reference. The initializerfor a hash is a hash reference.The initializer for a class element is also a hash reference, and thecontents of that hash are passed to the element's own constructor.See Example 3 below for an example of initialization.=head1 EXAMPLES=over=item Example 1Giving a struct element a class type that is also a struct is howstructs are nested. Here, C<timeval> represents a time (seconds andmicroseconds), and C<rusage> has two elements, each of which is oftype C<timeval>. use Automake::Struct; struct( rusage => { ru_utime => timeval, # seconds ru_stime => timeval, # microseconds }); struct( timeval => [ tv_secs => '$', tv_usecs => '$', ]); # create an object: my $t = new rusage; # $t->ru_utime and $t->ru_stime are objects of type timeval. # set $t->ru_utime to 100.0 sec and $t->ru_stime to 5.0 sec. $t->ru_utime->tv_secs(100); $t->ru_utime->tv_usecs(0); $t->ru_stime->tv_secs(5); $t->ru_stime->tv_usecs(0);=item Example 2An accessor function can be redefined in order to provideadditional checking of values, etc. Here, we want the C<count>element always to be nonnegative, so we redefine the C<count>accessor accordingly. package MyObj; use Automake::Struct; # declare the struct struct ( 'MyObj', { count => '$', stuff => '%' } ); # override the default accessor method for 'count' sub count { my $self = shift; if ( @_ ) { die 'count must be nonnegative' if $_[0] < 0; $self->{'count'} = shift; warn "Too many args to count" if @_; } return $self->{'count'}; } package main; $x = new MyObj; print "\$x->count(5) = ", $x->count(5), "\n"; # prints '$x->count(5) = 5' print "\$x->count = ", $x->count, "\n"; # prints '$x->count = 5' print "\$x->count(-5) = ", $x->count(-5), "\n"; # dies due to negative argument!=item Example 3The constructor of a generated class can be passed a listof I<element>=>I<value> pairs, with which to initialize the struct.If no initializer is specified for a particular element, its defaultinitialization is performed instead. Initializers for non-existentelements are silently ignored.Note that the initializer for a nested struct is specifiedas an anonymous hash of initializers, which is passed on to the nestedstruct's constructor. use Automake::Struct; struct Breed => { name => '$', cross => '$', }; struct Cat => [ name => '$', kittens => '@', markings => '%', breed => 'Breed', ]; my $cat = Cat->new( name => 'Socks', kittens => ['Monica', 'Kenneth'], markings => { socks=>1, blaze=>"white" }, breed => { name=>'short-hair', cross=>1 }, ); print "Once a cat called ", $cat->name, "\n"; print "(which was a ", $cat->breed->name, ")\n"; print "had two kittens: ", join(' and ', @{$cat->kittens}), "\n";=back=head1 Author and Modification HistoryModified by Akim Demaille, 2001-08-03 Rename as Automake::Struct to avoid name clashes with Class::Struct. Make it compatible with Perl 5.5.Modified by Damian Conway, 1999-03-05, v0.58. Added handling of hash-like arg list to class ctor. Changed to two-argument blessing in ctor to support derivation from created classes. Added classname prefixes to keys in hash-based classes (refer to "Perl Cookbook", Recipe 13.12 for rationale). Corrected behaviour of accessors for '*@' and '*%' struct elements. Package now implements documented behaviour when returning a reference to an entire hash or array element. Previously these were returned as a reference to a reference to the element.Renamed to C<Class::Struct> and modified by Jim Miner, 1997-04-02. members() function removed. Documentation corrected and extended. Use of struct() in a subclass prohibited. User definition of accessor allowed. Treatment of '*' in element types corrected. Treatment of classes as element types corrected. Class name to struct() made optional. Diagnostic checks added.Originally C<Class::Template> by Dean Roehrich. # Template.pm --- struct/member template builder # 12mar95 # Dean Roehrich # # changes/bugs fixed since 28nov94 version: # - podified # changes/bugs fixed since 21nov94 version: # - Fixed examples. # changes/bugs fixed since 02sep94 version: # - Moved to Class::Template. # changes/bugs fixed since 20feb94 version: # - Updated to be a more proper module. # - Added "use strict". # - Bug in build_methods, was using @var when @$var needed. # - Now using my() rather than local(). # # Uses perl5 classes to create nested data types. # This is offered as one implementation of Tom Christiansen's "structs.pl" # idea.=cut
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -