efoss has asked for the wisdom of the Perl Monks concerning the following question:

I have a bunch of file names in the array called "@array". I want to pull out those files that start with "KL" and then either 1 or 2 digits and then an underscore, and I want to push those files onto the array called "@files". This is how I tried to do this:
foreach $file (@array) { if ($file =~ /^KL\d{1|2}_/) { push (@files, $file); print "$file\n"; } }
This doesn't work. However, the following works, but only because all the files in "@array" have either 1 or 2 digits following the initial "KL". If there had been a file name in @array like "KL123_rest.txt" that I didn't want to push onto the array "@files", then my code wouldn't have worked.
foreach $file (@array) { if ($file =~ /^KL\d+_/) { push (@files, $file); print "$file\n"; } }
How do I correctly quantify \d in this situation? Thanks. Eric

Replies are listed 'Best First'.
Re: quantifiers with digits (\d{1|2} doesn't do what I expect)
by davido (Cardinal) on Aug 21, 2012 at 01:56 UTC

    The syntax for brace quantifiers is to use a comma:

    {0,2} # Max of 2 {1,3} # One to three {1,} # One or more {2} # Exactly two {1,2} # One to two.

    There is no concept of alternation within quantifier braces.


    Dave

      Thanks so much, Dave. Eric
Re: quantifiers with digits (\d{1|2} doesn't do what I expect)
by BillKSmith (Monsignor) on Aug 21, 2012 at 02:55 UTC

    Use grep

    use strict; use warnings; my @array = qw(KL1_something.txt KL12_anything.dat KL123_rest.txt); my @file = grep /^KL\d{1,2}_/, @array; print "@file\n";
    Bill
Re: quantifiers with digits (\d{1|2} doesn't do what I expect)
by ricDeez (Scribe) on Aug 21, 2012 at 07:56 UTC

    How about this as an alternative?

    if ($file =~ /^KL\d\d?_/) {...}