In Perl, when we need to create a process, we generally use a relatively simple and easy-to-use system, exec, or ''(single quotes). These usage are very simple, however, they cannot combine efficient tasks such as pipelines in the operating system.
Therefore, there is another way to create a process in Perl, which is to use the process as a file handle.
Open (whoproc, "Who |"); # Open who for reading
Observe this code. When we do not write |, who is considered as a file name, and then whoproc will eventually be a real file handle.
When | is added, a command is to be started.
Of course, | it can be in front of or behind who. The meanings are different.
When | is later, the result of the preceding command will be output to the previous process handle. When | in front of a command, it indicates that the previous handle is used for input, and the input data will be passed to the subsequent command.
Example:
(1)
- #! /Usr/bin/perl-W
- Open (flist, "dir | ");
- While (<flist> ){
- Print $;
- }
As mentioned above, execute the Dir command first, then the result will be output to flist, and then the subsequent loop will output the result in sequence
(2)
- Open (search, '| find "Learning "');
- Print search "learningperl. pl ";
- Close (Search );
As mentioned above, search will pass data to subsequent commands. If you write data to search in the second sentence, the data will be passed to the find command as a parameter.
Then run.
The following describes a comprehensive example of the two methods to illustrate their benefits.
- #! /Usr/bin/perl-W
- Print "using processes as filehandles/N ";
- Open (FLS, "dir | ");
- Open (search, '| find "Learning "');
- While (<FLS> ){
- Print search $ _;
- }
- Close (FLS );
- Close (Search );
First, the Dir result is output to the FLS handle, and then the search will be passed to the find command. In the while loop, the FLS data is written to the search, this is the output of the find command that uses the data passed by the Search handle as the parameter.
Finally, close the two handles.
It is worth noting that when you do not close the handle, the process you created may not exit at the end of your Perl process, it will not be controlled by your Perl process. When close is used to close the handle, your Perl process will exit until your process exits safely.
Of course, we can run multiple commands at a time,
Such as open (whopr, "ls | tail-r | ");
Through the example above, we can see the convenience of this usage, that is, data can be transmitted through pipelines or results can be obtained, so as to conveniently execute a series of operations, more efficient, more convenient.