【问题标题】:Getting error for reader and writer accessor method of Moose in perl在 perl 中获取 Moose 的读写器访问器方法错误
【发布时间】:2017-11-26 07:55:45
【问题描述】:

我正在尝试使用 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

如果我在1.pl 中注释$emp->set_salary(100000); 行,那么我会得到正确的输出(显然没有salary 属性的更新值)。

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

employee.pm 中,我已授予salary 属性的读写权限。谁能建议我哪里出错了?提前致谢。

【问题讨论】:

标签: perl moose


【解决方案1】:

你拼错了set_salary

writer => 'set_slalary'

应该是

writer => 'set_salary'

注意

is => 'rw'

只是另一种写作方式

accessor => 'salary'

通常。当readerwriter 和/或accessor 也为同一属性提供时,is 不可靠。例如,当readerwriter 和/或accessor 也为同一属性提供时,is 有时会被忽略。 (下面的演示。)您的程序就是这种情况。

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


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

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.

【讨论】:

    猜你喜欢
    • 2013-10-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    • 1970-01-01
    • 1970-01-01
    • 2011-09-07
    • 1970-01-01
    • 2012-09-04
    相关资源
    最近更新 更多