#define 3 variables, 2 for storage, one for temp...
my ($a, $b, $c);
#set the two variables to some value
$a = 5;
$b = 6;
#use the temp value to swap them
$c = $a;
$a = $b;
$b = $c;
#now, $a has $b and $b has what $a had
####
($b, $a) = ($a, $b); #swap two variables
####
#!/usr/bin/perl -w
use strict;
use Benchmark;
my $a = rand(10);
my $b = rand(10);
sub traditional {
my $c = $a;
$a = $b;
$b = $c;
}
sub non_trad {
($b, $a) = ($a, $b);
}
timethese (-10, { "traditional" => \&traditional,
"not traditional" => \&non_trad,
});
[ed@darkness ed]$ perl swap.pl
Benchmark: running not traditional, traditional,
each for at least 10 CPU seconds...
not traditional: 11 wallclock secs (10.25 usr + 0.00 sys = 10.25 CPU) @ 302846.15/s (n=3104173)
traditional: 11 wallclock secs (10.83 usr + 0.00 sys = 10.83 CPU) @ 491714.04/s (n=5325263)