簡體   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