[Perl]
Perlモジュールの書式は大抵以下のようになります。
package 任意のモジュール名;
use Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(sub1, sub2); #Exportするルーチン
sub sub1{
.
.
.
}
sub sub2{
.
.
.
}
スクリプトから作成したモジュールを読み込みにはuse文を使用します。
[例]
use モジュール名
モジュールのサブルーチンを呼び出すには&sub1()などとすればOK。以下実例。
[モジュール: Category.pm]
package Category;
use Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(new show_parent);
sub new {
my $pkg = shift;
my $self; { my %hash; $self = bless(\%hash, $pkg); }
my $options = {};
$self->{options} = $options;
my @required_options = qw /sub_category/;
# set default parameters in options hash
%$options = (
parent_category => 'Linux'
);
# new()にて渡されたオプションの処理
for (my $x = 0; $x <= $#_; $x += 2) {
defined($_[($x + 1)]) or warn("Category->new() called with odd number of option parameters - should be of the form option => value");
$options->{lc($_[$x])} = $_[($x + 1)];
}
# new()でオブジェクトを作成する際の必須オプションのチェック
#check required options
foreach (@required_options) {
defined($options->{$_}) or die ("set required option $_ with Category->new( $_ => VAL )");
}
return $self;
}
sub show_parent {
my $self = shift;
my $options = $self->{options};
print "$options->{sub_category} is sub category of $options->{parent_category}\n";
return ();
}
[モジュールを呼び出すスクリプト: use_module_sample.pl]
#!/usr/bin/perl use Category; my $category = Category->new( sub_category => 'Command' ); print $category->show_parent();
[出力結果]
Command is sub category of Linux
広告
|
初めてのPerl ¥ 3,780 / 売り上げランク: 10349 / 379 ページ いわゆるリャマ本として知られる定番書 初めてのとあるが初心者向きではないと思う。 よくできてはいるが、、。 |
|
新版Perl言語プログラミングレッスン入門編 ¥ 2,835 / 売り上げランク: 15202 / 512 ページ 非常に分かりやすい。 今までにも様々な参考書に目を通してきていたが、その中でもこの本かなり読みやすく、丁寧に書かれていた。 初心者には特にお勧め。 初心者以外の方でも軽く目を通す価値はあると思う。 |
|
Code Reading―オープンソースから学ぶソフトウェア開発技法 ¥ 5,460 / 売り上げランク: 22828 / 523 ページ CodeCompleteとCodeReadingを併せて読むとよいと、 組込み系のSESSAMEプロジェクトのメーリングリストと、 OS系のTOPPERSプロジェクトのメーリングリストで推薦を受けました。 CodeCompleteは読んだことがあったので、CodeReadingを読んでいます。 オープンソースを仕事にしているので、たいへん役立っています。 MISRA-Cは研修で取り上げてきたので、本書も研修の資料としても取り上げるように準備中です。 |



