use warnings; use strict; my $input = "one 1 two 2 three 3 odd_element"; my $REGEX = qr{ \s* \b (\w+) \s+ (\w+) \b \s* }msx; my %output; pos($input)=undef; while ($input=~/\G$REGEX/gc) { $output{$1} = $2; } my $rest = substr $input, pos $input; if (length $rest) { # leftovers $output{$rest} = 'turkeysandwich'; } use Data::Dumper; print Dumper(\%output); __END__ $VAR1 = { 'one' => '1', 'two' => '2', 'three' => '3', 'odd_element' => 'turkeysandwich' };