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

    Why would one want to bother avoiding global regex matches? (In fact, doesn't split at some level involve a global regex match?)

      Poor wording on my part! What I meant was "as an alternative to" but it came out wrong :-(

      Cheers,

      JohnGG