in reply to Swap the characters

The regex solutions seem to be simplest but here are a couple of alternatives. Using split, join and a slice.

$ perl -le ' $str = q{yands}; $str = join q{}, ( split m{}, $str )[ -1, 1 .. length( $str ) - 2, 0 ] +; print $str;' sandy $

Using substr.

$ perl -le ' $str = q{yands}; substr( $str, 0, 1 ) = substr $str, length( $str ) - 1, 1, substr $str +, 0, 1; print $str;' sandy $

I hope this is of interest.

Cheers,

JohnGG

Replies are listed 'Best First'.
Re^2: Swap the characters
by jwkrahn (Abbot) on Apr 14, 2009 at 13:21 UTC
    $ perl -le ' $str = q{yands}; ( substr( $str, 0, 1 ), substr $str, -1 ) = ( substr( $str, -1 ), subs +tr $str, 0, 1 ); print $str; ' sandy

      I don't know how I came to forget about using a negative offset with substr. Thanks for pointing it out.

      $ perl -le ' $str = q{yands}; substr( $str, 0, 1 ) = substr $str, -1, 1, substr $str, 0, 1; print $str;' sandy $

      Cheers,

      JohnGG