01 May 2011

Compiler Directive Module


ใจการสร้าง module ขึ้นมานั้นเราสามารถเลือกเฉพาะบาง subroutine หรือตัวแปร ให้ทำงานได้โดยใช้การทำ Compiler Directive ซึ่งโครงสร้างคร่าวๆจะเป็น

##############################
package modulename;
use Exporter;

#@ISA จะทำหน้าที่เก็บโมดูลที่ inheritance ถ้าไม่เจอใน package จะทำการค้นหาจาก ตัวแปรนี้
@ISA = qw(Exporter);

#เป็น default load เมื่อเรียกใช้โมดูล subroutine ใน @EXPORT จะสามารถทำงานได้
@EXPORT = qw(function $variable @arrayVar %hashVAr);

#ถ้าต้องการใช้ต้องส่งพารามิเตอร์ ตอนโหลดโมดูล
@EXPORT_OK = qw(functionTwo $var);

#เหมือน @EXPORT_OK แต่ทำเป็นกลุ่มเอาไว้
%EXPORT_TAGS = qw('name'=>[qw(function functionTwo)]);
##############################

ตัวอย่าง
package DModule;

use Exporter;

@ISA = qw(Exporter);
@EXPORT = qw(fnc1);
@EXPORT_OK = qw(fnc2);
%EXPORT_TAGS = ('all'=>[qw(fnc1 fnc2)]);

sub fnc1
{
print "fnc1 print
";
}

sub fnc2
{
print "fnc2 print
";
}

1;

วิธีการเรียกใช้
#!c:\perl\bin\perl.exe

print "content-type:text/html\n\n";
use DModule qw(:all !fnc2); #โหลดฟังก์ชั่นจาก %EXPORT_TAGS ยกเว้น fnc2

fnc1();
fnc2(); #ฟังก์ชั่นนี้จะไม่ทำงาน

การโหลดแบบอื่น
:DEFAUL เป็นค่าที่บอกว่าให้โหลดจาก @EXPORT
use DModule qw(:DEFAULT fnc2);
fnc1 และ fnc2 สามารถถูกเรียกใช้ได้

อ้างอิง
http://docstore.mik.ua/orelly/perl/prog3/ch12_05.htm
http://world.std.com/~swmcd/steven/perl/module_anatomy.html
http://perldoc.perl.org/Exporter.html

0 comments:

Post a Comment