简体   繁体   中英

How can I store Perl's system function output to a variable?

I have a problem with the system function. I want to store the system functions output to a variable.

For example,

system("ls");

Here I want all the file names in the current directory to store in a variable. I know that I can do this by redirecting the output into a file and read from that and store that to a variable. But I want a efficient way than that. Is there any way .

不,您不能存储ls输出的值,因为系统始终将命令作为子进程执行,所以请尝试使用backtick`command`,它在当前进程本身中执行命令!

The easiest way uses backticks or qx() :

my $value = qx(ls);
print $value;

The output is similar to the ls .

My answer does not address your problem. However, if you REALLY want to do directory listing, don't call system ls like that. Use opendir() , readdir() , or a while loop.

For example,

while (<*>){
    print $_ ."\n";
}

In fact, if it's not a third-party proprietary program, always try to user Perl's own functions.

As abubacker stated, you can use backticks to capture the output of a program into a variable for later use. However, if you also need to check for exceptional return values, or bypass invoking the shell, it's time to bring in a CPAN module, IPC::System::Simple :

use IPC::System::Simple qw(capture);

# Capture output into $result and throw exception on failure
my $result = capture("some_command"); 

This module can be called in a variety of ways, and allows you to customize which error return values are "acceptable", whether to bypass the shell or not, and how to handle grouping of arguments. It also provides a drop-in replacement for system() which adds more error-checking.

The official Perl documentation for the built-in system function states:

This is not what you want to use to capture the output from a command, for that you should use merely backticks or qx//, as described in " STRING " in perlop.

There are numerous ways to easily access the docs:

  1. At the command line: perldoc -f system
  2. Online at perldoc.perl.org .
  3. Search the web using google.

If you want each directory listing stored into a separate array element, use:

my @entries = qx(ls);

使用反引号将输出存储在变量中

$output = `ls`;

A quick and simple way to do this is to use qx() specifically for your example:

my $output = qx(ls 2>&1);

The 2>&1 part is to capture both stdout and stderr.

Since it has not been mentioned by other answers yet, you can also use Capture::Tiny to store any arbitrary STDOUT (and/or STDERR) into a variable, including from the system command.

use strict;
use warnings;
use Capture::Tiny 'capture_stdout';
my ($stdout, $return) = capture_stdout { system 'ls' };
# error checking for system return value required here

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