【问题标题】:Assigning a system command to an array in Perl在 Perl 中将系统命令分配给数组
【发布时间】:2013-04-26 06:45:03
【问题描述】:

我正在尝试将 Linux 系统命令 top -n1 分配给一个数组,然后消除写入文本文件的前七行文本。当我从我的数组中打印元素时,我收到一条错误消息,指出使用了未初始化的值。将我的阵列分配给系统命令时,有人可以显示我做错了什么吗?谢谢。

编辑:我还可以添加,我希望通过使用数组切片来删除前七行。

sub     processlist
{
     my $num_of_lines = 0;
    my @top_command = `top -bn1 >toptmp.txt`;

    #opening temp file, and output file.
    open(my $in, '<' , "toptmp.txt") or die "Can't read the file: $!"; #file used for initial reading
    open(my $out, '>', "top.txt") or die "can't write to file: $!"; 

    print $top_command[0], "\n";
    #looping deleting first 7 lines
    while(<$in>)
    {

            if($num_of_lines > 6) #starts writing to top.txt past line 7 (counting starts at 0)
            {
                    print $out $_;
            }
    $num_of_lines++;
    }
    close $out;
    close $in;
    system("rm toptmp.txt"); #erasing tmp file.

}

【问题讨论】:

    标签: linux perl command system


    【解决方案1】:

    改为使用

    top -bn1 | tail -n +8
    

    tail 命令已经可以满足您的需求时,无需重新发明轮子

    【讨论】:

    • 此外,具有top 的系统通常也具有tail。因此,添加 tail 并不会降低它的可移植性。
    【解决方案2】:

    您正在将排名靠前的结果写入文件,如果您想将它们放入变量中,您不应该这样做。

    使用top -bn1 而不是top -bn1 &gt;toptmp.txt

    【讨论】:

      猜你喜欢
      • 2015-04-05
      • 2010-12-29
      • 1970-01-01
      • 1970-01-01
      • 2021-11-24
      • 2013-06-25
      • 1970-01-01
      • 1970-01-01
      • 2011-05-23
      相关资源
      最近更新 更多