-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);
5
  • The easiest way to answer this question is try it out and see if it works Commented Apr 21, 2014 at 11:06
  • Your question is answered here: stackoverflow.com/q/11695110/133939 Commented Apr 21, 2014 at 11:07
  • i saw that post but no where related to this. Commented Apr 21, 2014 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. Commented Apr 21, 2014 at 11:15
  • perlobj #Indirect Object Syntax Commented Apr 21, 2014 at 11:20

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

@user3518094 You can mark this answer as Accepted by clicking on the tick-mark on the left side.

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.