Suppose I have:
my $string = "one.two.three.four";
How should I play with context to get the number of times the pattern found a match (3)? Can this be done using a one-liner?
I tried this:
my ($number) = scalar($string=~/\./gi);
I thought that by putting parentheses around $number
, I'd force array context, and by the use of scalar
, I'd get the count. However, all I get is 1
.
To count a regex pattern multiple times in a given string, use the method len(re. findall(pattern, string)) that returns the number of matching substrings or len([*re. finditer(pattern, text)]) that unpacks all matching substrings into a list and returns the length of it as well.
Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to the host language and is not the same as in PHP, Python, etc. Sometimes it is termed as “Perl 5 Compatible Regular Expressions“.
m operator in Perl is used to match a pattern within the given text. The string passed to m operator can be enclosed within any character which will be used as a delimiter to regular expressions.
That puts the regex itself in scalar context, which isn't what you want. Instead, put the regex in list context (to get the number of matches) and put that into scalar context.
my $number = () = $string =~ /\./gi;
I think the clearest way to describe this would be to avoid the instant-cast to scalar. First assign to an array, and then use that array in scalar context. That's basically what the = () =
idiom will do, but without the (rarely used) idiom:
my $string = "one.two.three.four"; my @count = $string =~ /\./g; print scalar @count;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With