Perl - Pipe command into another

2019-07-23 05:54发布

Quick question,

Is there a way to pipe a command into another command via perl like you can in the *Nix command line?

For example:
free -m | grep Mem

How would I be able to do the "piping" in Perl?

1条回答
霸刀☆藐视天下
2楼-- · 2019-07-23 07:00

You can invoke the command exactly like that:

system("free -m | grep Mem");

From the documentation:

If there is only one scalar argument, the argument is checked for shell metacharacters, and if there are any, the entire argument is passed to the system's command shell for parsing (this is /bin/sh -c on Unix platforms, but varies on other platforms). If there are no shell metacharacters in the argument, it is split into words and passed directly to execvp , which is more efficient.

You can do the same with other methods for invoking external commands, like open:

open my $fh, "-|", "free -m | grep Mem" or croak "failed to run pipeline";
# and now read from $fh as usual
查看更多
登录 后发表回答