【问题标题】:Perl : Get the objects of a particular classPerl:获取特定类的对象
【发布时间】:2014-01-14 00:47:41
【问题描述】:

有没有办法在 perl 中获取特定类的对象?

例子:

use <class1>;
use <class2>

sub Main {

    my $call1 = <class1>->new(<ARGS>)->(<Routine call>);
    my $call2 = <class1>->new(<ARGS>)->(<Routine call>);
    my $call3 = <class1>->new(<ARGS>)->(<Routine call>);

    .
    .
    .
    my $call4 = <class2>->new(<ARGS>)->(<Routine call>);
}

能否获取&lt;class1&gt; 的对象?

$call1
$call2
and
$call3

【问题讨论】:

    标签: perl object


    【解决方案1】:

    这里有几点建议: How can I list all variables that are in a given scope?

    使用此工具:http://search.cpan.org/dist/PadWalker/PadWalker.pm,您可以访问给定范围内的所有包和词法变量。

    或者您也可以直接访问给定范围的符号表:keys %{'main::'}

    您可以使用ref() 获取变量的类型/类。 http://perldoc.perl.org/functions/ref.html

    我认为您的问题没有直接的解决方案。

    也许您可以扩展类并将实例收集到覆盖构造函数中的哈希表中。

    【讨论】:

      【解决方案2】:

      通常的技术是编写Class1,使其构造函数保留对在某个数组或哈希中构造的每个对象的(可能是弱的)引用。如果您使用 Moose,有一个名为 MooseX::InstanceTracking 的扩展程序可以让您轻松完成:

      package Class1 {
          use Moose;
          use MooseX::InstanceTracking;
      
          # ... methods, etc here.
      }
      
      package Class2 {
          use Moose;
          extends 'Class1';
      }
      
      my $foo = Class1->new;
      my $bar = Class1->new;
      my $baz = Class2->new;
      
      my @all = Class1->meta->get_all_instances;
      

      如果您不使用 Moose;那么它仍然很容易:

      package Class1 {
          use Scalar::Util qw( weaken refaddr );
      
          my %all;
          sub new {
              my $class = shift;
      
              my $self  = bless {}, $class;
              # ... initialization stuff here
      
              weaken( $all{refaddr $self} = $self );
              return $self;
          }
      
          sub get_all_instances {
              values %all;
          }
      
          sub DESTROY {
              my $self = shift;
              delete( $all{refaddr $self} );
          }
      
          # ... methods, etc here.
      }
      
      package Class2 {
          our @ISA = 'Class1';
      }
      
      my $foo = Class1->new;
      my $bar = Class1->new;
      my $baz = Class2->new;
      
      my @all = Class1->get_all_instances;
      

      【讨论】:

      • 您还可以从%all 中删除DESTROY 中的实例密钥。
      • 如果在 %all 中有对它们的引用,它们将不会被垃圾收集,所以 DESTROY 不会被调用。 抱歉,我认为你的评论是有意义的,删除DESTROY 中的内容而不是 削弱哈希中的引用。但是,是的,如果你这样做 as well 那么它会为定义的值节省 grepping。我会将其添加到示例中。
      猜你喜欢
      • 2013-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-15
      • 2018-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多