Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Class::ArrayObjects?

Tags:

perl

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.

like image 550
Minh Le Avatar asked Feb 23 '26 08:02

Minh Le


1 Answers

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.

like image 109
innaM Avatar answered Feb 26 '26 04:02

innaM