Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Answer: How do I return the first n words of a string?

by runrig (Abbot)
on Oct 26, 2000 at 20:18 UTC ( #38655=categorized answer: print w/replies, xml ) Need Help??

Q&A > strings > How do I return the first n words of a string? - Answer contributed by runrig

Here's a slightly tested solution:
my $str="hello there bob smith and more words"; my $num_words=5; if (my ($words) = $str=~ /((?:\w+(?:\W+|$)){$num_words})/) { print $words; }
If you want to separate the words you can of course:
@words = split /\W+/, $words;

Log In?

What's my password?
Create A New User
[Discipulus]: echo 'a'\'' gives me the prompt and then go with error on ctrl-d
[Discipulus]: uch! worst than windows!
[marto]: It's not worse, just different. Different shells, different tools. Different ways
[choroba]: Perl to the rescue!

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (11)
As of 2017-11-24 10:23 GMT
Find Nodes?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:

    Results (346 votes). Check out past polls.