0

我有一个以下模块非常简单的 perl 模块 TEST.pm

package TEST;

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

sub test {
  my ($self, $args) = @_;         
  return "Test";
}

sub test2 {
  my ($self, $args) = @_;
  push @{$self->{CODES}}, 1 ;
  return;  
}


1;

然后我将此模块与 testmoduletest.pl 一起使用

#!/usr/bin/perl -w
  use lib "blablabla";
  use TEST;
  my $test = TEST->new();                  
  print "ref of test = ", ref($test), "\n";
  my $t = $test->test();
  print "t is now $t and ref of test is ",ref($test),"\n";
  $t = $test->test2();
  if ($t) {
    print "t is now $t and ref of test is ",ref($test),"\n";
  } else {
    print "t is uninitialized and ref of test is ",ref($test),"\n";
      print "code = $_\n" for @{$test->{CODES}};
  }

结果如预期:

ref of test = TEST
t is now Test and ref of test is TEST
t is uninitialized and ref of test is TEST
code = 1

但是,如果我通过 SOAP 将此模块与此服务 TESTService.cgi 一起使用

  #!/usr/bin/perl -w

  use SOAP::Transport::HTTP;
  use lib "blablabla";
  use TEST;

  SOAP::Transport::HTTP::CGI   
    -> dispatch_to('TEST')     
    -> handle;

并使用此客户端 testtestclient.pl

#!/usr/bin/perl -w
use SOAP::Lite #+trace => ['all', '-objects'],  
        +autodispatch  =>
      uri => 'http://blablabla.com/TESTService',                                             
      proxy => 'http://blablalba.com/cgi-bin/TESTService.cgi';

  my $test = TEST->new();                  
  print "ref of test = ", ref($test), "\n";
  my $t = $test->test();
  print "t is now $t and ref of test is ",ref($test),"\n";
  $t = $test->test2();
  if ($t) {
    print "t is now $t and ref of test is ",ref($test),"\n";
  } else {
    print "t is uninitialized and ref of test is ",ref($test),"\n";
      print "code = $_\n" for @{$test->{CODES}};
  }

结果是 $test 失去了参考:

ref of test = TEST
t is now Test and ref of test is TEST
t is uninitialized and ref of test is REF
Not a HASH reference at testtestclient.pl line 16.

感谢帮助。

4

1 回答 1

1

为什么你从 中返回一个字符串test,从 没有返回,在这种情况下test2你不想$self从两者中返回吗?

基本上,您从不返回任何内容return value的方法中获取。test2

package TestPackage;

use strict;
use warnings;

sub new {
    my $class = shift;
    my $self = {};

    bless $self, $class;
    return $self;
}

sub a {
    my $self = shift;
    # do stuff  

    return $self;
 }

查看此测试脚本的输出:

use TestPackage;

my $tp = TestPackage->new();

my $rv = $tp->a();
print STDERR "$rv: " . ref($rv) . "\n";
print STDERR "$tp: " . ref($tp) . "\n";

输出:

$ test.pl
TestPackage=HASH(0x1728998): TestPackage
TestPackage=HASH(0x1728998): TestPackage

你也不应该打破封装:

print "code = $_\n" for @{$test->{CODES}};` 

相反,你应该有一些方法get_codes,所以你可以说$test->get_codes();

于 2013-04-10T17:38:22.970 回答