note
$code or die
<p>As you say, programming like this probably causes some maintenance problems. Having said that, you should look at [http://www.perldoc.com/perl5.6.1/lib/UNIVERSAL.html|UNIVERSAL::isa()]</p>
<p>Your test of $invokant also won't work if called by a class inheriting from MyClass:</p>
<code>
package MyClass;
sub new
{
print shift;
}
package MySubClass;
@MySubClass::ISA = qw(MyClass);
package main
my $test = new MySubClass;
__DATA__
prints "MySubClass"
</code>
<p>So having said that, I probably would write the constructor like this:</p>
<code>
sub _new_or_old
{
my $invokant = shift;
defined( $invokant ) or return undef;
if( UNIVERSAL::isa($invokant, 'MyClass' )
{
return $invokant;
} else {
my $self = {};
bless( $self, $invokant );
return $self;
}
}
</code>
___
<a href="mailto:$code_or_die@simonflack.com">Simon Flack</a> (<A HREF="/index.pl?node=%24code%20or%20die&lastnode_id=14444">$code or die</A>)<BR><TT>
$,=reverse'"ro_';s,$,\$,;s,$,lc ref sub{},e;$,<BR>
=~y'_"' ';eval"die";print $_,lc substr$@,0,3;
</TT>
145896
145896