Perl: when called by a method, can ref ($ self) ever return anything other than __PACKAGE__ or undef?

I have a method in a class that needs to make sure that it is called only for an instance of the object, 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 think it will be more efficient:

sub foo
{
  my ($self) = @_;

  if (not ref($self)) { return; }

  ...do stuff
}

Questions:

  • Is it possible to assume that if ref () does not return undef, that it will return the current package?

  • Ideally, I would like to go back and do something similar in all of my health testing methods. It is a bad idea?

  • Is there an easier way to do what I want?

" " . , , , , . .

!

EDITED, , ref undef, .

2 . - :

$self->isa(__PACKAGE__)

? , , - , :

MyClass::MyMethod($ref_to_some_other_object)
+3
3

-, croak , , , , foo .

-, , . , :

#!/usr/bin/perl

package A;
use Carp;

sub new { bless {} => shift }
sub foo {
    croak "I am not in " . __PACKAGE__ unless __PACKAGE__ eq ref(shift)
}

package B;

use base 'A';

package main;

$x = B->new;

$x->foo;
C:\Temp> t
I am not in A at C:\Temp\t.pl line 19

. perldoc -f ref:

, . ref typeof.

:

sub foo {
    croak "Don't call as class method" unless ref shift;
}

, , ref undef.

? , .

, , , , , .

, .

,

sub foo {
    my ($self) = @_;

sub foo {
    my $self = shift;

@_ . :

sub foo {
    my ($self, $bar, $baz) = @_;
+7

, ref() undef, ?

.

my $bar = Bar->new;
Package::Foo::foo($bar);

foo, $bar $self, ref $self Bar.

, , , isa .

+4

isa, , , $self . , isa , can not override isa, , . - , , , UNIVERSAL:: isa.

sub isa {UNIVERSAL::isa @_ > 1 ? shift : $_, @_}

.....

return unless isa $self => __PACKAGE__;

for (@objects) {
    say $_->name if isa 'Package';
}
0

Source: https://habr.com/ru/post/1721485/


All Articles