http://www.perlmonks.org?node_id=960266


in reply to Error in my Regular expression pattern

perldoc://count occurrences

perldoc -q " count.*?occurrences "
perlfaq4#How can I count the number of occurrences of a substring within a string?

Learn more about the flying lentil operator

Replies are listed 'Best First'.
Re^2: Error in my Regular expression pattern
by Anonymous Monk on Mar 18, 2012 at 07:28 UTC
    Like perlop#m/PATTERN/msixpodualgc ( perlop#m// ), says,
    m// in scalar context returns true if it succeeds, false if it fails.

    Each time m// succeeds against a variable, like when  $n = m/twinkle/ig; executes, position is changed, so that  while(/twinkle/ig) { executes, only the second twinkle is counted.

    If you add this to your program before the while loop

    print "pos is ", pos, ", remainder '", substr($_, pos), "'\n"; pos($_) = undef;
    this resets pos associated with $_, and then your program will produce
    Number of occurences = 1 pos is 7, remainder ' twinkle little star' Found 2 times

    Like perlfaq4 says, if you want the number of occurances, use the flying lentil operator, use  my $count =()= m/twinkle/ig;