In Perl, objects are implemented through "blessing" references to standard data structures (arrays, hashes, scalars). Historically, OOP in Perl is built on accessing a hash, where keys are attribute names, and values are the data itself. This approach provides flexibility but requires discipline: the language does not implement strict encapsulation and access modifiers — everything is based on conventions.
Problem: Without explicit restrictions, access to attributes is possible from any code; it is easy to break object invariants, confuse namespaces, or make mistakes in inheritance.
Solution — strictly follow the conventions: hide internal data through convention (for example, with underscores), use accessor methods wherever possible, and for complex tasks, apply standard modules like Moose, Moo, Class::Accessor, etc.
Example code:
package Animal; sub new { my $class = shift; my $self = { _name => shift }; bless $self, $class; return $self; } sub get_name { $_[0]->{_name} } package Dog; use parent 'Animal'; sub bark { print "Woof! "; } my $dog = Dog->new("Buddy"); print $dog->get_name; $dog->bark;
Key features:
Can a Perl object be created without using bless?
Answer: No, only bless turns a regular reference into an object understood by the method ->
What is the purpose of base/parent and how do they differ from @ISA?
Answer: @ISA is an array that points to base classes. base/parent automate working with @ISA and make module inheritance safer: they prevent multiple inheritance and provide additional checks.
Will a child class override parent class methods if they are defined with the same name?
Answer: Yes, if a method is defined in the child class with the same name, '->' will choose it first — classical "method overriding" works.
In the Animal module, the data is stored in open attributes, which are accessed directly. Someone unknowingly changes the value of a field from outside — the object becomes inconsistent.
Pros:
Cons:
The module uses accessors, all internal fields start with _, there is a clear specification — data manipulation occurs only through get/set methods with checks introduced in set.
Pros:
Cons: