Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

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 final.pl 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"; }

Comment on Problem with hashes
Download Code
Re: Problem with hashes
by Ratazong (Prior) on Feb 09, 2012 at 14:52 UTC

    Hi!

    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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://952733]
Approved by Ratazong
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (9)
As of 2014-10-21 04:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (96 votes), past polls