简体   繁体   English

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

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

I'm attempting to assign the Linux system command top -n1 to an array and then eliminate the first seven lines of the text that is written to a text file. 我试图将Linux系统命令top -n1分配给一个数组,然后消除写入文本文件的文本的前七行。 When I go to print elements from my array, I get an error saying use of uninitialized value. 当我从数组中打印元素时,出现错误,提示使用未初始化的值。 Can someone show what I'm doing wrong when assigning my array to the system command? 将数组分配给系统命令时,有人可以显示我在做什么吗? Thank you. 谢谢。

Edit: I might also add, I'm looking to delete the first seven lines by using array slicing. 编辑:我可能还会添加,我想通过使用数组切片来删除前七行。

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.

} }

Use instead 改用

top -bn1 | tail -n +8

No need to reinvent the wheel when the tail command will already do what you want tail命令已经可以完成您想要的操作时,无需重新设计轮子

You are writing the top results to a file, if you want to get them to the variable you should not do that. 您正在将最上面的结果写到文件中,如果您想将它们添加到变量中,则不应该这样做。

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

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

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