对象如何访问当前包的符号表?

时间:2009-11-30 20:52:36

标签: perl symbol-table

如何访问实例化对象的当前包的符号表?例如,我有这样的事情:

my $object = MyModule->new;
# this looks in the current package, to see if there's a function named run_me
# I'd like to know how to do this without passing a sub reference
$object->do_your_job;

如果在do_your_job的实施中我使用__PACKAGE__,则会在MyModule包中进行搜索。我怎么能让它看起来正确?

编辑:我会尽量让这个更清楚。假设我有以下代码:

package MyMod;

sub new {
    return bless {},$_[0]
}

sub do_your_job {
    my $self = shift;
    # of course find_package_of is fictional here
    # just for this example's sake, $pkg should be main
    my $pkg = find_package_of($self);
    if(defined &{ $pkg . '::run_me' }) {
        # the function exists, call it.
    }
}

package main;

sub run_me {
   print "x should run me.\n";
}

my $x = MyMod->new;

# this should find the run_me sub in the current package and invoke it.
$x->do_your_job;

现在,$x应该注意到main是当前包,并搜索它的符号表。我尝试使用Scalar::Util的祝福,但它仍然给了我MyModule而不是main。希望现在有点清楚了。

2 个答案:

答案 0 :(得分:6)

您只想要caller

caller告诉你调用它的包。 (这里我添加了一些标准的perl。)

use Symbol qw<qualify_to_ref>;
#...
my $pkg = caller;

my $symb   = qualify_to_ref( 'run_me', $pkg );
my $run_me = *{$symb}{CODE};
$run_me->() if defined $run_me;

要查找它并查看它是否已定义,然后查找它会复制它,因为标准perl不会执行Common Subexpression Elimination,因此您可以1)检索它,以及2)检查定义的插槽,3)如果已定义则运行它。

现在,如果您在一个包中创建一个对象并在另一个包中使用它,那将不会有太多帮助。您可能需要在构造函数中添加其他字段,如'owning_package'

package MyMod;

#...
sub new { 
    #...
    $self->{owning_package} = caller || 'main';
    #...
}

现在$x->{owning_package}将包含'main'

答案 1 :(得分:1)

请参阅perldoc -f caller

#!/usr/bin/perl

package A;
use strict; use warnings;

sub do_your_job {
    my ($self) = @_;
    my ($pkg) = caller;
    if ( my $sub = $pkg->can('run_me') ) {
        $sub->();
    }
}

package B;
use strict; use warnings;

sub test {
    A->do_your_job;
}

sub run_me {
    print "No, you can't!\n";
}

package main;

use strict; use warnings;

B->test;

输出:

C:\Temp> h
No, you can't!