# How can I swap two Perl variables without using the third?

I want to swap two variables values without using the third variable in Perl, e. g.:

my $first = 10; my $second = 20;

Please suggest me how we can do this in Perl in a simple way.

## Answers

The best way that only provide us is like this in one line you can swap the values:

($first, $second) = ($second, $first);

You can write:

($first, $second) = ($second, $first);

(See §3.4 "List Assignment" in *Learning Perl*, Third Edition.)

The Perl-specific methods already listed are best, but here's a technique using XOR that works in many languages, including Perl:

use strict; my $x = 4; my $y = 8; print "X: $x Y: $y\n"; $x ^= $y; $y ^= $x; $x ^= $y; print "X: $x Y: $y\n"; X: 4 Y: 8 X: 8 Y: 4

You can do this relatively easy using simple maths.

We know;

First = 10 Second = 20

If we say First = First + Second

We now have the following;

First = 30 Second = 20

Now you can say Second = First - Second (Second = 30 - 20)

We now have;

First = 30 Second = 10

Now minus Second from First, and you get First = 20, and Second = 10.

$first = $first + $second; $second = $first - $second; $first = $first-$second;

This will swap two integer variables A better solution might be

$first = $first xor $second; $second = $first xor $second; $first = $first xor $second;

#!/usr/bin/perl $a=5; $b=6; print "\n The value of a and b before swap is --> $a,$b \n"; $a=$a+$b; $b=$a-$b; $a=$a-$b; print "\n The value of a and b after swap is as follows:"; print "\n The value of a is ---->$a \n"; print "\n The value of b is----->$b \n";

you can use this logic

firstValue = firstValue + secondValue; secondValue = firstValue - secondValue; firstValue = firstValue - secondValue;