Struct Embedding in Perl

package Base;

sub new {
    my ($class, $num) = @_;
    return bless { num => $num }, $class;
}

sub describe {
    my $self = shift;
    return sprintf("base with num=%d", $self->{num});
}

package Container;
use parent 'Base';

sub new {
    my ($class, $num, $str) = @_;
    my $self = $class->SUPER::new($num);
    $self->{str} = $str;
    return bless $self, $class;
}

package main;

use strict;
use warnings;

# Create a new Container object
my $co = Container->new(1, "some name");

# We can access the base's fields directly on $co
printf("co={num: %d, str: %s}\n", $co->{num}, $co->{str});

# Alternatively, we can use the inherited method
print "also num: ", $co->{num}, "\n";

# Since Container inherits from Base, the methods of
# Base also become methods of Container. Here
# we invoke a method that was inherited from Base
# directly on $co.
print "describe: ", $co->describe(), "\n";

# In Perl, we don't need to explicitly define interfaces.
# Any object that implements the 'describe' method
# can be treated as a 'describer'.
my $d = $co;
print "describer: ", $d->describe(), "\n";

This Perl code demonstrates a concept similar to struct embedding in Go. Here’s how it works:

  1. We define a Base package (similar to a class) with a constructor (new) and a describe method.

  2. We then define a Container package that inherits from Base using use parent 'Base'. This is similar to embedding in Go.

  3. In the main package, we create a Container object and demonstrate that it has access to both its own properties and those inherited from Base.

  4. We show that methods from Base (like describe) are available on Container objects.

  5. In Perl, we don’t need to explicitly define interfaces. Any object that implements the required methods can be used polymorphically. This is demonstrated in the last part where we treat $co as a generic “describer”.

To run this program, save it as inheritance.pl and use:

$ perl inheritance.pl
co={num: 1, str: some name}
also num: 1
describe: base with num=1
describer: base with num=1

This example shows how Perl achieves a similar concept to Go’s struct embedding through inheritance. While the syntax and some details differ, the core idea of composition and method inheritance is preserved.