I would suggest starting by ordering your array by string length, shortest to longest. Then, take element 0 as your first approximation at the shortest substring and compare it to the same length section (via substr()) to the next string. If they do not match, reduce the test sequence until you arrive at a match, or an empty string. Repeat until you have examined all strings, or have an empty approximation string.

Untested code example:

my @string = sort { length $a <=> length $b } ( qw/ quux asdfasdfasdf asdfasdf asdfzxcv as / ); my $common = shift @string; while ( my $teststr = shift @string and length $common ) { if ( $common eq substr( $teststr, 0, length $common ) ) { next; } my $flag = length $common; while ( $flag ) { if ( $common eq substr( $teststr, 0, $flag ) ) { $flag = 0; } else { $flag--; $common = substr( $common, 0, $flag ); } } } # print $common;

Hope that helps.

Update: 2015-11-15
Fixed errors in code sample. (My thanks to oiskuu for pointing their existence!)


In reply to Re: An efficient way to gather a common portion of several strings' beginnings by atcroft
in thread An efficient way to gather a common portion of several strings' beginnings by igoryonya

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.