Translate

2013年8月17日土曜日

[perl]コンストラクタで値の初期化

学習のため、某JavaのソースコードをPerlで表現してみる。

class Rectangle {
    int width;
    int height;
    Rectangle(){
        setSize(10, 20);
    }
    void setSize(int w, int h){
        width = w;
        height = h;
    }
    int getArea(){
        return width * height;
    }
}

引数無しでnewされた場合
setSizeメソッドを使って幅10, 高さ20を指定するわけですね。
では、やってみましょう。
package Rectangle;
use strict;
use warnings;
use utf8;
binmode STDERR, ":utf8";

sub new{
    my $class = shift;
    my $self  = bless {width=>0, height=>0}, $class;

    #引数無しでnewされたらデフォルト値を指定                                       
    if (@_==0){$self->setSize(10, 20)};                                            

    return $self;
}

sub setSize{
    my $self = shift;
    if(@_!=2){die("setSizeの引数を2つ指定してください(width, height)")}
    $self->{width}  = $_[0];
    $self->{height} = $_[1];
}

sub getArea{
    my $self = shift;                                                              
    return $self->{width} * $self->{height};
}

1;

ポイントは第一引数にオブジェクトを渡すためには、blessした
オブジェクト経由でメソッドを呼ばないといけないというあたりですかね・・・
これで最初に書いたメソッドをうまく再利用できてますね。
では使ってみます。
use strict;
use warnings;
use utf8;
use feature 'say';
binmode STDOUT, ":utf8";

use lib qw(lib);
use Rectangle;

my $r = Rectangle->new();
                                                                                   
say "幅 :". $r->{width};
say "高さ:". $r->{height};
say "面積:". $r->getArea();

出力結果:
幅 :10
高さ:20
面積:200


初期化の時は直接記載しようよ。
というのであれば、
class Rectangle {
    int width = 10;
    int height = 20;
    void setSize(int w, int h){
        width = w;
        height = h;
    }
    int getArea(){
        return width * height;
    }
}
こうなると思います。
では、Perlでは
package Rectangle;
use strict;
use warnings;
use utf8;
binmode STDERR, ":utf8";

sub new{
    return bless {width=>10, height=>20}, shift;
}                                                                                  

sub setSize{
    my $self = shift;
    if(@_!=2){die("setSizeの引数を2つ指定してください(width, height)")}
    $self->{width}  = $_[0];
    $self->{height} = $_[1];
}

sub getArea{
    my $self = shift;
    return $self->{width} * $self->{height};
}

1;

0 件のコメント: