in reply to Capturing the nth word in a string

Yet another way:
$_ = "ele1 ele2 ele3 ele4 ele5 ele6"; m/(\w+\s*){$ARGV[0]}/; print $1;
pass in a parameter to indicate which word you want. (you can eaily turn this into a function). This does not create an array and saves space, assuming the only thing you care is the nth.

Replies are listed 'Best First'.
Re: Re: Capturing the nth word in a string
by etcshadow (Priest) on Oct 14, 2003 at 05:04 UTC
    Nice. Tiny changes, though... want nth char, not (n+1)th... also, you want \s+, not \s*... and might as well decide that by "word" we mean a run of non-whitespace (that is... probably a bad idea to mix \w and \S... so I'll just go with \S).
    [me@host bin]$ perl -we '$n = $ARGV[0]; $_ = "a b csadf sdfas ddd"; /( +?:\S+\s+){@{[$n-1]}}(\S+)/; print "$1\n"' 1 a [me@host bin]$ perl -we '$n = $ARGV[0]; $_ = "a b csadf sdfas ddd"; /( +?:\S+\s+){@{[$n-1]}}(\S+)/; print "$1\n"' 2 b [me@host bin]$ perl -we '$n = $ARGV[0]; $_ = "a b csadf sdfas ddd"; /( +?:\S+\s+){@{[$n-1]}}(\S+)/; print "$1\n"' 4 sdfas [me@host bin]$

    ------------
    :Wq
    Not an editor command: Wq
      The reason I used \s* not \s+ is, to make it also work for the last word, as there is no space after that one.
        I think you misunderstand... \s not the same as \S.

        ------------
        :Wq
        Not an editor command: Wq