将键/值名称分配给perl哈希并迭代

时间:2014-03-27 21:31:11

标签: perl hash

我有一个哈希,这个哈希由这种格式的数百行数据填充。基本上我希望第一个元素是键,行中的所有其他元素都是值。如何为这些元素指定键/值名称并打印某些元素?

810804 20140320          spores    -         20140324          spores     8.0.5    -          WONT_FIX   3 - HW           -                  0       fast        -                 |its broken!
801001 20140214          nagaraju   PANIC     20140220          geetha      6.0      -          NEW        5 D SW_OCUM      -                  0       fast        -                 |  dead

我在这里将基本上获取数据,创建哈希并打印所有内容。

#!/usr/software/bin/perl
use strict;
my $command = `very_long_cli_cmd`;
my %burtinfo = $command;
print "$_ $burtinfo{$_}\n" for (keys %burtinfo);

如何为这些元素添加名称并打印特定的内容?我正在尝试这样的事情,但它只是覆盖了我现有的哈希:

 my %burthash = (
        "id"                 => "",
        "date_create"        => "",
        "sub_by"           => "",
        "impact"           => "",
        "date-lastmod"     => "",
        "lastmod_by"       => "",
        "bug_rel"          => "",
        "case_score"       => "",
        "state"            => "",
        "s"                => "",
        "p"                => "",
        "tye"              => "",
        "subtype"          => "",
        "subteam"          => "",
        "found_by"         => "",
        "target_release"   => "",
        "title"            => "",
    );

1 个答案:

答案 0 :(得分:0)

你可以尝试

use strict;
use warnings;

my @cols = qw/date_create sub_by impact/;  #etc. Removed id, because the 
                                          #key for the entry is the id
my @burtInfo = `cli command`;
my %burtHash;
while(my $ele = shift(@burtInfo)){
    my ($index, @data) = split(/\s+/, $ele);
    for my $i(0 .. $#cols){
        $burtHash{$index}->{$cols[$i]} = shift(@data);
    }
}

以上是以下示例数据结构。注意%burthash是哈希的散列。

$VAR1 = '801001';
$VAR2 = {
          'date_create' => '20140214',
          'impact' => 'PANIC',
          'sub_by' => 'nagaraju'
        };
$VAR3 = '810804';
$VAR4 = {
          'date_create' => '20140320',
          'impact' => '-',
          'sub_by' => 'spores'
        };

我们无法告诉您为什么在没有相关代码的情况下覆盖%burtHash

以下是打印所有日期的示例。

for my $key(keys %burtHash){
    print $burtHash{$key}->{'date_create'}, "\n"; #notice, we got the id from the key,
                                           #and use that to access that ids info.
}

以上版画:

20140214
20140320

仅打印键

print "$_\n" for(keys %burtHash);

输出:

801001
810804