ЭЛЕКТРОННАЯ БИБЛИОТЕКА КОАПП |
Сборники Художественной, Технической, Справочной, Английской, Нормативной, Исторической, и др. литературы. |
14.2 Using BackquotesAnother way to launch a process is to put a /bin/sh shell command line between backquotes. Like the shell, this fires off a command and waits for its completion, capturing the standard output as it goes along: $now = "the time is now ".`date`; # gets text and date output The value of the time is now Fri Aug 13 23:59:59 PDT 1993 If the backquoted command is used in a list context rather than a scalar context, you get a list of strings, each one being a line (terminated in a newline[2]) from the command's output. For the date example, we'd have just one element because it generated only one line of text. The output of who looks like this: merlyn tty42 Dec 7 19:41 fred tty1A Aug 31 07:02 barney tty1F Sep 1 09:22
Here's how to grab this output in a list context: foreach $_ (`who`) { # once per text line from who ($who,$where,$when) = /(\S+)\s+(\S+)\s+(.*)/; print "$who on $where at $when\n"; } Each pass through the loop works on a separate line of the output of who, because the backquoted command is evaluated within a list context. The standard input and standard error of the command within backquotes are inherited from the Perl process.[3] This means that you normally get just the standard output of the commands within the backquotes as the value of the backquoted-string. One common thing to do is to merge the standard error into the standard output so that the backquoted command picks up both, using the
die "rm spoke!" if `rm fred 2>&1`; Here, the Perl process is terminated if rm says anything, either to standard output or standard error, because the result will no longer be an empty string (an empty string would be false). |