我写了一个使用Class :: ArrayObjects的简单程序,但它没有按照我的预期工作.该计划是:
TestArrayObject.pm:
package TestArrayObject; use Class::ArrayObjects define => { fields => [qw(name id address)], }; sub new { my ($class) = @_; my $self = []; bless $self, $class; $self->[name] = ''; $self->[id] = ''; $self->[address] = ''; return $self; } 1;
Test.pl
use TestArrayObject; use Data::Dumper; my $test = new TestArrayObject; $test->[name] = 'Minh'; $test->[id] = '123456'; $test->[address] = 'HN'; print Dumper $test;
当我运行Test.pl时,输出数据是:
$VAR1 = bless( [ 'HN', '', '' ], 'TestArrayObject' );
我想知道'name'和'id'的数据在哪里?
谢谢,明.
一直用use strict
.尝试尽可能多地使用use warnings
.
由于use strict
您的测试脚本甚至无法运行,Perl将发出以下错误消息:
Bareword "name" not allowed while "strict subs" in use at test.pl line 8. Bareword "id" not allowed while "strict subs" in use at test.pl line 9. Bareword "address" not allowed while "strict subs" in use at test.pl line 10. Execution of test.pl aborted due to compilation errors.
这是因为数组索引的名称仅对TestArrayObject模块可见,但对测试脚本不可见.
为了使您的类面向对象,我建议您为变量实现访问器,例如get_name/set_name,并使用类模块外部的访问器.