1

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

1
  • 7
    Because, perl evaluates Vehicule->new(2, "bleu") as new Vehicule 2 "bleu" akin to other perl subroutine calls. IOW, new is just a sub. Have a look at perlobj Commented Mar 31, 2013 at 15:05

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.