将对象引用存储在哈希键值(不同类)中并调用方法

时间:2018-12-31 02:44:34

标签: perl

filename : Frames.pm

如果是为最终用户托管/提供方法的用户,则为Class。

BEGIN
{
          require Exporter;
          our @ISA = qw(Exporter);
          our @EXPORT_OK =  qw();
          our @EXPORT =  qw(print_me);

 }

 package Frames;

 sub new
 {
     my ($clsname,$self) = @_;
     $self = {};
     bless $self,$clsname;
     return $self;
 }

 sub print_me
 { 
      print "Testing my Frame Object Reference call";
 } 

  1;

 Filename = Testing.pm

该类是一个,在哈希键值对中保存帧Class对象的引用。我试图基于此哈希值调用methof。

 package Test;

 sub new
 {
        my ($clsname,$frame_ref) = @_;
        my $self = { frame => $frame_ref };   
        # here storing frame     reference as value not key
        bless $self,$clsname;
        return $self;
 }

 sub test_call
 {
        my ($self) = shift;
        ## invoking object reference based method

        %{$self->{frame}}->print_me;

        ## Above method call is failing
  }

  Filename Test.pl

  use Frames;

  my $frobj = Frames->new;
  my $testobj = Test->new($frobj); 
  # Frame object passed

  $testobj->test_call;

框架是类,它承载/提供了一些方法 测试是保存框架对象的类 我当时想通过Test类调用框架的对象。

1 个答案:

答案 0 :(得分:2)

您太努力了。 ->的左侧应该是对该对象的引用,并且您已将该引用存储在$self->{frame}中(而不是%{$self->{frame}})。

sub test_call
{
    my ($self) = shift;
    ## invoking object reference based method

    $self->{frame}->print_me;

    ## Above method call will now work.
}