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.


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;



print "\n The value of a and b before swap is --> $a,$b \n";


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;

Need Your Help

how to change the color of a single bar if condition is True matplotlib

python matplotlib

I've been googleing to find if it's possible to change only the color of a bar in a graph made by matplotlib.

Sequel Pro Alternative for Windows

mysql windows user-interface

Well my macbook pro is kind of not cutting it for me anymore and I have a perfectly good Windows Laptop I would actually rather use but I cannot find a reliable replacement for my SQL client. So I am