I have a string like this:
$a = "Mike , Tree ";
I want to reverse it to "Tree, Mike"
.
Is there any function to do that?
I have a string like this:
$a = "Mike , Tree ";
I want to reverse it to "Tree, Mike"
.
Is there any function to do that?
Use the reverse
function:
$reversed = join(",", reverse split(",", $string));
If you are guaranteed the your string that you want to be reversed will be separated by commas then I would split the string at the comma and then go through the array it produces from the length of it to 0 and append it to an empty string.
Split the string into two strings, flip them, and rejoin them.
Or, use a regex:
$a =~ s/(.+),(.+)/\2,\1/g;
Just for your problem.
$a =~ s/([A-Za-z]+)([^A-Za-z]+)([A-Za-z]+)/$3$2$1/;
[JJ@JJ trunk]$ perl -E '$a = "Mike , Tree "; $a =~ s/([A-Za-z]+)([^A-Za-z]+)([A-Za-z]+)/$3$2$1/; say $a;'
Tree , Mike