in reply to Problem generating a hashtable

This (basically exact same as yours) code works for me (prints "k1\nk2\n") -- what is a sample of your <FILE>?:
use strict; use warnings; my %hash = map { (split /:/, $_ )[0] => (split /:/, $_ )[2] } <DATA>; print join ( "\n", sort keys %hash ) . "\n"; __DATA__ k1:asd:v1 k2:asd:v2
One suggestion though, would be to change the map so that the split() is only done once (no functionality change, just for efficiency):
map { my @tmp = split /:/, $_; $tmp[0] => $tmp[2]; } <FILE>
(could also do map { (split(/:/, $_)) [0,2] } but that's not as clear that it's key/value pairs)
Update: Oops. I see now that OP said he won't be using the two splits....

Replies are listed 'Best First'.
Re^2: Problem generating a hashtable
by techra (Pilgrim) on May 13, 2005 at 14:36 UTC
    I only wish everyone who used map in their code would do so as beautifully as you did in your 2nd example. Multiple lines! Named variables! I can understand at a glance exactly what this does. Map has been a learning hurdle for me in all my years of Perl Development, mostly because nearly all examples of it I see obfuscate its actual function. Thank you for this good example.
Re^2: Problem generating a hashtable
by Tomtom (Scribe) on May 13, 2005 at 13:34 UTC
    Actually, I changed it to
    my ( $key, $value ) = map { (split(/:/, $_)) [0,2] } <FILE>;
    :) In fact,
    (split /:/, $_ )[0] => (split /:/, $_ )[2]
    does work a first time on another tab, but seems to invert the keys and the values the second time :/
Re^2: Problem generating a hashtable
by blazar (Canon) on Jul 19, 2005 at 14:23 UTC
    could also do map { (split(/:/, $_)) [0,2] } but that's not as clear that it's key/value pairs
    This is indeed a good point, but if you're not too much concerned about it, then
    my %hash=map +(split /:/)[0,2], <DATA>;
    would be shorter and clearer, IMHO. In particular a very nice point about $_ is that it is the "topicalizer" so that it's the default implicit argument of just so many "actions"...