in reply to creating a hash from a text file.
Assuming you want to ignore the 'asdgjhashdnh gsdh sjs klja' stuff and only extract single-digit/alpha-string pairs, this might be a way to go (sorry for the wrap-around):
>perl -wMstrict -le "my $s = '1 human 2 flower 3 fruits 5 human 6 car 9 flower asdgjhashdn +h gsdh sjs klja'; my %hash = $s =~ m{ (\d) \s+ ([[:alpha:]]+) }xmsg; use Data::Dumper; print Dumper \%hash; " $VAR1 = { '6' => 'car', '1' => 'human', '3' => 'fruits', '9' => 'flower', '2' => 'flower', '5' => 'human' };
One problem with
my ($index, $data)=split (/\s+/,$line);
is that it only captures the first index/data pair, and the example in the OP has several pairs per line. (Update: This is actually pointed out by moritz.) Another problem is that the extraneous data (the 'asdgjhashdnh gsdh sjs klja' stuff) would not be filtered out by a split that simply captured all the field pairs generated.
|
|---|