[tpm] problems with what regex returns ... in context ?

Fulko Hew fulko.hew at gmail.com
Fri May 10 07:06:42 PDT 2013


I'm having yet another mental block w.r.t. capturing regexes...

Given a string to match, and a list of regexes
I need to process the captured data (if any), if the pattern matches.

So generically I do:

if (@capture = ($line =~ m/$regex/)) {
  foreach @capture { ... }
} else {
  no match
}

When the regex has some capturing defined, all is fine.
The foreach does its thing.

But when the regex DOESN'T have any captures
it @capture still contains a single value ... '1'
(The success/truth indication.)

How can I tell the difference between:
- a successful match with no captured data
- a successful match with captured data
- an unsuccessful match

TIA
Fulko




my $line        = 'this is stuff in here';
my @patterns    = qw / stuff (stuff) /;
foreach $regex (@patterns) {
    my @capture = ();
    print "regex is '$regex' ... ";
    if (@capture = ($line =~ m/$regex/)) {
        print "captured " . scalar @capture . " items \n";
        my $i = 0;
        foreach my $item (@capture) {
            print " capture[$i]: '$item'\n";
            $i++;
        }
    } else {
        print "nothing captured\n";
    }
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.pm.org/pipermail/toronto-pm/attachments/20130510/733b5cf5/attachment.html>


More information about the toronto-pm mailing list