2015-01-31 94 views
1

我有這樣一組CSV值:如何構建一個Perl多維數組或哈希?

device name, CPU value, frequency of CPU value, CPU in percentage 

例如

router1,5,10,4 
router1,5,1,5 
router2,5,10,4 
router2,5,2,5 
router3,4,5,6 
router3,7,6,5 

我需要以形成數據結構是這樣的:

array = { 
    router1 => [5,10,4],[5,1,5], 
    router2 => [5,10,4],[5,2,5], 
    router3 => [4,5,6],[7,6,5] 
} 

我需要在形成的幫助這個數據結構在Perl中。

我試圖想象如何做到這一點,但我無法這樣做。我將不勝感激任何幫助。

我的最終目標是將其轉換爲JSON對象。

回答

2

這應該讓你開始。它使用DATA文件句柄,以便我可以將數據嵌入到程序本身中。我使用JSON模塊中的to_json將散列格式化爲JSON數據。語句$_ += 0 for @values@values的內容從字符串轉換爲數字,以避免生成的JSON數據中的引號。

use strict; 
use warnings; 

use JSON; 

my %data; 

while (<DATA>) { 
    chomp; 
    my ($device, @values) = split /,/; 
    $_ += 0 for @values; 
    push @{ $data{$device} }, \@values; 
} 

print to_json(\%data, { pretty => 1, canonical => 1 }); 

__DATA__ 
router1,5,10,4 
router1,5,1,5 
router2,5,10,4 
router2,5,2,5 
router3,4,5,6 
router3,7,6,5 

輸出

{ 
    "router1" : [ 
     [ 
     5, 
     10, 
     4 
     ], 
     [ 
     5, 
     1, 
     5 
     ] 
    ], 
    "router2" : [ 
     [ 
     5, 
     10, 
     4 
     ], 
     [ 
     5, 
     2, 
     5 
     ] 
    ], 
    "router3" : [ 
     [ 
     4, 
     5, 
     6 
     ], 
     [ 
     7, 
     6, 
     5 
     ] 
    ] 
} 
+0

非常感謝幫助。代碼工作得很好! – user3199303 2015-02-01 16:12:51

0

這裏是一個所需的列印的JSON對象的簡單解決方案。

#!/usr/bin/env perl  

use strict; 
use warnings; 
use 5.010; 

my %hash; 

while (my $line = <DATA>) { 
    chomp $line; 
    my ($device, @cpu_values) = split(/,/, $line); 
    my $cpu_token = join(",", @cpu_values); 
    $hash{$device} .= '[' . $cpu_token . '], '; 
} 

my @devices = keys %hash; 

print "array = { \n"; 
foreach (sort @devices) { 

    print "$_ => [$hash{$_}]\n"; 

} 
print "}\n"; 

__DATA__ 
router1,5,10,4 
router1,5,1,5 
router2,5,10,4 
router2,5,2,5 
router3,4,5,6 
router3,7,6,5 
+1

非常感謝!!!!這工作得很好。 – user3199303 2015-02-01 16:13:23

0

在Perl中,你需要使用匿名數組的方式引用和哈希值進行多維數組,數組的數組,包含哈希和之間的任何哈希值。 perlreftut應該包括如何完成你正在嘗試做的事情。這是我前幾天寫的一個例子,可以幫助解釋:

print "\nFun with multidimensional arrays\n"; 
my @myMultiArray = ([1,2,3],[1,2,3],[1,2,3]); 

for my $a (@myMultiArray){ 
    for my $b (@{$a}){ 
     print "$b\n"; 
    } 
} 

print "\nFun with multidimensional arrays containing hashes\nwhich contains an anonymous array\n"; 
my @myArrayFullOfHashes = (
    {'this-key'=>'this-value','that-key'=>'that-value'}, 
    {'this-array'=>[1,2,3], 'this-sub' => sub {return 'hi'}}, 
); 

for my $a (@myArrayFullOfHashes){ 
    for my $b (keys %{$a}){ 
     if (ref $a->{$b} eq 'ARRAY'){ 
      for my $c (@{$a->{$b}}){ 
       print "$b.$c => $c\n"; 
      } 
     } elsif ($a->{$b} =~ /^CODE/){ 
      print "$b => ". $a->{$b}() . "\n"; 
     } else { 
      print "$b => $a->{$b}\n"; 
     } 
    } 
} 
+0

感謝您解釋! – user3199303 2015-02-01 17:18:04