Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi all, The following code works fine to print out values in a hash. But how can i alter it so that it prints out those values that dont exist in the hash?
%naccess = map { /^\s+\S+\s+\S+\s+(\S+)/; ($1 => $_) } <IN2>; close (IN2); while (<IN>) { chomp; /^\s+(\S+)/; print OUT ($naccess{$1}) if (exists($naccess{$1})); }

Replies are listed 'Best First'.
Re: hash question
by ikegami (Patriarch) on Nov 21, 2004 at 21:25 UTC

    print OUT ($1) if (!exists($naccess{$1}));
    or
    print OUT ($1) unless (exists($naccess{$1}));

    Although it's not quite proper English, it reads rather nicely if you remove the optional parens:
    print OUT ($1) if not exists $naccess{$1};

    Update: It's useless to print $naccess{$1} if it doesn't exist! I substituted $naccess{$1} with the key ($1).

      these are what i thought might work, but do not!
        oops, fixed.
Re: hash question
by pg (Canon) on Nov 21, 2004 at 21:36 UTC
    "print OUT ($naccess{$1}) if (exists($naccess{$1}));"

    To make your code more robust, you better first check whether $1 is actually set, before you check whether it exists in the hash.

      i know that the $1 is being called correctly. prints the values i want
        this is my code
        $first = shift@ARGV; $second = shift@ARGV; open (IN, "<$first"); open (IN2, "<$second"); open (OUT, ">NACCESS"); %naccess = map { /^\s+\S+\s+\S+\s+(\S+)/; ($1 => $_) } <IN2>; close (IN2); while (<IN>) { chomp; /^\s+(\S+)/; print OUT ($1) unless (exists($naccess{$1})); } close (IN);
        IN2 FILE
        1 59 49 0.0 0 100.0 0.0 1 60 50 0.0 0 100.0 0.0
        IN FILE
        112 104.35 141.94 115 22.34 29.13