简体   繁体   English

如何在perl脚本中使用IPC :: Run模块

[英]How to use IPC::Run module in perl script

I have this Perl script which connects to sqlplus database and run the below command. 我有这个Perl脚本连接到sqlplus数据库并运行以下命令。

my $SQLPLUS='/opt/oracle/product/11g/db_1/bin/sqlplus -S system/coolman7@vsdb';
`$SQLPLUS \@${basePath}/VoucherQuery1.sql $startdate> ${basePath}/QueryResult1.txt`;

Now I am trying to run the second command through IPC::Run. 现在我试图通过IPC :: Run运行第二个命令。 I have tried in many ways without any success. 我在很多方面都尝试过没有任何成功。 like 喜欢

open (WFH1, ">", "${basePath}/QueryResult4.txt");
run('$SQLPLUS \@${basePath}/VoucherQuery4.sql $startdate', '>', \\WFH1);
close(WH1);

but it is not able to connect to sqlplus or write to the output file. 但它无法连接到sqlplus或写入输出文件。 I have searched in google and in other forums but haven't got any solution. 我在谷歌和其他论坛搜索过但没有得到任何解决方案。 Please help. 请帮忙。 :) :)

Using lexical filehandles makes life much easier in general. 使用词法文件句柄可以使生活变得更加容易。 They aren't global, and they will automatically close when they go out of scope. 它们不是全局的,当它们超出范围时它们将自动关闭。

open (my $wfh1, ">", "${basePath}/QueryResult4.txt");

It's possible the whole problem is that open failed, you're not checking if it succeeded. 整个问题可能是open失败,你没有检查它是否成功。 You can do this two ways. 你可以用两种方法做到这一点。 First is to do it by hand... 首先是手工完成......

my $query_result_file = "${basePath}/QueryResult4.txt";
open (my $wfh1, ">", $query_result_file)
    or die "Couldn't open $query_result_file for writing: $!";

Or you can use autodie to do it for you. 或者您可以使用autodie为您完成。

use autodie;
open (my $wfh1, ">", "${basePath}/QueryResult4.txt");

But you don't need to manually open the file at all, IPC::Run will do that for you if you pass it a filename. 但是您根本不需要手动打开文件,如果您传递文件名,IPC :: Run会为您执行此操作。

The next problem is what you're passing to run . 接下来的问题是你传递什么run It's in single quotes, which means none of the variables will be interpolated. 它是单引号,这意味着不会插入任何变量。 You're literally trying to run $SQLPLUS @${basePath}/VoucherQuery4.sql $startdate . 你真的试图运行$SQLPLUS @${basePath}/VoucherQuery4.sql $startdate You need double quotes. 你需要双引号。

But it's better to pass your command and arguments as an array ref, that way IPC::Run will handle the shell quoting for you. 但最好将命令和参数作为数组引用传递,这样IPC :: Run将为您处理shell引用。

Here's a simple example reading a file using cat , adding line numbers, and outputting the result to a file. 这是一个使用cat读取文件,添加行号并将结果输出到文件的简单示例。

use IPC::Run qw(run);
run ["cat", "-n"], "<", "/etc/passwd", ">", "test.out";

Putting it all together... 把它们放在一起......

my $SQLPLUS_EXE = '/opt/oracle/product/11g/db_1/bin/sqlplus';
my $SQLPLUS_DB  = 'system/coolman7@vsdb';
my @SQLPLUS_CMD = ($SQLPLUS_EXE, '-S', $SQLPLUS_DB);

run [@SQLPLUS_CMD, "\@${basePath}/VoucherQuery4.sql", $startdate],
    ">", "${basePath}/QueryResult4.txt";

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

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