It is further assumed that @cmd
contains the program and its arguments (if any).
my @cmd = ('foo');
If you want to capture the output, you can use any of the following:
use String::ShellQuote qw( shell_quote ); my $cmd1 = shell_quote('printf', '%s', $_); my $cmd2 = shell_quote(@cmd); my $output = qx{$cmd1 | $cmd2};
use IPC::Run3 qw( run3 ); run3(\@cmd, \$_, \my $output);
use IPC::Run qw( run ); run(\@cmd, \$_, \my $output);
If you do not want to record the output, you can use any of the following:
use String::ShellQuote qw( shell_quote ); my $cmd1 = shell_quote('printf', '%s', $_); my $cmd2 = shell_quote(@cmd); system("$cmd1 | $cmd2");
system('/bin/sh', '-c', 'printf "%s" "$0" | " $@ "', $_, @cmd);
use String::ShellQuote qw( shell_quote ); my $cmd = shell_quote(@cmd); open(my $pipe, '|-', $cmd); print($pipe $_); close($pipe);
open(my $pipe, '|-', '/bin/sh', '-c', '" $@ "', 'dummy', @cmd); print($pipe $_); close($pipe);
use IPC::Run3 qw( run3 ); run3(\@cmd, \$_);
use IPC::Run qw( run ); run(\@cmd, \$_);
If you do not want to record the output, but you also do not want to see it, you can use any of the following actions:
use String::ShellQuote qw( shell_quote ); my $cmd1 = shell_quote('printf', '%s', $_); my $cmd2 = shell_quote(@cmd); system("$cmd1 | $cmd2 >/dev/null");
system('/bin/sh', '-c', 'printf "%s" "$0" | " $@ " >/dev/null', $_, @cmd);
use String::ShellQuote qw( shell_quote ); my $cmd = shell_quote(@cmd); open(my $pipe, '|-', "$cmd >/dev/null"); print($pipe $_); close($pipe);
open(my $pipe, '|-', '/bin/sh', '-c', '" $@ " >/dev/null', 'dummy', @cmd); print($pipe $_); close($pipe);
use IPC::Run3 qw( run3 ); run3(\@cmd, \$_, \undef);
use IPC::Run qw( run ); run(\@cmd, \$_, \undef);
Notes:
Solutions using printf
impose a limit on the size of the data passed to the STDIN program.
Solutions using printf
cannot pass NUL to the STDIN program.
The solutions presented using IPC :: Run3 and IPC :: Run do not include a shell. This avoids problems.
You should probably use system
and capture
from IPC :: System :: Simple instead of the built-in system
and qx
to get a “free” error check.