0AP0 has asked for the wisdom of the Perl Monks concerning the following question:

I'm having a hair-pulling time with this one and I'm hoping someone will point me to a simple over-looked mistake.

The program reads data into a hash from one file, then goes through a few other files that contain lists of keys for the hash, and I'm trying to construct lists of hashed values from those keys.

The code, up to where it's going all pear-shaped, is as follows:

#!/usr/bin/perl -w use strict; use Statistics::Distributions; $|=1; open my $OUTPUT, ">", "mh_dist_outliers1d.tsv" or die $!; my %PCA=(); open my $PRCOMPFILE, "<", "strain_PCA.csv" or die $!; while (my $line=<$PRCOMPFILE>){ chomp $line; my @line=split /,/, $line; $PCA{$line[0]}=$line[1]; } close $PRCOMPFILE; my %results=(); my @sizes=(1,25,50,100); for my $size (@sizes){ print "\n###Starting pop$size###\n"; open my $POPLIST, "<", "pops.$size.tsv" or die $!; while (my $line=<$POPLIST>){ print "."; chomp $line; my @line=split /\t/, $line; my $pop=shift @line; my @pos= map {$PCA{$_};} @line;

The problem is when I get to the last line there $PCA{$_} is always returning "null", even if I hand-feed it keys from the hash. The debugger (in Komodo) shows the hash to be properly filled. I'd be most appreciative if someone can point out why I'm unable to access these hash elements.

Replies are listed 'Best First'.
Re: Simple? problem accesssing elements in a hash
by moritz (Cardinal) on Aug 29, 2008 at 10:48 UTC
    I don't see any obvious errors in your code. When %PCA is populated correctly, maybe @line doesn't contain what you think it does?

    (You can also simplify your last line to read my @pos = @PCA{@lines};, see perldata for details).

      I found the error. Being told that it didn't look like a code problem and more like an input problem helped.

      It was in the initialization of the PCA hash the keys, instead of being numbers, had quotation marks around them.

        and the general answer for this is:
        debug.
        print out variables, if you're not sure what's in it.
        and even if you're sure.
        use Data::Dumper; $Data::Dumper::Useqq = 1; # print non-printable chars warn Dumper $blackbox;