Keys in Perl hash disappeared

231 views Asked by At

I have a list of data that I want to put into a Perl hash

file missing_rs.txt

rs11273140
rs79236118
rs63414861
rs11414981
...

So I built a while loop

#! usr/bin/perl
use warnings;
use strict;

my (%hash1, %hash2, %hash3); #%hash1, %hash3 are for other purposes
open (my $FH2, '<', 'missing_rs.txt') or die $!;

my $count2 = 0;
while ( my $line2 = <$FH2> ) {
        chomp $line2;
        my @key2 = split /\t/, $line2;
        $hash2{$key2[0]} = 1;
        $count2++;
}

my @missing_rs_keys = keys %hash2; # added to help troubleshoot
my @missing_rs_values = values %hash2; # added to help troubleshoot
my $item;
print "@missing_rs_keys"; 

my $missing_rs = scalar @missing_rs_keys; #added to help troubleshoot
print "Total missing rs (non-redundant) count is $count2\n"; # added to help troubleshoot
print "Total number of missing rs after buidling hash is $missing_rs\n"; # added to help troubleshoot

My question is, why can I not print the %hash2 keys, as the output from print "@missing_rs_keys"; is empty but $missing_rs = 20.

I tried to build a foreach loop to print out each key in %hash2, and the loop ran well and gave me what I expected, but somehow I could not print "@missing_rs_keys" directly.

Update

When I ran the script I got this output

[chenb07@minerva4 ~]$ perl crazy2
Total missing rs (non-redundant) count is 23
Total number of missing rs after buidling hash is 20
[chenb07@minerva4 ~]$
1

There are 1 answers

4
Borodin On

You are processing a Windows text file in a non-Windows environment, so your chomp is removing the trailing linefeed on each record but leaving the carriage-return. That has the effect of making each line of output on the console overwrite the preceding one so it appears as if there is nothing in the array

Just replace your chomp with s/\s+\z// and all will be well