![](/img/trans.png)
[英]Perl How to access a hash that is the element of an array that is the value of another hash?
[英]Unable to Access Element in a Perl Hash
我有一个散列,其中填充了以下测试数据:
my %non_root_files = ('views/SPYGLASS_HOME/bin/sample_sgdc_file_contents_1.sgdc' => 1,
'views/SPYGLASS_HOME/bin/sample_sgdc_file_contents.sgdc' => 1,
'views/SPYGLASS_HOME/bin/test_2.sgdc' => 1,
'views/SPYGLASS_HOME/bin/test_4.sgdc' => 1,
'views/SPYGLASS_HOME/bin/test_5.sgdc' => 1,
'views/SPYGLASS_HOME/bin/test_6.sgdc' => 1);
在另一个数组中,我有以下数据:
my @files = ('views/SPYGLASS_HOME/bin/sample_sgdc_file_contents.sgdc',
'views/SPYGLASS_HOME/bin/test_2.sgdc',
'views/SPYGLASS_HOME/bin/sample_sgdc_file_contents_1.sgdc',
'views/SPYGLASS_HOME/bin/test_5.sgdc',
'views/SPYGLASS_HOME/bin/test_7.sgdc',
'views/SPYGLASS_HOME/bin/sample_sgdc_file_contents_2.sgdc');
我需要做的是检查数组中的每个条目是否存在于哈希中,并从原始数组中删除,因此我如下进行操作:
sub deleteDuplicate{
$originalList_ref = shift;
my $index = 0;
foreach my $element (@{$originalList_ref})
{
if(exists $non_root_files{$element})
{
splice(@{$originalList_ref}, $index, 1);
}
$index++;
}
}
但是,对于哈希中实际存在的某些条目,存在的查找失败。 该元素在哈希表中,但是如果condition返回false。 谁能解释这个原因以及如何纠正呢?
谢谢!
Brian的评论是正确的。 你要:
if(exists $non_root_files{$element})
{
splice(@{$originalList_ref}, $index, 1);
}
else
{
$index++;
}
(如果删除数组中的一个条目,则下一个条目将移回相同的索引)。
关于perldoc perlsyn中的 foreach
循环:
如果LIST的任何部分是数组,则在循环体中添加或删除元素(例如使用splice)时,foreach会非常混乱。 所以不要那样做。
有一种更简单的方法可以做到这一点:
sub deleteDuplicate {
$original_ref = shift;
$originalList_ref = [ grep { ! exists $non_root_files{$_} } @$originalList_ref ];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.