Search code examples
perlobjectfile-iomethodsperl-data-structures

How Can I Store a File Handle in a Perl Object and how can I access the result?


I wanted to store a file handle in a Perl Object. Here is how I went about it.

sub openFiles {
     my $self = shift;
     open (my $itemsFile, "<", "items.txt")     or die $!;
     open (my $nameFile,  "<", "FullNames.txt") or die $!;      
     $self->{itemsFile} = $itemsFile;                   
     $self->{nameFile}  = $nameFile;
     return $self;
}

Then I'm looking to access some information from one of these files. Here is how I go about it.

sub getItemDescription {
     my $self = @_;
     chomp(my $record = $self->{itemsFile});
     return $record;
}

I attempt to access it in another procedure as follows:

print "Test 3: $self->getItemDescription()\n";

My questions are as follows:

  1. Is the way I'm saving the file handle in the object correct? If not, how is it wrong?
  2. Is the way I'm reading the lines of the file correct? If not, how can I get it right?
  3. Finally, is the way I'm printing the returned object correct?

This is really important to me. If there is any way that I can improve the structure of my code, i.e. making a global variable for file handling or changing the structure of the object, please let me know.


Solution

  • The openFiles piece is correct.

    The errors occur primarily getItemDescription method.

    First as previously mentioned my $self = @_; should be my ($self) = @_;.

    However, the crux of the question is solved in the following fashion:

    Change chomp(my $record = $self->{itemsFile}); to two lines:

    $file1 = $self->{itemsFile};

    chomp(my $record = $file1);

    To clarify you must (in my experience and I tried all the solutions suggested) use a scalar value.

    Finally, see the last two paragraphs in ikagami's answer.