Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Create a constructor named the same as your package name!

by merlyn (Sage)
on Jul 01, 2004 at 12:47 UTC ( #371060=snippet: print w/replies, xml ) Need Help??
Description: 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);
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?

    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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://371060]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (4)
As of 2018-06-23 22:21 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (126 votes). Check out past polls.