How to calculate the number of match occurrences directly?

L

Long Li

Hi,
I want to calculate the number of match occurrences, for examples,

$string = "abcdabcd";
@a = $string =~ m/a/g;
$num_a = @a;

However, I do not want to use the array "@a" because I do not care
that array, espcially "$string" is very large and include many "a", I
just want to know the number of "a" occurrences. I tried

$num_a = $string =~ m/(a)/g;
or
$num_a = ( $string =~ m/a/g );

They both did not work. Please give me some suggestions, thanks.
 
A

Anno Siegel

Long Li said:
Hi,
I want to calculate the number of match occurrences, for examples,

$string = "abcdabcd";
@a = $string =~ m/a/g;
$num_a = @a;

However, I do not want to use the array "@a" because I do not care
that array, espcially "$string" is very large and include many "a", I
just want to know the number of "a" occurrences. I tried

$num_a = $string =~ m/(a)/g;
or
$num_a = ( $string =~ m/a/g );

They both did not work. Please give me some suggestions, thanks.

There's a trick to that:

$num = () = /a/g;

The "()" provide list context to the regex, but the actual variable
(a scalar) is assigned the number of elements. Capturing parentheses
are not necessary.

If you only ever want to count single characters, tr/// is simpler
and more efficient:

$num = tr/a//;

Anno
 
G

Gunnar Hjalmarsson

Long said:
I want to calculate the number of match occurrences, for examples,

$string = "abcdabcd";
@a = $string =~ m/a/g;
$num_a = @a;

However, I do not want to use the array "@a" because I do not care
that array, espcially "$string" is very large and include many "a",
I just want to know the number of "a" occurrences. I tried

$num_a = $string =~ m/(a)/g;
or
$num_a = ( $string =~ m/a/g );

They both did not work. Please give me some suggestions, thanks.

You are asking a FAQ.

perldoc -q count

Please consult the FAQ, thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,038
Latest member
OrderProperKetocapsules

Latest Threads

Top