我有一个源列表,从中我可以选择随机项目并填充目标列表。列表中的项目具有特定格式。例如:
item1{'name'}
item1{'日期'}
等等以及更多领域。
在插入目标列表时,我检查项目上的唯一名称并将其插入该列表。为此,我必须遍历整个目标列表以检查具有给定名称的项目是否存在,如果不存在,则插入它。
我认为如果我再次将目标列表设为散列而不是列表会更好,这样我就可以更快、更有效地查找项目。我是 Perl 的新手,不知道如何做到这一点。任何人,请帮助我如何插入项目,查找特定项目名称以及删除哈希中的项目?
如何将名称和日期作为键并将整个项目作为值?
最佳答案
我的 %hash;
$hash{$K} = $V
if (exists $hash{$K}) { print "it is in there with value '$hash{$K}'\n"; } else { print "it is NOT in there\n" }
Delete a particular name / key?
delete $hash{$K}
Make name and date as key and entire item as value?
Easy Way: Just string everything together
set: $hash{ "$name:$date" } = "$name:$date:$field1:$field2"
get: my ($name2,$date2,$field1,$field2) = split ':', $hash{ "$name:$date" }
del: delete $hash{ "$name:$date" }
更难的方法:在哈希中存储为哈希(谷歌“perl 对象”)
放:
my %temp;
$temp{"name"} = $name;
$temp{"date"} = $date;
$temp{"field1"} = $field1;
$temp{"field2"} = $field2
$hash{"$name:$date"} = \$temp;
得到:
my $find = exists $hash{"$name:$date"} ? $hash{"$name:$date"} : undef;
if (defined find) { # i.e. it was found
printf "field 1 is %s\n", $find->{"field1"}
} else {
print "Not found\n";
}
删除:
delete $hash{"$name:$date"}
关于perl - 在 perl 中散列的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3199185/