in reply to regular expression in a hash

It doesn't do what you are thinking. Not that I can figure out what you are thinking quite, but I'm quite sure it doesn't do it.

For a start rrv193\d{4}cm => "RNF191", is a syntax error. Possibly you want 'rrv193\d{4}cm' => "RNF191", which at least compiles, but my guess is that you are heading at the problem from the wrong direction. I suspect you are hoping that the hash key in some magical fashion will behave as a regular expression and will "match" any string provided as a "key" that it matches on. Sorry, it don't work that way.

So, what are you really trying to do. Not the solution you've come up with, but the bigger problem you are trying to solve?

My guess is you have a number of these matches and you want to provide a different replacement string for each one. So lets run with that idea for a moment. Consider:

use strict; use warnings; my %Ren2Dol = ( 'rrv193\d{4}cm' => "RNF191", 'rrv194\d{4}cm' => "RNF196", 'rrv195\d{4}cm' => "RNF200", ); while (<DATA>) { chomp; my ($base, $rest) = split /[\.\_]/, $_, 2; my ($match) = grep {$base =~ /$_/} keys %Ren2Dol; if (defined $match) { print "$Ren2Dol{$match}\n"; } else { print "$base\n"; } } __DATA__ rrv1931009cm.new090626 rrv1941009cm.new090626 rrv1951009cm.new090626 rrv1961009cm.new090626 rrv1931234cm.new090626

Prints:

RNF191 RNF196 RNF200 rrv1961009cm RNF191

True laziness is hard work

Replies are listed 'Best First'.
Re^2: regular expression in a hash
by spazm (Monk) on Jul 08, 2009 at 21:55 UTC
    If you regular expressions as your keys, then you save the overhead of recompiling them everytime. The qr// operator does this for you.
    my %Ren2Dol = ( qr(rrv193\d{4}cm) => "RNF191", qr(rrv194\d{4}cm) => "RNF196", qr(rrv195\d{4}cm) => "RNF200", );

    Here's your code with tests. This does the actual search/replace as necessary as it converts @data to @output.

    use strict; use warnings; use Test::More tests=>1; use Data::Dumper; my %Ren2Dol = ( qr(rrv193\d{4}cm) => "RNF191", qr(rrv194\d{4}cm) => "RNF196", qr(rrv195\d{4}cm) => "RNF200", ); my @data = qw( rrv1931009cm.new090626 rrv1941009cm.new090626 rrv1951009cm.new090626 rrv1961009cm.new090626 rrv1931234cm.new090626 ); my @expected = qw( RNF191.new090626 RNF196.new090626 RNF200.new090626 rrv1961009cm.new090626 RNF191.new090626 ); my @output; foreach (@data) { while( my( $regex, $replace ) = each (%Ren2Dol)) { s/$regex/$replace/ex; } push @output, $_; } is_deeply( \@expected, \@output, "names updated correctly") or diag( Dumper{ expected=>\@expected, got=>\@output });
Re^2: regular expression in a hash
by lamasculo (Novice) on Jul 08, 2009 at 16:06 UTC
    Hi Grandfather your prediction as to what I was trying to achieve was absolutely perfect. I have now go the remainder of the script I have been trying for a couple of weeks to solve Thanks to you and everyone else who has made suggestions David