What's the differences between system and backticks and pipes in Perl?

大憨熊 提交于 2019-12-28 02:58:26

问题


Perl supports three ways (that I know of) of running external programs:

system:

   system PROGRAM LIST

as in:

system "abc";

backticks as in:

`abc`;

running it through a pipe as in:

open ABC, "abc|";

What are the differences between them? Here's what I know:

  1. You can use backticks and pipes to get the output of the command easily.
  2. that's it (more in future edits?)

回答1:


  • system(): runs command and returns command's exit status
  • backticks: runs command and returns the command's output
  • pipes : runs command and allows you to use them as an handle

Also backticks redirects the executed program's STDOUT to a variable, and system sends it to your main program's STDOUT.




回答2:


The perlipc documentation explains the various ways that you can interact with other processes from Perl, and perlfunc's open documentation explains the piped filehandles.

  • The system sends its output to standard output (and error)
  • The backticks captures the standard output and returns it (but not standard error)
  • The piped open allows you to capture the output and read it from a file handle, or to print to a file handle and use that as the input for the external command.

There are also modules that handle these details with the cross-platform edge cases.




回答3:


system is also returning the exit value of the application (ERRORLEVEL in Windows). Pipes are a bit more complicated to use, as reading from them and closing them adds extra code. Finally, they have different implementation which was meant to do different things. Using pipes you're able to communicate back with the executed applications, while the other commands doesn't allow that (easily).




回答4:


Getting the program's exit status is not limited to system(). When you call close(PIPE), it returns the exit status, and you can get the latest exit status for all 3 methods from $?.

Please also note that

readpipe('...')

is the same as

`...`


来源:https://stackoverflow.com/questions/797127/whats-the-differences-between-system-and-backticks-and-pipes-in-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!