如何在Perl中的不同包之间共享全局值?

前端之家收集整理的这篇文章主要介绍了如何在Perl中的不同包之间共享全局值?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
是否有一种标准方法来编写模块以保存全局应用程序参数以包含在每个其他包中?例如:使用Config;?

一个只包含我们变量的简单包?那些只读变量怎么样?

解决方法

已经有一个 standard Config module,所以选择一个不同的名称.

假设您有MyConfig.pm,其中包含以下内容

  1. package MyConfig;
  2.  
  3. our $Foo = "bar";
  4.  
  5. our %Baz = (quux => "potrzebie");
  6.  
  7. 1;

然后其他模块可能会使用它

  1. #! /usr/bin/perl
  2.  
  3. use warnings;
  4. use strict;
  5.  
  6. use MyConfig;
  7.  
  8. print "Foo = $MyConfig::Foo\n";
  9.  
  10. print $MyConfig::Baz{quux},"\n";

如果您不想完全限定名称,请使用标准Exporter模块.

在MyConfig.pm中添加三行:

  1. package MyConfig;
  2.  
  3. require Exporter;
  4. our @ISA = qw/ Exporter /;
  5. our @EXPORT = qw/ $Foo %Baz /;
  6.  
  7. our $Foo = "bar";
  8.  
  9. our %Baz = (quux => "potrzebie");
  10.  
  11. 1;

现在不再需要完整的包名称

  1. #! /usr/bin/perl
  2.  
  3. use warnings;
  4. use strict;
  5.  
  6. use MyConfig;
  7.  
  8. print "Foo = $Foo\n";
  9.  
  10. print $Baz{quux},"\n";

你可以用MyConfig.pm添加一个只读标量

  1. our $READONLY;
  2. *READONLY = \42;

这在perlmod中记录.

将它添加到@MyConfig :: EXPORT后,您可以尝试

  1. $READONLY = 3;

在一个不同的模块中,但你会得到

  1. Modification of a read-only value attempted at ./program line 12.

作为替代方案,您可以使用constant模块在MyConfig.pm常量中声明,然后导出它们.

猜你在找的Perl相关文章