Call command-line function in Perl and get output

2019-07-05 23:45发布

问题:

What is the best/easiest way to execute a command line function in Perl, such that I can get the output as a String?

What I'm actually trying to do is call a Java program from within a PL/Perl function in PostgreSQL, and I want the output String, however at the moment it seems to just be returning 0.

Here is a simple piece of code to explain what I am after:

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

回答1:

You can use backticks. Quoting from 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.

You can't use system for this, since it just returns the return value of the argument (when run as a shell command). This should work:

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;

Note that the output of a backticked command usually includes a trailing newline, so it's often useful to get rid of that via chomp.