我正在尝试使用 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";
}
最佳答案
当您输入 {}
时,您明确要求 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};
}
关于perl - 尝试使用 for 循环读取数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13037965/