我如何使用Class :: ArrayObjects?

时间:2009-03-03 09:07:47

标签: perl

我写了一个使用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'的数据在哪里?

谢谢, 胡志明。

2 个答案:

答案 0 :(得分:9)

始终使用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,并使用类模块外部的访问器。

答案 1 :(得分:0)

根据Manni的评论,我在程序中做了一些更改,如下所示:

TestArrayObject.pm:

package TestArrayObject;
use strict;
use Class::ArrayObjects define => {
                                  fields  => [qw(name id address)],
                                };
sub new {
    my ($class) = @_;
    my $self = [];
    bless $self, $class;    
    return $self;
}

sub Name {
    my $self = shift;
    $self->[name] = shift if @_;
    return $self->[name];
}

sub Id {
    my $self = shift;
    $self->[id] = shift if @_;
    return $self->[id];
}

sub Address {
    my $self = shift;
    $self->[address] = shift if @_;
    return $self->[address];
}

1;

==>我添加了一些get / set方法来访问内部数组对象。

Test.pl:

use strict;
use TestArrayObject;
use Data::Dumper;

my $test = new TestArrayObject;
$test->Name('Minh');
$test->Id('123456');
$test->Address('HN');
print Dumper $test;

最终输出是:

$VAR1 = bless( [
             'Minh',
             '123456',
             'HN'
           ], 'TestArrayObject' );

这正是我的预期。

感谢。