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?

( #38655=categorized answer: print w/ replies, xml ) Need Help??

Q&A > strings > How do I return the first n words of a string? 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;

Comment on Answer: How do I return the first n words of a string?
Select or Download Code
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 chanting in the Monastery: (4)
As of 2014-12-27 11:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (177 votes), past polls