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:
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.
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.