Checking if a value in one hash exists in another

Discussion in 'Perl Misc' started by mwthayer, Nov 19, 2005.

  1. mwthayer

    mwthayer Guest

    Hi
    I have searched the groups and haven't found exactly what I need. If
    this is a duplicate, forgive me.

    I need to compare to hashes. I want to know if the value to a certain
    key from one hash is found as a value in another hash then print the
    key from both hashes where the match.
    Example:
    Hash 1
    Key.......Value
    21A00001 Brown Fox
    21A00002 Brown Fox
    Hash 2
    Key....Value
    212121 Brown Fox
    Result after the compare (a tab delimited file)
    21A00001 {tab or \t} 212121
    21A00002 {tab or \t} 212121

    Grateful for any suggestions
     
    mwthayer, Nov 19, 2005
    #1
    1. Advertisements

  2. mwthayer

    xhoster Guest

    That isn't what hashes do. If you want to look up by the value, then
    you should have made that the key rather than the value.

    Your values-turned-keys are not unique, so you need a HoA.

    my %inverted1;
    while (my ($k,$v) = each %hash1) {
    push @{$inverted{$v}}, $k
    };

    Xho
     
    xhoster, Nov 19, 2005
    #2
    1. Advertisements

  3. mwthayer

    John Bokma Guest


    How about:

    hash 1:

    'Brown Fox' => [ '21A00001', '21A00002' ],
    :
    :


    hash 2:

    'Brown Fox' => [ '212121' ],
    :
    :


    and then:

    for my $key ( keys %hash1 ) {

    exists $hash2{ $key } or next;

    my @items = @{ $hash1{ $key } };

    for my $item ( @items ) {

    print join( "\t", $item, @{ $hash2{ $key } } ), "\n";
    }
    }
     
    John Bokma, Nov 19, 2005
    #3
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.