gpt4 book ai didi

perl - 如何使用 Class::ArrayObjects?

转载 作者:行者123 更新时间:2023-12-01 09:11:32 25 4
gpt4 key购买 nike

我编写了一个使用 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' );

我想知道“姓名”和“身份证”的数据在哪里?

谢谢,明。

最佳答案

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

关于perl - 如何使用 Class::ArrayObjects?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/605641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com