如何构建Perl多维数组或哈希?

时间:2015-01-31 19:00:32

标签: arrays perl hash

我有一组这样的CSV值:

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对象。

3 个答案:

答案 0 :(得分: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
      ]
   ]
}

答案 1 :(得分: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

答案 2 :(得分: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";
        }
    }
}
相关问题