我想把命令的输出放到一个数组中——像这样:
my @output = `$cmd`;
但似乎命令的输出没有进入@output
数组。
知道它会去哪里吗?
这个简单的脚本对我有用:
#!/usr/bin/env perl
use strict;
use warnings;
my $cmd = "ls";
my @output = `$cmd`;
chomp @output;
foreach my $line (@output)
{
print "<<$line>>\n";
}
它产生了输出(三个点除外):
$ perl xx.pl
<<args>>
<<args.c>>
<<args.dSYM>>
<<atob.c>>
<<bp.pl>>
...
<<schwartz.pl>>
<<timer.c>>
<<timer.h>>
<<utf8reader.c>>
<<xx.pl>>
$
命令的输出在行边界上拆分(默认情况下,在列表上下文中)。删除数组元素中的chomp
换行符。
(标准)输出确实转到该数组:
david@cyberman:listing # cat > demo.pl
#!/usr/bin/perl
use strict;
use warnings;
use v5.14;
use Data::Dump qw/ddx/;
my @output = `ls -lh`;
ddx \@output;
david@cyberman:listing # touch a b c d
david@cyberman:listing # perl demo.pl
# demo.pl:8: [
# "total 8\n",
# "-rw-r--r-- 1 david staff 0B 5 Jun 12:15 a\n",
# "-rw-r--r-- 1 david staff 0B 5 Jun 12:15 b\n",
# "-rw-r--r-- 1 david staff 0B 5 Jun 12:15 c\n",
# "-rw-r--r-- 1 david staff 0B 5 Jun 12:15 d\n",
# "-rw-r--r-- 1 david staff 115B 5 Jun 12:15 demo.pl\n",
# ]
启用自动错误检查:
require IPC::System::Simple;
use autodie qw(:all);
⋮
my @output = `$cmd`;