Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

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);
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
}

...

Comment on Create a constructor named the same as your package name!
Download Code
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.

Back to Snippets Section

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://371060]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2014-07-30 22:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (241 votes), past polls