Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

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

by runrig (Abbot)
on Oct 26, 2000 at 20:18 UTC ( [id://38655]=note: print w/replies, xml ) Need Help??


in reply to How do I return the first n words of a string?

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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://38655]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (5)
As of 2024-04-19 20:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found