Reading output from command into Perl array

大城市里の小女人 提交于 2019-11-29 13:19:07

This simple script works for me:

#!/usr/bin/env perl
use strict;
use warnings;

my $cmd = "ls";    
my @output = `$cmd`;    
chomp @output;

foreach my $line (@output)
{
    print "<<$line>>\n";
}

It produced the output (except for the triple dots):

$ perl xx.pl
<<args>>
<<args.c>>
<<args.dSYM>>
<<atob.c>>
<<bp.pl>>
...
<<schwartz.pl>>
<<timer.c>>
<<timer.h>>
<<utf8reader.c>>
<<xx.pl>>
$

The output of command is split on line boundaries (by default, in list context). The chomp deletes the newlines in the array elements.

The (standard) output does go to that array:

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",
# ]

Enable automatic error checks:

require IPC::System::Simple;
use autodie qw(:all);
⋮
my @output = `$cmd`;
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!