Hi Fellas,
I'm looking for the most succinct and elegant way to get the number of times a regexp matches, using only one statement. I don't want to use a loop, or any unnecessary variables, and as always, efficiency counts. At first, I assumed one could simply scalar a list returned by the match, but using scalar forces the regexp itself into scalar evaluation mode, so the following won't work:
$count = scalar ($str =~ m/pattern/g);
A few working solutions from the CB were:
$count = scalar map {1} ($str =~ m/pattern/g);
$count = scalar @{[$str =~ m/pattern/g]};
$count = ($str =~ s/pattern/$1/g);
But these seem either too unintuitive or inefficient for such a common task. Is there a better way?
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.