第十一章 子產品:
傳統子產品為調用者的輸入和使用定義了子過程和 變量。面向對象的子產品的
運轉類似類聲明并且是通過方法調用來通路的
如果你的子產品的名字是 Red::Blue::Green,Perl 就會把它看作Red/Blue/Green.pm。
11.2 建立子產品
我們前面說過,一個子產品可以有兩個方法把它的接口提供給你的程式使用:符号輸出或者允許方法調用
面向對象的子產品應該不輸出任何東西,因為方法最重要的改變就是Perl以該對象的類型為基礎自動幫你找到方法的自身
/********* 第一種使用@EXPORT 來導出符号
Vsftp:/root/perl/7# cat Bestiary.pm
package Bestiary;
require Exporter;
our @ISA =qw(Exporter);
our @EXPORT =qw($weight camel); # 按要求輸出的符号
our $VERSION = 1.00; # 版本号
### 在這裡包含你的變量和函數
sub camel { print "One-hump dromedary" }
$weight = 1024;
1;
Vsftp:/root/perl/7# cat a10.pl
unshift(@INC,"/root/perl/7");
use Bestiary ;
print "\$weight is $weight\n";
my $var=camel ();
print "\$var is $var\n";
Vsftp:/root/perl/7# perl a10.pl
$weight is 1024
One-hump dromedary$var is 1
/*******************第2種使用@EXPORT_OK
Vsftp:/root/perl/7# cat Bestiary.pm
package Bestiary;
require Exporter;
our @ISA =qw(Exporter);
our @EXPORT_OK =qw($weight camel); # 按要求輸出的符号
our $VERSION = 1.00; # 版本号
### 在這裡包含你的變量和函數
sub camel { print "One-hump dromedary" }
$weight = 1024;
1;
Vsftp:/root/perl/7# cat a10.pl
unshift(@INC,"/root/perl/7");
use Bestiary ;
print "\$weight is $weight\n";
my $var=camel ();
print "\$var is $var\n";
Vsftp:/root/perl/7# perl a10.pl
$weight is
Undefined subroutine &main::camel called at a10.pl line 5.
此時無法調用,需要use Bestiary qw($weight camel) ;
Vsftp:/root/perl/7# cat a10.pl
unshift(@INC,"/root/perl/7");
use Bestiary qw($weight camel) ;
print "\$weight is $weight\n";
my $var=camel ();
print "\$var is $var\n";
Vsftp:/root/perl/7# perl a10.pl
$weight is 1024
One-hump dromedary$var is 1
11.2.1 子產品私有和輸出器
require Exporter;
our @ISA = ("Exporter");
這兩行指令該子產品從Exporter 類中繼承下來,我們在下一章講繼承,
但是在這裡你要知道的,所有東西就是我們的Bestiary 子產品現在可以用
類似下面的行把符号表輸出到其他包裡:
從輸出子產品的角度出發,@EXPORT 數組包含預設要輸出的變量和函數的名字: 當你的程式說
use Bestary 的時候得到的東西,在@EXPORT_OK裡的變量和函數 隻有當程式在use 語句裡面
特别要求它們的時候才輸出。
Vsftp:/root/perl/7# cat Bestiary.pm
package Bestiary;
require Exporter;
our @ISA =qw(Exporter);
our @EXPORT_OK =qw($weight camel); # 按要求輸出的符号
our $VERSION = 1.00; # 版本号
### 在這裡包含你的變量和函數
sub camel { print "One-hump dromedary" }
$weight = 1024;
1;
Vsftp:/root/perl/7# cat a10.pl
unshift(@INC,"/root/perl/7");
#use Bestiary qw($weight camel) ;
BEGIN {
require Bestiary;
import Bestiary qw($weight camel) ;
}
print "\$weight is $weight\n";
my $var=camel ();
print "\$var is $var\n";
Vsftp:/root/perl/7# perl a1
a10.pl a1.pl
Vsftp:/root/perl/7# perl a10.pl
$weight is 1024
One-hump dromedary$var is 1