Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

So I have a text file where each line contains an entry, a colon, and a definition, e.g.
natural number: a non-negative integer counting number: a positive integer rational number: a real that can be expressed as a fraction
etc. I want to load these into a hash, with with entries as keys. I currently do it like this:
%words = (); while (<>) { chop; ($word, $def) = split /: */; $words{$word} = $def; }
This works. But isn't there a simpler, shorter, cooler way to do this? Maybe a one-liner?

Replies are listed 'Best First'.
Re: Loading a textfile into a hash
by kabel (Chaplain) on Nov 14, 2002 at 10:23 UTC
    use strict; use warnings; use Data::Dumper; my %hash = map {chomp; split /: */} <DATA>; print Dumper \%hash; __DATA__ natural number: a non-negative integer counting number: a positive integer rational number: a real that can be expressed as a fraction
    UPDATE: included chomp
Re: Loading a textfile into a hash
by Monky Python (Scribe) on Nov 14, 2002 at 10:38 UTC
    a regex solution.
    my %words =(); map { chomp; if (/([^:]+):[\s]+(.*)/) { $words{$1} = $2;} }<>;