Wednesday, August 5, 2009

Perl: Swap string value using s///

This a funny way to swap two values from a string using perl's s///. This will only work if the two words contain exactly one times inside string. I was just wondering about it, and think to add here for all.

Let say you have a string, and you want to swap the words "demo" and "test" with each other. So the simple code will be as below.
## initial string to swap
my $string = "test string and demo string";
## swaping test with demo
$string =~ s/(test)(.*?)(demo)/$3$2$1/;
print "$string\n";


Inside the regex you'll need to change the position of test and demo depending upon the position from original string. And remember this will work only if both string exist only once. For multiple I didn't check, So don't know.

Once again, its a funny stuff, but may come helpful for somebody. Don't forget to add a comment if anyone find such.

No comments:

Get function name programaticaly - Python

This little piece of code will help you to get the function name programatically. This is very helpful when you are implementing the debug...