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

does anyone have a reference on a good comparison of the two? i remember reading one a while back, but I can't find it in man perl, this site, or online, so my googling skills are just not working right now.

Replies are listed 'Best First'.
Re: Foo->new() vs. new Foo()
by jeffa (Bishop) on Oct 24, 2005 at 16:58 UTC
Re: Foo->new() vs. new Foo()
by ikegami (Patriarch) on Oct 24, 2005 at 16:57 UTC

    The indirect syntax (new Foo) is problematic. I can't remember any specific examples, but I have seen errors due to ambiguities in the parsing of the indirect syntax. Foo->new is recommended.

      With the indirect object syntax, the classname is a bareword. If Perl doesn't recognize the name of the class when it compiles the statement, there'll be trouble.

Re: Foo->new() vs. new Foo()
by JohnMG (Beadle) on Oct 24, 2005 at 18:07 UTC

    Is there a Foo::new() you can call as well (instead of Foo->new())?

      Calling Foo::new() calls the function new in the package Foo as a direct function call. It doesn't magically put the class name in the first element of @_ in Foo::new(). The call is completely different. This example will show that:
      # this is the file Foo.pm package Foo; use strict; use warnings; sub new { my $class = shift @_; print "class = $class\n"; my $self = {}; return bless $self, $class; } 1; # heres a test program using it, called foo_test.pl # #!/usr/bin/perl use strict; use warnings; use Foo; use Data::Dumper; { print "Arrow test:\n"; my $regular_foo = Foo->new(); print Dumper($regular_foo); print "\n\nColon test:\n"; my $colon_foo = Foo::new(); print Dumper($colon_foo); }
      And heres the output from running foo_test.pl
      Arrow test: class = Foo $VAR1 = bless( {}, 'Foo' ); Colon test: Use of uninitialized value in concatenation (.) or string at Foo.pm li +ne 9. class = Use of uninitialized value in bless at Foo.pm line 13. Explicit blessing to '' (assuming package main) at Foo.pm line 13. $VAR1 = bless( {}, 'main' );
      I use the most powerful debugger available: print!
        To allow the caller to use the Foo::new() syntax, the sub could be coded thus:
        sub new { my $class = shift @_ || __PACKAGE__; ... }
        This gives the same result as calling using the Foo->new syntax.

             "Man cannot live by bread alone...
                 He'd better have some goat cheese and wine to go with it!"