Stops fools from doing $obj = Class::new(...) when they should be doing $obj = new Class (...) or $obj = Class->new(...), or even $obj = Class::new(Class, ...).
This works in all but pathological cases such as:
my $foo = Class->new( this => 2, that => 3 ); my $bar = Class::new( $foo => 4, that => 5 );
where the first argument to the constructor (after the class name) is an object which isa-resolves to the package name.
package Class; sub new { unshift @_, __PACKAGE__ unless $_[0]->isa(__PACKAGE__); # rest of code... }

Replies are listed 'Best First'.
(tye)Re: OO Slip-up Preventor
by tye (Sage) on Jan 18, 2001 at 20:05 UTC

    Rather than $_[0]->isa I'd write UNIVERSAL::isa($_[0],__PACKAGE__) because if your first argument is "" or "\t", just to give two examples, then your code dies.

            - tye (but my friends call me "Tye")
      I find that silly. Why does Perl allow "what a croc"->isa('foo'), but doesn't allow " what a croc"->isa('foo')? I find that highly shifty. (Harumph.)

      japhy -- Perl and Regex Hacker
Re: OO Slip-up Preventor
by Anonymous Monk on May 28, 2002 at 23:26 UTC
    Stops fools

    This is nit-picking, but I'd say it does the opposite; it lets fools continue to be fools.

    Also, Class::new([]); makes it break. Another good reason to use UNIVERSAL::isa($_[0], __PACKAGE__).

    Cheers,
    -Anomo