如果存在哈希键,则将新值添加到现有值

时间:2013-07-16 09:52:11

标签: perl hash

我有一个哈希结构,我想为现有值添加新值(不用新值更新) 这是我的代码。

use strict;
    use warnings;
    my %hash;
    while(<DATA>){
        my $line=$_;
        my ($ID)=$line=~/ID=(.*?);/;
        #make a hash with ID as key                                                                                                                                                                                                                                                                                                                                             
        if (!exists $hash{$ID}){
            $hash{$ID}= $line;
        }
        else{
           #add $line to the existing value                                                                                                                                                                                                                                                                                                                                     
        }
    }
    for my $key(keys %hash){
        print $key.":".$hash{$key}."\n";
    }
    __DATA__
    ID=13_76; gi|386755343
    ID=13_75; gi|383750074
    ID=13_75; gi|208434224
    ID=13_76; gi|410023515
    ID=13_77; gi|499086767

3 个答案:

答案 0 :(得分:1)

    else{
       $hash{$ID} .= $line;                                                                                                                                                                                                                                                                                                                                  
    }

答案 1 :(得分:1)

您所需要的只是$hash{$ID} .= $line;。没有if-elses。 如果散列中没有键$ID,它将创建一个并将$line连接到空字符串,从而产生您所需要的。

答案 2 :(得分:0)

您应该将数据存储在数组的散列中:

#!/usr/bin/env perl

use strict;
use warnings;

# --------------------------------------

use charnames qw( :full :short   );
use English   qw( -no_match_vars );  # Avoids regex performance penalty

use Data::Dumper;

# Make Data::Dumper pretty
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Indent   = 1;

# Set maximum depth for Data::Dumper, zero means unlimited
local $Data::Dumper::Maxdepth = 0;

# conditional compile DEBUGging statements
# See http://lookatperl.blogspot.ca/2013/07/a-look-at-conditional-compiling-of.html
use constant DEBUG => $ENV{DEBUG};

# --------------------------------------

my %HoA = ();
while( my $line = <DATA> ){
  if( my ( $ID ) = $line =~ m{ ID \= ([^;]+) }msx ){
    push @{ $HoA{$ID} }, $line;
  }
}
print Dumper \%HoA;


__DATA__
ID=13_76; gi|386755343
ID=13_75; gi|383750074
ID=13_75; gi|208434224
ID=13_76; gi|410023515
ID=13_77; gi|499086767