【发布时间】:2021-06-23 21:55:36
【问题描述】:
我正在开展一个向我们介绍匿名哈希的项目。作业要求我们使用匿名哈希作为基础对象,然后添加键值“pizza_toppings”,这是一个至少有 5 个元素的数组;和 'movies',一个包含至少 3 个哈希对象的数组,其键必须是 'title' 和 'genre'。还有一些关于修改披萨的事情,我已经做到了。
我坚持的是,当它们具有相同的键时,我不确定如何访问单个哈希值。我的目标是清理输出,因此我需要能够在最后一个条目之前切断循环,添加“and”,然后打印最后一个,使其看起来像这样:
我理想的披萨有菠萝、蘑菇、洋葱、番茄、奶酪和青椒。
我喜欢看科幻、动作和奇幻电影。
我最喜欢的一些是《降临》、《地下六号》和《实用魔法》!
这是我目前所拥有的。它可以工作,但格式不正确。我也很想听听任何比我所做的更好的打印流派和标题的解决方案。我还是个小编剧!我们并没有真正得到任何解释,我也无法找到如何访问像这样的几个级别的东西。
use 5.26.1;
use strict;
use warnings;
my %hash = (
'pizza_toppings' => ['pineapple', 'mushroom', 'onion', 'tomato', 'cheese'],
'movies' => [
{'genre' => 'SciFi', 'title' => 'Arrival'},
{'genre' => 'Action', 'title' => 'Six Underground'},
{'genre' => 'Fantasy', 'title' => 'Practical Magic'}
]
);
#adding 'green peppers' to the list of toppings
my $rf = $hash{pizza_toppings};
$rf -> [5] = 'green peppers';
print "My ideal pizza has ";
#Printing out the list of toppings
foreach my $i ( @{ $hash{pizza_toppings} } ) {
print $i . ", ";
};
print ".\nI like to watch ";
#printing out the list of genres
foreach my $i ( @{ $hash{movies} } ) {
my %g = (%{$i});
print $g {'genre'} . ", ";
};
say " movies.";
print "Some of my favourites are ";
#printing out the list of titles
foreach my $j ( @{ $hash{movies} } ) {
my %t = (%{$j});
print $t {'title'} . ", ";
};
say "!";
【问题讨论】:
标签: arrays perl data-structures anonymous-types