本文介绍了我如何在Perl中的不同包中共享全局值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种标准的方法来编写模块来保存全局应用程序参数以包含在其他程序包中?例如:使用配置;



一个简单的包只包含 code>变量? readonly变量怎么样?

解决方案

已经有一个模块。



将三行添加到 MyConfig.pm

  package MyConfig; 

需要出口商;
我们的@ISA = qw /出口商/;
我们的@EXPORT = qw / $ Foo%Baz /;

我们的$ Foo =bar;

我们%Baz =(quux =>potrzebie);

1;

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

 #! / usr / bin / perl 

使用警告;
使用strict;

使用MyConfig;

printFoo = $ Foo\\\
;

print $ Baz {quux},\\\
;

您可以将只读标量添加到 MyConfig.pm with

 我们的$ READONLY; 
* READONLY = \42;

记录在。



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

  $ READONLY = 3; 

在不同的模块中,但您会得到

修改./program line 12中的只读值。

或者,您可以声明 MyConfig.pm 常量使用模块,然后出口这些。


Is there a standard way to code a module to hold global application parameters to be included in every other package? For instance: use Config;?

A simple package that only contains our variables? What about readonly variables?

解决方案

There's already a standard Config module, so choose a different name.

Say you have MyConfig.pm with the following contents:

package MyConfig;

our $Foo = "bar";

our %Baz = (quux => "potrzebie");

1;

Then other modules might use it as in

#! /usr/bin/perl

use warnings;
use strict;

use MyConfig;

print "Foo = $MyConfig::Foo\n";

print $MyConfig::Baz{quux}, "\n";

If you don't want to fully qualify the names, then use the standard Exporter module instead.

Add three lines to MyConfig.pm:

package MyConfig;

require Exporter;
our @ISA = qw/ Exporter /;
our @EXPORT = qw/ $Foo %Baz /;

our $Foo = "bar";

our %Baz = (quux => "potrzebie");

1;

Now the full package name is no longer necessary:

#! /usr/bin/perl

use warnings;
use strict;

use MyConfig;

print "Foo = $Foo\n";

print $Baz{quux}, "\n";

You could add a read-only scalar to MyConfig.pm with

our $READONLY;
*READONLY = \42;

This is documented in perlmod.

After adding it to @MyConfig::EXPORT, you might try

$READONLY = 3;

in a different module, but you'll get

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

As an alternative, you could declare in MyConfig.pm constants using the constant module and then export those.

这篇关于我如何在Perl中的不同包中共享全局值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 03:22