2)need to know how many matches has regex hit
This statement could be interpreted different ways.. Do you want to know how many captures there were (i.e, $1, $2, ...)? Or do you want to see how many times the entire regex is matched globally in the string (i.e, as with m//g)? Judging from #6 above, you seem to mean the former.

From perlop: In list context, m// returns:

This seems to give most of the information you need, with the catch that the last 2 cases overlap (i.e, "1" =~ /(1)/ and "foo" =~ /./ return the same thing in list context, but one has captures and one doesn't). To distinguish between these cases, you can look at @-, as you suggested. It will tell you whether there were captures in the last successful match, so you know how to interpret the return value of the match statement. Finally, to catch the case that the (user-provided) regex is invalid, you can wrap the whole thing in an eval.

Putting it all together:

use strict; my $string = "foobar1"; for my $regex (<DATA>) { chomp $regex; my ($success, @captures); eval { @captures = $string =~ /$regex/; $success = 1 if @captures; @captures = () if $success and @- == 1; }; print "$regex: "; if ($@) { print "invalid regex\n"; ## optionally print $@ here } elsif ($success and @captures) { print "matched: @captures\n"; } elsif ($success and !@captures) { print "matched (no captures)\n"; } else { print "didn't match\n"; } } __DATA__ foo((( (fo(o))(bar) o(.*)a foobar baz(bar)( blah(foo) (.)$
Output:
foo(((: invalid regex (fo(o))(bar): matched: foo o bar o(.*)a: matched: ob foobar: matched (no captures) baz(bar)(: invalid regex blah(foo): didn't match (.)$: matched: 1

blokhead


In reply to Re: regex persistence of matches by blokhead
in thread regex persistence of matches by spx2

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.