首页 > 解决方案 > 从另一个调用一个 Perl 程序

问题描述

我有两个 Perl 文件,我想用参数从另一个文件调用一个文件

第一个文件a.pl

$OUTFILE  = "C://programs/perls/$ARGV[0]";
# this should be some out file created inside work like C://programs/perls/abc.log

第二个文件abc.pl

require "a.pl" "abc.log";

# $OUTFILE is a variable inside a.pl and want to append current file's name as log.

我希望它创建一个输出文件,其日志名称与当前文件的名称相同。

我还有一个限制是同时$OUTFILE使用a.pland abc.pl

如果有更好的方法请提出建议。

标签: perl

解决方案


require关键字只接受一个参数。那是文件名或包名。你的线

require "a.pl" "abc.log";

是错的。它给出了一个语法错误,类似于 String found where operator expected

您可以要求另一个.pl文件中的一个文件.pl,但这是非常老式的、编写得很糟糕的 Perl 代码。

如果两个文件都没有定义包,则代码将隐式放置在main包中。您可以在外部文件中声明一个包变量,并在需要的文件中使用它。

abc.pl

use strict;
use warnings;

# declare a package variable
our $OUTFILE  = "C://programs/perls/filename";

# load and execute the other program
require 'a.pl';

并在a.pl

use strict;
use warnings;

# do something with $OUTFILE, like use it to open a file handle
print $OUTFILE;

如果你运行它,它将打印

C://programs/perls/filename

推荐阅读