交換兩個純量變數值,不使用暫存變數

方法:
($VAR1, $VAR2) = ($VAR2, $VAR1);

一般交換兩變數值須使用:

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

Perl 直接指定即可交換:

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

也可同時交換超過兩個變數:

($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);

最後 $alpha, $beta, $production 的值為 "March", "August", "January"

搗蛋鬼 發表在 痞客邦 PIXNET 留言(0) 人氣()