http://www.perlmonks.org?node_id=371060

Why type ->new? Have your package create a function so that the package name itself is the constructor! For example, you can have:
my $e = Example::Module->new(@list);
or
my $e = Example::Module(@list);
Both are supported by the snippet code! Even works if ->new is inherited, and doesn't disturb any other class methods.
package Example::Module; ... sub Example::Module { return "Example::Module" unless @_; Example::Module::->new(@_); # extra colons are necessary } ...

Replies are listed 'Best First'.
Re: Create a constructor named the same as your package name!
by DrHyde (Prior) on Jul 01, 2004 at 13:03 UTC
    So you've created a subroutine in some other namespace. That's not something I'd want to encourage.
Re: Create a constructor named the same as your package name!
by Solo (Deacon) on Jul 01, 2004 at 13:41 UTC
    Neat idea, but what if a constructor needs no arguments?

    --Solo
    --
    You said you wanted to be around when I made a mistake; well, this could be it, sweetheart.

      I'm confused, what's wrong with this?

      my $e = Example::Module();
        my $e = Example::Module();
        That would be the same as:
        my $e = "Example::Module";
        So no, it doesn't work. I thought about it for a while... and I can't figure out a way around that corner case that doesn't break other class methods. Oh well... gotta say "new" sometime, I guess.

        -- Randal L. Schwartz, Perl hacker
        Be sure to read my standard disclaimer if this is a reply.