Perl 如何仅使用另一个文件中的变量名?
我只想使用另一个文件中的变量名 test1.plPerl 如何仅使用另一个文件中的变量名?,perl,Perl,我只想使用另一个文件中的变量名 test1.pl use warnings; use strict; our $name = "hello world"; print "Helllloo\n"; use warnings; use strict; require "test.pl"; our $name; print "$name\n"; use strict; use warnings; use MyConfig 'NAME'; print NAME, "\n"; test2.pl
use warnings;
use strict;
our $name = "hello world";
print "Helllloo\n";
use warnings;
use strict;
require "test.pl";
our $name;
print "$name\n";
use strict;
use warnings;
use MyConfig 'NAME';
print NAME, "\n";
test2.pl
use warnings;
use strict;
our $name = "hello world";
print "Helllloo\n";
use warnings;
use strict;
require "test.pl";
our $name;
print "$name\n";
use strict;
use warnings;
use MyConfig 'NAME';
print NAME, "\n";
test1.pl
包含一些包含许多函数的内容。我使用了test1.pl中的变量$name
。但是在运行test2.pl
时不要运行test1.pl
。例如,当运行test2.pl
时,结果是
Helllloo
hello world
从
test1.pl
打印Helllloo
。如何仅使用另一个文件变量名?如何操作?您应该将test1.pl
和test2.pl
重写为使用MyConfig
,如下所示
test2.pl
use warnings;
use strict;
our $name = "hello world";
print "Helllloo\n";
use warnings;
use strict;
require "test.pl";
our $name;
print "$name\n";
use strict;
use warnings;
use MyConfig 'NAME';
print NAME, "\n";
MyConfig.pm
use strict;
use warnings;
package MyConfig;
use Exporter 'import';
our @EXPORT_OK = qw/ NAME /;
use constant NAME => "hello world";
1;
输出
hello world
用于从模块导出变量:
use strict;
use warnings;
use My::Config '$NAME';
print "$NAME\n";
在My/Config.pm
中:
use strict;
use warnings;
package My::Config;
use Exporter 'import';
our @EXPORT = ();
our @EXPORT_OK = qw{ $NAME };
use Const::Fast;
const our $NAME => "hello world";
__PACKAGE__;
__END__
file1.pl
和file2.pl
在哪里?@serensat抱歉,请查看我的编辑如果您不想运行test1.pl中的代码,请将其移动到子例程。这是一种黑客行为,您不应该这样编码。您应该让两个程序使用一个设置值(最好是常量而不是全局变量)的配置模块,并使用导出器导出它们