Here's some trickery with the oft-forgotten index.

sub in_common { my $all = join '', scalar( reverse $_[ 0 ] ), @_[ 1 .. $#_ ]; my $offs = length $_[ 0 ]; my $minpos = 0; return grep { my $pos = index( $all, $_, $offs-- ); $pos >= $minpos++; } split //, $_[ 0 ]; }

The trick is to fold checking for non-existant characters and already-checked-for characters into a single condition: index returns -1 if it doesn't find the character and a 0-based offset if it does. Therefore in the first iteration, the check is for >= 0. This seen character is then included in the searched string. On the next iteration, the check is for offset >= 1 — ie it must exist in the string (offset > -1) but not be the character already seen (offset >= 1). In the next iteration, the offset must be >= 2 to account for already seen characters.

In C, this approach would beat all others for speed and would be the most straightforward one too. But in Perl, it is harder to read than the others and slower than most too. sleepingsquirrel's regex is probably the fastest because it doesn't loop explicitly in Perl; merlyn's variation of your own solution is the clearest.

Makeshifts last the longest.


In reply to Re: Unique List of Common Characters Between Two Strings by Aristotle
in thread Unique List of Common Characters Between Two Strings by Limbic~Region

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.