nmerriweather has asked for the wisdom of the Perl Monks concerning the following question:

I have a class that subclasses a base class with a custom constructor object.

My problem lay in that I want to share an generic init function (_init) called from new that will process common arguments passed to the constructor. Passing the args in @_ is easy to do - i'm just trying to figure out the best way to do it, and I'm unsure of how perl treats @_.

Should I devise a way to reference/de-reference @_ when it is passed/accessed? Is that completely unnecessary? I doubt I will be tossing large amounts of data around, but in the case that I do, I don't want to be needlessly copying variables all over when a simple reference will do.

Perhaps this will explain things better:
package Framework::myPackage ; sub _init { my $this = shift; # shift off the ref in $_[0] so we can access the pa +rams as @_ my %param = @_; #or my %param = $@_; # do i want something like that (i know thats not + real perl) } package MyApp::myPackage ; sub new { ... $this->_init( @_ ); #or $this->_init( \@_ ); #? }

Replies are listed 'Best First'.
Re: forwarding arguments to a constructor to a new function
by friedo (Prior) on Dec 21, 2005 at 05:28 UTC
    Your first instinct was correct in both cases. To get named arguments out of the argument array, use my %params = @_;. To pass the arguments to another method in your constructor, do

    sub new { my $this = shift; $this->_init( @_ ); }

    It doesn't really matter, but Perl convention is to use $self instead of $this. It's worth using if you ever plan to have other Perl people look at your code.

Re: forwarding arguments to a constructor to a new function
by blazar (Canon) on Dec 21, 2005 at 11:05 UTC
    I see no particular reason to do ref/de-ref madness in this simple case. You would just be doing something only to undo it later: there's nothing in the way perl treats @_ that would justify that.