株式会社はてなでは日々、開発者が持ち回りでひとつの技術トピックについて発表を行っており、公開可能なものについては、その内容を音声と動画で公開しています。
11月08日に行われました技術発表会の内容を撮影した動画ファイルを公開いたしました。内容は以下のとおりです。
| テーマ | perlのattributes |
|---|---|
| 発表者 | d:id:jkondo |
| 時間 | 23:17 |
| ファイルサイズ | 135,101,776Bytes |
以下よりダウンロードしてご覧ください。
http://www.hatena.ne.jp/sound/tech/051108hatenatech.wmv
attribute ... 属性、特性
attributes.pm
sub foo : method ;
my ($x,@y,%z) : Bent = 1;
my $s = sub : method { ... };
use attributes (); # optional, to get subroutine declarations
my @attrlist = attributes::get(\&foo);
use attributes 'get'; # import the attributes::get subroutine
my @attrlist = get \&foo;
このように書いてサブルーチンや変数に宣言や定義を書くことができる。
(ただし、変数の宣言は実験段階にあって、将来的に仕様が変更される可能性があるので実験だけに使うべし)
上記の例は、
use attributes __PACKAGE__, \&foo, 'method';
や
use attributes (); my ($x,@y,%z); attributes::->import(__PACKAGE__, \$x, 'Bent'); attributes::->import(__PACKAGE__, \@y, 'Bent'); attributes::->import(__PACKAGE__, \%z, 'Bent'); ($x,@y,%z) = 1;
と等価である。
Perlそのものがハンドルで切るattributesはわずかしかない。
Package-specific attributesは色々拡張可能である。
subroutine attributesはコンパイル時に評価される。
our変数のattributesもコンパイル時に評価される。
my変数は実行時に評価される。
This
means that you have to reach the run-time component of the "my" before
those attributes will get applied. For example:
my $x : Bent = 42 if 0;
will neither assign 42 to $x nor will it apply the "Bent" attribute to
the variable.
run-timeコンポーネントをattributesの前にapplyしないと、上記のように書いても42は代入されないし、Bent属性も有効にならない。
良く分からないattributesがセットされると、fatal errorになる。evalの中でも止まっちゃう。
全部小文字のattributesをセットすると、-w とか use warnings 'reserved' しているときにwarningが出る。
subroutinesに適応できるbuilt-in Attributes は以下の通り
multiple threadsで実行される時だけ有効。
lockedをsubroutineに宣言しておくと、Perlが第1引数を暗黙のうちにlockしておいてくれる。
non-methodなsubroutineに対して宣言すると、subroutineそのものに対してlockされるようになる。
lockのsemanticsはsubroutineに入った後にlock演算子が使われるのと同じ。
subroutineがmethodであることを示す。
lockedと一緒に用いられることで意味がある。
"Ambiguous call resolved as CORE::%s" warningのtriggerにもならないようになる。
subroutineがlvalidであることを示す。
subroutineはperlsubに書いてあるmodifiable valueを返さないといけない。
それから、global変数にはunique attributeが使える。perlfunc our に書いてある。
subroutineか変数のリファレンスを渡すとそのattributesの一覧を返してくれる。
subroutineか変数のリファレンスを渡すと built-in typeを教えてくれる。
まだ実験的な内容なので注意。
In particular, there is no provision for applying package attributes to 'cloned' copies of subroutines used as closures. (See "Making References" in perlref for information on closures.) Package-specific attribute handling may change incompatibly in a future release.
...その他色々
attributesの目的
sub handler : method locked {
my $self = shift;
}
attributes::get(&\handler) eq 'method' ?
$class->foo('var');
$class->foo = 'var';
substr , keys も lvalue
sub foo : lvalue {
}
reftype $class # HASH not "Class"
miyagawaモジュール