Link to home
Start Free TrialLog in
Avatar of jamie_lynn
jamie_lynn

asked on

How to swap letters in Perl

Hi,
I want to create a function that swaps adjacent letters within  a word.

i.e
var str = "abcdef"

var newstr = swap($str)
print OUT $str

And this prints out
badcfe

a is swapped with b, c is swapped with d, e is swapped with f

What is the best way to create this function?

Thanks
Jamie
SOLUTION
Avatar of clockwatcher
clockwatcher

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of clockwatcher
clockwatcher

Actually you probably want it back in a variable:

$str="abcdef";
@letters = split //, $str;
while (@letters) { ($a,$b) = splice(@letters,0,2); $swapped .= "$b$a"; }
print $swapped;
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
as a function,
$newstr = swap($str);
 would you want
print OUT $str;
to print out
badcfe
or would you want
print OUT $newstr;
to print out
badcfe
or both?
Also, what would you want to do with non-letters?
Avatar of jamie_lynn

ASKER

Oh yeah.. the non letters. We need to swap those too
to swap non-letters too
  $str =~ s/(.)(.)/$2$1/gs;

But you still didn't clarify whether
 print OUT $str;
should print out
badcfe
or whether
 print OUT $newstr;
should print out
badcfe
after doing
  $str = "abcdef";
  $newstr = swap($str);
Those could be different functions, but one of the answers seemed to assume one, while your question indicated the other.
Cool. Thanks.  I wanted to return the $newstr from the function.  

sub swap{
  my $str=shift;
  $str =~ s/(.)(.)/$2$1/gs;
  return $str;
}
can be used as
print swap("abcdef");
but
sub swap{
  s/(.)(.)/$2$1/gs for @_;
}
can be used as
 $str = "abcdef";
 swap($str);
 print OUT $str;


Thanks ozo!