in reply to Selecting particular key-value pairs in hashes

Simply test the keys against your pattern:

foreach my $key ( keys %hash ) { if( $key =~ m/\d+_\d+/ ) { print "key = $key, value = $hash{$key}\n"; } }

Or am I missing something?

HTH

Update: I forgot about the "modify hash" requirement - sorry. merlyn came up with a great one-liner, of course!

Replies are listed 'Best First'.
Re^2: Selecting particular key-value pairs in hashes
by kiat (Vicar) on Sep 18, 2004 at 03:02 UTC
    Thanks, bobf!

    That was what I was going to do. But if I had proportionately more unwanted key-value pairs, the looping of keys to get to the right key-value pair might become an expensive operation.

Re^2: Selecting particular key-value pairs in hashes
by Aristotle (Chancellor) on Sep 18, 2004 at 22:00 UTC

    Or some iterative versions which do a little less work:

    # destructive while( my $k = each %hash ) { delete $hash{ $k } unless $k =~ /\d+_\d+/; } # nondestructive my %hash2; while( my( $k, $v ) = each %hash ) { $hash2{ $k } = $v if $k =~ /\d+_\d+/; }
    or maybe
    # destructive /\d+_\d+/ or delete $hash{ $_ } while local $_ = each %hash; # nondestructive my %hash2; /\d+_\d+/ and $hash2{ $_ } = $a while local( $_, $a ) = each %hash;

    Makeshifts last the longest.