http://www.perlmonks.org?node_id=293989


in reply to Needing to take out 3rd word of sting

A different way of approaching the problem - use a hash to store the order of the words and the words themselves. This makes it easy to delete or add words in the order that you want. This makes use of a property of delete() that I didn't realize existed - it returns the value of the hash element that it deletes.

my $string = "This is a only a test"; my %words; my $i = 1; # Assign the order of the words as a key, the word itself as # a value $words{$i++} = $_ foreach(split(' ', $string)); # Delete the word that you want to delete my $deleted_word = delete($words{3}); # Put the word back in $words{3} = $deleted_word; # Join the values back together based on the order of # the keys $string = join(" ", map { $_ = $words{$_} } sort keys %words); print $string . "\n";

«Rich36»