Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

Answer: How do I make deterministic constructors?

by btrott (Parson)
on Jun 21, 2000 at 23:49 UTC ( #19319=categorized answer: print w/replies, xml ) Need Help??

Q&A > object-oriented programming > How do I make deterministic constructors? - Answer contributed by btrott

You mean can you make your constructors prototyped so that the correct constructor gets invoked based on the number of parameters you provide, like you might do in C++?

I don't think you can do this in Perl, because Perl's version of prototypes isn't the same as C++'s. Differently-prototyped subroutines with the same name don't fly in Perl. I don't think.

My question would be: are you sure you need to do this? Perhaps there's a better way of handling this in Perl that doesn't require such a thing.

One way to do it would be to pass in the parameters as a hash, then just dump that hash into the hash-reference object that you create:

package R; sub new { my $this = shift; my $class = ref($this) || $this; my $self = { @_ }; bless $self, $class; }
Now people can create a new R object any way they please:
my $r1 = new R; my $r2 = new R (foo => 'bar'); my $r3 = new R (baz => 'quux', foo => 'bar');
and so on. Would that work for you?

Log In?

What's my password?
Create A New User
[ambrus]: "all the bugs" -- hehe, good luck
[ambrus]: Corion: what I don't understand is, if you make a one-shot AnyEvent timer with short timeout, does this code guarantee that the Prima timer can't queue two timeout events before invoking any of them?
[ambrus]: Because that could break AnyEvent code, which is why I added a guard.
[ambrus]: (It might be easier to use the callback scalar as a guard, as in $c and &$c(); $c = ();)
[Corion]: ambrus: Hurr - yes, that might happen, as Prima will queue lots of stuff (Well, Windows will)
[Corion]: But I'm really amazed that it just took this little code (plus the idle handler I have in mind and something else dk suggested)

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (7)
As of 2016-12-09 09:01 GMT
Find Nodes?
    Voting Booth?
    On a regular basis, I'm most likely to spy upon:

    Results (150 votes). Check out past polls.