Problemas com a excluir na hash do perl
-
21-12-2019 - |
Pergunta
Hash do outro contém o nome como chave (dividir por _) e tem 4 partes(eu estou comparando as três primeiras partes).O valor é uma seqüência de caracteres cujo tamanho que eu preciso para comparar e Se o nome é o mesmo e já existe o hash (a primeira de três partes), eu preciso manter a cadeia de caracteres mais longa duração e se os comprimentos são iguais, eu não me importo que ele mantém.Eu sei que com a iteração é a criação de problemas como os pares de valor-chave estão sendo excluídos.
my %temphash=();
%temphash=%anotherhash;
foreach my $tempkey(keys %temphash){
my @tempkey_splitted = split /\_/, $tempkey;
my $tempkey_newfamily = $tempkey_splitted[0];
my $tempkey_newgenera = $tempkey_splitted[1];
my $tempkey_newspecies = $tempkey_splitted[2];
my $tempkey_catstring ="$tempkey_newfamily"."_$tempkey_newgenera"."_$tempkey_newspecies";
my $sequence_realkey="";
my $sequence_tempkey="";
my $length_realkey="";
my $length_tempkey="";
if ($realkey_catstring eq $tempkey_catstring){
$sequence_realkey = $anotherhash{$realkey};
$length_realkey = length($sequence_realkey);
#print "$anotherhash{$realkey}";
#print "$length_realkey";
$sequence_tempkey = $temphash{$tempkey};
#print "$anotherhash{$tempkey}";
$length_tempkey = length($sequence_tempkey);
# print "$length_tempkey";
if($length_realkey>$length_tempkey){
delete($temphash{$tempkey});
#print ">$realkey\n$anotherhash{$realkey}\n\n";
}
elsif($length_tempkey>$length_realkey){
delete($temphash{$realkey});
#print ">$tempkey\n$anotherhash{$tempkey}\n\n";
}
elsif($length_tempkey eq $length_realkey){
delete($temphash{$realkey});
}
}
else{
print "do nothing";
}
}
}
Solução
Seu código é bastante complicado, mas eu acho que o código de exemplo a seguir faz o que você precisa.Ele funciona copiando o conteúdo de %anotherhash
(por favor não usar tais terrível sem sentido nomes para as variáveis) para %temphash
um elemento de cada vez, e apenas se o novo valor a partir de %anotherhash
é mais do que o %temphash
my %temphash;
while (my ($key, $val) = each %anotherhash) {
my @key = split /_/, $key;
my $tempkey = join '_', @key[0,1,2];
my $tempval = $temphash{$tempkey};
unless (defined $tempval and length $tempval >= length $val) {
$temphash{$tempkey} = $val;
}
}