4

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
  • 2
    system returns the result code of executing the program. So it's a good thing that it returns 0. That just means you'll have to use backticks per Jack Maney's answer. Commented Apr 18, 2012 at 14:37

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Actually, this seems to return an error: Can't modify quoted execution (``, qx) in chomp at line 1, near "java -version)” And when trying it without the chomp, it just returns an empty cell. Any ideas? Thanks!
Hmmm...try the chomp separately (as done in the edited code above).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.