3

I want to invoke a shell command from a Perl script. The arguments to the command are present in a Perl array.

What's the simplest way to do this?

Thanks for replies

0

2 Answers 2

4

You probably need to call system, and it is most efficient to pass the parameters as a list, which avoids using the shell to parse the command line. A call like

my $status = system 'command', @arguments;

should do what you need.

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

1 Comment

See stackoverflow.com/a/3478060 for a better way regarding error handling.
1

There are usually two forms accepted by most functions to launch programs:

  • Accepts a path and a list of arguments
  • Accepts a shell command.

The first is safer, and require fewer resources.

system($prog, @args);             # @args > 0
system({ $prog } $prog, @args);   # @args >= 0

But if you must use the shell or if you must provide a shell command, there are String::ShellQuote (if you're on a unix system) or Win32::ShellQuote (if on a Win32 system) to help you.

use String::ShellQuote qw( shell_quote );
my $shell_cmd = shell_quote($prog, @args);
system($shell_cmd);

2 Comments

Note: You don't actually need to use an array. For both system and shell_quote, any expression that results in a list (including a list literal) is acceptable.
@daxim, oo! Didn't know about Win32::ShellQuote.

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.