我是perl的新手。我無法理解以下代碼的輸出。perl中'++'運算符的行爲
my %fruit_color = (apple => "red", banana => "yellow", grape => "purple");
my @fruits = keys %fruit_color;
my @colors = values %fruit_color;
print "The color of apple is ", $fruit_color{"apple"}, "\n";
$cnt = 0;
while ($cnt < @fruits) {
print $fruits[$cnt ++], " ";
}
print "\n";
$cnt = 0;
while ($cnt < @colors) {
print $colors[$cnt ++], " ";
}
輸出粘貼在這裏:
The color of apple is red
grape banana apple
purple yellow red
但是,如果我改變了我的代碼是這樣的:
my %fruit_color = (apple => "red", banana => "yellow", grape => "purple");
my @fruits = keys %fruit_color;
my @colors = values %fruit_color;
print "The color of apple is ", $fruit_color{"apple"}, "\n";
$cnt = 0;
while ($cnt < @fruits) {
print $fruits[$cnt], " "; # DIFF HERE !
$cnt ++;
}
print "\n";
$cnt = 0;
while ($cnt < @colors) {
print $colors[$cnt ++], " ";
}
輸出將是:
The color of apple is red
apple grape banana
red purple yellow
我無法理解這些考試之間的區別特別是爲什麼第一個while循環的變化會影響第二個循環。有誰能告訴我爲什麼輸出是顛倒的?非常感謝。
[爲什麼哈希鍵有打印時不同的順序?](https://stackoverflow.com/questions/30340027/why-do-hash-keys-have-different-order - 打印時) – mkHun
「問題」不是你的「++」調用。這很完美。但是調用'keys%fruit_color;'以某種任意順序返回哈希鍵,並且不能依賴它在不同腳本運行之間相同。從[docs](http://perldoc.perl.org/functions/keys.html):_「哈希條目以明顯隨機的順序返回。」_ – PerlDuck