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

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

Replies are listed 'Best First'.
Re^3: Yet another Can't locate object method question
by nemesdani (Friar) on Mar 17, 2012 at 06:23 UTC
    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.
        Clear now :). Thanks.