homepage Welcome to WebmasterWorld Guest from 54.235.227.60
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / Perl Server Side CGI Scripting
Forum Library, Charter, Moderators: coopster & jatar k & phranque

Perl Server Side CGI Scripting Forum

    
Determining how many times a string appears in a string
adni18




msg:444353
 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




msg:444354
 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




msg:444355
 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




msg:444356
 5:03 pm on Oct 30, 2004 (gmt 0)

"There's More Than One Way To Do It"

kaled




msg:444357
 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.

Kaled.

upside




msg:444358
 9:50 am on Nov 3, 2004 (gmt 0)

kaled has the right idea, but this syntax works:

my $count = ($string =~ tr/$substring//);

adni18




msg:444359
 12:32 pm on Nov 4, 2004 (gmt 0)

Thanks everyone!

DrDoc




msg:444360
 3:46 pm on Nov 4, 2004 (gmt 0)

Here's yet another possibility:

$count = @{[$string =~ /$match/g]};

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / Perl Server Side CGI Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved