2

我正在尝试使用 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";
}
4

1 回答 1

5

当您放置时{},您明确要求perl对 a 进行引用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在整个范围内预先声明,看我在哪里声明
  • 更好的方法(取决于您的需要)是使用 aHASH而不是两个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};
}
于 2012-10-23T19:42:44.983 回答