How to use Class :: ArrayObjects?

I wrote a simple program that used Class :: ArrayObjects , but it did not work as I expected. Program:

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 is:

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

I wonder where is my data for 'name' and 'id'?

Thanks, Min.

+3
source share
2 answers

Always use use strict. Try to use use warningsas often as possible.

Since use strictyour test script will not even start, Perl will display the following error messages:

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.

This is because the names of your array indices are visible only to your TestArrayObject module, and not to the test script.

-, , get_name/set_name, .

+9

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' );

, .

.

0

Source: https://habr.com/ru/post/1704112/


All Articles