πŸ“˜ Swap two values in Perl 6

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]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s