0

I have a perl script which takes 2 arguments as follows and calls appropriate function depending on the argument. I call this script from bash, but i want to call it from perl, is it possible?

/opt/sbin/script.pl --group="value1" --rule="value2";

Also the script exits with a return value that I would like to read.

5
  • 1
    Why not just call it with require? require "/path/to/your/script.pl"; Commented Sep 13, 2013 at 16:48
  • 1
    @konsolebox, Don't require files without package directive; use do. Commented Sep 13, 2013 at 16:51
  • Scripts can't return value. Do you mean you want the process's exit code, or do you mean you want to capture its output? Commented Sep 13, 2013 at 16:58
  • System worked in my case. I have to do $? >> 8 to get the exit code. Thanks Commented Sep 13, 2013 at 18:02
  • Yes, system probably returns the same as the wait(pid, &status) system call puts into status. Commented Sep 13, 2013 at 18:04

3 Answers 3

5

The Perl equivalent of sh command

/opt/sbin/script.pl --group="value1" --rule="value2"

is

system('/opt/sbin/script.pl', '--group=value1', '--rule=value2');

You could also launch the command in a shell by using the following, though I'd avoid doing so:

system(q{/opt/sbin/script.pl --group="value1" --rule="value2"});

Just like you'd have to do in sh, you'll have to follow up with some error checking (whichever approach you took). You can do so by using use autodie qw( system );. Check the docs for how to do it "manually" if you want more flexibility.

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

Comments

3

If you want to capture the output:

$foo = `/opt/sbin/script.pl --group="value1" --rule="value2"`;

If you want to capture the exit status, but send script.pl's output to stdout:

$status = system "/opt/sbin/script.pl --group=value1 --rule=value2";

If you want to read its output like from a file:

open SCRIPT, "/opt/sbin/script.pl --group=value1 --rule=value2 |" or die $!;
while (<SCRIPT>) ...

1 Comment

System worked in my case. I have to do $? >> 8 to get the exit code. Thanks
1

Yes. You can use system, exec, or <backticks>.

The main difference between system and exec is that exec "executes a command and never returns.

Example of system:

system("perl", "foo.pl", "arg");

Comments

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.