in reply to regex problem: doesn't work on the first search but works on the second

G'day onlyauto,

Welcome to the monastery.

I see you have a solution to your posted problem. There's another issue I thought I'd point out.

All those if statements:

Consider writing your code more along these lines:

#!/usr/bin/env perl -l use strict; use warnings; my @data = ('X_12_yzAAA', 'X_34_yzBBB', 'X_56_yzCCC', 'X_78_yzAAA',); my $re = qr{^.+_(\d+)_.+([A-C]{3})$}; my %despatch = ( AAA => sub { print 'found1 with digits: ', shift }, BBB => sub { print 'found2 with digits: ', shift }, CCC => sub { print 'found3 with digits: ', shift }, ); /$re/ && $despatch{$2}->($1) for @data;

Output:

found1 with digits: 12 found2 with digits: 34 found3 with digits: 56 found1 with digits: 78

Now you have:

-- Ken

Replies are listed 'Best First'.
Re^2: regex problem: doesn't work on the first search but works on the second
by hdb (Monsignor) on Nov 29, 2013 at 07:07 UTC

    You could build your regex from the keys of the %despatch hash. Then you only have to change the code in one place.