本文介绍了将命令的输出读入 Perl 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想把一个命令的输出放到一个数组中 —像这样:

I want to get the output of a command into an array — like this:

my @output = `$cmd`;

但该命令的输出似乎没有进入 @output 数组.

but it seems that the output from the command does not go into the @output array.

知道它的去向吗?

推荐答案

这个简单的脚本适合我:

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>>
";
}

它产生了输出(除了三个点):

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>>
$

命令的输出在行边界上分割(默认情况下,在列表上下文中).chomp 删除数组元素中的换行符.

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

这篇关于将命令的输出读入 Perl 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 00:33