Hi,
I have method in a class that I need to make sure is only called on an object instance, and not as a class method.
I will probably do something like this:
# Edit: this is terrible, don't do this, it breaks inheritance.
sub foo
{
my ($self) = @_;
if (ref($self) ne __PACKAGE__) { return; }
...do stuff
}
But I'm thinking it will be more efficient to do this:
sub foo
{
my ($self) = @_;
if (not ref($self)) { return; }
...do stuff
}
Questions:
Is it safe to assume that if ref() returns not undef that it will return the current package?
I would ideally like to go back through and do something like this in all my methods for sanity checking. Is that a bad idea?
Is there a more perlish way to do what I want?
"Use moose" is not an acceptable answer in this case. However if you are compelled to say that, please tell me how moose makes this easy or more efficient. I might want to incorporate it into my own object system.
Thanks!
EDITED to reflect that ref never returns undef, only an empty string.
EDIT 2 Here's a follow up question. Someone below suggested using:
$self->isa(__PACKAGE__)
But won't that always succeed? Unless of course the caller does something really boneheaded like:
MyClass::MyMethod($ref_to_some_other_object)