2012-10-23 55 views
2

我正在嘗試使用for循環讀取數組中的元素,但似乎無法使其正確工作。當我運行程序時,它會打印出一個奇怪的「HASH」,或者不打印任何東西。誰能幫忙?嘗試使用for循環讀取數組中的元素

#!/usr/bin/perl 
use strict; 

my $he; 
my @selections = {"Hamburger","Frankfurter","French Fries","Large Coke","Medium Coke","Small Coke","Onion Rings"}; 
my @prices = {3.49, 2.19, 1.69, 1.79, 1.59, 1.39, 1.19}; 

for($he= 0; $he<= 6; $he++) 
{ 
     print "@selections[$he]"; 
     print "@prices[$he]\n"; 
} 
+2

不宜硬編碼 「6」。 'for(my $ he = 0; $ he <= 6; $ he ++)'應該爲'(my $ he = 0; $ he <@selections; $ he ++)',並且它的可讀性更高,爲'for我$他(0 .. $#選擇)' – ikegami

回答

5

當你把{},您明確要求perl做出一個HASH參考。您似乎需要使用括號來聲明ARRAY

所以:

#!/usr/bin/perl 
use strict; use warnings; 

my @selections = (
    "Hamburger", 
    "Frankfurter", 
    "French Fries", 
    "Large Coke", 
    "Medium Coke", 
    "Small Coke", 
    "Onion Rings" 
); 
my @prices = (3.49, 2.19, 1.69, 1.79, 1.59, 1.39, 1.19); 

for(my $he = 0; $he <= 6; $he++) 
{ 
    print "$selections[$he]=$prices[$he]\n"; 
} 

而且,使得陣列更有趣且穿這樣的:

my @selections = qw/foo bar base/; 

但是當你不具備任何價值空間,它纔會起作用。

注意

  • 我建議你使用use warnings;所有的時間
  • 不寫@selections[$he]$selections[$he]
  • 沒有必要在全範圍預先聲明$he,看到我的聲明它
  • 更好的方法(取決於您的需求)是使用HASH而不是兩個ARRAYS

這樣的:

#!/usr/bin/perl -l 
use strict; use warnings; 

my %hash = (
    "Hamburger" => 3.49, 
    "Frankfurter" => 2.19, 
    "French Fries" => 1.69, 
    "Large Coke" => 1.79, 
    "Medium Coke" => 1.59, 
    "Small Coke" => 1.39, 
    "Onion Rings" => 1.19 
); 

foreach my $key (keys %hash) { 
    print $key . "=" . $hash{$key}; 
} 
相關問題