Sharki Sharki - 11 months ago 172
Perl Question

Perl regex hash to match string

Right now I have the following code...

%strings = ( 'a' => 'x',
'b0' => 'y',
'b1' => 'y',
'b2' => 'y',
...
'bN' => 'y'
'c' => 'z');
....


if(grep { $_ eq $line[0] } keys %strings){
....
}


So over all I setup this hash. $line is created by reading a file. I then look to see if the first string in the line is contained within my hash. This code works perfectly. However, my problem arises with the fact that in the hash, b is growing. For instance right now I have to explicitly list out b0 - b63. This is 64 different definitions that all just need to have the same value. Is there a way to have a regex for the hash key like
b\/d\
?

Answer Source

If you want to use a regular expression, nothing prevents you from doing so:

%strings = (
  'a'    => 'x',
  'b\d+' => 'y',
  'c'    => 'z'
);
...

if( grep { $line[0] =~ /^$_$/ } keys %strings ) {
  ...
}

The ^ and $ are necessary to make sure the full string $line[0] matches and not only a part of it.

Bear in mind that this will be much slower than the eq comparison. On the other hand, the number of expressions to evaluate by grep will be much lower, so you may want to profile different options if the speed of execution is an issue.

Also, keep in mind that you may want to refine the regular expression. For instance, ^b\d{1,2}$ will match a b followed by one or two digits. Or even ^b[1-6]?\d$...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download