今回のテーマ
今回は,
サンプルアプリケーション
本連載では,
svn co -r 455 http:// svn. coderepos. org/ share/ lang/ perl/ Gopper/ trunk Gopper
attributeとは
attributeとは,
たとえばCatalystを利用してControllerを書くときには
sub auto : Private {
my ( $self, $c ) = @_;
...
}
/code>
などと書きますよね。この例ではPrivateの部分がattributeになります。
この説明だけでは,
Perl標準で利用できるattribute
たとえば標準ではlvalueという属性が利用できます。
package Jitensya;
use strict;
use warnings;
sub new { bless { sound => 'リンリン' }, shift }
sub sound : lvalue {
shift->{sound};
}
1;
package main;
use strict;
use warnings;
my $mama = Jitensya->new;
print $mama->sound; # 「リンリン」と出力
$mama->sound = 'チリンチリン';
print $mama->sound; # 「チリンチリン」と出力
と記述でき,
標準で利用できるattributeはlvalueの他に,
ただ,
Package-specific Attribute Handling
自作モジュール中に独自のattributeを実装する事もできます。普通の状態では,
#example.pl
use strict;
use warnings;
sub foo : bar {
}
$ perl ./example.pl
Invalid CODE attribute: bar at ./example.pl line 4
BEGIN failed--compilation aborted at ./example.pl line 5.
ではどうするのかというと,
#example2.pl
use strict;
use warnings;
print "script start\n";
sub MODIFY_CODE_ATTRIBUTES {
my ($pkg, $ref, @attrs) = @_;
print "MODIFY_CODE_ATTRIBUTES: set up\n";
print "MODIFY_CODE_ATTRIBUTES: attrs: $_\n" for @attrs;
return;
}
sub test : catalyst sledge(miyagawa) soozy(yappo) boofy {
print "test: start\n";
}
test;
$ perl ./example2.pl
MODIFY_CODE_ATTRIBUTES: set up
MODIFY_CODE_ATTRIBUTES: attrs: catalyst
MODIFY_CODE_ATTRIBUTES: attrs: sledge(miyagawa)
MODIFY_CODE_ATTRIBUTES: attrs: soozy(yappo)
MODIFY_CODE_ATTRIBUTES: attrs: boofy
script start
test: start
このような形でattributeを活用する事が出来ます。
更に詳細の話は,
余談になりますが,
WARNING: the mechanisms described here are still experimental. Do not rely on the current implementation. 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.
と記載されており,