Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 757
  • Last Modified:

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
0
jamie_lynn
Asked:
jamie_lynn
  • 4
  • 3
  • 3
3 Solutions
 
clockwatcherCommented:
$str="abcdef";
@letters = split //, $str;
while (@letters) { ($a,$b) = splice(@letters,0,2); print "$b$a"; }
0
 
clockwatcherCommented:
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;
0
 
clockwatcherCommented:
As a function,

sub swapletters {
   my @letters = split //, shift;
   while (@letters) { my ($a,$b) = splice(@letters,0,2); $_ .= "$b$a"; }
   return $_;
}

print swapletters("abcdef");

0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
ozoCommented:
$str = "abcdef";
$str =~ s/(\w)(\w)/$2$1/g;
print $str;
0
 
ozoCommented:
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?
0
 
jamie_lynnAuthor Commented:
Oh yeah.. the non letters. We need to swap those too
0
 
ozoCommented:
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.
0
 
jamie_lynnAuthor Commented:
Cool. Thanks.  I wanted to return the $newstr from the function.  

0
 
ozoCommented:
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;


0
 
jamie_lynnAuthor Commented:
Thanks ozo!
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 4
  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now