I wrote some object-oriented Perl and I used the new keyword as the name of my constructor. If I change new to car, it still works.
Is new a predefined keyword required for constructors or can you use your own constructor name?
new is not a keyword, and it has absolutely no meaning to Perl. bless is what constructs objects. If you want a constructor called load, that's no problem. car doesn't seem to be a good choice of name for a constructor. But as you said, it works too.
Quoting the perlootut:
In Perl, there is no special keyword for constructing an object. However, most OO modules on CPAN use a method named "new()" to construct a new object
I suggest you to experiment how it works by running the following perl program:
#!/usr/bin/perl -w
use strict;
use warnings;
use feature qw/say/;
package A;
sub new { say "hello: @_"; bless [] }
package B;
sub new { say "world: @_"; bless [] }
sub old { say "hi: @_" };
package main;
# This prints 'hello: 1 2 3', since it calls directly the sub A::new
A::new(1,2,3);
# Equivalent forms, print 'hello: A 1 2 3'
new A(1,2,3);
A->new(1,2,3);
# Both forms call the A::new sub and pass a string "A" as first argument.
# The bareword B is used this time. Perl knows the B::new function
# must be called. "B" is passed as first parameter.
# This prints 'world B 1 2 3'
my $b = new B(1,2,3);
# Prints something similar to 'hi: B=ARRAY(0x16b7630) 4 5 6'
# A blessed reference always carries around as context information
# about its package.
$b->old(4,5,6);
# Equivalent
B::old($b, 4, 5, 6);
Once you've understood this, you can see how the constructor is simply a function returning a blessed reference. You can call it whatever you want.
It is important to notice the difference between A::new and A->new, since only the second form uses the package name as first parameter. In line of principle, the user of your package might call new in both ways. In the example we are not using the parameters except for printing, but if you are using them, you'd better document how people should call your construtor.
See also this related question: In Perl OOP, is there any official recommendations on initialisation within the constructor?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With