comp( 'foo', 'foo' ); # False

So, how do you know those 'o's aren't transposed? ;-)

Anyway, here's my attempt. I think it'll work correctly in boolean and numeric contexts. I return either undef or a string but you might prefer to return either undef or an integer (which will force you to check for undef.) Or maybe undef or an array with one element (which will work in boolean context even if the match is at the zeroth position.) Or you might want to start your positions at one... You weren't very specific about that.

sub comp { return undef unless length $_[0] == length $_[1]; my $where; for ( 0 .. length $_[0] ) { next if substr($_[0], $_, 2) eq substr($_[1], $_, 2); if ( substr($_[0], $_, 2) eq reverse substr($_[1], $_, 2) ) { return undef if defined $where; $where = $_; } else { return undef; } } return "+$where" if defined $where; }

I imagine there are ways to do this better. This method is limited to N comparisons of 2 character strings for successful comparisons and less on failures. It might fare pretty well if you expect failures most of the time. What kind of input do you expect?

-sauoq
"My two cents aren't worth a dime.";

In reply to Re: Detecting transpositions by sauoq
in thread Detecting transpositions by BrowserUk

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.