Perl Inheritance - Who Calls the Parent Class

I have a situation where I need to find the calling package, and my code looks something like this:

Inherited.pm:

package Inherited;
our @ISA = qw(BaseClass);
sub new {
   SUPER::new();
}

Baseclass.pm

package BaseClass;
sub new {
  $a = caller(0);
  print $a
}

Now I have another class (MyClass.pm) that does:
MyClass.pm:

$obj = Inherited->new();  

Imprint of Inherited. But I need MyClass to print.

Can someone please help me decide how to solve this?

+5
source share
2 answers

When you give caller an argument, you tell it how many levels need to be returned. You gave him an argument 0, which is the current level. If you want one level up, add 1:

use v5.12;

package Inherited {
    our @ISA = qw(BaseClass);
    sub new {
       $_[0]->SUPER::new();
    }
}

package BaseClass {
    sub new {
      say "0: ", scalar caller(0);
      say "1: ", scalar caller(1);
    }
}

package MyClass {
    my $obj = Inherited->new;
    }

Now the result:

0: Inherited
1: MyClass

. Perl, , , caller.

+5

, , .

package BaseClass;
sub new {
    my $a = caller(0);
    for (my $n=0; my @c=caller($n); $n++) {
        last if $c[4] !~ /::new$/;
        $a = $c[0];
    }
    print $a;
}

package BaseClass;
sub new {
    my @a;
    unshift @a, [ caller(@a) ] while caller(@a);
    my ($a) = grep { $_->[4] =~ /::new$/ } @a;
    print $a // caller(0);
}

, , , ,

 GrandChild::new
 GrandChild::init
 Inherited::new
 BaseClass::new

Inherited::new ( GrandChild, GrandChild::new.

+1

All Articles