Kyle Weise Kyle Weise - 1 year ago 136
Perl Question

creating hash from array in perl

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

to be the keys of the hash, and
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:

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 Source

@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 (<>) {
    my @fields = split /\t/;
    $hash{ $fields[0] } = $fields[1];

Better yet,

my %hash;
while (<>) {
    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 ' '


split /\t/

This required the addition of chomp.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download