Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Problem with hashes

by rattytatty (Initiate)
on Feb 09, 2012 at 14:35 UTC ( #952733=perlquestion: print w/replies, xml ) Need Help??
rattytatty has asked for the wisdom of the Perl Monks concerning the following question:

This code won't work and I don't know why
A line in the file that the hash is made from looks like this:
af361872 A1
With af361872 being the key and A1 being the value
I'm trying to add the value to the second file in which each line looks like this:
0_0 af457052
The console says this
Use of uninitialized value in concatenation (.) or string at line 29, <FILE>
line 29 is "print OUT "$_\t$hash{$word-1}\n";"

use warnings; use strict; my %hash; open FILES,"Final.txt"or die "Can not open file"; while(<FILES>){ chomp $_; my @words; @words=split(/\t/,$_); my $len=scalar(@words)-1; $hash{$words[$len]}=$words[0]; } open FILE,"output.txt" or die "Can not open file";<br> open OUT, ">cladeST.txt" or die "Can not open file Final.txt"; while(<FILE>){<br> chomp $_; my @word; @word=split(/\t/,$_); print OUT "$_\t$hash{$word[-1]}\n"; }

Replies are listed 'Best First'.
Re: Problem with hashes
by Ratazong (Monsignor) on Feb 09, 2012 at 14:52 UTC


    The reason of this error-message is that there is no entry for $word[-1] in the hash. You could check with exists before to handle that situation.

    HTH, Rata

    PS.: please use <code>-tags!
      I've checked manually for a few of the keys in the hash
      file and the exist. I know for a fact that they all do
      exist as I used them to generate the hash in the first place.
        Rule one for debugging: checking is better than knowing for sure. So try copying the following code before your print and look what is happening ...:
        if (exists ($hash{$word[-1]})) { print("$word[-1] OK\n"); } else { print("$word[-1] isn't in the hash\n"); }

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://952733]
Approved by Ratazong
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (7)
As of 2018-06-20 07:37 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (116 votes). Check out past polls.