sironekotoroの日記

Perl で楽をしたい

今日の午後3時間くらい悩んでいた事

オブジェクト指向の勉強中・・・

クラスを作ったパッケージ内にある変数に、メソッドを経由してアクセスしたい

  • testClass クラス の中の access サブルーチンから、おなじパッケージ内の $str にアクセスしたい
  • 不精をして、1つのファイルで package で分けることでクラスを作ったりという事をしておりました(フラグ
# test.pl
use 5.012;
use warnings;
use utf8;
binmode STDOUT, ':encoding(UTF-8)';

# オブジェクト作成
my $object = testClass->new;

# オブジェクト経由でメソッド動かして、
# testClassの中の $str の値を表示させたい
print $object->access;


# ----- main パッケージここまで -----
package testClass;

# packageの中にはあるけど、メソッドの中には無い変数
my $str = 'testClass package';

# コンストラクタ
sub new {
    my $class = shift;
    my $name = {};
    bless $name , $class;
}

# このメソッドで同じ pakcage の中にある $str を返す
sub access {
    my $class = shift;
    return $str;
}
1;
  • が、エラー

    Use of uninitialized value in print at ...

  • $str にアクセスできない・・・なぜだ

  • このあと、use strict 外したり、 my の代わりに our とか local 使うなどするも解決せず。

解決

  • ちゃんとファイルを分けたら動いた
  • でも、なぜ1つのファイルで分けたらダメなのか理解できず
  • 不精はいかん、ってことだけど、うーん、なぜだ。分からん。
# test.pl
use 5.012;
use warnings;
use utf8;
use testClass;
binmode STDOUT, ':encoding(UTF-8)';

# オブジェクト作成
my $object = testClass->new;

# オブジェクト経由でメソッド動かして、
# testClassの中の $str の値を表示させたい
print $object->access;
# testClass.pm
package testClass;

# packageの中にはあるけど、メソッドの中には無い変数
my $str = 'testClass package';

# コンストラクタ
sub new {
    my $class = shift;
    my $name = {};
    bless $name , $class;
}

# このメソッドで同じ pakcage の中にある $str を返す
sub access {
    my $class = shift;
    return $str;
}
1;

しかし・・・

  • testClass.pm の $str を { } で囲むと動かなくなる・・・これではカプセル化が・・・ううむ