简体   繁体   中英

Perl - Pipe command into another

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM