in reply to Removing a certain number of hash keys

You need a hash slice.
my %h = ( 100 => "a", 101 => "b", 102 => "c", 103 => "d", 104 => "e" );
print join(",", keys %h), "\n";

my $start = 101;
my $stop = 103;
delete @h{ $start .. $stop };
print join(",", keys %h), "\n";
prints
101,102,103,104
101,104
  • Comment on Re: Removing a certain number of hash keys

Replies are listed 'Best First'.
Re: Re: Removing a certain number of hash keys
by myocom (Deacon) on Dec 12, 2000 at 02:43 UTC

    That's the sort of thing I was looking for. Now to complicate matters a bit, I oversimplified my example somewhat. I actually have a hash that looks more like this:

    my %hash = ( 100 => 1, 100.1 => 1, 103 => 1, 103.1 => 1, 103.2 => 1, 1 +05 => 1 );

    More to the point, the keys will always be nice and sortable, but they won't necessarily be integers and they won't always be consecutive. Is there a way to do some sort of indexing into a hash slice?

      Not nearly as efficient as delete @hash{101..105}, but the following looks nice:

      delete @hash{ grep {/^101$/../^105$/} sort keys %hash };
      Unless you keep a sorted list of keys separately, I don't think you can do much better than that.

      Updated slightly.

              - tye (but my friends call me "Tye")
      This should still work, provided you still want to delete all in a range:
      map { delete $hash{$_} if ($_ > 101 && $_ < 103) } keys %hash;

      Alan "Hot Pastrami" Bellows