⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 struct.pm

📁 Astercon2 开源软交换 2.2.0
💻 PM
📖 第 1 页 / 共 2 页
字号:
    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 Class Creation at Compile TimeC<Class::Struct> can create your class at compile time.  The main reasonfor doing this is obvious, so your class acts like every other class inPerl.  Creating your class at compile time will make the order of eventssimilar to using any other class ( or Perl module ).There is no significant speed gain between compile time and run timeclass creation, there is just a new, more standard order of events.=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 4=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.As a special case, when the accessor is called with an array referenceas the sole argument, this causes an assignment of the whole array element.The object reference is returned.=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.As a special case, when the accessor is called with a hash referenceas the sole argument, this causes an assignment of the whole hash element.The object reference 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 not initializedby default.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. The initializer for an array element is an array reference. The initializerfor a hash is a hash reference.The initializer for a class element is an object of the corresponding class,or of one of it's subclasses, or a reference to a hash containing named arguments to be passed to the element's constructor.See Example 3 below for an example of initialization.=head1 EXAMPLES=over 4=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 Class::Struct;    struct( Rusage => {        ru_utime => 'Timeval',  # user time used        ru_stime => 'Timeval',  # system time used    });    struct( Timeval => [        tv_secs  => '$',        # seconds        tv_usecs => '$',        # microseconds    ]);        # create an object:    my $t = Rusage->new(ru_utime=>Timeval->new(), ru_stime=>Timeval->new());        # $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 Class::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->{'MyObj::count'} = shift;            warn "Too many args to count" if @_;        }        return $self->{'MyObj::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 class may be specified asan object of that class, or as a reference to a hash of initializersthat are passed on to the nested struct's constructor.    use Class::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    => Breed->new(name=>'short-hair', cross=>1),                   or:  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 Damian Conway, 2001-09-10, v0.62.   Modified implicit construction of nested objects.   Now will also take an object ref instead of requiring a hash ref.   Also default initializes nested object attributes to undef, rather   than calling object constructor without args   Original over-helpfulness was fraught with problems:       * the class's constructor might not be called 'new'       * the class might not have a hash-like-arguments constructor       * the class might not have a no-argument constructor       * "recursive" data structures didn't work well:                 package Person;                 struct { mother => 'Person', father => 'Person'};Modified by Casey West, 2000-11-08, v0.59.    Added the ability for compile time class creation.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 + -