English 中文(简体)
多个次级作物之间的分享变量
原标题:Sharing variables between multiple submodules

我有一个模块 f,它扩大了子气球和香蕉。 我想用巴和巴兹来修改同样的oo。

现在我有这样的东西:

my $foo = new foo;
my $bar = new foo::bar( $foo );
$bar->doStuff();
$bar->printSelf();
my $baz = new foo::bar( $foo );
$baz->doOtherStuff();
$baz->printSelf();

在次模块中,施工者认为:

sub new {
  my $class = shift;
  my $self  = shift;
  --stuff--
  bless $self, $class;
  return $self;
}

请不要太困难。 难道我可以这样做,而不通过 $?

感谢阅读:

最佳回答

我倾向于通过方法分享东西。 这样,没有人必须知道数据结构或变量名称(尽管你确实需要知道方法名称):

 {
 package SomeParent;

 my %hash1 = ();
 my %hash2 = ();

 sub get_hash1 { \%hash1 }
 sub get_hash2 { \%hash2 }

 sub set_hash1_value { ... }
 sub set_hash1_value { ... }
 }

由于<代码>SomeParent 提供接口,以便在私人数据结构查阅,该接口在<代码>中使用。 一些儿童:

 {
 package SomeChild;
 use parent  SomeParent ;

 sub some_method {
      my $self = shift;
      my $hash = $self->get_hash1;
      ...;
      }

 sub some_other_method {
      my $self = shift;
      $self->set_hash2_value(  foo ,  bar  );
      }

 }
问题回答

你的问题并不明确,也不存在任何 has。 但是,如果您需要<>经修改的模块变量,你可以使用完全合格的名称:

package Foo;        # don t use lowercase named, they are reserved for pragmas

our %hash1 = ();
our %hash2 = ();


package Foo::Bar;
use Data::Dump qw(dd);

sub do_stuff {
    $Foo::hash1{new_item} =  thing ;
}

sub do_other_stuff {
    dd \%Foo::hash1;
}


package main;

Foo::Bar->do_stuff();
Foo::Bar->do_other_stuff();

但是,如果你需要修改instance变量,你需要参考这一例子。 我看到一些战略将发挥作用:

  • inherit from Foo, so the hashes will be in instance of Foo::Bar
  • pass reference to Foo in constructor and store it as property in Foo::Bar
  • pass Foo reference as parameter to method

妥善解决取决于你努力做什么,以及你如何使用。





相关问题
Why does my chdir to a filehandle not work in Perl?

When I try a "chdir" with a filehandle as argument, "chdir" returns 0 and a pwd returns still the same directory. Should that be so? I tried this, because in the documentation to chdir I found: "...

How do I use GetOptions to get the default argument?

I ve read the doc for GetOptions but I can t seem to find what I need... (maybe I am blind) What I want to do is to parse command line like this myperlscript.pl -mode [sth] [inputfile] I can use ...

Object-Oriented Perl constructor syntax and named parameters

I m a little confused about what is going on in Perl constructors. I found these two examples perldoc perlbot. package Foo; #In Perl, the constructor is just a subroutine called new. sub new { #I ...

Where can I find object-oriented Perl tutorials? [closed]

A Google search yields a number of results - but which ones are the best? The Perl site appears to contain two - perlboot and perltoot. I m reading these now, but what else is out there? Note: I ve ...

热门标签