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
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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?
$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?
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.
$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.
ASKER
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;
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;
ASKER
Thanks ozo!
$str="abcdef";
@letters = split //, $str;
while (@letters) { ($a,$b) = splice(@letters,0,2); $swapped .= "$b$a"; }
print $swapped;