Perlでサブルーチンプロトタイプ宣言を行う
Params::Validate使えば出来るよ!
プロトタイプ宣言して、型がおかしければ例外発生させてくれます。
test_params_validate.pl
6 package TestClass; 7 8 use Params::Validate qw/:all/; 9 use Data::Dumper; 10 11 sub new { 12 my $self = bless {}, shift; 13 my %args = 14 validate(@_, { name => { type => SCALAR }, 15 skills => { type => ARRAYREF, 16 default => ["Banter"] }, 17 age => { type => SCALAR }, 18 hair => { type => SCALAR, 19 optional => 1 }, 20 }); 21 #if ($!) { 22 # print "error:", $!, $/; 23 #} 24 return $self; 25 } 26 27 1; 28 29 package main; 30 31 use Data::Dumper; 32 33 my $faith = TestClass->new( 34 name => "Faith", 35 age => "17", 36 hair => [1,2,3], 37 ); 38 print Dumper($faith), $/; 39 40 1;
これを、実行すると
[yuki@sorauta web]$ perl docs/test_params_validate.pl
The 'hair' parameter ("ARRAY(0x1a3812a0)") to TestClass::new was an 'arrayref', which is not one of the allowed types: scalar
at /usr/lib/perl5/site_perl/5.8.8/Params/ValidatePP.pm line 630
Params::Validate::__ANON__('The \'hair\' parameter ("ARRAY(0x1a3812a0)") to TestClass::ne...') called at /usr/lib/perl5/site_perl/5.8.8/Params/ValidatePP.pm line 484
Params::Validate::_validate_one_param('ARRAY(0x1a3812a0)', 'HASH(0x1a57aea0)', 'HASH(0x1a568460)', 'The \'hair\' parameter ("ARRAY(0x1a3812a0)")') called at /usr/lib/perl5/site_perl/5.8.8/Params/ValidatePP.pm line 353
Params::Validate::validate('ARRAY(0x1a507910)', 'HASH(0x1a57ae40)') called at docs/test_params_validate.pl line 13
TestClass::new('undef', 'name', 'Faith', 'age', 17, 'hair', 'ARRAY(0x1a3812a0)') called at docs/test_params_validate.pl line 33
こんなふーに怒ってくれます!
やったね!