tags:

views:

123

answers:

4

I have a string like this:

$a = "Mike , Tree "; 

I want to reverse it to "Tree, Mike".

Is there any function to do that?

+9  A: 

Use the reverse function:

$reversed = join(",", reverse split(",", $string));
The MYYN
hey that's a fancy feature in perl... I like.
rockinthesixstring
This sample code is not using the reverse function in scalar context.
mobrule
corrected. thx.
The MYYN
i like this answer ....
Tree
Nice..Looks very "functional". :)
Bart J
+1  A: 

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.

Kyra
+10  A: 

Split the string into two strings, flip them, and rejoin them.

Or, use a regex:

$a =~ s/(.+),(.+)/\2,\1/g;
Andy Lester
Better than Roque answer from my point of view as the regex allow you more control on how to deal with extra space. In your case I would exactly do $a =~ s/(\S+)\s*,\s*(\S+)/\2, \1/g;
radius
\1, etc in the replacement side is long deprecated and will trigger a warning; do this instead: `$a =~ s/(.+),(.+)/$2,$1/g;`
ysth
Its Good answer
Tree
The `g` modifier seems superfluous here, doesn't it?
Svante
**@radius:** in rogue's answer you could still do a regex to replace the space, though if you're going to regex, you might as just do it all in one step.
vol7ron
+1  A: 

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
J.J.