上一个办法(http://blog.csdn.net/zhyuh_perl/archive/2010/03/09/5361055.aspx)达到了perl脚本之间传递参数的目的,但是不符合use strict的风格。
我们用use strict风格重新实现该功能。需要注意:-
1. 被调用的脚本没有程序主体,都是sub子程序。
2. 每个函数显式指明返回值。
3. 调用的脚本除了require语句外,还需显式赋值
==被调用的函数function1.pl==
#!/usr/bin/perl -w
#
# functon1.pl
# To be called by other scripts,
# to get parameters from configuration files
use strict;
sub function1{
my ($line,
@array1,
%hash1);
while (<FILE>){
chomp($_);
$line = $_;
$line =~ s/^/s*|/s*$//g;
@array1=split(/=/,$line);
$array1[0] =~ s/^/s*|/s*$//g;
$array1[1] =~ s/^/s*|/s*$//g;
$hash1{$array1[0]} = $array1[1];
}
%hash1; #要返回的结果
}
1;
==调用function1.pl的脚本call_function1.pl==
#!/usr/bin/perl -w
#
# call_function1.pl
# Try to call another perl script "function1.pl",
# and get the values from "function1.pl"
use strict;
use Data::Dumper;
require "function1.pl"; ==调用function1.pl脚本
my ($arg,
$file_name,
$bin_dir,
%hash1);
$arg = shift(@ARGV);
while ($arg)
{
if ($arg eq "-f" or $arg eq "-F")
{
$file_name = shift(@ARGV);
}
$arg = shift(@ARGV);
}
open FILE,"$file_name" or die "Cannot open $file_name: $!";
%hash1=&function1; ==显式赋值
close(FILE);
$bin_dir=$hash1{'BIN_DIR'};
print Dumper(/%hash1);
print Dumper($bin_dir);
==执行结果==
C:/temp1>perl call_function1.pl -f Env_Var.txt
$VAR1 = {
'DATA_FILE_LOCATION' => 'I://INTEL_DATA',
'AUDIT_ARCHIVE_DIR' => 'H://INTEL_DB_DUMPS//GDCPW1169//AUDIT_ARCHIVE',
'BIN_DIR' => 'G://mssql2005//MSSQL.1//MSSQL//Binn',
'DUMP_DIR' => 'H://INTEL_DB_DUMPS//GDCPW1169',
'TRAN_DIR' => 'H://INTEL_TRAN_DUMPS//GDCPW1169',
'INSTANCE' => 'GDCPW1169',
'LOG_FILE_LOCATION' => 'J://INTEL_LOG',
'SCRIPT_LOG' => 'G://mssql2005//log',
'SERVER' => 'GDCPW1169',
'SQL_VER' => '2005'
};
$VAR1 = 'G://mssql2005//MSSQL.1//MSSQL//Binn';