繁体   English   中英

在Perl中将系统命令分配给阵列

[英]Assigning a system command to an array in Perl

我试图将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.

}

改用

top -bn1 | tail -n +8

tail命令已经可以完成您想要的操作时,无需重新设计轮子

您正在将最上面的结果写到文件中,如果您想将它们添加到变量中,则不应该这样做。

使用top -bn1而不是top -bn1 >toptmp.txt

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM