Jump to content

Exchange Values Without Using Temporary Variables in Perl

+ 1
  gnat's Photo
Posted Oct 20 2009 02:03 PM

If you want to exchange the values of two scalar variables, but don't want to use a temporary variable, use list assignment to reorder the variables.

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


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".

Cover of Perl Cookbook
Learn more about this topic from Perl Cookbook, 2nd Edition. 

Find a Perl programmer, and you'll find a copy of Perl Cookbook nearby. Perl Cookbook is a comprehensive collection of problems, solutions, and practical examples for anyone programming in Perl. The book contains hundreds of rigorously reviewed Perl "recipes" and thousands of examples ranging from brief one-liners to complete applications.

The second edition of Perl Cookbook has been fully updated for Perl 5.8, with extensive changes for Unicode support, I/O layers, mod_perl, and new technologies that have emerged since the previous edition of the book. Recipes have been updated to include the latest modules. New recipes have been added to every chapter of the book, and some chapters have almost doubled in size.

Learn More Read Now on Safari


Tags:
0 Subscribe


0 Replies