![](/img/trans.png)
[英]comparing key of one hash with value of another to create third hash in perl
[英]Perl: Find first hash key of one hash that's also in another hash
我寫了這個簡單的子,它可以按賣出的方式工作:
sub search_dispatch_table
{
my ($href1, $href2) = @_;
foreach my $key (keys %$href1)
{
return $key if exists $href2->{$key};
}
return undef;
}
我只是想返回href1
的第一個鍵,該鍵也存在於href2
。
有更好的方法嗎?
您沒有指定希望用來評估哪種解決方案更好的標准。
假設您的意思是“更快”,則可以通過使用each
而不是keys
來加快最佳情況,僅此而已。
sub search_dispatch_table {
my ($href1, $href2) = @_;
while (my ($key) = each(%$href1)) {
if (exists($href2->{$key})) {
keys(%$href1); # Reset iterator.
return $key;
}
}
return undef;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.