This question concerns Perl’s class
syntax (new as of Perl 5.38.0). I have two classes, Rectangle
and Square
, with Square
inheriting from Rectangle
. They have different constructor arguments; Rectangle
expects length
& height
while Square
expects just side
. My hope was that Square
would be able to inject the length
and height
arguments into the constructor for Square
‘s parent Rectangle
object, based on side
‘s value. Something akin to this, though the BUILD
syntax from Object::Pad
doesn’t work:
class Rectangle
{
field $length :param;
field $height :param;
method get_area { return $length * $height; }
}
class Square :isa(Rectangle)
{
field $side :param;
BUILD {
my(%args) = @_;
my($side) = $args{'side'};
push(@_, length => $side, height => $side);
}
}
Here’s my test script:
my($rect) = Rectangle->new(length => 5, height => 6);
say $rect->get_area();
my($sq) = Square->new(side => 5);
say $sq->get_area();
My expected output would be:
30
25
Is there a way to do this in 5.38.x? I’m thinking that the class
implementation is simply not evolved enough yet to do this.