[ Team LiB ] Previous Section Next Section

Recipe 1.3 Exchanging Values Without Using Temporary Variables

1.3.1 Problem

You want to exchange the values of two scalar variables, but don't want to use a temporary variable.

1.3.2 Solution

Use list assignment to reorder the variables.

($VAR1, $VAR2) = ($VAR2, $VAR1);

1.3.3 Discussion

Most programming languages require an intermediate step when swapping two variables' values:

$temp    = $a;
$a       = $b;
$b       = $temp;

Not so in Perl. It tracks both sides of the assignment, guaranteeing that you don't accidentally clobber any of your values. This eliminates the temporary variable:

$a       = "alpha";
$b       = "omega";
($a, $b) = ($b, $a);        # the first shall be last -- and versa vice

You can even exchange more than two variables at once:

($alpha, $beta, $production) = qw(January March August);
# move beta       to alpha,
# move production to beta,
# move alpha      to production
($alpha, $beta, $production) = ($beta, $production, $alpha);

When this code finishes, $alpha, $beta, and $production have the values "March", "August", and "January".

1.3.4 See Also

The section on "List value constructors" in perldata(1) and on "List Values and Arrays" in Chapter 2 of Programming Perl

    [ Team LiB ] Previous Section Next Section