0

次のモジュールVERY SIMPLE perl module 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

ただし、このサービス TESTService.cgi で SOAP 経由でこのモジュールを使用する場合

  #!/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

Why are you returning a string from test, nothing from test2, don't you want to return $self from both in this case?

Basically you're getting the return value from the test2 method that returns nothing.

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;
 }

See the output from this test script:

use TestPackage;

my $tp = TestPackage->new();

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

Output:

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

Also you shouldn't be breaking encapsulation:

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

Instead you should have some method get_codes so you can say $test->get_codes();

于 2013-04-10T17:38:22.970 に答える