Swap the values of two variables.
In Perl 6, there is no need to use temporary variables to swap the values of two variables. Just use the lists on both sides of the equation:
($b, $a) = ($a, $b);
Alternatively, call theΒ reverse
method and assign the result back to the values:
($a, $b).=reverse;
Consider the complete program:
my ($a, $b) = (10, 20);
($b, $a) = ($a, $b);
say "\$a = $a, \$b = $b";
This program prints the swapped values:
$a = 20, $b = 10
This approach also works with elements of an array:
my @a = (3, 5, 7, 4);
(@a[2], @a[3]) = (@a[3], @a[2]);
say @a; # [3 5 4 7]
A slice of an array may be used instead of an explicit list:
my @a = (3, 5, 7, 4);
@a[1, 2] = @a[2, 1];
say @a; # [3 7 5 4]
One thought on “π Swap two values in Perl 6”