我是 Perl 的新手,目前正在学习 Perl 面向对象,并且偶然发现了编写构造函数。
使用 new
时的样子对于子例程的名称,第一个参数将是包名称。
构造函数必须使用关键字 new
?还是因为当我们调用 new
使用包名的子程序,那么要传入的第一个参数是包名?
packagename->new;
当子例程有其他名称时,第一个参数将是对对象的引用?还是因为当通过对对象的引用调用子例程时,要传入的第一个参数将是对对象的引用?
$objRef->subroutine;
最佳答案
它不是 new
的第一个参数,但间接对象语法,
perl -MO=Deparse -e 'my $o = new X 1, 2'
被解析为
my $o = 'X'->new(1, 2);
来自 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.
话虽如此,
new
不是构造函数调用的某种保留字,而是方法/构造函数本身的名称,在 perl 中不强制执行(即 DBI
具有 connect
构造函数)
关于perl 构造函数关键字 'new',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24106193/