http://qs1969.pair.com?node_id=294014

seaver has asked for the wisdom of the Perl Monks concerning the following question:

Dear all,

I have a large hash where every key in the hash is of the format:\w\d\d, and I want to use keys to extract an array of keys that match any \d\d pattern, (hence ignoring letters) like so:

my $r = 44; foreach my $key (keys %{$self->{'residues'}{$modelCount}{/^\w$r$/}}){ print $key."\n"; }
This doesnt work as it is, but is there a possible solution, or should I just step through the keys ahd store an array of the ones that match?

Cheers
Sam

Replies are listed 'Best First'.
Re: Using regex to extract keys
by perlmonkey (Hermit) on Sep 24, 2003 at 20:59 UTC
    use grep:
    my $r = 44; my $hash = $self->{'residues'}{$modelCount}; for my $key ( grep { /^\w$r$/ } keys %$hash ) { print $key."\n"; }
    Update:Yup, as abigail suggested use each for large hashes so you dont duplicate the memory needed for the keys:
    my $r = 44; my $hash = $self->{'residues'}{$modelCount}; while( my ($key, $value) = each %$hash ) { next if $key =~ /^\w$r$/; print $key."\n"; }
      Since the hash is given to be large, one might prefer iterating over the hash using each in a while loop. In the loop, test whether the key matches /^\w$r$/. If not, do a next.

      Abigail

      Fantastic, Thanks!

      I was disappointed because I was hoping that there was some inherent regex in calling a hash key, but obviously I cant do it that way. The while loop with each does the job just grand.

      Cheers
      Sam

Re: Using regex to extract keys
by Mr. Muskrat (Canon) on Sep 24, 2003 at 20:59 UTC

    Get your keys and check for matches.

    my %hash = ( a44 => 'aha!', b33 => 'boo!', c45 => 'close.', d44 => 'aha!', e44 => 'aha!', f46 => 'too far...', ); my $r = 44; foreach my $key (keys %hash){ print $key."\n" if $key =~ /\w$r/; } __DATA__ e44 a44 d44