[英]Perl array attribute inside an object
Tried to write a perl module with OOP, but it can add an object to an array, when I use Dump method, it will output wrong data like this. 试图用OOP编写一个perl模块,但是它可以向数组添加一个对象,当我使用Dump方法时,它将输出这样的错误数据。 Where is my error ? 我的错误在哪里?
Thanks 谢谢
bless( {
'_name' => 'CUSIP',
'_validation_array' => [],
'_seq' => '1'
}, 'Field' );
source code: 源代码:
package Field;
sub new {
my $class = shift;
my $self = {
_name => shift,
_seq => shift,
_validation_array => [ @_ ],
};
bless($self, $class);
return $self;
};
sub pushValidation(){
my $validation = shift;
push(@{$self->{_validation_array}}, $validation);
};
sub dump(){
foreach my $validation (@{$self->{_validation_array} }) {
#print Dumper($validation);#will work,
print $validation->{name}; #error, Use of uninitialized value
}
}
1;
This is the way I call this method : 这就是我调用此方法的方式:
my $validationObj = new Validation($validation->{name}, $validation->{seq});
$field->pushValidation($validationObj);
I see several problems here, but the most serious one is here: 我在这里看到了几个问题,但最严重的是在这里:
sub pushValidation() {
my $validation = shift;
push(@{$self->{_validation_array}}, $validation);
};
This function is expecting a $self
argument, but isn't shifting it from the arguments. 该函数需要一个$self
参数,但不会将其从参数中移出。 You need to add use strict;
您需要添加use strict;
at the top of your Perl file. 在您的Perl文件的顶部。 If it had been enabled, the issue would have been immediately obvious: 如果已启用,则问题将立即显而易见:
Global symbol "$self" requires explicit package name at <filename> line <line>.
Same thing goes for the dump()
function. dump()
函数也是如此。 (By the way, dump
is a bad method name, as there is an (obscure) Perl builtin function with the same name. But that's not a huge issue.) (顺便说一句, dump
是一个不好的方法名称,因为有一个(同名的)Perl内置函数具有相同的名称。但这不是一个大问题。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.