Sharki
Sharki

Reputation: 375

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\?

Upvotes: 1

Views: 253

Answers (3)

Javier Elices
Javier Elices

Reputation: 2154

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$...

Upvotes: 4

Flying_whale
Flying_whale

Reputation: 377

my %strings = ('a' => 'x',
         map{("b$_" , 'y') } 0..63,
         'c' => 'z');

should do the trick ;)

if it is what you want

if you need to add a 'b value' later in the code, you still can do $strings{"b$value"} = 'y'; to add the new value in the hash

Upvotes: 0

Matheus Lacerda
Matheus Lacerda

Reputation: 6007

If I undestood you correctly,

b\d+

This will match "b" followed by any string of only numbers.

Upvotes: 0

Related Questions