Perl6::Export::Attrsを触ってみる
DamianさんオススメのPerl6::Export::Attrs-0.0.3を触ってみた。
ドキュメントほぼそのまんまだけど下記にソースをば。
package Hoge::Module; use strict; use Perl6::Export::Attrs; sub hoge :Export(:DEFAULT) {} sub muge :Export(:DEFAULT :foo :bar) {} sub hage :Export(:bar) {} sub mage :Export(:MANDATORY) {}
「:DEFAULT」と「:MANDATORY」が予約語。で、次が呼び出し側
use Hoge::Module; # 引数省略すると:DEFAULT設定されているものが対象 hoge(); muge(); mage(); # :MANDATORYはどんな呼び出し方をされてもエクスポートされる。 use Hoge::Module qw(:foo); # :fooが対象 muge(); mage(); use Hoge::Module qw(:bar); # :barが対象 muge(); hage(); mage(); use Hoge::Module qw(:ALL); # :ALLは予約語。全てエクスポートされる hoge(); muge(); muge(); mage();
と、こんな感じでエクスポートできる。
また、モジュールを作る時にIMPORTメソッドを定義しておけばuseしたときに呼ばれる。
package Hoge::Module; use strict; use Perl6::Export::Attrs; sub hoge :Export(:DEFAULT) {} sub muge :Export(:DEFAULT :foo :bar) {} sub hage :Export(:bar) {} sub mage :Export(:MANDATORY) {} # ドキュメントには IMPORT {} と書いてあったけど実際は sub IMPORT {} と書かないといけない。 sub IMPORT { print @_; } # useするとIMPORTが呼ばれる。引数にはqw()の値が渡ってくる。 use Hoge::Module qw(:bar);
という感じですね。
Exporter使うよりもこっちの方がかっこいいよね。
というわけで次から使ってみようかな。