In Perl, how to match several prefixes
        Posted  
        
            by 
                xorsyst
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by xorsyst
        
        
        
        Published on 2014-06-05T15:12:23Z
        Indexed on 
            2014/06/05
            15:24 UTC
        
        
        Read the original article
        Hit count: 182
        
I have 2 input files. One is a list of prefix and lengths, like this:
101xxx
102xxx
30xx
31xx
(where x is any number)
And another is a list of numbers.
I want to iterate through the second file, matching each number against any of the prefix/lengths. This is fairly easy. I build a list of regexps:
my @regexps = ('101...', '102...', '30..', '31..');
Then:
foreach my $regexp (@regexps) {
    if (/$regexp/) {
        # do something
But, as you can guess, this is slow for a long list.
I could convert this to a single regexp:
my $super_regexp = '101...|102...|30..|31..';
...but, what I need is to know which regexp matched the item, and what the ..s matched.
I tried this:
my $catching_regexp = '(101)(...)|(102)(...)|(30)(..)|(31)(..)';
but then I don't know whether to look in $1, $3, %5 or $7.
Any ideas? How can I match against any of these prefix/lengths and know which prefix, and what the remaining digits where?
© Stack Overflow or respective owner