2012-04-18 74 views
3

在Perl中执行命令行函数的最佳/最简单的方法是什么,以便我可以将输出作为字符串获取?在Perl中调用命令行函数并获得输出为字符串

什么实际上,我试图做的是从PostgreSQL中PL/Perl函数中调用Java程序,我想输出字符串,但目前它似乎只是返回0。

下面是一段简单的代码来解释我后面的内容:

CREATE OR REPLACE FUNCTION perl_func() 
    RETURNS character varying AS 
$BODY$  
    return system("java -version"); 
$BODY$ 
    LANGUAGE plperlu VOLATILE 
    COST 100; 
+2

'system'返回执行程序的结果代码。所以它返回0是一件好事。这意味着你必须根据Jack Maney的回答使用反引号。 – Axeman 2012-04-18 14:37:28

回答

3

您可以使用反引号。从perldoc perlop报价:

*qx/STRING/

*`STRING`

A string which is (possibly) interpolated and then executed as a system command with /bin/sh or its equivalent. Shell wildcards, pipes, and redirections will be honored. The collected standard output of the command is returned; standard error is unaffected. In scalar context, it comes back as a single (potentially multi-line) string, or undef if the command failed. In list context, returns a list of lines (however you've defined lines with $/ or $INPUT_RECORD_SEPARATOR), or an empty list if the command failed.

不能使用system对于这一点,因为它只是返回的参数(当作为shell命令运行)的返回值。这应该工作:

CREATE OR REPLACE FUNCTION perl_func() 
    RETURNS character varying AS 
$BODY$ 
    my $output=`java -version`; 
    chomp($output); 
    return $output; 
$BODY$ 
    LANGUAGE plperlu VOLATILE 
    COST 100; 

注意,一个backticked命令的输出通常包括结尾的新行,所以这是可以得到通过chomp摆脱这一点。

+0

实际上,这似乎会返回一个错误:'不能修改chomp中在第1行,在''java -version'附近的引用执行('',qx))''而且在没有chomp的情况下尝试时,它只是返回一个空单元格,任何想法?谢谢! – Larry 2012-04-18 14:33:19

+0

嗯......试试'chomp'分开(就像上面编辑过的代码一样) – 2012-04-18 14:42:23

+1

是的..很好!thanx! – Larry 2012-04-18 14:46:03

相关问题