Gossamer Forum
Home : General : Perl Programming :

First n words of a string

Quote Reply
First n words of a string
I want to extract the first n words of a string. The expression I have is the following (for extracting five words)
Code:
$out =~ s/^((\w*\s){5})(.*)/$1/;
It works OK if there are no punctuation signs, but doesn't work if there are, i.e. if $out is "The Victoria Yoga Centre Society is bla bla bla" then it works, if it is "Producing & selling of yogaprops like bla bla bla" does not work

How should I modify the above statement to simply ignore punctuation signs?

Thanks a lot.

Ivan
-----
Iyengar Yoga Resources / GT Plugins
Quote Reply
Re: [yogi] First n words of a string In reply to
http://www.perlmonks.org/...amp;lastnode_id=1826

- wil
Quote Reply
Re: [Wil] First n words of a string In reply to
Thanks, Wil.

The second example works (the third removed the punctuation signs, haven't tested the first).

Ivan
-----
Iyengar Yoga Resources / GT Plugins

Last edited by:

yogi: Jan 14, 2002, 2:48 AM
Quote Reply
Re: [yogi] First n words of a string In reply to
No worries. Lucky I just happened to have that bookmarked.

- wil

Last edited by:

Wil: Jan 14, 2002, 2:46 AM
Quote Reply
Re: [yogi] First n words of a string In reply to
Yeah you could use \b but you could just do it with:

@words = split /\s+/, $string, 4;

print join ' ', @words;

Or something like that :)

Last edited by:

RedRum: Jan 14, 2002, 3:23 AM
Quote Reply
Re: [RedRum] First n words of a string In reply to
Yes. That's the last example in the URi given.

Code:
$str=
'yo ho ho and a bottle crumbs.
hangin and bangin in the upper-class slums.';

@word = ($str =~ /(\w+)/g);

print join ':', @word[0..4];

But that's not the best way, IMO.

- wil

Last edited by:

Wil: Jan 14, 2002, 3:28 AM
Quote Reply
Re: [Wil] First n words of a string In reply to
Thats nothing like what I just gave Wink

...nevertheless it is a good way as it limits split to what it needs.

Last edited by:

RedRum: Jan 14, 2002, 3:52 AM
Quote Reply
Re: [RedRum] First n words of a string In reply to
True. Which probably makes it a fraction faster. Maybe?

- wil