I read through the responses so far and figured that it might be useful to someone to examine how someone might solve this problem using regular expressions (since that's how the problem was originally framed), even though I'd probably do something with substr() myself. Here are my thought processes.

First I thought, "how would I do this manually?" and I came up with the following REs

s/^(.)(.)(.*)/$2$1$3/s; # 12345 -> 21345 s/^(.)(.)(.)(.*)/$1$3$2$4/s; # 12345 -> 13245 s/^(..)(.)(.)(.*)/$1$3$2$4/s; # 12345 -> 12435 s/^(...)(.)(.)(.*)/$1$3$2$4/s; # 12345 -> 12354

The "(.)(.)" part matches the two characters we're going to swap and the "(.*)" part matches whatever is left in the string. I put the /s modifier on there in case a linefeed character was in the string.

Then I got to thinking ... it sure would be nice if that first s/// looked like all the others. So, of course, I got

s/^()(.)(.)(.*)/$1$3$2$4/s;

So now how do I put that stuff in a loop? One of the many cool things in perl is that you can interpolate your patterns like so:

my $dots = ".."; s/^($dots)(.)(.)(.*)/$1$3$2$4/s; # 12345 -> 12435

So, all I need to do is loop until length($dots) is greater than length($str)-2 (the -2 is because of the pair of characters we are swapping). So that gives me this final bit of code:

my $str = "12345"; my $dots = ""; while (length($dots) <= length($str)-2) { $_ = $str; s/^($dots)(.)(.)(.*)/$1$3$2$4/s; print; $dots .= "."; }

Hope this helps,


In reply to Re: YET another regexp puzzle by duff
in thread YET another regexp puzzle by carric

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.