1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | package InsideOut; require Exporter; @InsideOut::ISA = qw (Exporter); @InsideOut::EXPORT = qw (define_attributes); sub define_attributes { my $package = caller; @{"${package}::_ATTRIBUTES_"} = @_; my $code = ""; foreach my $attribute ( get_attribute_names($package) ) { @{"${package}::_$attribute"} = (); unless ( $package->can("get_${attribute}") ) { $code = $code . _define_get_accessor ($package, $attribute); } unless ( $package->can("set_${attribute}") ) { $code = $code . _define_set_accessor ($package, $attribute); } } $code .= _define_constructor ($package); eval $code; if ($@) { print $code . "\n"; die "ERROR: Unable to define constructor and accessor for $package \n" ; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | sub _define_get_accessor { my ($package, $attribute) = @_; my $code = qq { package $package; sub get_${attribute} { return \$_${attribute}\[\${\$_[0]}] } if ( !defined ( \$_free ) ) { \*_free = \*_$attribute; \$_free = 0; } }; return $code; } sub _define_set_accessor { my ($package, $attribute) = @_; my $code = qq { package $package; sub set_${attribute} { if ( scalar (\@_) > 1 ) { \$_${attribute}\[\${\$_[0]}] = \$_[1]; } } }; return $code; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | sub _define_constructor { my $package = shift; my $code = qq { package $package; sub new { my \$class = shift; my \$id; if ( defined (\$_free[\$_free]) ) { \$id = \$_free; \$_free = \$_free[\$_free]; undef \$_free[\$_id]; } else { \$id = \$_free++; } my \$object = bless \\\$id, \$class; if ( \@_ ) { \$object->set_attributes (\@_) } \$object->initialize(); return \$object; } }; return $code; } |
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) | Powered by Discuz! 7.0.0 |