Can you give us some more details? How long are your strings on average? How many do you expect to have in the list? What characters do they contain?

This looks like you might be doing something biology related so I would not be surprised if the strings you are working for consisted of only ACGT characters or something similar.

Also there are two problems with your code. First, you should not be using the $a and $b variables. They are kinda special (used inside the block optionaly passed to sort()) which is why "use strict" did not complain about them not being declared.

Second, you are not excaping special characters in $a when making the regexp, what if the "words" contain some dots, question marks, asterisks, parenthesis, ... You should use $b =~ /\Q$a\E/i if you want to use the regexp to find the substring. There is actually no reason to do that, you'd better use the index() function. No need to escape anything and it should be quicker. Though if you really want your comparison to be case insensitive you'd have to uppercase (or lowercase) both strings before you try to find one in the other.

Last thing, finding the strings length is quick. Much quicker than trying to find a substring. You should revert your condition and only try to find short strings in longer ones. A ten chars long string cannot contain a 20 char long one ;-)

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