在perl中获取Moose的读写器访问器方法的错误

时间:2017-11-26 07:55:45

标签: perl moose

我尝试使用Moose readerwriter来设置和获取值。

以下是employee.pm

package employee;
use Moose;

has 'firstName' => (is => 'ro' , isa => 'Str' , required => 1);

has 'salary' => (is => 'rw',
         isa => 'Str',
         writer => 'set_slalary',
         reader => 'get_salary',
         );

has 'department' => (is => 'rw' , default => 'support' );
has 'age' => (is => 'ro' , isa=> 'Str');

no Moose;
__PACKAGE__->meta->make_immutable;
1;

以下是我的脚本1.pl(使用上述模块):

use employee;
use strict;
use warnings;

my $emp = employee->new(firstName => 'Tom' , salary => 50000 , department => 'R&D' , age => '27');

$emp->set_salary(100000);

print $emp->firstName, " works in ", $emp->department, " and his salary is ",  $emp->get_salary() , " and age is ", $emp->age ,"\n" ;

在脚本中,我尝试将salary属性更新为100000。 我收到以下错误:

Can't locate object method "set_salary" via package "employee" at 1.pl line 7

如果我对$emp->set_salary(100000);中的行1.pl发表评论,那么我会获得正确的输出(显然没有salary属性的更新值。

Tom works in R&D and his salary is 50000 and age is 27

employee.pm中,我已授予salary属性的读写权限。任何人都可以建议我哪里出错了?提前谢谢。

1 个答案:

答案 0 :(得分:0)

你拼错了set_salary

writer => 'set_slalary'

应该是

writer => 'set_salary'

请注意

is => 'rw'

只是另一种写作方式

accessor => 'salary'

一般。如果同一属性也提供isreader和/或writer,则accessor不可靠。例如,如果同一属性也提供isreader和/或writer,则有时会忽略accessor。 (以下演示。)这是您的计划的情况。

因此,将isreader / writer / accessor混合起来是个不错的主意。对于任何给定的属性,请使用一种或另一种,但不能同时使用两种。在你的情况下,你应该摆脱无用的is => 'rw'

is=>'rw' + reader + writer错误的演示:

Class.pm

package Class;

use Moose;

has attr1 => (
   is => 'rw',
   default => 'val1',
);

has attr2 => (
   is => 'rw',
   reader => 'get_attr2',
   writer => 'set_attr2',
   default => 'val2',
);

1;

a.pl

use feature qw( say );

use FindBin qw( $RealBin );
use lib $RealBin;

use Class;

my $o = Class->new();
say $o->attr1();
say $o->attr2();

输出:

val1
Can't locate object method "attr2" via package "Class" at a.pl line 10.