in reply to Re: Hash Question
in thread Hash Question

It seems to be what I'm looking for but I couldn't get it to work.

This is what I have

while (my $seq = <$IN>) { if ($seq =~ /^>(\w+).+\((\d+)\s+aa\)$/) { %sequence = ( $1 => $2, ); my $max = max(values %sequence); for (keys %sequence) { delete $sequence{$_} unless $sequence{$_} == $max } print Dumper(\%sequence); while ( my ($key, $value) = each(%sequence) ) { print $OUT "$key $value\n"; } } }


Here is an example from the hash
CIMG_00046 => 399 CIMG_00047 => 865 CIMG_00048 => 330 CIMG_00048 => 506 CIMG_00053 => 167 CIMG_00063 => 468


I want to delete "CIMG_00048 => 330" because it is less than CIMG_00048 => 506.

So I would only have
CIMG_00046 => 399 CIMG_00047 => 865 CIMG_00048 => 506 CIMG_00053 => 167 CIMG_00063 => 468

Replies are listed 'Best First'.
Re^3: Hash Question
by keszler (Priest) on Nov 23, 2009 at 03:16 UTC
    use strict; use warnings; my %sequence; while (my $seq = <DATA>) { if ($seq =~ /^(\w+)\s*=>\s*(\d+)/) { $sequence{$1} = $2 unless defined $sequence{$1} && $sequence{$1} > + $2; } } for my $key (sort keys %sequence) { print "$key $sequence{$key}\n"; } __DATA__ CIMG_00046 => 399 CIMG_00047 => 865 CIMG_00048 => 330 CIMG_00048 => 506 CIMG_00053 => 167 CIMG_00063 => 468 CIMG_00063 => 467 CIMG_00063 => 466 CIMG_00063 => 469 CIMG_00063 => 460 __END__ CIMG_00046 399 CIMG_00047 865 CIMG_00048 506 CIMG_00053 167 CIMG_00063 469

    Hashes cannot have multiple same-named keys at the same level.

    perl -le ' use Data::Dump qw/dump/; %hash = { a => 3, a => 2, a => 1, b => 6, }; print dump \%hash; ' { a => 1, b => 6 }