@techno_neko
組み込み系
Hokkaido.pm
良くあるPerlスクリプト
再利用する準備
packageブロックが使える
カレントパッケージを出力する
use strict;
sub hello {
print 'Hello! from ' . __PACKAGE__ . "\n";
}
hello(); # Hello! from main
RGB値が分かるようにダンプする関数
use strict;
sub to_rgb {
return
'R: ' . (($_[0] >> 16) & 0xFF) . ', '
. 'G: ' . (($_[0] >> 8) & 0xFF) . ', '
. 'B: ' . (($_[0] >> 0) & 0xFF);
}
print to_rgb( 0xFF0000 ); # R: 255, G: 0, B: 0
こんな風に書ける
use strict;
package ColorDumper;
sub to_rgb {
return
'R: ' . (($_[0] >> 16) & 0xFF) . ', '
. 'G: ' . (($_[0] >> 8) & 0xFF) . ', '
. 'B: ' . (($_[0] >> 0) & 0xFF);
}
package main;
print ColorDumper::to_rgb( 0xFF0000 ); # R: 255, G: 0, B: 0
こんな風に書ける
use strict;
package ColorDumper;
sub to_rgb {
return
'R: ' . (($_[0] >> 16) & 0xFF) . ', '
. 'G: ' . (($_[0] >> 8) & 0xFF) . ', '
. 'B: ' . (($_[0] >> 0) & 0xFF);
}
package main;
my $func = \&ColorDumper::to_rgb;
print $func->( 0xFF0000 ); # R: 255, G: 0, B: 0
何事もやり方は一つじゃない
use strict;
sub ColorDumper::to_rgb {
return
'R: ' . (($_[0] >> 16) & 0xFF) . ', '
. 'G: ' . (($_[0] >> 8) & 0xFF) . ', '
. 'B: ' . (($_[0] >> 0) & 0xFF);
}
my $func = \&ColorDumper::to_rgb;
print $func->( 0xFF0000 ); # R: 255, G: 0, B: 0
5.16で追加された書き方
use strict;
package ColorDumper {
sub to_rgb {
return
'R: ' . (($_[0] >> 16) & 0xFF) . ', '
. 'G: ' . (($_[0] >> 8) & 0xFF) . ', '
. 'B: ' . (($_[0] >> 0) & 0xFF);
}
}
my $func = \&ColorDumper::to_rgb;
print $func->( 0xFF0000 ); # R: 255, G: 0, B: 0
最後の行の"1;"をお忘れなく
package ColorDumper;
use strict;
sub to_rgb {
return
'R: ' . (($_[0] >> 16) & 0xFF) . ', '
. 'G: ' . (($_[0] >> 8) & 0xFF) . ', '
. 'B: ' . (($_[0] >> 0) & 0xFF);
}
1;
モジュール完成!
use strict;
use ColorDumper;
my $func = \&ColorDumper::to_rgb;
print $func->( 0xFF0000 ); # R: 255, G: 0, B: 0
このスライドのネタ元はこの本
どなたかお願いします
8/24発売予定!(北海道は入荷が少し遅れるよ!!)
/
#