Reputation: 121
I read in a tutorial, something like that to call the constructor:
my $v = Vehicule->new( 2, "bleu" );
Then the concerned class is something like that
sub new {
my ($class,$nbRoues,$couleur) = @_;
my $this = {};
bless($this, $class);
$this->{NB_ROUES} = $nbRoues;
$this->{COULEUR} = $couleur;
return $this;
}
The thing I don't understand is how/why @_
first element contains the classname?
my ($class,$nbRoues,$couleur) = @_
when we call it like this Vehicule->new( 2, "bleu" );
Same for method/function of the class with something like that
my ($this) = @_ ;
Actually I don't really understand Class->new
or $var->method
Upvotes: 1
Views: 117
Reputation: 46187
The short, but admittedly unsatisfying, answer to your question is simply "because that's the way it works".
Perl was not an OO language initially, so the OO support was kind of taped to the side of existing things in a way that allows it to make use of as much of what was previously there as possible. Part of that implementation is that when a sub
is called as a method, the class or object that it was called on is added to the beginning of its argument list. MyClass->new(@args)
is roughly equivalent to MyClass::new('MyClass', @args)
and, if $obj
is an instance of MyClass
, $obj->foo(@args)
is roughly equivalent to MyClass::foo($obj, @args)
.
The reason that I say they're "roughly equivalent" rather than "identical" is that the method call version (using ->
) will search @ISA
for inherited implementations if the method isn't implemented by MyClass
, while the sub
call version will not.
Upvotes: 3