2013-02-03 70 views
0

我有一個對象具有另一組對象的數組的屬性。我有一個toString方法,我想打印出對象的全部內容。主要目標是讓Job對象調用數組中的所有後處理作業。我想調用對象數組中對象的方法toString。目前,我得到這個錯誤:使用moose從perl中的對象數組中調用對象方法

Can't call method "toString" without a package or object reference at JobClass.pm line 52, <JOBFILE> line 5. (which is $item->toString(); in the foreach loop)

自卸車在$項目顯示以下內容:

$VAR1 = bless({ 
      'ImportID' => '22', 
      'ImportTableID' => '1234', 
      'ImportTable' => 'testImport' 
      }, 'PostJob'); 

的什麼,我想了解的主要目標是我怎麼能叫的方法在從成員數組返回的對象上。

類實例化這種方式:

 

    my $postJob = PostJob->new(ImportTable => "testImport",ImportTableID => "1234", ImportID => "22"); 
    my @postJobs =""; 
    push (@postJobs,$postJob); 
    $postJob->toString(); #this works fine 
    my $job = Job->new(DirectoryName => "testDir",StagingTableName => "stageTable", QBStagingTableID => "5678",postProcessJobs => \@postJobs); 
    $job->toString(); #Breaks with error above 

代碼如下:

 

    package PostJob; 
    use Moose; 
    use strict; 
    use Data::Dumper; 

    has 'ImportTable' => (isa => 'Str', is => 'rw', required => 1); 
    has 'ImportTableID' => (isa => 'Str', is => 'rw', required => 1); 
    has 'ImportID' => (isa => 'Str', is => 'rw', required => 1); 

    sub toString { 
    # Print all the values 
    my $self = shift;; 
    print "Table Name for Post Job is ".$self->ImportTable."\n"; 
    print "Table ID for Post Job is ".$self->ImportTableID."\n"; 
    print "Import ID for Post Job is ".$self->ImportID."\n"; 
    } 

    package Job; 

    use strict; 
    use Data::Dumper; 
    use Moose; 

    has 'DirectoryName' => (isa => 'Str', is => 'rw', required => 1); 
    has 'StagingTableName' => (isa => 'Str', is => 'rw', required => 1); 
    has 'StagingTableID' => (isa => 'Str', is => 'rw', required => 1); 
    has 'postProcessJobs'=> (isa => 'ArrayRef', is => 'rw', required => 0); 


    sub addPostJob { 
    my ($self,$postJob) = @_; 
    push(@{$self->postProcessJobs()},$postJob); 

    } 

    sub toString 
    { 
    # Print all the values. 
    my $self = shift; 
    print "DUMPING JOB OBJECT CONTENTS*****************************\n"; 
    print "Directory is ".$self->DirectoryName."\n"; 
    print "Staging Table is ".$self->StagingTableName."\n"; 
    print "Staging Table ID is ".$self->StagingTableID."\n"; 

     print "DUMPING POST JOB CONTENTS*****************************\n"; 
     foreach my $item (@{$self->postProcessJobs()}) 
      { 

       $item->toString(); 
       print Dumper($item); 
      } 
     print "END DUMPING JOBS*****************************\n";  
    } 


    1; 

回答

2

的問題是上下面的行:

my @postJobs =""; 

這產生了陣列的第一構件,但這個成員不是一份工作,它是一個空字符串。將其替換爲

my @postJobs; 

錯誤消失。

+0

太棒了!謝謝!那麼確定一個數組是否爲空並且在perl中沒有元素的正確方法是什麼? – glacierDiscomfort

+0

@glacier不舒服:如果你正在聲明它,'my'本身會將數組創建爲空。如果要清除數組,請使用'undef @ array'或'@array =()'(分配內存)。 – choroba

+0

非常感謝你! – glacierDiscomfort