LesleyB has asked for the wisdom of the Perl Monks concerning the following question:

I know I have read, somewhere else, that it is being recommended to use one of these in declaring an object of type class

my $obj = <class>->new(); my $obj = new <class>;

in preference to the other (for some value of 'recommended', 'class' and 'prefence', probably) .

For example

use CGI; my $obj1 = new CGI; my $obj2 = CGI->new();

but I have forgotten both which and why? Can anyone here clarify this please?

I prefer the my $obj2 = CGI->new(); format and I'm hoping that's the 'better' one to use. (For some value of 'better', of course.)

Thank you for your time

Replies are listed 'Best First'.
Re: new <class> or <class>->new()?
by davido (Cardinal) on Nov 20, 2011 at 22:30 UTC

    my $obj = CGI->new(); is preferable.

    The other method is known as "Indirect Object Syntax", and is usually discouraged because the syntax is ambiguous, and in some cases can be interpreted the wrong way. There's an explanation in perlobj under the heading, "Indirect Object Syntax".


    Dave

      CGI->new
      is ambiguous as well. Are you calling CGI::new() here, or CGI()->new()? If you want to be clear, write:
      CGI::->new
      which is not ambiguous.
Re: new <class> or <class>->new()?
by GrandFather (Saint) on Nov 20, 2011 at 22:36 UTC
    my $obj = <class>->new();

    always. There is nothing magical about "new" in Perl, it is just an identifier that happens to be commonly used as the name of a function generally used to construct objects. The down side with the non -> version of the function call is that perl may become confused at times and not recognise it as a function call (although I can't think of an example at present).

    True laziness is hard work
Re: new <class> or <class>->new()?
by ikegami (Patriarch) on Nov 21, 2011 at 01:05 UTC
    method $class_or_object ARGS
    is called an indirect method call. Like omitting parens around function arguments, some people find this visually appealing, but it confuses Perl at times. I play it safe and use direct method calls.
    $class_or_object->method(ARGS)
Re: new <class> or <class>->new()?
by JavaFan (Canon) on Nov 21, 2011 at 11:56 UTC
    The argument is: new CGI; is potentially wrong, because it you have a subroutine new in your namespace, it calls that, and not the one in CGI.

    However, if you write CGI->new, and you have a subroutine CGI, it will call that instead of new in the class CGI. So, if you want to avoid conflict, write

    CGI::->new
    will will call the method new in the class CGI, regardless whether you have subroutines new or CGI in your current class.