我有一个源列表,我从中获取随机项并填充目标列表.列表中的项目具有特定格式.例如:
item1{'name'} item1{'date'}
等等以及更多领域.
插入目的地列表时,我检查项目上的唯一名称,并将其插入该列表.为此,我必须遍历整个目标列表以检查具有给定名称的项是否存在,如果不存在则插入它.
我认为如果我将目标列表再次作为哈希而不是列表,这样会更好,这样我就可以更快更有效地查找项目.我是Perl的新手,我没有得到如何做到这一点.任何人,请帮助我如何插入项目,找到特定的项目名称,并删除哈希项目?
如何将名称和日期作为键,将整个项目作为值?
解决方法
我的%哈希;
>使用密钥$K插入$V项?
$hash {$K} = $V.
>查找特定名称/密钥$K?
if (exists $hash{$K}) { print "it is in there with value '$hash{$K}'\n"; } else { print "it is NOT in there\n" }
删除$hash {$K}
>将名称和日期作为键,将整个项目作为值?
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"}