Actually, I think you're OK as is for the moment (but consider the other replies above, as well). Optimization probably won't gain you much for the case in point.
However, consider the case in which you try to deal with multiple "parents:"
#!/usr/bin/perl use strict; use warnings; #829841 my @parent =<DATA>; my $substring = 'xxx'; my @count; my $total; for my $parent (@parent) { @count = split /$substring/, $parent; $total = $#count; print "there are $total $substring in $parent\n"; if($parent =~ /$substring[\s\S]*$substring/) { print "Duplicates\n" } elsif( $parent !~ /$substring/) { print "None\n"; } else { print "Unique\n" } print "-"x25 ."\n"; @count=""; $total=0; } __DATA__ xxx xxx xxx xxx yyy xxx yyy xxx yyy zyx zyx xx x
Unless you reset your array and counter, you'll encounter off-by-1 inaccuracies.
Moving on to your actual question: the standard technique is to use a hash (keys are unique and values can provide the counter for each variant element in your "$parent").
The excellent reply by JSchmitz to Count number of words on a web page? provides code; the "Perl Cookbook" (Christiansen & Torkington, O'Reilly) offers alternates and explanations at pp102-103 (at least in my May 1999 edition)
Updated: Took me so long to write this that citing only the first reply above was misleading
In reply to Re: Counting SubStrings, Style Question
by ww
in thread Counting SubStrings, Style Question
by se@n
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |