简体   繁体   English

在perl中,使用必需的命令将参数传递给脚本

[英]In perl passing a parameter to a script using a required command

I have two file tmp.pl and tmp2.pl. 我有两个文件tmp.pl和tmp2.pl。 I want to call tmp2.pl with a require command but also send a parameter. 我想用require命令调用tmp2.pl,但还要发送一个参数。 Is there a better way of doing this? 有更好的方法吗?

tmp.pl tmp.pl

require "tmp2.pl" "passed parameter";

tmp2.pl tmp2.pl

print @_;

As far as I know, require cannot be used to send a parameter. 据我所知, require不能用于发送参数。 But that's a good thing, I think, because I cannot think of a reason why you should want to. 但这是一件好事,因为我无法想到您为什么要这么做的原因。 Looks to me that your design is wrong. 在我看来,您的设计是错误的。

tmp2.pl should be either: tmp2.pl应该为:

  • a independent perl program, which you should run with system or qx() 一个独立的perl程序,应与systemqx()
  • a module, with optional exported tags etc. 一个模块,带有可选的导出标签等。
  • a package which defines a class 定义类的包

but that's just my idea.... 但这只是我的主意。

There's probably a better way to accomplish whatever it is you're trying to do, but you could achieve your current sub goal with something like 可能有更好的方法来完成您要执行的操作,但是您可以通过以下方法实现当前的子目标

{
    local @_ = ("passed parameter");
    require "tmp2.pl";
}

I might consider this idiom in a place where I wanted to run a perl script from within a perl script. 我可能会在想从perl脚本中运行perl脚本的地方考虑这个习惯用法。 That is, I could say 也就是说,我可以说

{
    local @ARGV = ("foo","bar");
    require "my_script.pl";
}

instead of 代替

system("perl","my_script.pl","foo","bar");

(There are plenty of subtle and not-so-subtle differences between these two calls, so a lot depends on what "features" of these calls you need) (这两个调用之间有很多细微的差别,所以很大程度上取决于您需要这些调用的“功能”)

Yes, I think this should work. 是的,我认为这应该可行。 Use "require" to include the script. 使用“要求”包括脚本。 After that you can pass the parameter by calling the sub function. 之后,您可以通过调用子函数来传递参数。 The modified script can be 修改后的脚本可以是

require "tmp2.pl" ;
subfunc(parameter);
print @_;

Supposing that you want to execute other program and capture its output I'm partial to using the IPC::Run module. 假设您要执行其他程序并捕获其输出,我偏爱使用IPC :: Run模块。

#!/usr/bin/perl

use strict;
use warnings;
use IPC::Run qw( run );

run( [ './tmp2.pl', @ARGV ], \'', \my $out, \my $err );

print "out: $out\n";
print "err: $err\n";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM