将文件解析为数组

c0d*_*3rs 0 perl

我是Perl的新手,但我想基本上读一个文件来获取一些数据.我想将这些数据解析成一个数组.为什么一个阵列?因为,我想使用数据生成图形(数据的条形图或饼图).

到目前为止,这是我的Perl代码:

#!/usr/bin/perl -w
use warnings;

#Creating an array 
my @cpu_util;

#Creating a test file to read data from
my $file = "test.txt";      
#Opening the while      
open(DATA, $file) || die "Can't open $file: $!\n";

#Looping through the end of the file
while (<DATA>) 
{
if (/(\w+)\s+\d+\s+(\d+)\.(\d+)\%/){ #Getting only the "processes"
chomp;
push @cpu_util, split /\t/; #I was hoping this would split the data at the tabs
}
}

close ($file);

foreach $value (@cpu_util) {
print $value . "\n";
}
Run Code Online (Sandbox Code Playgroud)

这是我正在阅读的文件(test.txt):

=========================================

CPU Utilization 

=========================================

Name      CPU Time     CPU Usage    

-----------------------------------------

System                7962         3.00% 

Adobe Photoshop       6783         0.19% 

MSN Messenger         4490         0.01% 

Google Chrome         8783         0.02% 

Idle                   120        94.00% 

=========================================
Run Code Online (Sandbox Code Playgroud)

但是,我注意到我成功填充了数组,但它没有拆分选项卡并给我一个多维数组.我真的不关心CPU时间字段,但我确实想要CPU使用率,所以我想要打印一个XY图表,其中Y轴具有CPU使用率和x轴,即进程名称.

我希望有一个数组"cpu_util"并且有cpu_util [0] [0] = System和cpu_util [0] [1] = 3.00.这甚至可能吗?我认为拆分/\/ t \会照顾它,但显然我错了......

bri*_*foy 6

我想你想要哈希.密钥是CPU名称,值将是使用百分比.你快到了.成功匹配后,使用捕获($1$2)填充哈希:

my %cpu_util;   
while (<DATA>) 
    {
    if (/(.*?)\s+\d+\s+(\d+\.\d+)\%/){ #Getting only the "processes"
        $cpu_util{ $1 } = $2;
        }
    }

use Data::Dumper;   
print Dumper( \%cpu_util );
Run Code Online (Sandbox Code Playgroud)

您的数据结构应该更容易使用:

$VAR1 = {
          'Google Chrome' => '0.02',
          'System' => '3.00',
          'Adobe Photoshop' => '0.19',
          'Idle' => '94.00',
          'MSN Messenger' => '0.01'
        };
Run Code Online (Sandbox Code Playgroud)

你的分裂可能不起作用,因为那里没有标签.无论如何,这不是真正的方式.