Perl数据结构与类型通配符深度解析
1. 奥斯卡获奖者数据处理
在处理包含奥斯卡获奖者信息的文本文件时,我们有一系列需求,如根据年份和类别查询对应条目、按年份打印所有条目等。
1.1 数据表示
为了能按类别或年份检索条目,采用了双重索引方案。每个条目包含类别、年份和获奖者姓名,存储在匿名数组中。通过 %year_index
和 %category_index
两个索引将年份和类别映射到包含条目引用的匿名数组。以下是构建该结构的代码:
open (F, "oscar.txt") || die "Could not open database: $!";
%category_index = (); %year_index = ();
while ($line = <F>) {
chomp $line;
($year, $category, $name) = split (/:/, $line);
create_entry($year, $category, $name) if $name;
}
sub create_entry { # create_entry (year, category, name)
my($year, $category, $name) = @_;
# Create an anonymous array for each entry
$rlEntry = [$year, $category, $name];
# Add this