in reply to Capturing the nth word in a string

I tried to make a solution that captured the nth word, where n was the more human index. 1 being first, etc.
$str = "this is a sentence of words and I want the nth one"; $n = 4; # the word we want $a = 0; $a = 1 + index $str, $", $a while --$n; $word = substr $str, $a, -$a + index $str, $", $a; print "$word";
prints "sentence". It seems very complicated, though.

Doesn't work for the last word. Bah! Unless I change it to index"$str ", $", $a everywhere. Nuts.

Replies are listed 'Best First'.
Re: Re: Capturing the nth word in a string
by Jasper (Chaplain) on Oct 14, 2003 at 13:14 UTC
    Here's another possibility
    $num = 4; for($str=~/.?/g){ $h{space} += !/\S/; $word .= $_ if $h{space} == $num-1 && /\S/ .. !/\S/ } print $word;