http://www.perlmonks.org?node_id=1085978


in reply to How to compare hash values to array values in Perl

Since you claim to be a "perl beginner" - kcott's (++) code may be a little esoteric.

Here is somewhat simpler and more traditional code (with no module dependencies):

use strict; use warnings; open(my $table, "<", "table.txt") or die "Cannot open Tables"; my %ids2proteins; while (<$table>){ chomp; my ( $protein, $nbr) = split ; next unless $nbr; $ids2proteins{$nbr} = $protein; } close $table; open(my $val, "<", "values.txt") or die "Cannot open Values"; while (<$val>){ chomp; next unless length $_ > 1; next unless my $prot = $ids2proteins{$_}; print "$prot => $_ \n"; } close $val;

        What is the sound of Perl? Is it not the sound of a wall that people have stopped banging their heads against?
              -Larry Wall, 1992

Replies are listed 'Best First'.
Re^2: How to compare hash values to array values in Perl
by kcott (Archbishop) on May 14, 2014 at 06:52 UTC
    "Since you claim to be a "perl beginner" - kcott's (++) code may be a little esoteric."

    To NetWallah: Thanks for the ++; esotericism was not the intention.

    To To_Bz: If there was something in my original code you didn't understand, please feel free to ask; however, first see the clarification below.

    "Here is somewhat simpler and more traditional code (with no module dependencies):"

    The module (Inline::Files) was not intended for To_Bz's code; it was purely for my test.

    I was aiming to use (what appeared to be) the smaller file (values.txt) to create the hash; then selectively printing from (what appeared to be) the larger file (table.txt).

    As a clarification, here's the entire script I envisaged for To_Bz (correcting the open syntax errors and applying my lexical filehandle recommendation):

    #!/usr/bin/env perl -l use strict; use warnings; use autodie; open my $table, '<', 'table.txt'; open my $values, '<', 'values.txt'; my %vals = map { $_ => 1 } <$values>; print $_->[0] for grep { $vals{$_->[1]} } map { [ split / / ] } <$tabl +e>;

    [Note: autodie used in lieu of hand-crafting die messages for both open statements.]

    -- Ken