in reply to Yet another Can't locate object method question

I had some fun with this:
package MyFilehandler; my $fh; sub openForRead { my $class = shift(); my $filename = shift(); bless \$filename, $class; open FH, '<', $filename or die "could not open file: $!"; $fh = \*FH; sub writeOut { my (@lines) = <$fh>; print @lines; }; } close $fh; writeOut( my $testfh = MyFilehandler->openForRead('somefile') );

Replies are listed 'Best First'.
Re^2: Yet another Can't locate object method question
by GrandFather (Saint) on Mar 16, 2012 at 08:47 UTC

    You may have had fun, but maintenance programmers or those seeking inspiration or enlightenment would not. Your code contains the same errors that choroba describes, it adds a needlessly nested named sub, a bogus close statement and a nonsensical call to writeOut. The following more conventional code would have served as a simpler and better example:

    #!/usr/bin/perl use strict; use warnings; package MyFilehandler; sub openForRead { my ($class, $file) = @_; my $self = bless {file => $file}, $class; open $self->{fh}, '<', $file or die "could not open '$self->{file} +': $!"; return $self; } sub DESTROY { my ($self) = @_; close $self->{fh}; } sub writeOut { my ($self) = @_; my $fh = $self->{fh}; print <$fh>; } package main; my $testfh = MyFilehandler->openForRead('somefile'); $testfh->writeOut();
    True laziness is hard work
      Thank you for your answer and solution. It works of course, but one thing is not clear to me: $self->{fh} seems to pop out of nowhere. Is it a filehandle which is immediately bound to $self?
        From where do you think OUT pops out in
        open OUT, '<', $file;
        $self is a hash ref, $self->{fh} does not exist, so it is created by Perl when calling open, and the filehandle is assigned to it.