crenz has asked for the wisdom of the Perl Monks concerning the following question:
For years now, I've been using something like this as my default constructor:
sub new { my $class = shift; my %params = @_; my $self = {}; foreach (qw(param1 param2 param3)) { $self->{$_} = $params{$_} } # further initialization. # ... bless $self, $class; }
Now I'm transitioning to using fields, as I quite like the idea and it's been in core since 5.6.1. The documentation for fields suggests something like this:
use fields qw(param1 param2 param3); sub new { my ClassName $self = shift; unless (ref $self) { $self = fields::new($self); } # initialization # ... return $self; }
So, my questions are: Is bless $self, $class being phased out in favour of the my HardCodedClassName $self form? Are there any benefits to this? Will inheritance still work even despite the hard coded class name?
Update: Sorry, I saw that for subclasses, fields still recommends the my $class = shift form. So I don't need to bless $self, class anymore, since fields does that for me, but I don't have to specify the class name in the code.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Writing constructors
by brian_d_foy (Abbot) on Feb 25, 2005 at 12:06 UTC | |
Re: Writing constructors
by Anonymous Monk on Feb 28, 2005 at 11:34 UTC | |
Re: Writing constructors
by perlfan (Vicar) on Feb 25, 2005 at 17:02 UTC |