将 "ls " 命令捕获到 Perl 中的数组中

Capture "ls " command into an array in Perl

我需要将 ls 命令的输出捕获到数组中。 我试过这样的事情:

use strict;
use warnings;
use diagnostics;

use feature 'say';

use feature "switch";

my $a= system("ls  /media");
my @words = split / /, $a;
my $name = $words[0];
my $name2 = $words[1];
say $name;

但是,它不仅输出与 $a 相同的字符串,而且仅限于 2 个元素。有什么想法吗?

使用readpipe或其shorthand

my @lines = `ls /media`;
chomp @lines;

system returns the exit status, not the output of the command. Use backticks, qx{}, or readpipe 得到输出:

# The following lines are equivalent.
my @lines = `ls`;
my @lines = qx{ ls };
my @lines = readpipe 'ls';

要获取目录的内容,通常更安全(文件名可以包含空格和换行符)和更快(不脱壳)运行

my @files = glob '*';

opendir my $dir, "/path/to/dir" or die $!;
my @files = readdir $dir;

永远不要使用 my $a$asort 中使用的特殊变量,对其进行词汇化可能会阻止 sort 工作。