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

后端 未结 7 922
盖世英雄少女心
盖世英雄少女心 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:32

    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
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-17 13:39

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

     ($first, $second) = ($second, $first);
    
    0 讨论(0)
  • 2021-01-17 13:44
    $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;
    
    0 讨论(0)
  • 2021-01-17 13:49

    you can use this logic

    firstValue = firstValue + secondValue;
    
    secondValue = firstValue - secondValue;
    
    firstValue = firstValue - secondValue;
    
    0 讨论(0)
  • 2021-01-17 13:52
    #!/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";
    
    0 讨论(0)
提交回复
热议问题