user2763829 user2763829 - 2 years ago 110
Perl Question

perl constructor keyword 'new'

I am new to Perl and currently learning Perl object oriented and came across writing a constructor.
It looks like when using

new
for the name of the subroutine the first parameter will be the package name.

Must the constructor be using the keyword
new
? Or is it because when we are calling the
new
subroutine using the packagename, then the first parameter to be passed in will be package name?

packagename->new;


and when the subroutine have other name it will be the first parameter will be the reference to an object? Or is it because when the subroutine is call via the reference to the object so that the first parameter to be passed in will be the reference to the object?

$objRef->subroutine;

Answer Source

It is not first parameter to new, but indirect object syntax,

perl -MO=Deparse -e 'my $o = new X 1, 2'

which gets parsed as

my $o = 'X'->new(1, 2);

From perldoc,

Perl suports another method invocation syntax called "indirect object" notation. This syntax is called "indirect" because the method comes before the object it is being invoked on.

That being said, new is not some kind of reserved word for constructor invocation, but name of method/constructor itself, which in perl is not enforced (ie. DBI has connect constructor)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download