in reply to Using Split to load a hash

I am wondering if we can load a HOA in a similar way. I have always used the following:
use strict; use Data::Dumper; my %hash; while(<DATA>) { chomp; my $line = $_; my $key = (split/\t/, $line)[0]; push @{ $hash{$key} }, $line; } print Dumper(\%hash); __DATA__ 1 a 101 1 b 110 2 c 201 3 d 301 3 e 310 3 f 320 4 g 401

Replies are listed 'Best First'.
Re^2: Using Split to load a hash
by umasuresh (Hermit) on Apr 30, 2010 at 17:33 UTC
    Following the hint in http://www.perlmonks.com/?node_id=564943,
    I tried the following with map and grep:
    use strict; use Data::Dumper; my ($hash, @array); my @array = <DATA>; $hash ={ map { chomp; my $key = (split(/\t/) )[0]; $key => [ grep { chomp; $_ if( (split(/\t/) )[0] =~/$key/) } @array ] } @array }; print Dumper(\%$hash); __DATA__ 1 2 a 1 13 w 1 20 c 2 1 b 2 40 n 3 30 a
    Note: DATA should be tab delimited for this to work