コンストラクタ・デストラクタ

コンストラクタは生成時、デストラクタは解放時に実行される

'work/Module.pm'

# パッケージ名定義
package Module;
 
# プロパティ
my $name;
my $data;
 
# コンストラクタ
sub new {
	# オブジェクトを取得
	my $class = shift;
 
	print "test-constract\n";
 
	# リファレンス
	my $ref = {};
	$ref->{name} = $name;
	$ref->{data} = $data;
 
	# オブジェクト生成
	my $obj = bless $ref, $class;
 
	# オブジェクト返却
	return $obj;
}
 
 
# インスタンスメソッド
# プロパティnameに値を設定
sub setName{
	my $obj = shift;
	my ($_name) = @_;
 
	$obj->{name} = $_name;
 
	print "test-method1\n";
 
}
 
# インスタンスメソッド
# プロパティdataに値を設定
sub setData{
	my $obj = shift;
	my ($_data) = @_;
 
	$obj->{data} = $_data;
 
	print "test-method2\n";
 
}
 
# プロパティの値を出力
sub getDisplay{
	my $obj = shift;
	print $obj->{name} . "\n";
	print $obj->{data} . "\n";
	print "test-method2\n";
}
 
# デストラクタ
sub DESTROY {
	# オブジェクトを取得
	my $obj = shift;
 
	# 処理
	print "test-descract\n";
 
}
 
# モジュール終端
1;
 
 

sample.pl

use strict;
use warnings;
 
# モジュール取り込み
use work::Module;
 
# メインスクリプト
my $obj = Module->new();
 
# プロパティに設定
$obj->setName("aaaaa");
$obj->setData("bbbbb");
 
# プロパティの値を表示
$obj->getDisplay();
 
 
# 処理開始
BEGIN {
	print "test-script-start\n";
}
 
# 処理終了
END {
	print "test-script-end\n";
}
 
 

結果

>perl sample.pl
test-script-start
test-constract
test-method1
test-method2
aaaaa
bbbbb
test-method2
test-descract
test-script-end
 
>
 
 




最終更新:2012年01月14日 21:29