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

后端 未结 7 990
盖世英雄少女心
盖世英雄少女心 2021-01-17 13:27

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

7条回答
  •  遥遥无期
    2021-01-17 13:34

    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.

提交回复
热议问题