in reply to calling a method within a constructor

I'd change the setInformation subroutine to

sub setInformation { my $self = shift; my $device = shift || $self->{device}; $self->{info} = _setInformation($device); } sub _setInformation { my $device = shift; my $model = `hdparm -i $device`; return $model =~ /model=([^,]+)/i; }

And the constructor to

sub new { my $class = shift; my $device = shift; my $self = { 'device' => $device, 'info' => _setInformation($device), }; bless $self, $class; }

This way, you're calling _setInformation as a normal subroutine, without having to use the (as yet uninstantiated) Disk object. By preceding the subroutine name with an underscore you're also indicating that this subroutine is for private use of your module alone and should not be called by outside code (this is a common convention in Perl modules). You might also want to call that subroutine something different to make differentiation with the method easier (e.g. _setInformationInternal or something) but that's purely an aethetic decision. The setInformation method remains for outside code to call after the Disk object has been instantiated with Disk->new() (if you don't think this is necessary you can leave the method out entirely).

One of the beauties of OO programming in Perl is that the language doesn't force you into the OO paradigm the entire time and allows for sensible little shortcuts like the above. If this doesn't appeal to you you could always just call your original setInformation method after blessing $self. There's nothing that forces you to return from the constructor immediately after blessing after all.

I also slightly changed the way you were parsing the hdparm output. Since you need a regex to obtain the model specification anyway I don't see the point of calling grep via the shell. And the regex I use is slightly more clear. IMO. YMMV.


All dogma is stupid.

Replies are listed 'Best First'.
Re^2: calling a method within a constructor
by ocs (Monk) on Apr 11, 2007 at 08:53 UTC
    Thank you for your view and time on that. I live, I learn :)

    tennis players have fuzzy balls.