将文件解析为数组

时间:2010-10-18 21:02:03

标签: 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";
}

这是我正在阅读的文件(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 \会照顾它,但显然我错了......

2 个答案:

答案 0 :(得分: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 );

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

$VAR1 = {
          'Google Chrome' => '0.02',
          'System' => '3.00',
          'Adobe Photoshop' => '0.19',
          'Idle' => '94.00',
          'MSN Messenger' => '0.01'
        };

您的split可能无效,因为那里没有标签。无论如何,这不是真正的方式。

答案 1 :(得分:-1)

这是你的代码修复了ihateme:

use Data::Dumper;
#use strict;

#Creating an array
my @cpu_util;

#Creating a test file to read data from
my $file = "bar.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+)\%/)
  {
    chomp;
    my ( $name, $cpuusage, @rest  ) = split ( /\s+\d+\s+(\d+\.\d+)\%/);
    push @cpu_util, [$name, $cpuusage ];
  }

}
close $file;

print Dumper(\@cpu_util);
$ref = $cpu_util[0];  # this will set the reference to the first array
$ref -> [2]; # this will return the 3rd value
print Dumper ($ref -> [1]);


 $VAR1 = [
      [
        'System',
        '3.00'
      ],
      [
        'Adobe Photoshop',
        '0.19'
      ],
      [
        'MSN Messenger',
        '0.01'
      ],
      [
        'Google Chrome',
        '0.02'
      ],
      [
        'Idle',
        '94.00'
      ]
    ];

$ VAR1 ='3.00';