Determining how many times a string appears in a string
adni18
2:57 pm on Oct 30, 2004 (gmt 0)
Is there a way to determine the number of instances a string appears in a larger string like here [javascript.internet.com], except in Perl, not JavaScript?
SlowMove
4:56 pm on Oct 30, 2004 (gmt 0)
This should do it, even with regular expressions:
my $string = "substring substring substring oefiojoifasubstringioafesjvaiosubstring"; my $count = 0; my $flag = 0; do { if ( $string =~ /substring/) { $string = $'; $count++; } else { $flag = 1; } } until $flag == 1;
print "$count\n";
jollymcfats
5:01 pm on Oct 30, 2004 (gmt 0)
This is answered in the Perl FAQ that ships with perl. Type this at the command line:
perldoc -q count
SlowMove
5:03 pm on Oct 30, 2004 (gmt 0)
"There's More Than One Way To Do It"
kaled
12:01 am on Nov 1, 2004 (gmt 0)
I think something like this will work.
$tmp = $str; $count = ($tmp ~= s/$search//g);
i.e. a global substitute with a null string. I'm not certain the syntax above is correct - my perl is a bit rusty.