Easiest way to Swap in Perl

There are many ways to swap values in Perl. I'm giving you three ways to swap two variables in Perl. It would help you to swap string with string or number with number.

1) Below is the Perl code to swap that would 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 and string swap. If the both string's length are same. This swap operation is done using bitwise XOR operation. Similar for other languages, 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.

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'd suggest you to follow the first method. This method is not available for most of the languages.

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;