in reply to Hash Question

I'm not sure what you mean by 'Some keys are redundant', but here is one way to delete all hash elements except for the key whose value is the maximum:
use strict; use warnings; use List::Util qw(max); use Data::Dumper; my %h = (a=>2, b=>8, c=>7); my $max = max(values %h); for (keys %h) { delete $h{$_} unless $h{$_} == $max } print Dumper(\%h); __END__ $VAR1 = { 'b' => 8 };
If this is not what you are looking for, post some of your hash contents and some of your code.

Replies are listed 'Best First'.
Re^2: Hash Question
by perl_n00b (Acolyte) on Nov 23, 2009 at 02:03 UTC
    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
      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 }