Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

Using regex to extract keys

by seaver (Pilgrim)
on Sep 24, 2003 at 20:52 UTC ( #294014=perlquestion: print w/replies, xml ) Need Help??

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?


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.


      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.


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

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://294014]
Approved by Mr. Muskrat
Front-paged by broquaint
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (3)
As of 2022-09-28 02:51 GMT
Find Nodes?
    Voting Booth?
    I prefer my indexes to start at:

    Results (124 votes). Check out past polls.