面向对象的Perl:在同一个类中调用另一个函数

时间:2014-05-04 21:46:31

标签: perl class oop

我有一个处理目录中的一些文件。

所以,我使用的是非OO Perl代码,如下所示(仅在下面打印重要的片段):

#!/usr/bin/perl  
use strict;
use warnings;

my $dnaFilesDirectory = "./projectGeneSequencingPfzr";
my %properties = &returnGeneticSequences($dnaFilesDirectory);  

sub returnGeneticSequences {
  my $dnaDirectory = shift;
  my @dnaFiles = ();
  opendir(DNADIR, $dnaFilesDirectory) or die "Cannot open directory:$!";
  @dnaFiles = readdir(DIR);

  foreach my $file (@dnaFiles) {
    my $dnaFilePath = $dnaFilesDirectory."\/".$file;
    if($file =~ /dna_file.*\.dnaPrj/) {
      my %diseaseStages = &returnDiseasesStages($dnaFilePath);
      ## Do some data analysis on the %diseaseStages Hash;
    }
  }
}

sub returnDiseasesStages {
  my $dnaFile = shift;
  ## Do something with DNA file and build a hash called %diseasesStagesHash;
  return %diseasesStagesHash;
}

上面的代码工作正常。

但我们必须为上述函数创建等效的OO Perl代码。

我正在尝试执行以下操作,但它似乎无法正常工作。显然,我在从returnDiseasesStages调用类方法returnGeneticSequences时做错了。

#!/usr/bin/perl
use strict;
use warnings;

package main;

my $obj = GeneticSequences->new(dnaFilesDir => "./projectGeneSequencingPfzr");
$obj->returnGeneticSequences();

package GeneticSequences;

sub new {
  my $class = shift;
  my $self = {
    dnaFilesDir => "dnaFilesDir",
    @_,
  };
  return (bless($self,$class));
}

sub returnGeneticSequences {
  my $self = shift;
  my $dnaFilesDirectoryGS = $self->{dnaFilesDir};
  my @dnaFiles = ();
  opendir(DNADIR,$dnaFilesDirectoryGS) or die "Cannot open directory:$!";
  @dnaFiles = readdir(DIR);

  foreach my $file (@dnaFiles) {
    my $dnaFilePath = $dnaFilesDirectory."\/".$file;
    if($file =~ /dna_file.*\.dnaPrj/) {
      my $gsObj = GeneticSequences->new();
      my %diseaseStages = $gsObj->returnDiseasesStages($dnaFilePath);
      ## Do some data analysis on the %diseaseStages Hash;
    }
  }
}

sub returnDiseasesStages {
  my $dnaFile = shift;
  ##Do something with DNA file and build a hash called %diseasesStagesHash;
  return %diseasesStagesHash;
}

请帮助我理解我做错了什么。

1 个答案:

答案 0 :(得分:6)

语法

$gsObj->returnDiseasesStages($dnaFilePath)

等同于语法

returnDiseasesStages($gsObj, $dnaFilePath)

(使用Perl检查$gsObj的引用类型,以查看要在其中搜索returnDiseasesStages函数的包。)

所以你的returnDiseasesStages函数应该有两个参数:

sub returnDiseasesStages {
    my ($self, $dnaFile) = @_;
    ...
}