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