簡體   English   中英

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM