in reply to oo design q: SUPER::_init

one way to do it is to use named parameters

package Dragon; sub _init { my $self = shift; my %args = @_; foreach my $key qw(NAME AGE COLOR) { $self->{$key} = $args{$key}; } $self->awaken(); } package Trogdor; sub new { my $class = shift; $class->new(@_, NAME => "Trogdor", AGE => "one year old"; COLOR => "green"); }

If the values are overridable, put @_ at the end of the parameter list.

Replies are listed 'Best First'.
Re^2: oo design q: SUPER::_init
by lestrrat (Deacon) on Feb 21, 2006 at 00:14 UTC

    No, you miss my point. If you use named parameters, you can use the code that I posted.

      Shoot. You're right. I misunderstood your example.

      And yours has the advantage of making it harder for the user to screw up the assignment by passing the arguments out of order (that is to say, there is no order if they're passed as named arguments).

      ----------
      Using perl 5.8.1-RC3 unless otherwise noted. Apache/1.3.33 (Darwin) unless otherwise noted. Mac OS X 10.3.9 unless otherwise noted.

        For completeness sake (and because I might want to refer to this in the future), here's my code with named params. Thanks for your help and patience.

        ----------
        Using perl 5.8.1-RC3 unless otherwise noted. Apache/1.3.33 (Darwin) unless otherwise noted. Mac OS X 10.3.9 unless otherwise noted.
Re^2: oo design q: SUPER::_init
by alienhuman (Pilgrim) on Feb 20, 2006 at 23:26 UTC

    Thanks to both of you for your help. Incidentally, lestrrat, there is a minor error in your (elegant) solution: my %args = @_; assigns to the hash keys, so the foreach loop $self->{key} = $args{$key} actually assigns a null value to $self->{key}.

    I mention this just in case someone else grabs this code in the future and spends a few minutes scratching their head, like I did. Luckily, the fix is even simpler:

    package Dragon sub _init { my $self = shift; foreach my $key qw(NAME AGE COLOR) { $self->{$key} = shift; } }

    In the unlikely event that anyone is interested, my complete code follows:

    AH

    ----------
    Using perl 5.8.1-RC3 unless otherwise noted. Apache/1.3.33 (Darwin) unless otherwise noted. Mac OS X 10.3.9 unless otherwise noted.