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 useuse warningsas often as possible.With
use strictyour test script won’t even run, Perl will issue the following error messages instead: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.