-1

i was thinking about new() constructor. As we know that we can give any name. Generally we do like this..

package PP;
sub new
{
    my $class = shift;
    my $self = {
        _first => shift,
        _last  => shift,
        _st       => shift,
    };

    print "First Name is $self->{_first}\n";
    print "Last Name is $self->{_last}\n";
    print "ST is $self->{_st}\n";
    bless $self, $class;
    return $self;
}

and at the time of calling we do as below:

$object = new PP( "Mohan", "Sohan", 223345);

So here we are using new because we have constructor name 'new()' but how we will handle that if constructor name is few() (instead of new()). is that like below?

$object = few PP( "Mohan", "Sohan", 223345);
user3518094
  • 79
  • 1
  • 3
  • The easiest way to answer this question is try it out and see if it works – Zaid Apr 21 '14 at 11:06
  • Your question is answered here: http://stackoverflow.com/q/11695110/133939 – Zaid Apr 21 '14 at 11:07
  • i saw that post but no where related to this. – user3518094 Apr 21 '14 at 11:12
  • The question may not be similar, but the accepted answer there is applicable to your query. It explains 'indirect method notation', which is what you are asking about. – Zaid Apr 21 '14 at 11:15
  • [`perlobj #Indirect Object Syntax`](http://perldoc.perl.org/5.12.3/perlobj.html#Indirect-Object-Syntax) – Miller Apr 21 '14 at 11:20

1 Answers1

4

There's nothing special about new. (bless is what really constructs the object.) So

$object = few PP( "Mohan", "Sohan", 223345);

is the equivalent of

$object = new PP( "Mohan", "Sohan", 223345);

Indirect method calls can cause confusing errors, so the following is usually recommended

$object = PP->new( "Mohan", "Sohan", 223345);

$object = PP->few( "Mohan", "Sohan", 223345);
ikegami
  • 367,544
  • 15
  • 269
  • 518