Struct Embedding in Perl
This Perl code demonstrates a concept similar to struct embedding in Go. Here’s how it works:
We define a
Base
package (similar to a class) with a constructor (new
) and adescribe
method.We then define a
Container
package that inherits fromBase
usinguse parent 'Base'
. This is similar to embedding in Go.In the
main
package, we create aContainer
object and demonstrate that it has access to both its own properties and those inherited fromBase
.We show that methods from
Base
(likedescribe
) are available onContainer
objects.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:
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.