在Perl中为系统命令分配系统命令

时间:2013-04-26 06:45:03

标签: linux perl command system

我正在尝试将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.

}

2 个答案:

答案 0 :(得分:1)

改为使用

top -bn1 | tail -n +8

tail命令已经完成你想做的事情时,无需重新发明轮子

答案 1 :(得分:0)

您正在将最高结果写入文件,如果您想将它们转换为变量,则不应该这样做。

使用top -bn1代替top -bn1 >toptmp.txt

相关问题