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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.