Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (5)
As of 2024-04-20 02:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found