cross.pl 程式內容

#!/usr/bin/perl
use strict;
use lib "/home/cross/test/lib";         # 我把自寫的perl module 寫在/home/cross/test/lib/Cross.pm
                                                        # 所以我要用 use lib 引用路徑
use Cross;                                       # 再用 use 去使用 Cross模組

my $c = new Cross('cross','yes');     # 名子是 cross,說了 yes
print "
my name is ",$c->getname,", say ",$c->getyes;      # 取得值

/home/cross/test/lib/Cross.pm 的內容

package Cross;

sub new {
        my $class = shift;                # 這個 $class 會得到 Cross 模組名稱
                                                    # 應該是這行 my $c = new Cross('cross','yes');   的 Cross
        my $aa = {};                       # 宣告一個 HASH
        $aa->{name} = shift;          # 給 name=> 為 cross
        $aa->{yes} = shift;             # 而 yes => 為 yes
                                                     # $aa 長這樣子
                                                      # $VAR1 = {
                                                      #          'yes' => 'yes',
                                                      #         'name' => 'cross'
                                                      #        };

        bless $aa;
        return $aa;
}

sub getname {
        my $class = shift;                  # $class 的樣子
                                                      # $VAR1 = bless( {
                                                      #                 'yes' => 'yes',
                                                      #                 'name' => 'cross'
                                                      #               }, 'Cross' );

        return $class->{name};
}

sub getyes {
        my $class = shift;                  # $class 的樣子
                                                      # $VAR1 = bless( {
                                                      #                 'yes' => 'yes',
                                                      #                 'name' => 'cross'
                                                      #               }, 'Cross' );
        return $class->{yes};
}

1;

執行結果

my name is cross, say yes

最後修改日期: 2011 年 04 月 03 日

作者

留言

撰寫回覆或留言

發佈留言必須填寫的電子郵件地址不會公開。