尝试使用for循环读取数组中的元素

时间:2012-10-23 19:41:11

标签: perl

我正在尝试使用for循环从数组中读取元素,但我似乎无法使其正常工作。当我运行程序时,它打印出一个奇怪的“HASH”,或者不打印任何东西。有人可以帮忙吗?

#!/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";
}

1 个答案:

答案 0 :(得分: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};
}