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
.
Is the following code a one-liner?
checked with Benchmark, it's pretty fast
Friedo's method is:
$a = () = $b =~ $c
.But it's possible to simplify this even further to just
($a) = $b =~ $c
, like so :You could thank just wrap this up in a function,
getMatchCount()
, and not worry about it destroying the passed string.On the other hand, you can add in a swap, which may be a bit more computation, but does not result in altering the string.
Try this:
It returns
3
for me. By creating a reference to an array the regular expression is evaluated in list context and the@{..}
de-references the array reference.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.
another way,