CPANモジュール等を使って、Perlっぽくないことをしてみましょう。
PerlにはJavaのような例外処理機構がありません。やろうとするとevalで囲ってif( $@ ){ 例外処理 }を繰り返すことになり美しくありません。そこでErrorモジュール(日本語訳)を使います。
use Error qw(:try);
try {
do_some_stuff();
}
catch Error with {
my $err = shift;
print "Exception at line ",$err->{-line}," in ",$err->{-file},"\n";
}
finally {
print "Goodbye\n";
};
sub do_some_stuff{
die;
}
Perlにはswitch文がありません。そこでSwitchモジュール(日本語訳)を使います。これはPerl 5.8.0から標準モジュールとなりました。
my $cond = 1;
switch ($cond) {
case 1 { print "this is 1"; }
case 2 { print "this is 2"; }
case 'a' { print "this is a"; }
case /^\d+$/ { print "this is digital"; }
else { print "this is something else"; }
}
(某掲示板でちらっと話題になっていたので追加(2003-11-26))
上のスクリプトが実際にはどういう風にPerlに解釈されるかというと
>perl -MO=Deparse test.pl
use Switch;
my $cond = 1;
S_W_I_T_C_H: while (1) {
local $_S_W_I_T_C_H;
&Switch::switch($cond);
if (&Switch::case(1)) {
while (1) {
print 'this is 1';
last S_W_I_T_C_H;
}
continue {
goto C_A_S_E_1;
}
last S_W_I_T_C_H;
C_A_S_E_1: ;
}
if (&Switch::case(2)) {
while (1) {
print 'this is 2';
last S_W_I_T_C_H;
}
continue {
goto C_A_S_E_2;
}
last S_W_I_T_C_H;
C_A_S_E_2: ;
}
if (&Switch::case('a')) {
while (1) {
print 'this is a';
last S_W_I_T_C_H;
}
continue {
goto C_A_S_E_3;
}
last S_W_I_T_C_H;
C_A_S_E_3: ;
}
if (&Switch::case(qr/^\d+$/)) {
while (1) {
print 'this is digital';
last S_W_I_T_C_H;
}
continue {
goto C_A_S_E_4;
}
last S_W_I_T_C_H;
C_A_S_E_4: ;
}
else {
print 'this is something else';
}
}
continue {
last;
}
てな具合で。こりゃ大変だなぁ。
Perlのコメントは'#'なので一行形式。複数行にまたがるコメントアウトはPOD形式にする、というのが基本。あと、codeをコメントアウトするならif(0){ }で囲むとか。
/* こんな風にできんのか? */ という場合は、Acme::Commentを使ってみます。
use Acme::Comment type=>'C++', own_line => 0, one_line => 1; // print "ok\n"; /* コメント */ /* 複数行にわたる コメントも可能 */
例からもわかるように、様々な言語に対応していますし、自前でコメントアウト文字をセットすることもできます。まあ、PODで十分なはずですが。
ちなみに、先のSwitchとAcme::Commentは場合によっては相性悪いです。