perl:如何在各种perl文件中共享变量和子例程



我正在尝试这样的东西:

main.pl

use YAML::XS
our $yaml_input = YAML::XS::LoadFile("$input_file");
parse_yaml($yaml_input); 
#this variable has to be passed to the function parse_yaml which is in other file.

parser.pl

sub parse_yaml($yaml_input)
{
#some processing
}

我读过一些关于使用包的答案,但在这种情况下我们如何使用它。

基本上,您需要parse_yaml子例程导入到当前程序中,而不是尝试导出参数的值,但我不确定为什么YAML::XS::LoadFile已经为您编写了自己的parse_yaml实用程序

Exporter模块的文档中对此进行了非常清楚的描述

以下是的一个简单示例

main.pl

use strict;
use warnings 'all';
use YAML::XS 'LoadFile';
use MyUtils 'parse_yaml';
my $input_file = 'data.yaml';
my $yaml_input = LoadFile($input_file);
parse_yaml($input_file);
# this variable has to be passed to the function parse_yaml which is in other file.

MyUtils.pm

package MyUtils;
use strict;
use warnings;
use Exporter 'import';
our @EXPORT_OK = 'parse_yaml';
sub parse_yaml {
    my ($yaml_file) = @_;
    # some processing
}
1;

最新更新