in reply to creating a hash from a text file.
You can avoid global regex matches if you split into key/value pairs then further split on spaces slicing out the first two elements.
$ perl -MData::Dumper -e ' > my $str = q{1 human 2 flower 3 fruits 5 human 6 car 9 flower asdgjha +shdnh gsdh sjs klja}; > my %hash = > map { ( split m{\s+} )[ 0, 1 ] } > split m{(?x) (?<=\w) \s+ (?=\d)}, $str; > print Data::Dumper->Dumpxs( [ \ %hash ], [ qw{ hash } ] );' $hash = { '6' => 'car', '1' => 'human', '3' => 'fruits', '9' => 'flower', '2' => 'flower', '5' => 'human' }; $
I hope this is of interest.
Cheers,
JohnGG
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: creating a hash from a text file.
by AnomalousMonk (Archbishop) on Jul 27, 2010 at 18:20 UTC | |
by johngg (Canon) on Jul 27, 2010 at 22:30 UTC |