Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

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?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (9)
As of 2016-09-30 16:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Extraterrestrials haven't visited the Earth yet because:







    Results (570 votes). Check out past polls.