1

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

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
4

3 回答 3

1
    else{
       $hash{$ID} .= $line;                                                                                                                                                                                                                                                                                                                                  
    }
于 2013-07-16T09:53:53.410 回答
1

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

于 2016-11-20T10:57:19.427 回答
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
于 2013-07-16T13:06:51.940 回答