user3602207
user3602207

Reputation: 75

Object Oriented Perl: Calling another function within the same class

I have a to process some files in a directory.

So, I am using non-OO Perl code as below (just the important snippets are printed below):

#!/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;
}

The above code works fine.

But we have to create the equivalent OO Perl code for the above functions.

I am trying to do the following, but it does not seem to work. Obviously, I am doing something wrong in calling the class method returnDiseasesStages from 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;
}

Please help me understand what I am doing wrong.

Upvotes: 0

Views: 825

Answers (1)

mob
mob

Reputation: 118595

The syntax

$gsObj->returnDiseasesStages($dnaFilePath)

is equivalent to the syntax

returnDiseasesStages($gsObj, $dnaFilePath)

(with Perl checking the reference type of $gsObj to see what package to search for the returnDiseasesStages function in).

So your returnDiseasesStages function should expect two arguments:

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

Upvotes: 6

Related Questions