Count occurrences of a substring: Difference between revisions

Content added Content deleted
No edit summary
Line 1,773: Line 1,773:


=={{header|Perl 6}}==
=={{header|Perl 6}}==
<lang perl6>sub count-substring($big,$little) { +$big.comb: /$little/ }
<lang perl6>sub count-substring($big,$little) { +$big.comb: ~$little }


say count-substring("the three truths","th");
say count-substring("the three truths","th"); # 3
say count-substring("ababababab","abab");</lang>
say count-substring("ababababab","abab"); # 4

Note that in Perl 6 the <tt>/$little/</tt> matches the variable literally, so there's no need to quote regex metacharacters. Also, prefix <tt>+</tt> forces numeric context in Perl&nbsp;6 (it's a no-op in Perl&nbsp;5). One other style point: we now tend to prefer hyphenated names over camelCase.
say count-substring(123123123,12); # 3</lang>
The <tt>~</tt> prefix operator converts <tt>$little</tt> to a <tt>Str</tt> if it isn't already, and <tt>.comb</tt> when given a <tt>Str</tt> as an argument returns instances of that substring. You can think of it as if the argument was a regex that matched the string literally <tt>/$little/</tt>. Also, prefix <tt>+</tt> forces numeric context in Perl&nbsp;6 (it's a no-op in Perl&nbsp;5). For the built in listy types that is the same as calling <tt>.elems</tt> method. One other style point: we now tend to prefer hyphenated names over camelCase.


=={{header|Phix}}==
=={{header|Phix}}==