我有一个哈希结构,我想为现有值添加新值(不用新值更新) 这是我的代码。
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
答案 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