>
> What happens when you bless something in a module?
>
In Perl 5 an object is a reference that has been blessed (with a package
name). The namespace of that package is used to find the methods
associated with the object. If no methods can be found, then the @ISA
package variable is checked to see if any other packages should be searched
(this is how inheritance works).
So,
my $ref = { foo => 1 };
my $object = bless $ref, "Some::Class";
Will instantiate an object of class Some::Class. It is convention (but not
required) for a class to contain a method named new that performs the
proper set of steps to create an object:
package Some::Class;
sub new {
my $class = shift;
my %self = @_;
return bless \%self, $class;
}
package main;
my $object = Some::Class->new(foo => 1);
How do I implement interfaces in perl?
>
Interfaces are needed in languages that have strong typing. Perl 5 has
duck typing (if it walks like a duck, quacks like a duck, etc), so if you
want to treat two classes the same way, you can just manually make sure the
both have the same method names.
A better way to deal with this are roles, but that isn't part of the
vanilla language.
> BTW, why are classes based on upside-down inheritance called virtual
> classes? They´re as real as others.
>
To enforce a contract, you can create a virtual class (note, unlike in C++,
Java, etc, there is no real difference between virtual and real classes in
Perl 5) that both inherit from. The class should look something like this:
package Duck::Interface;
sub quack {
my $class = ref $_[0] ? ref $_[0] : %_[0];
die "$class is very naughty and didn't implement quack";
}
In languages with strong typing (like C++, Java, etc), you cannot
instantiate class that have been marked virtual or contain methods that are
marked virtual. Perl 5 does not have this concept, so in truth, there is
no such thing as a virtual class in Perl 5 (we just have things that sort
of look like one as I showed above).