我有一个对象具有另一组对象的数组属性。我有一个toString方法,我想打印出对象的全部内容。主要目标是让Job对象调用数组中的所有后期处理作业。我想在对象数组中的对象上调用方法toString。目前,我收到了这个错误:
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)
$ item上的Dumper显示以下内容:
$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;
答案 0 :(得分:2)
问题出在以下几行:
my @postJobs ="";
这将创建数组的第一个成员,但此成员不是作业,而是空字符串。替换为
my @postJobs;
并且错误消失了。