The original code searched for the substrings case insensitively so you'd have to uc() or lc() the strings before passing to index() if you want to behave the same. There is also one more thing that might be worth trying. We might create a character bitmap of all strings beforehand and then only search for the substring if the longer string contains all the characters that the substring does:

use strict; use Bit::Vector; my @data = qw/a mnk ab m b bc abcd cd bcd bd m nk/; @data = sort {length($b) <=> length($a)} @data; @data = map [$_, uc($_), Bit::Vector->new_Enum(256, join(',', map ord( +$_), (split //, uc($_))))->Block_Read()], @data; my @result = (); while (@data) { push @result, $data[0][0]; @data = grep { ($data[0][2] & $_->[2]) ne $_->[2] or index($data[0 +][1], $_->[1]) == -1 } @data; } print "@result\n";
Whether and how much would this help depends on the strings. In this case I saved just 5 calls to index() from the original 18.

Jenda
We'd like to help you learn to help yourself
Look around you, all you see are sympathetic eyes
Stroll around the grounds until you feel at home
   -- P. Simon in Mrs. Robinson


In reply to Re^2: Seeking the longest string in an array by Jenda
in thread Seeking the longest string in an array by johnnywang

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.