Kyle Weise Kyle Weise - 1 month ago 9
Perl Question

creating hash from array in perl

I have an array that I want to convert into a hash table. Basically, I want

@array[0]
to be the keys of the hash, and
@array[1]
to be the values of the hash. Is there an easy way to do this in perl? The code I have so far is as follows:

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

unless( open(INFILE, "<", 'scratch/Drosophila/fb_synonym_fb_2014_05.tsv')) {
die "Cannot open file for reading: ", $!;

while(<INFILE>) {
my @values = split();
#convert values[0] to keys, values[1] to values
}


the file is available for download here

Answer

@array[0] (an array slice, used to return multiple elements) is a bad way of writing $array[0] (an array lookup, used to return a single element). use warnings; would have told you this.


To set a hash element, one uses

$hash{$key} = $val;

So the code becomes

my %hash;
while (<>) {
    chomp;
    my @fields = split /\t/;
    $hash{ $fields[0] } = $fields[1];
}

Better yet,

my %hash;
while (<>) {
    chomp;
    my ($key, $val) = split /\t/;
    $hash{$key} = $val;
}

The name of the file implies the fields are tab-separated, not whitespace separated, so I switched

split ' '

to

split /\t/

This required the addition of chomp.