2009-03-03 7 views
3

Class::ArrayObjects을 사용하는 간단한 프로그램을 작성했지만 예상대로 작동하지 않았습니다. 이 프로그램은 다음과 같습니다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'); 

I을 'name'과 'id'에 대한 내 데이터는 어디에 있습니까?

감사합니다. 민.

답변

9

항상use strict을 사용하십시오. 가능한 한 자주 use warnings을 사용해보십시오. use strict

도 실행되지 않습니다 테스트 스크립트, 펄 대신 다음과 같은 오류 메시지를 발행합니다 :

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과 같은 변수에 접근자를 구현하고 클래스 모듈 외부에서 접근자를 사용하는 것이 좋습니다.

마니의 코멘트에서
0

, 나는 아래로 내 프로그램에서 일부 내용을 변경했습니다 :

TestArrayObject.pm : 나는 일부는 내부 배열 개체에 액세스하기위한/set 메소드를 얻을 추가 ==>

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; 

.

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

메소드 생성기'BEGIN {(qw (name id address))에 대해 {엄격한 'refs가 없습니다.';}를 작성할 때 일부 코드 행과 관리를 저장할 수 있습니다. my $ no = &$_; * {ucfirst()} = sub {my $ self = shift; $ self -> [$ no] = 시프트 @@; return $ self -> [$ no];};}}' –

+0

어쨌든 get/set을 싫어하고 get과 set을 분리하여 사용하는 것이 좋습니다. 'BEGIN {for (qw (name id address)) {엄격한 'refs'없음; 내 $ 아니오 = &$_; 내 $ 이름 = ucfirst; * { "get $ name"} = sub {shift -> [$ no]}; –

+0

예, get/set 사용에 관해서는 동의합니다. * { "set $ name"} = sub {$ _ [0] -> [$ no] = $ _ [1]};}} 그것은 코드를 더 많은 것으로 만든다. –

관련 문제