I wrote a simple program that using Class::ArrayObjects but It did not work as I expected. The program is:
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;
When I run Test.pl, the output data is:
$VAR1 = bless( [
'HN',
'',
''
], 'TestArrayObject' );
I wonder where is my data for 'name' and 'id'?
Thanks, Minh.
Always use use strict. Try to use use warnings as often as possible.
With use strict your test script won't even run, Perl will issue the following error messages instead:
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.
That's because the names for your arrays indices are only visible to your TestArrayObject module, but not to the test script.
To keep your class object-oriented, I suggest you implement accessors for your variables, such as get_name/set_name and use those accessors from outside your class module.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With