【发布时间】:2011-02-04 00:11:40
【问题描述】:
我对 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";
}
这是我正在阅读的文件(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%
=========================================
但是,我注意到我成功填充了数组,但它没有拆分选项卡并给我一个多维数组。我并不真正关心 CPU 时间字段,但我确实想要 CPU 使用率,所以我想打印一个 XY 图表,其中 Y 轴具有 CPU 使用率和 x 轴,进程名称。
我希望有一个数组“cpu_util”,并且 cpu_util[0][0] = System 和 cpu_util[0][1] = 3.00。这甚至可能吗?我以为拆分 /\/t\ 会解决它,但显然我错了......
【问题讨论】:
标签: perl