in reply to Load a single column file into a hash

How do I load this into a hash with one column .
You can't have a hash with just one column. Hash elements have to be key-value pairs, although the value may be anything you want (you don't really care anyway), including undef, as in the code suggested by jahero.

I think that, in such a case, most people use either undef or simply 1. The upside of using 1 is that testing the hash value will return a true value, so that you can test existence by a simple look up:

say "Found it" if $hash{$key};
This is marginally useful in one-liners because it is less key stokes than:
say "Found it" if exists $hash{$key};
which is the more standard way of testing a hash for existence.

You can use map, as shown by jahero, or you can use a for loop. Assuming the file name is stored in the $file_in variable, this may look like this:

my %hash; open my $INPUT, "<", $file_in or die "Cannot open $file_in $!"; # the +die "..." part is not needed if you use autodie. while (my $line = <$INPUT>) { chomp $line; $hash{$line} = 1; # or undef or anything you like for the value } close $INPUT; # You can use %hash for lookup now
Update: fixed a typo: $hash{$line} instead of $hash{line}. Thanks to vighneshmufc for pointing it out.

Replies are listed 'Best First'.
Re^2: Load a single column file into a hash
by vighneshmufc (Acolyte) on Feb 05, 2018 at 15:03 UTC
    thanks a lot However i would love to know why was in $hash{line} = 1.....{line} used
      Yeah, it's a typo, sorry and thanks. I should obviously be $hash{$line}. I fixed it in my original post.