Saturday, March 15, 2008

Perl : Easiest way to Swap


Share at Facebook

There are many ways to Swap in Perl. i'm giving you three ways to swap two variables in Perl. It will help you to swap string with string or number with number.

1) Below is the Perl code to swap that will work both for string and number.

my $a = "TeXT-1";
my $b = "TeXT-2";
print "Original : $a - $b\n";
($a,$b) = ($b,$a);
print "Swap : $a - $b\n";

2) This one will work for number swap. Also work for string swap, if the both string length is same. This swap operation is done using bitwise XOR operation. Similar for other language, Perl also support XOR operation.

my $a = 19201;
my $b = 12311;
print "Original : $a - $b\n";
$a = $a ^ $b;
$b = $a ^ $b;
$a = $a ^ $b;
print "Swap : $a - $b\n";

3) This one will only work for number swap. Not for text swap.

my $a = 1234;
my $b = 4211;
print "Original : $a - $b\n";
$a = $a + $b;
$b = $a - $b;
$a = $a - $b;
print "Swap : $a - $b\n";


Since you are using Perl, i suggest you to follow the first method. This method is not available for most of the languages.




3 comments:

Anonymous said...

Third method doesn't work in practice. It results in overflow, if values are large.

The most common method using a temporar value is missing:
my $tmp = $a;
$a = $b;
$b = $a;

hbalint said...

$tmp = $a;
$a = $b;
$b = $tmp;

hbalint said...

$tmp = $a;
$a = $b;
$b = $tmp;