Steven's Blog

A Dream Land of Peace!

Perl中的constructor和destructor

For Perl constructor, we can seperate the process of object creation from the process of initialization.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package CD::Music;
use strict;
sub new {
	my $self = {};
	bless $self, shift;
	$self->_incr_count();
	$self->_init(@_);
	return $self;
}
{
	my @_init_mems =
	qw( _name _artist _publisher _ISBN _tracks _room _shelf _rating );
	sub _init {
		my ($self,@args) = @_;
		my %inits;
		@inits{@_init_mems} = @args;
		%$self = %inits;
	}
}