in reply to Two argument bless syntax

It makes your constructor slightly more flexible. It means that as well as calling it as a class method:

my $foo = SomeClass->new;

You can also call it as an object method:

my $bar = $foo->new;

In general, I'd say that this isn't a good idea. If I want a constructor that can be called as an object method then I'll create a different constructor method with a different (and more meaningful) name - perhaps something like 'clone'.

--
<http://dave.org.uk>

"The first rule of Perl club is you do not talk about Perl club."
-- Chip Salzenberg

Replies are listed 'Best First'.
Re^2: Syntactic Question
by themage (Friar) on Nov 22, 2006 at 16:27 UTC
    Hi davorg,

    I would agree with you that should be used a new object called clone if the object was copied to the new object, which do not happen in the specified case.

    I don't like that much allowing new called on a ref/obj, but it is safer to do it that way, that just bless the object with $_[0].

    On the other hand, I think that croak or die with new called on a ref would be a better solution. The usual solution of just bless on $_[0] also die with "Attempt to bless into a reference", so I don't think it matters much.

Re^2: Syntactic Question
by doom (Deacon) on Nov 24, 2006 at 00:44 UTC
    Damien Conway weighs in against this in his "Perl Best Practices" book. In the section titled "Cloning", p. 334 he argues that blending object creation and cloning makes it harder to tell what the code is doing, e.g.
    my $obj = $name->new( @args );
    Might be doing creation or cloning depending on whether $name is a string or a reference. Also he makes the point that it complicates the constructor code for no good reason.

    So yeah, this is a slick trick that people used to like, but it's gone out of favor.

    (You can blame Conway for helping to promulgate this idiom: he uses it in places in his earlier work "Object Oriented Perl".)