IT story

Perl에서 해시를 결합하려면 어떻게해야합니까?

hot-time 2020. 9. 2. 20:45
반응형

Perl에서 해시를 결합하려면 어떻게해야합니까?


두 해시를 % hash1에 결합하는 가장 좋은 방법은 무엇입니까? 저는 항상 % hash2와 % hash1에 고유 한 키가 있다는 것을 알고 있습니다. 가능하면 한 줄의 코드를 선호합니다.

$hash1{'1'} = 'red';
$hash1{'2'} = 'blue';
$hash2{'3'} = 'green';
$hash2{'4'} = 'yellow';

빠른 답변 (TL; DR)


    % hash1 = (% hash1, % hash2)

    ## 아니면 ...

    @ hash1 {keys % hash2} = 값 % hash2;

    ## 또는 참조 포함 ...

    $ hash_ref1 = {% $ hash_ref1, % $ hash_ref2};

개요

  • 컨텍스트 : Perl 5.x
  • 문제 : 사용자가 두 개의 해시 1 을 단일 변수로 병합하려고 합니다.

해결책

  • 간단한 변수에 위의 구문을 사용하십시오.
  • 복잡한 중첩 변수에 Hash :: Merge 사용

함정

또한보십시오


각주

1 * (일명 연관 배열 , 일명 사전 )


perlfaq4 확인 : 두 개의 해시를 병합하는 방법 . Perl 문서에는 이미 많은 좋은 정보가 있으며 다른 사람이 대답하기를 기다리지 않고 바로 얻을 수 있습니다. :)


두 해시를 병합하기로 결정하기 전에 두 해시에 동일한 키가 포함되어 있고 원래 해시를 그대로 유지하려는 경우 수행 할 작업을 결정해야합니다.

원래 해시를 유지하려면 하나의 해시 (% hash1)를 새 해시 (% new_hash)에 복사 한 다음 다른 해시 (% hash2)의 키를 새 해시에 추가합니다. 키가 이미 % new_hash에 있는지 확인합니다. 중복 항목으로 수행 할 작업을 결정할 수있는 기회를 제공합니다.

my %new_hash = %hash1; # make a copy; leave %hash1 alone

foreach my $key2 ( keys %hash2 )
    {
    if( exists $new_hash{$key2} )
        {
        warn "Key [$key2] is in both hashes!";
        # handle the duplicate (perhaps only warning)
        ...
        next;
        }
    else
        {
        $new_hash{$key2} = $hash2{$key2};
        }
    }

새 해시를 만들고 싶지 않은 경우에도이 루핑 기술을 사용할 수 있습니다. % new_hash를 % hash1로 변경하십시오.

foreach my $key2 ( keys %hash2 )
    {
    if( exists $hash1{$key2} )
        {
        warn "Key [$key2] is in both hashes!";
        # handle the duplicate (perhaps only warning)
        ...
        next;
        }
    else
        {
        $hash1{$key2} = $hash2{$key2};
        }
    }

If you don't care that one hash overwrites keys and values from the other, you could just use a hash slice to add one hash to another. In this case, values from %hash2 replace values from %hash1 when they have keys in common:

@hash1{ keys %hash2 } = values %hash2;

This is an old question, but comes out high in my Google search for 'perl merge hashes' - and yet it does not mention the very helpful CPAN module Hash::Merge


For hash references. You should use curly braces like the following:

$hash_ref1 = {%$hash_ref1, %$hash_ref2};

and not the suggested answer above using parenthesis:

$hash_ref1 = ($hash_ref1, $hash_ref2);

참고URL : https://stackoverflow.com/questions/350018/how-can-i-combine-hashes-in-perl

반응형