$self = shift if ref $_[0] eq __PACKAGE__;
Note that this unfortunately breaks for subclasses. Personally I prefer Scalar::Util's blessed and UNIVERSAL's isa.
use warnings;
use strict;
{ package Foo;
use Data::Dump;
use Scalar::Util qw/blessed/;
sub new { return bless {}, shift }
sub foo {
my $self = shift if ref $_[0] eq __PACKAGE__;
dd 'foo', $self, \@_;
}
sub bar {
my $self = shift if defined blessed($_[0])
&& $_[0]->isa(__PACKAGE__);
dd 'bar', $self, \@_;
}
}
{ package Bar;
use parent -norequire, 'Foo';
}
Foo::foo('a'); # ("foo", undef, ["a"])
Foo::bar('b'); # ("bar", undef, ["b"])
my $f = Foo->new();
$f->foo('c'); # ("foo", bless({}, "Foo"), ["c"])
$f->bar('d'); # ("bar", bless({}, "Foo"), ["d"])
my $g = Bar->new();
$g->foo('e'); # ("foo", undef, [bless({}, "Bar"), "e"]) - oops!
$g->bar('f'); # ("bar", bless({}, "Bar"), ["f"])
Update: Added arguments to calls to make @_ more clear. Update 2: I guess in case the package name is "0", one could be doing defined blessed instead of just plain blessed, so I've updated the above, but since that's pretty unlikely, I'd say it's optional. |